commit c652a5276d29b2e3647866039cd71b2ccc006622 Author: Brian Holman Date: Fri Nov 13 00:14:03 2026 -0700 Publish VCC Plus OSS source distribution for 3.6.2 build 60 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dec1616 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +# Preserve exact source bytes on every host for EXPORT.json fingerprints. +* -text +*.dsk binary +*.cas binary +*.vhd binary +*.bin binary +*.pdf binary +tools/toolchain/patches/*.patch whitespace=-blank-at-eol diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2807a84 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Local build products, user inputs and editor state +/.build/ +/build/ +/dist/ +/platforms/macos/LocalResources/ +*.sqlite +*.sqlite3 +*.sqlite-* +*.db +*.db-* +*.rom +*.vhd +*.app/ +*.dmg +*.xcresult/ +xcuserdata/ +*.xcuserstate +__pycache__/ +*.pyc +.DS_Store +*.o +*.a +*.obj +*.exe +*.dll +# Dependency trees are generated by tools/dependencies/fetch.py. +/third_party/* +!/third_party/manifests/ +!/third_party/README.md diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/EXPORT.json b/EXPORT.json new file mode 100644 index 0000000..2a741a7 --- /dev/null +++ b/EXPORT.json @@ -0,0 +1,5965 @@ +{ + "datasets": "Build-generated empty schemas; no populated content", + "files": { + ".gitattributes": { + "bytes": 204, + "mode": "0644", + "sha256": "b1d667073033164c5edd14374b6cc50396dcbd66bad1b581c02ae785eed4604f" + }, + ".gitignore": { + "bytes": 399, + "mode": "0644", + "sha256": "33934ec8aca799aee1ec2c911fddc0ec3743c759e44fe5c7da964ff37de39c80" + }, + "COPYING": { + "bytes": 35147, + "mode": "0644", + "sha256": "8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903" + }, + "README.md": { + "bytes": 10668, + "mode": "0644", + "sha256": "7c7f385dd5c84d440b6134a7c850024bb72b84742f83725abbdcb1b7d59d4935" + }, + "RELEASES.md": { + "bytes": 13336, + "mode": "0644", + "sha256": "b1b5d13db9ea530571c69dac0b74794dcb9112fa56b9b9a08f7ef1e8b5d924e7" + }, + "docs/WHITE_PAPER_EVIDENCE.md": { + "bytes": 2442, + "mode": "0644", + "sha256": "e2ca76b652b733daafa026ec929705d4fea9cbad8460f2ace30d3bbc4429945d" + }, + "docs/development/ASSEMBLY_WORKSPACE.md": { + "bytes": 6628, + "mode": "0644", + "sha256": "f1f4500dca0170bccf999b4f30a215315f4bd0221e5f56336c05ec379cf4a6a9" + }, + "docs/development/BASIC_WORKSPACE.md": { + "bytes": 21562, + "mode": "0644", + "sha256": "d73ec36d94f37bf064700c8c1d19b30fca23fd2c4c7b45a443759d4e16947cf5" + }, + "docs/development/CMOC_BENCHMARKS.md": { + "bytes": 4057, + "mode": "0644", + "sha256": "d17929f26a5bca3f31fef22018eec7969b5d3ae9306c089c63487ec173ef6f95" + }, + "docs/development/CMOC_INDEXED_ARGUMENT_LOAD.md": { + "bytes": 5066, + "mode": "0644", + "sha256": "f15d646071a02075c91f790420833b735c8537e6e114a02d495df906ca579c16" + }, + "docs/development/CMOC_RELEASE_QUALIFICATION.md": { + "bytes": 3692, + "mode": "0644", + "sha256": "80a4c553da8ff3eb4df7464ca0663c221b39604345c2c5f3ba3e0f06e8bd9aab" + }, + "docs/development/CMOC_RUNTIME.md": { + "bytes": 8749, + "mode": "0644", + "sha256": "c76871a76088b08e8c47110f596631f0cc426a73adb75f956c0abe508a6de9f7" + }, + "docs/development/CMOC_SOURCE_DEBUGGING.md": { + "bytes": 17907, + "mode": "0644", + "sha256": "4c68e24b09ff3c6d3f0d72ad1fb7573c212fb35f81010c983da034fdbf65f454" + }, + "docs/development/MCP_AUDIO_CAPTURE.md": { + "bytes": 3508, + "mode": "0644", + "sha256": "5b4746bc68ea2e93c5bb1f5d54aa063fb409557b6ba2b085118225a304ed841b" + }, + "docs/development/MCP_BANKED_PLAYTEST.md": { + "bytes": 23592, + "mode": "0644", + "sha256": "fad90fcb7e5ca3670d803f02578e44e637b0b126f7716dc4198f253ea7eae3a6" + }, + "docs/development/MCP_BUILD45_VALIDATION.md": { + "bytes": 1836, + "mode": "0644", + "sha256": "d9fb9382d0e908cd8060d50c0a473a479ce8e9f1ea184a29ac1a174feecfc621" + }, + "docs/development/MCP_CALL_CONTEXT.md": { + "bytes": 6422, + "mode": "0644", + "sha256": "1bd9f44f14ab8eabd289571834307ebc6ceb1fe3f81109fc5a2d8bf3857438c9" + }, + "docs/development/MCP_DEBUG_EVIDENCE.md": { + "bytes": 7817, + "mode": "0644", + "sha256": "79fe80ae2c40808e6da821bae1d2de1aa4c18b5f7e24b3a40707fdd473cf086e" + }, + "docs/development/MCP_PLAYTEST_MEDIA.md": { + "bytes": 9578, + "mode": "0644", + "sha256": "cffb200d9efc5ff9e85720e66aeb1693f1cfc88f99d5a675b1afb7ee7e3af09c" + }, + "docs/development/MCP_PLAYTEST_PROCESSORS.md": { + "bytes": 3943, + "mode": "0644", + "sha256": "14ad39d6b95f8efca3d95f622587806514066cfde98358d1808d7c5cd039aae1" + }, + "docs/development/MCP_PROJECT_RELIABILITY.md": { + "bytes": 5547, + "mode": "0644", + "sha256": "109fd4c39ac16c8b2b497fadf50f283772e2f9b39bca394e271e9d79d597ae83" + }, + "docs/development/REPOSITORY_LAYOUT.md": { + "bytes": 1505, + "mode": "0644", + "sha256": "238f26baba46e8e1419595bc32c9c92f74b90c4efe43539e4f154c5901568fe1" + }, + "docs/macos/AUDIO_CASSETTE.md": { + "bytes": 5549, + "mode": "0644", + "sha256": "e250421aef2f4c9fa88480acffd773a66edcdfd7783d25bbc226a3d2cce0c9da" + }, + "docs/macos/AUDIO_ROUTING.md": { + "bytes": 7110, + "mode": "0644", + "sha256": "eacd467a5dd6d736a3492a81a3d4390152b63fa63353af0327e2087d8cec8057" + }, + "docs/macos/CARTRIDGES.md": { + "bytes": 5723, + "mode": "0644", + "sha256": "a12aa417fbef14bc8c5aae804803d50879649df0b4cd30fcb493c49a236b0697" + }, + "docs/macos/CPU_CORE.md": { + "bytes": 7209, + "mode": "0644", + "sha256": "6180aca7c7a9a6d4f793ca76b45633c2e083f84e095adfaa8ea21512162ed4fc" + }, + "docs/macos/DEBUGGER.md": { + "bytes": 12234, + "mode": "0644", + "sha256": "43f57e99efcd15b90da092f938aaccb07c35882f0dc6bb03a0b983b810838224" + }, + "docs/macos/DEBUGGER_MEMORY_TOOLS.md": { + "bytes": 5603, + "mode": "0644", + "sha256": "030ff6d680359c1656c091f6e0176ebacd0b685b79cd1c0996b49906b483dbb7" + }, + "docs/macos/DEBUGGER_TRACING.md": { + "bytes": 5558, + "mode": "0644", + "sha256": "9da93fdaeb87f7868b1adeecb99e9ee3c20b3e3bfb61278a2d74ad048b1d2b65" + }, + "docs/macos/FLOPPY_CORE.md": { + "bytes": 11389, + "mode": "0644", + "sha256": "eeb5d4a7cbc9a41473a69ce44823a4e6c717854693b4770046c290ed746c3091" + }, + "docs/macos/GRAPHICS_CORE.md": { + "bytes": 6020, + "mode": "0644", + "sha256": "89fe9dcdbf12294b61de961ded09d64146394a552be932d4b61520db4fd15879" + }, + "docs/macos/HARD_DISKS.md": { + "bytes": 6449, + "mode": "0644", + "sha256": "2adb2ad908404c3b274d9cc4e4460ae4d4f7bba26ddabcf66f96e1d13fa87945" + }, + "docs/macos/MACHINE_CORE.md": { + "bytes": 5789, + "mode": "0644", + "sha256": "f23234c546286bf03ff162dd1595f99192ea7f395688e5873aa6a010e74193a0" + }, + "docs/macos/MAC_CONTROLLER.md": { + "bytes": 6558, + "mode": "0644", + "sha256": "f0d89e49a3467085bf1cffaeadfcabd883c324fc3567eeb85c9140a3e2e4d104" + }, + "docs/macos/NATIVE_BOOT.md": { + "bytes": 4022, + "mode": "0644", + "sha256": "c668a13507b0a3c1508c2f606b592cca0631ac9d2f963402eb2f1458e0e4144d" + }, + "docs/macos/PORTING_PLAN.md": { + "bytes": 4468, + "mode": "0644", + "sha256": "b9d7dcf3a2e8d223f7049ca7810e5758e13253c6c80913b628dc3b6d451faa47" + }, + "docs/macos/TIMING_RELIABILITY.md": { + "bytes": 11771, + "mode": "0644", + "sha256": "aee9a63a900c9fcf64849886001ee66bd52b18dc7bed690afb3a90d9c95f3ba3" + }, + "docs/media/ATTRIBUTION.md": { + "bytes": 9527, + "mode": "0644", + "sha256": "6edd9bb45f6d03abf2d7cac404a498f342b60fa2ea6307004beac0c4b875696c" + }, + "docs/media/about/dezota-dark.svg": { + "bytes": 5805, + "mode": "0644", + "sha256": "0eb371c7069210f0d5acc783438f0d7c2c0a4b15b70d8c34bbcab03b8a629ce6" + }, + "docs/media/about/dezota.svg": { + "bytes": 5805, + "mode": "0644", + "sha256": "5b41c84cfae4d349fad615e06a0970c9b185ae979889f08220a1828f75e55175" + }, + "docs/media/about/founder.svg": { + "bytes": 286417, + "mode": "0644", + "sha256": "a1bf3619e46be3b4ab0b2d12a837510e67aaff8681a8e59e1cc9a2624ab56d15" + }, + "docs/media/coco-sdc-label.svg": { + "bytes": 22514, + "mode": "0644", + "sha256": "f8d63737f051270258901f4b031aba9c823174d977426497732b0fe1d47f283a" + }, + "docs/media/hitachi-inside-badge.svg": { + "bytes": 24221, + "mode": "0644", + "sha256": "1c25d4302f6f6d5a787979d7b81a22d75150fdbc2b223afa2875e62107ce0819" + }, + "docs/media/manual-help.svg": { + "bytes": 3443, + "mode": "0644", + "sha256": "6701a7094b59956489e9022c4481ba6f31e25ac61e60d0efe60545182ab46ef0" + }, + "docs/media/motorola-inside-badge.svg": { + "bytes": 22402, + "mode": "0644", + "sha256": "5db9ce26fbc046b4b09f948fd20ecf4e9de06eb6785470860af29892504dd8bd" + }, + "docs/media/orchestra-90-label.svg": { + "bytes": 20931, + "mode": "0644", + "sha256": "451bb22707e194967025fcd6d3eb675a6f53b91f2f051c56d7dd3891ffcc5394" + }, + "docs/media/proposal/stacked-system.svg": { + "bytes": 1551987, + "mode": "0644", + "sha256": "d329de5f3e0b981c0ab44a9412487833d505d8a05d6862df3558c3348a3a35ca" + }, + "docs/media/runtime-system.svg": { + "bytes": 4429648, + "mode": "0644", + "sha256": "523d46ec8f80650e62d7b41a22e258d58b582ab021dd56888a25f13f0b24582a" + }, + "docs/media/speech-sound-label.svg": { + "bytes": 19210, + "mode": "0644", + "sha256": "42a79dd376bdcc07d64ab8219c0a4dd38b86d84854eed77d8b20bb5b0cdc512e" + }, + "docs/media/tandy-128k-color-computer-3-badge.svg": { + "bytes": 27743, + "mode": "0644", + "sha256": "7011f8b946e6bf3b336f5ea5208cf0a5c2e1054864f5e94074d7a005563436bf" + }, + "docs/media/tandy-cm-8-monitor.svg": { + "bytes": 70236, + "mode": "0644", + "sha256": "a1f178007f8bfddf5343b295f1de681179adce8bd91b3ceafc93d6a7fba04a09" + }, + "docs/media/tandy-color-computer-3-computer.svg": { + "bytes": 211809, + "mode": "0644", + "sha256": "55e5049e44cd885404fac9fcc2aa40dd79e4f9e6adbe1fe16c161f4d7e7bf89a" + }, + "docs/media/tandy-color-computer-3-full-system.svg": { + "bytes": 1951421, + "mode": "0644", + "sha256": "db8ee1f308f806aada9f0f67ddaca1ba975284636c70e09fb74c9db52ea2e234" + }, + "docs/media/tandy-color-computer-3-system.svg": { + "bytes": 354091, + "mode": "0644", + "sha256": "56e3475f6802f608561776b7339e960ea7efa54df396de2b5259033ca9b780cc" + }, + "docs/media/tandy-color-computer-3-virtual-system.svg": { + "bytes": 2031090, + "mode": "0644", + "sha256": "8a31bcbb6e7ebc19b4df89da9e386d44bb6f58ff00b622bb3e2a7683092eebb4" + }, + "docs/media/tandy-color-computer-3-with-drive.svg": { + "bytes": 378626, + "mode": "0644", + "sha256": "eb405d78d9e8144d49e16a98032cad4da468faa87421921c390a06947d25d6e1" + }, + "docs/media/tandy-color-computer-3.svg": { + "bytes": 281336, + "mode": "0644", + "sha256": "0585ae59f26d11ee88f6082f7d13b3c2c3cdea228737c0aa3ed95f0dcddb79bc" + }, + "docs/media/tandy-color-computer-rom-cartridge-colors.svg": { + "bytes": 210709, + "mode": "0644", + "sha256": "c771666bf78658a1421094573adc408fa52f06497aef36db812b2805fee47fd4" + }, + "docs/media/tandy-color-computer-rom-cartridge-green.svg": { + "bytes": 45178, + "mode": "0644", + "sha256": "337e2eee553bbed95052a9827c0c3bfdd35a68d54ca2febd1318751c7e26490f" + }, + "docs/media/tandy-color-computer-rom-cartridge-red.svg": { + "bytes": 45168, + "mode": "0644", + "sha256": "c91e9b5aa3755cefd4bd3e70199a314e24c23dc09fd5773a210c5f795f91cdba" + }, + "docs/media/tandy-color-computer-rom-cartridge-yellow.svg": { + "bytes": 45186, + "mode": "0644", + "sha256": "6fa6116f8e39ba707d4d744624345120c0a8632af1e1c912d4220854f26e9e26" + }, + "docs/media/tandy-color-computer-rom-cartridge.svg": { + "bytes": 45060, + "mode": "0644", + "sha256": "5687da3ba2b487acb3258cdac6de72098dacc58a22405d59fb3c0058939e01e8" + }, + "docs/media/tandy-computer-cassette-recorder-badge.svg": { + "bytes": 17685, + "mode": "0644", + "sha256": "585c80d9713bc08af9a5375b9871b824296ec959d8127f6cc905d2e6cc89308f" + }, + "docs/media/tandy-computer-cassette-recorder.svg": { + "bytes": 368266, + "mode": "0644", + "sha256": "0e275802271592171db23c77b477905a11a7cbcc1d09a82d875346fb6e881f82" + }, + "docs/media/tandy-deluxe-joystick-badge.svg": { + "bytes": 10370, + "mode": "0644", + "sha256": "649722a23d32147dadae1f8782bcbc3aac4f4969ece485b7db8c3b310dcf5471" + }, + "docs/media/tandy-deluxe-joystick.svg": { + "bytes": 24099, + "mode": "0644", + "sha256": "89bd70fff576b9bf31b4060b5593ec29216f5ecac886d0781dfc6dfae27fddd8" + }, + "docs/media/tandy-fd-502-controller.svg": { + "bytes": 40955, + "mode": "0644", + "sha256": "1638248e0cce0bc3b1601bc8db46322176b1b46acb90ccd059dc0caf1a615e01" + }, + "docs/media/tandy-fd-502-disk-drive-badge.svg": { + "bytes": 10729, + "mode": "0644", + "sha256": "c6acbfc41126f69ade20b29e5cf8efa6d9881fd7c821e530e29f9601bd1daba7" + }, + "docs/media/tandy-fd-502-disk-drive.svg": { + "bytes": 97661, + "mode": "0644", + "sha256": "c822a3ba86f84e57006e07297fc8f434a7f72ded99e963e6281c7c4d633ad9aa" + }, + "docs/media/tandy-fd-502-ribbon-cable.svg": { + "bytes": 162265, + "mode": "0644", + "sha256": "a13239bf8bd882fdc0b5012375d7782a4a9316c7ebc95d9c224675964e0d58b0" + }, + "docs/media/tandy-multi-pak-interface-badge.svg": { + "bytes": 10015, + "mode": "0644", + "sha256": "64b13c1b88b470b51d8ee477695f0489d6ef4642be440a60f47a800267ce79bf" + }, + "docs/media/tandy-multi-pak-interface.svg": { + "bytes": 72696, + "mode": "0644", + "sha256": "0676c9b44b548237717a0a1d508689be67ba6999bd1465f2ba9bd56edc21b8be" + }, + "docs/media/tandy-rgb-color-monitor-cm-8-badge.svg": { + "bytes": 15698, + "mode": "0644", + "sha256": "e6d12fc2541c7975d371a8893c52d0faf83879ffefa4944f962bfc7d87341db0" + }, + "docs/media/tandy-thermal-printer-tp-10-badge.svg": { + "bytes": 10565, + "mode": "0644", + "sha256": "85264812128eea7f682f6a3b0aeb95a1214963e1ad3a77907a64d7250571f36b" + }, + "docs/media/tandy-tp-10-printer.svg": { + "bytes": 2139804, + "mode": "0644", + "sha256": "958daf473ef9152e33764f916dc02db5ceb4a4a878fed7579a5c8fc15bd91dd2" + }, + "docs/media/tandy-tp-10-shell.png": { + "bytes": 1594658, + "mode": "0644", + "sha256": "b779235aaa7bb1597d01b58b2f2d512d764dec147a3fd14bb143ac036c863125" + }, + "docs/media/tandy-virtual-drive-system-badge.svg": { + "bytes": 11674, + "mode": "0644", + "sha256": "77438811da2b5e382aa8a425c86ca74bf3a1d987fa024928383020e42a959433" + }, + "docs/media/tandy-virtual-drive-system-controller.svg": { + "bytes": 33932, + "mode": "0644", + "sha256": "ac9ffdc105ba66bb4cd0a956b522fba4ac7ca2ba989b557f2eef1c9f16f53590" + }, + "docs/media/tandy-virtual-drive-system-ribbon-cable.svg": { + "bytes": 161601, + "mode": "0644", + "sha256": "293f40dcbcff879eaa947d5906f9b465d1e8c8571c29912f9cbaa047e786b49c" + }, + "docs/media/tandy-virtual-drive-system.svg": { + "bytes": 162848, + "mode": "0644", + "sha256": "60b7bc6e42d01a8f288e50d947d76d22df58493470ca162dac9b1d8405f3fad5" + }, + "docs/white-paper-evidence.json": { + "bytes": 18421, + "mode": "0644", + "sha256": "f0da3f3d4e67e756d0b51471b2917197d51ec39cb15cb6ff19268aab3ea19ade" + }, + "examples/assembly/Dispatch/layout.link": { + "bytes": 35, + "mode": "0644", + "sha256": "3e3ea5fc6404072bd2c5e868a5a67c0099166b32965f166dfd22497ea15bafdb" + }, + "examples/assembly/Dispatch/main.asm": { + "bytes": 1141, + "mode": "0644", + "sha256": "e366bff18701bf96cc3ca4562dd7c5e9055b62eabfe82f409dec257905ac00b3" + }, + "examples/assembly/Dispatch/receive.asm": { + "bytes": 403, + "mode": "0644", + "sha256": "c5911a26781f1911dc99a121f9b4790098f811f26ee150506bccfdc3ee5db904" + }, + "examples/assembly/Dispatch/vccplus-assembly.json": { + "bytes": 86, + "mode": "0644", + "sha256": "95527d82aee41eadd1f92f8b5c99f5026a07abb9f05c15bdaa22730bdfcb4d15" + }, + "examples/assembly/hardware-debugging/pixel-mask.asm": { + "bytes": 707, + "mode": "0644", + "sha256": "bbfc0960be075ded6a2116d9889a7aa9799992c6fe22f095ed05aedab0f77a68" + }, + "examples/assembly/manual/bankwalk.asm": { + "bytes": 1320, + "mode": "0644", + "sha256": "badadb37bc94cfd8b2a7a74b6359b9180863714a0d3640e3aa072c62cb3f4bd3" + }, + "examples/assembly/manual/byte.asm": { + "bytes": 353, + "mode": "0644", + "sha256": "6a925a371db9db47e81aa2e64030247a730ba76e4d90296fbe37cc9d0fe18ccc" + }, + "examples/assembly/manual/choice.asm": { + "bytes": 902, + "mode": "0644", + "sha256": "021fdac022f2f6246489f42f8cf0cd56127250dbc889ec0b2c03ec4c67ee1bea" + }, + "examples/assembly/manual/dispatch.asm": { + "bytes": 1691, + "mode": "0644", + "sha256": "af6735c1ced57cf391a834c70bc17c4fea1707ef3658d381ae732abedbbb41a5" + }, + "examples/assembly/manual/dispatch6309.asm": { + "bytes": 851, + "mode": "0644", + "sha256": "7fe4e4eedc0a71e4626b4dba6083aa6c356fbd9d083af19311a0c1bb4d2a6325" + }, + "examples/assembly/manual/letter.asm": { + "bytes": 591, + "mode": "0644", + "sha256": "7a3614fda84294408d93b4695599f9ea6e1a96c91b7ef34f514b8a27f0fd2923" + }, + "examples/assembly/manual/mode.asm": { + "bytes": 698, + "mode": "0644", + "sha256": "714d9f925529e03765fd50c0c0d0069abf154f988a18be537f962652e8907390" + }, + "examples/assembly/manual/return.asm": { + "bytes": 732, + "mode": "0644", + "sha256": "5ae7bd5c8a81540d06b7b9e5cafc1b96d312462f589965c7aeaf475d781874a4" + }, + "examples/assembly/manual/softirq.asm": { + "bytes": 1456, + "mode": "0644", + "sha256": "f778f154fcb22f919e8776c9eddc632df9b2409a9e86608f7380b570291643f8" + }, + "examples/assembly/planet.asm": { + "bytes": 2380, + "mode": "0644", + "sha256": "4c04d5a0e00490ad2f962278128f2db4e62b541f3b1c8d12ecb902fb1f5901f0" + }, + "examples/basic/back-at-the-coco/PORT.bas": { + "bytes": 125, + "mode": "0644", + "sha256": "30ce3386e645296c827539ab04c42a36d1a237a8c882445edf6ce111f6f4cefa" + }, + "examples/basic/back-at-the-coco/STRIPES.bas": { + "bytes": 173, + "mode": "0644", + "sha256": "fbcc0ddddc015044e40376af0a55c567b53c79420e8d28a4d9129a673d03b369" + }, + "examples/basic/hardware-debugging/BEACON.bas": { + "bytes": 433, + "mode": "0644", + "sha256": "4b8b38d656d17f5156eea902419b01f2b3add924baebda01d4b9d364ac7bd5bd" + }, + "examples/basic/meet-your-color-computer/BEACON.bas": { + "bytes": 58, + "mode": "0644", + "sha256": "f8970e0a724041d3e681876bd335d3590836ff1abe21a82c654574fe95ca3bf7" + }, + "examples/basic/meet-your-color-computer/QUIZ.bas": { + "bytes": 401, + "mode": "0644", + "sha256": "60fa94a0e944d07b0d9f083d112948d44ba87151e45da3c01e4e1e7957ba13b3" + }, + "examples/basic/meet-your-color-computer/SIGNAL.bas": { + "bytes": 76, + "mode": "0644", + "sha256": "c6b2dfa8ccddf89990554cb4606c1a761f68fbf3364b2fc1234f5f274a0586aa" + }, + "examples/basic/planet-explorer/ADDRESS.bas": { + "bytes": 124, + "mode": "0644", + "sha256": "c59fa986502cc52ee4a89395322b63223361ef0a61dc7264d1b07e72d1353bc2" + }, + "examples/basic/planet-explorer/CHART.bas": { + "bytes": 540, + "mode": "0644", + "sha256": "d411229f03fc0cdf4711639e36db385be4c9b78abb349edc3ea5cbd0b663a384" + }, + "examples/basic/planet-explorer/CONSOLE.bas": { + "bytes": 432, + "mode": "0644", + "sha256": "c458a4133305aa08d0809f64d467756fb8ae6ce7f91535389e2665c90b8df5c6" + }, + "examples/basic/planet-explorer/HELM.bas": { + "bytes": 235, + "mode": "0644", + "sha256": "a8a4c9701fa29d58ea910918fa59a434b00f59fd8486c4b0eb920542816e13d1" + }, + "examples/basic/planet-explorer/LEAK.bas": { + "bytes": 106, + "mode": "0644", + "sha256": "d3416ac9884453a24e60e4d0cb519cacd81693b5d778d442603c348ad577b339" + }, + "examples/basic/planet-explorer/LOCKERS.bas": { + "bytes": 208, + "mode": "0644", + "sha256": "df45eb32d9b77c2dcedd156efdbb8fbbd1020269b3894f9cbb23d0b7328c1b6f" + }, + "examples/basic/planet-explorer/LOGBOOK.bas": { + "bytes": 201, + "mode": "0644", + "sha256": "e814f026f9f06b9ce439a16665adea1434c768d5ee7fde19afeec48c5dab1e6d" + }, + "examples/basic/planet-explorer/ORDER.bas": { + "bytes": 173, + "mode": "0644", + "sha256": "cc7a6c5b8f9f95780a43b44c977d8d542995138dda9d7ed1f868b0c421a30d08" + }, + "examples/basic/planet-explorer/PAGES.bas": { + "bytes": 329, + "mode": "0644", + "sha256": "abcc17a384213147b8d686d5eb82f0bd583d3a5108ede99a8d2206f80d062adb" + }, + "examples/basic/planet-explorer/RADAR.bas": { + "bytes": 239, + "mode": "0644", + "sha256": "70e075d1d55e0b729a094dd6f309c302b7bf80b5934efcfc0ee263c8632b7c0d" + }, + "examples/basic/planet-explorer/RATIONS.bas": { + "bytes": 97, + "mode": "0644", + "sha256": "1203274dca804bca6c30627aa43c60f3b2a09465f88a133e7b168346926460ee" + }, + "examples/basic/planet-explorer/VOYAGE.bas": { + "bytes": 813, + "mode": "0644", + "sha256": "fe41e8da34c21aa1c4ca68023fb282470d75f45596e623b1fa70157414bd119d" + }, + "examples/basic/planet.bas": { + "bytes": 333, + "mode": "0644", + "sha256": "edb7048938cac8762273d2634455000a5209ac0d5fd7590b65391d06a29da80c" + }, + "examples/basic/software-storage-and-peripherals/CARGO.bas": { + "bytes": 26, + "mode": "0644", + "sha256": "24cd5848825989fea43442f1c148b9beb9d8e45920e93d01fd369805fbf65a4a" + }, + "examples/basic/software-storage-and-peripherals/VOICE.bas": { + "bytes": 326, + "mode": "0644", + "sha256": "f0ef3c229c32262c401a4b755e10837717d24b29695cbe5d41603eb7ddab18fb" + }, + "examples/basic/users-handbook/KEYS.bas": { + "bytes": 61, + "mode": "0644", + "sha256": "ae470121f7bd8b02dbee7a57bec3af37dae380d13ce5d50b0efe8de94c80ffed" + }, + "examples/basic/users-handbook/LANDPAD.bas": { + "bytes": 533, + "mode": "0644", + "sha256": "11f79be5ff7179912b74d3635dcbdc90c23a7a37014d02f6ffe3cfdcda389e0c" + }, + "examples/cmoc/HelloDisk/.gitignore": { + "bytes": 73, + "mode": "0644", + "sha256": "de68e5eb55d18f4953112c132bc64f8731c1f17da6ddf3b213e65205236d2e8b" + }, + "examples/cmoc/HelloDisk/Makefile": { + "bytes": 5122, + "mode": "0644", + "sha256": "88a0a205e30e559d713efb3928103ca374e7cd20113f9834f63a2838ac2f03c1" + }, + "examples/cmoc/HelloDisk/README.md": { + "bytes": 3008, + "mode": "0644", + "sha256": "187037dd112e4a2ddd08d4843b5be135cc8641c8ec5ffd977e25d566a9191bb5" + }, + "examples/cmoc/HelloDisk/assets/words.txt": { + "bytes": 26, + "mode": "0644", + "sha256": "3eea2ee5b042e5d173143a829c4b5d55a1e8079ff5e3b193c8f57a52a47f6e27" + }, + "examples/cmoc/HelloDisk/include/hello.h": { + "bytes": 221, + "mode": "0644", + "sha256": "20bffba066a4b7a6fe9b0ee433d763eb8edb1fc92f9e6add4db10a198ac3b9fc" + }, + "examples/cmoc/HelloDisk/main.c": { + "bytes": 368, + "mode": "0644", + "sha256": "9cd12958ff94a9d3cdc6594a2332738227e3d7372eeca99f44d53772774cf68f" + }, + "examples/cmoc/HelloDisk/src/disk.c": { + "bytes": 683, + "mode": "0644", + "sha256": "12ac7d7ddef0c43d30e6930f7e5b918ac50c8a2a85d5440bb707333cef004eca" + }, + "examples/cmoc/HelloDisk/src/display.c": { + "bytes": 206, + "mode": "0644", + "sha256": "3d23b9b787ae13949c18b74625b02ef441ca773139d0b283c68cf384193a1043" + }, + "examples/cmoc/HelloDisk/tools/build-data.pl": { + "bytes": 956, + "mode": "0644", + "sha256": "af152f04798cc5b54b69e7bba06fb9dacdc9da7743504edeed2df21b326c2cd1" + }, + "examples/cmoc/HelloDisk/vccplus-project.json": { + "bytes": 1456, + "mode": "0644", + "sha256": "52f0abc9bd08451c9c14f2fcf7b1ccc3790e5bc3f9dbb1fec52b66e05612874f" + }, + "examples/cmoc/MissionRecorder/Makefile": { + "bytes": 1648, + "mode": "0644", + "sha256": "ccbf0133b20b31e48da0557ed7b66d68701d315a3d84dc67cd4c3aba72b5970f" + }, + "examples/cmoc/MissionRecorder/flight.c": { + "bytes": 6669, + "mode": "0644", + "sha256": "0b7abfad091805f05c45f06d601895611be498bb9a0e441524aff1b12520f93d" + }, + "examples/cmoc/MissionRecorder/main.c": { + "bytes": 576, + "mode": "0644", + "sha256": "dd1a0c97e3266540f4f0105a74277f0ea824ab670323442f959e4ce75593db19" + }, + "examples/cmoc/MissionRecorder/mission.h": { + "bytes": 294, + "mode": "0644", + "sha256": "0c7dd14427df4a2ef3e1386175a20ec988182daa1c3aa126dfe467788ab4d314" + }, + "examples/cmoc/MissionRecorder/report.c": { + "bytes": 2516, + "mode": "0644", + "sha256": "bbea9152e4c3c869506409f3d6c3210157b707844ed1d0d25a80645fff41b8ef" + }, + "examples/cmoc/MissionRecorder/vccplus-project.json": { + "bytes": 1118, + "mode": "0644", + "sha256": "870c3e5c4c5ea7544d19cfb5bfe2a6af4843191810932c0fc71809eace964523" + }, + "examples/cmoc/PlanetExpedition/Makefile": { + "bytes": 1336, + "mode": "0644", + "sha256": "b20e1bddac6bb23f25b821be854473a258b39ca5d95889890439fa69e937217f" + }, + "examples/cmoc/PlanetExpedition/assets/earth.txt": { + "bytes": 47, + "mode": "0644", + "sha256": "97096946d041ab55b08f6d5efde3ddc8cecec53b70d4ecf996eb2a23e6eb8b00" + }, + "examples/cmoc/PlanetExpedition/assets/mars.txt": { + "bytes": 44, + "mode": "0644", + "sha256": "41f75bd5faab64c0a9e504753d25b0fe95677752ebc6d466db97493b14408414" + }, + "examples/cmoc/PlanetExpedition/expedition.c": { + "bytes": 2748, + "mode": "0644", + "sha256": "fcb24b2e5f1f5e620467cc8dc3d1ee809d01ecd1ae1a8d59345386f6b0a57b36" + }, + "examples/cmoc/PlanetExpedition/vccplus-project.json": { + "bytes": 693, + "mode": "0644", + "sha256": "09112947675674b38650be36ff7ff51701e2a1cf9b9a28f5e21129526457dde0" + }, + "examples/cmoc/PlanetSurvey/.gitignore": { + "bytes": 77, + "mode": "0644", + "sha256": "02821050ff9ce2aa7d240153a2cdfab15dc25e7f0290f3edb005f2718ac41a25" + }, + "examples/cmoc/PlanetSurvey/Makefile": { + "bytes": 1575, + "mode": "0644", + "sha256": "b07f5d20dd831b7083b3105efd0bcb7e47ada2a524a30fd2b58e5cff043935b1" + }, + "examples/cmoc/PlanetSurvey/assets/planets.txt": { + "bytes": 270, + "mode": "0644", + "sha256": "409d6d79dcde5da8676bb9a491760829c4a830af95055af4ff123614e53a8d6e" + }, + "examples/cmoc/PlanetSurvey/main.c": { + "bytes": 2691, + "mode": "0644", + "sha256": "c7278b848738d77cf998879e9b452f08b8d0bbcbcb3195a82a15962e98de0a7b" + }, + "examples/cmoc/PlanetSurvey/vccplus-project.json": { + "bytes": 1246, + "mode": "0644", + "sha256": "1111765f965d4d2ad7303c7a0d87117d37887a4f53a7059ca8c249542706f726" + }, + "examples/cmoc/TalkingPlanetLander/.gitignore": { + "bytes": 66, + "mode": "0644", + "sha256": "a6ecbe721944467a5b36b5418446a29a4ceb7d50ea3f39e994eee1ba14aa5af6" + }, + "examples/cmoc/TalkingPlanetLander/Makefile": { + "bytes": 1308, + "mode": "0644", + "sha256": "ae7e81a577c374554e5d80beb7a8a847bf69207c7a945cb9f6dc1602c2cda80c" + }, + "examples/cmoc/TalkingPlanetLander/README.md": { + "bytes": 1301, + "mode": "0644", + "sha256": "45ccaf9dd37d769d54e30dbe3ea50088dcaf8c3d4291eb7d315ce98bf8058cd3" + }, + "examples/cmoc/TalkingPlanetLander/main.c": { + "bytes": 2498, + "mode": "0644", + "sha256": "884e9b92da094affa99038481ff1f8a82f7c0708a2fc83c8cc607b097d474437" + }, + "examples/cmoc/TalkingPlanetLander/vccplus-project.json": { + "bytes": 974, + "mode": "0644", + "sha256": "374553c28236043434fd4d342350f01af6a35c4b7ddc073580673fa27bd328bb" + }, + "examples/cmoc/manual/announcer.c": { + "bytes": 2648, + "mode": "0644", + "sha256": "93fe5d90fb392e18c3e95756fa079c2579a2da88c77fec52b78f57d70369aabe" + }, + "examples/cmoc/manual/atlas.c": { + "bytes": 4538, + "mode": "0644", + "sha256": "863167b851cfa752d9b90f8dadba80206025d25417e94c1fc03be67f3f251e79" + }, + "examples/cmoc/manual/atlasbackup.c": { + "bytes": 4279, + "mode": "0644", + "sha256": "9ce1bb2dc37d8bae0ad0b8e29f7273db47e25cc88979fbb882b9f7420f939ee0" + }, + "examples/cmoc/manual/beacon.c": { + "bytes": 1302, + "mode": "0644", + "sha256": "7f59c9a715ce1327cba0504baa72e8eaeb1bfd1b6f3fe774b8b308449b89b046" + }, + "examples/cmoc/manual/cargo.c": { + "bytes": 884, + "mode": "0644", + "sha256": "371d4e504f5b472fcf48edfe8d6a9dfe36a9675d01693ac16d01e8c0ddc4ccd4" + }, + "examples/cmoc/manual/crew.c": { + "bytes": 1162, + "mode": "0644", + "sha256": "885e2af919dc53d5f4dfafa1232025a850cb9c49ee3bbc611a9a775b0c3de050" + }, + "examples/cmoc/manual/deal.c": { + "bytes": 334, + "mode": "0644", + "sha256": "ad64c21aecd57c6096e9418de62af7dcd9ba4a9e3c32e95b101d414f112a967f" + }, + "examples/cmoc/manual/descent.c": { + "bytes": 1345, + "mode": "0644", + "sha256": "a839e3add755efbebfeb3a046f686c8a5c4ed619c52569a87208e82c7ea412c2" + }, + "examples/cmoc/manual/editlog.c": { + "bytes": 1125, + "mode": "0644", + "sha256": "f066d45f6297240e2446dab2401e531d0d7b74effc40c94a8defe5dde74b4c50" + }, + "examples/cmoc/manual/fieldlog.c": { + "bytes": 1564, + "mode": "0644", + "sha256": "12bdafe3f77909facc7c107299f6c0a9b845a0043cf414eb5b211210bd619412" + }, + "examples/cmoc/manual/flightread.bas": { + "bytes": 129, + "mode": "0644", + "sha256": "cf7c9099aba0c4174ab0a801713434a0e3183bc71e91bce9794c75afc0f0e223" + }, + "examples/cmoc/manual/flightrecorder.c": { + "bytes": 1583, + "mode": "0644", + "sha256": "8e92d1cd4b8fb3439fc4da51e448b4e931920ed4766b560798b383bc789ac72f" + }, + "examples/cmoc/manual/flightreport.c": { + "bytes": 1100, + "mode": "0644", + "sha256": "2105e8f3a9c10d0cc6cd76658c78963cf5d19c6ac98c88e1ac30adc55cfac059" + }, + "examples/cmoc/manual/flightwrite.bas": { + "bytes": 124, + "mode": "0644", + "sha256": "6cc91a06e7b27e230f75250ec155ee6b3485e79eedba97d15a5a4355f044ada1" + }, + "examples/cmoc/manual/flyby.c": { + "bytes": 2593, + "mode": "0644", + "sha256": "32ae1610426665b80c7ceafde6e32621362e763392e7fc96f52cd222f759418b" + }, + "examples/cmoc/manual/glyph.c": { + "bytes": 778, + "mode": "0644", + "sha256": "5be650fb340044be8cfdda3b6d1e121417357ad541c34115673dad021d0041bc" + }, + "examples/cmoc/manual/lander.c": { + "bytes": 4146, + "mode": "0644", + "sha256": "34a67ddf0acd8e6c10c338d080e06afb12a219d3979015c34df9a81547356a61" + }, + "examples/cmoc/manual/message.c": { + "bytes": 725, + "mode": "0644", + "sha256": "03a120a718501cef961a28bbeb1c210073f7c490dd771a34731c36014a189a11" + }, + "examples/cmoc/manual/pool.c": { + "bytes": 725, + "mode": "0644", + "sha256": "ab0523393d571aeeedf70ce79c8404c78fe07e92fe7e037fc72443fb78f07cb9" + }, + "examples/cmoc/manual/probe.c": { + "bytes": 4383, + "mode": "0644", + "sha256": "11e59716854af3d25649bb7088b2c08dd1e37a258335596eac6c62f2fb53b22d" + }, + "examples/cmoc/manual/returntrip.c": { + "bytes": 2759, + "mode": "0644", + "sha256": "7adb266b8eb648d841eb7592fd55ab356ea9c2eeadd9953e26bd928a80ff87a4" + }, + "examples/cmoc/manual/ridge.c": { + "bytes": 4650, + "mode": "0644", + "sha256": "fe072e355c4807ec870ba2db291844ad99923f6e14fc2da9281a8a804b1e29bd" + }, + "examples/cmoc/manual/route.c": { + "bytes": 629, + "mode": "0644", + "sha256": "3a963e03f7c90cb82bff5883091b61739eed771c1508ce0db64f11ca49bae56e" + }, + "examples/cmoc/manual/stick.c": { + "bytes": 719, + "mode": "0644", + "sha256": "afd775b0485f89f6ccf88f79e586efe4930e0f1dd8a474ff3fc6d4442e2bbf2e" + }, + "examples/cmoc/manual/tone.c": { + "bytes": 342, + "mode": "0644", + "sha256": "d2ecae22082288b405b11d84636170a5de68e03d2796092615e0438ec92e0b36" + }, + "examples/cmoc/planet.c": { + "bytes": 730, + "mode": "0644", + "sha256": "67aefce1a0d87a41d3f5340fd3f75ebd940634e2bd0bc898b593d963f51edd23" + }, + "license.txt": { + "bytes": 35147, + "mode": "0644", + "sha256": "8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903" + }, + "platforms/macos/App/AboutView.swift": { + "bytes": 23366, + "mode": "0644", + "sha256": "f511eda02c28214698a7f9a29607aaaadda6f181664afbc4840530c93693d9b7" + }, + "platforms/macos/App/ArchiveInlinePreview.swift": { + "bytes": 11867, + "mode": "0644", + "sha256": "40aa6fb9fef1dc8d1756547238709af3e937e8091eb083837e6996e69a6b0862" + }, + "platforms/macos/App/ArchiveLibraryCatalog.swift": { + "bytes": 12730, + "mode": "0644", + "sha256": "576b5d6c45497fc1db3a754493d9f8cc8d0badcf4f555dd14b7f6c13febfe103" + }, + "platforms/macos/App/ArchiveLibraryReader.swift": { + "bytes": 34330, + "mode": "0644", + "sha256": "d2f32012a5afb7ae24ed49f6fbae9ef689ca8f633c404720a9fd950afd9b4f29" + }, + "platforms/macos/App/ArchiveLibraryView.swift": { + "bytes": 17166, + "mode": "0644", + "sha256": "081b7bc6cd56ab3e37762ea96f40d062d843aa0dc93308834b36aa087fb698b8" + }, + "platforms/macos/App/AssemblyBuildService.swift": { + "bytes": 18307, + "mode": "0644", + "sha256": "ee57c67b48a54599c07641a9970ef76ea08ef612c32f46f2144530b30891f7ca" + }, + "platforms/macos/App/AssemblyDevelopmentFiles.swift": { + "bytes": 6396, + "mode": "0644", + "sha256": "8a729e902af96b5df690529c5d1985d3c394fe134c52e28781018c3002291f71" + }, + "platforms/macos/App/AssemblyDevelopmentModel.swift": { + "bytes": 37076, + "mode": "0644", + "sha256": "a265da5c6c207260b0c5ff377742c81deae4475428d4c62f12ee4fccd45ec95f" + }, + "platforms/macos/App/AssemblyDevelopmentView.swift": { + "bytes": 14704, + "mode": "0644", + "sha256": "762cf1a59e13407e479add00487feb915c8c2d2517bc40a1a68807dabb2c9990" + }, + "platforms/macos/App/AssemblyEditor.swift": { + "bytes": 13440, + "mode": "0644", + "sha256": "19169f27c3c6a7ce9b2cdae8146f1c21a1b02d36c61aed6ab4cbe146ea820036" + }, + "platforms/macos/App/AssemblyProject.swift": { + "bytes": 7531, + "mode": "0644", + "sha256": "472e52cb2a79e720484b2e1d751cda0cda9ee72b74cda2e16b04beacf0218556" + }, + "platforms/macos/App/AssemblyReference.swift": { + "bytes": 4790, + "mode": "0644", + "sha256": "40477ebea1373139ea0f5268d95d79eb22222949839bc3a6316bbf3c7e0a6525" + }, + "platforms/macos/App/AssemblyReferenceContext.swift": { + "bytes": 7761, + "mode": "0644", + "sha256": "4c8cc08086ff49d5b21dbd96f2186f079f3d91659d40f5cdb9006cd383875caf" + }, + "platforms/macos/App/AssemblyReferenceInstructions.swift": { + "bytes": 17963, + "mode": "0644", + "sha256": "678c88cd5fcac102a63092065db9435f53851e96a8049b69055e1c6c93748660" + }, + "platforms/macos/App/AssemblyReferenceTopics.swift": { + "bytes": 23221, + "mode": "0644", + "sha256": "ef992593f5649ee8d7a3cf1d8a159d511dfbf38667639e2c5c727e3168244e9c" + }, + "platforms/macos/App/AssemblyReferenceView.swift": { + "bytes": 8964, + "mode": "0644", + "sha256": "bb231c70175bcc3acb0b1efe55f84c8b0daadf5bae51d9f423c6725688bdb34c" + }, + "platforms/macos/App/BASICDevelopmentModel.swift": { + "bytes": 31524, + "mode": "0644", + "sha256": "37303762a3737fb65f19da732068640e67023cac587be6b3b4569b60f8aed3d3" + }, + "platforms/macos/App/BASICDevelopmentView.swift": { + "bytes": 51022, + "mode": "0644", + "sha256": "62b21df283c2307847ff8bb2c136b648dd61b582fee20e8e6d2b1815295fe909" + }, + "platforms/macos/App/BASICLanguage.swift": { + "bytes": 28593, + "mode": "0644", + "sha256": "3fb52c3148165146b3fdae8436aee7bc2f01b9c5c2b2a2049bfc7145372620fd" + }, + "platforms/macos/App/BASICReference.swift": { + "bytes": 5178, + "mode": "0644", + "sha256": "cdab324a944afb2070ea1ee9470295ef75e7e45499aabdc3d7729be7e028e981" + }, + "platforms/macos/App/BASICReferenceContext.swift": { + "bytes": 5507, + "mode": "0644", + "sha256": "98b6d2293d11e1c6e9f2e142d6f6b7d4bcbb47e04f7f3fc0445ad37c45d24655" + }, + "platforms/macos/App/BASICReferenceIntegration.swift": { + "bytes": 1328, + "mode": "0644", + "sha256": "6407da2c7f5340552202a67c469332fa769907e5e711ae76f27df3c07e637d19" + }, + "platforms/macos/App/BASICReferenceView.swift": { + "bytes": 14297, + "mode": "0644", + "sha256": "f8f90a5ca54ec3b2a193115fbc0ca6e7f9e7b5234e3d7d7c10863223835e172d" + }, + "platforms/macos/App/BinaryFile.swift": { + "bytes": 1047, + "mode": "0644", + "sha256": "5ef71300a52836d36807ec3c49a9e577f2ba2962530c9bec71cfe900b49c5c02" + }, + "platforms/macos/App/CMOCBankedDebug.swift": { + "bytes": 16327, + "mode": "0644", + "sha256": "cc8559bee949cc4ad2aa797cdd8b4672b13c8e48d3b647b3a113ca402de3153e" + }, + "platforms/macos/App/CMOCBuildHistory.swift": { + "bytes": 12696, + "mode": "0644", + "sha256": "1cff64a2401713b838a02bcf759951a8875f44572c915f8d7775349c89476d16" + }, + "platforms/macos/App/CMOCBuildService.swift": { + "bytes": 124358, + "mode": "0644", + "sha256": "1cf1d98b9023481a73ff1ffbdde991f6811029a9c01374307383634845130898" + }, + "platforms/macos/App/CMOCCallStack.swift": { + "bytes": 7305, + "mode": "0644", + "sha256": "c8dc626e1ea881296db6832fa8179a3aef1b87b2f23ff4438e9cd0cabd39e33f" + }, + "platforms/macos/App/CMOCCompletion.swift": { + "bytes": 13349, + "mode": "0644", + "sha256": "06fb62d4d850b37a572af03e518fc71029037b0c69e1178f72903d5f4c5eba1a" + }, + "platforms/macos/App/CMOCCompletionEditor.swift": { + "bytes": 5018, + "mode": "0644", + "sha256": "962d3d6168c3e1cddb9eac1f8127dcb6734aa1cb95c17ff97c57ea80eda36059" + }, + "platforms/macos/App/CMOCDevelopmentModel.swift": { + "bytes": 100828, + "mode": "0644", + "sha256": "a97ce09ac5518fa49290fe835b5f0b2339ba394ed8e8f876a84af38c5cefaf9d" + }, + "platforms/macos/App/CMOCDevelopmentView.swift": { + "bytes": 101176, + "mode": "0644", + "sha256": "b5c6c4c2dcaec9c27be071ec7421ca45e7ce0c5aba29d4a6ba2941def9122857" + }, + "platforms/macos/App/CMOCEditing.swift": { + "bytes": 10345, + "mode": "0644", + "sha256": "f5a414b6afeb6bab027d8938c3f1774368b428d9d54f7b40fb992d138b2e6021" + }, + "platforms/macos/App/CMOCIndexInputs.swift": { + "bytes": 11963, + "mode": "0644", + "sha256": "352693382b6deee428a9fff517863b9c7274c0b1c43263e8df5c4dec8beca92f" + }, + "platforms/macos/App/CMOCOwnedCallContext.swift": { + "bytes": 11636, + "mode": "0644", + "sha256": "05ce15caa98462f820c091c4c192ddc1f4d6131f4f7271e360b8d23abd1f494a" + }, + "platforms/macos/App/CMOCProjectIndex.swift": { + "bytes": 40453, + "mode": "0644", + "sha256": "00bae07672616be9df02c2612727aab60cb386e3985780bab8c3b3240fe1699b" + }, + "platforms/macos/App/CMOCProjectInputs.swift": { + "bytes": 16205, + "mode": "0644", + "sha256": "8c38bb3feb3fd227dfee8333a86784881ad0fe88c5dbb5ff7abb9cc15250291d" + }, + "platforms/macos/App/CMOCSourceMap.swift": { + "bytes": 67364, + "mode": "0644", + "sha256": "dd193224ed3ad463d842be2b500de10f19b9327d6e5acbb46fea95221a399396" + }, + "platforms/macos/App/CMOCVariableDebug.swift": { + "bytes": 21531, + "mode": "0644", + "sha256": "382b099aa2da8c719288be7f81c727fc9c56141c7251260ed235254d044d512b" + }, + "platforms/macos/App/CMOCWatchEvaluator.swift": { + "bytes": 31434, + "mode": "0644", + "sha256": "b00cc51e7ceb4f3ee4864c7497c7b354e918eca8ce0803ea35fac38e2e9d7072" + }, + "platforms/macos/App/CMOCWorkspaceRecovery.swift": { + "bytes": 10672, + "mode": "0644", + "sha256": "1ac5c0d24305d7b1aa2f3bc7afb1d1b9666ebc21a836fe4f5347c167def0fede" + }, + "platforms/macos/App/CartridgeControlsView.swift": { + "bytes": 19088, + "mode": "0644", + "sha256": "a35c21b5fa11a7450b2a35220b8d61001660f0aff27713f7139c6b76443ae46b" + }, + "platforms/macos/App/CassetteControlsView.swift": { + "bytes": 9399, + "mode": "0644", + "sha256": "27aeb59f9481ad9ace6280e47b3255ebfa0c1964dc8b0bacec56719fa681ddac" + }, + "platforms/macos/App/CocoKeyboard.swift": { + "bytes": 7938, + "mode": "0644", + "sha256": "d9cc7a5eec1ee2d6136a488e45d4a20d25f64d71882db4fcd22551b207ed61d0" + }, + "platforms/macos/App/CompanionLibraryAuthority.swift": { + "bytes": 10400, + "mode": "0644", + "sha256": "cad38dff8cb39a1e9f405937908e4f7037d7e7deaa6f993c9e1341ffcf1ba0c6" + }, + "platforms/macos/App/CompanionLibraryTypes.swift": { + "bytes": 3555, + "mode": "0644", + "sha256": "41ee0805ef73656c1d645feb7f3ac879cbcb0b7eac23d7dcfdd30ca5217b73d8" + }, + "platforms/macos/App/ConfigurationProfile.swift": { + "bytes": 15465, + "mode": "0644", + "sha256": "03e1305db9cc862115bf3e41533c2794bc8880aab41a2f249128a8ec0abe0922" + }, + "platforms/macos/App/ControllerDevices.swift": { + "bytes": 6995, + "mode": "0644", + "sha256": "c1b8454fef5f33f31e2378cde3b60d7177b3849fa2801fbe6506bb7832d2f995" + }, + "platforms/macos/App/DebugSourceListing.swift": { + "bytes": 6728, + "mode": "0644", + "sha256": "51de1cbb8eef78e427f92e70175c06a4fd5ae45b8e152bc2f7ef129c30adfbeb" + }, + "platforms/macos/App/DebugSourceView.swift": { + "bytes": 8595, + "mode": "0644", + "sha256": "e2777f307ab60bc451b386f1b1b263f00d69f04917818aa333302043d8bfc067" + }, + "platforms/macos/App/DebuggerModel.swift": { + "bytes": 14715, + "mode": "0644", + "sha256": "5fc332e038706ad95b0896393292337a7730a31266e6db4373a4e18cb1136546" + }, + "platforms/macos/App/DebuggerView.swift": { + "bytes": 31936, + "mode": "0644", + "sha256": "1957f6858bfcc01f8c54ee305e0355a2ba0cce196a28b4aaf0288ab4052dfb6d" + }, + "platforms/macos/App/DevelopmentStarterSource.swift": { + "bytes": 566, + "mode": "0644", + "sha256": "8c272bf72c60835e9bfadc04c7d5da63d73afbaf8faa8c1c2186d42f927010ea" + }, + "platforms/macos/App/DiskAssignments.swift": { + "bytes": 6052, + "mode": "0644", + "sha256": "356234ff0b44863a9c07835107a3d810d895d09209e9d8a3a82a21aff2a1dc10" + }, + "platforms/macos/App/DiskControlsView.swift": { + "bytes": 15818, + "mode": "0644", + "sha256": "81d234df53ecb030e0d3548c90597c6c1f70c0c242f4a5081c70740ac52a76b9" + }, + "platforms/macos/App/DiskEditorFileTable.swift": { + "bytes": 22121, + "mode": "0644", + "sha256": "cd0a90377d5b84dc00ae8976f1064e8d9aadc541864415d3c2e7b1e456c81b45" + }, + "platforms/macos/App/DiskEditorSession.swift": { + "bytes": 9288, + "mode": "0644", + "sha256": "7a970bf0ab66479b5eb54691b779a08dbbf54ecc67272f74301d49eb8f7f1403" + }, + "platforms/macos/App/DiskFiles.swift": { + "bytes": 7558, + "mode": "0644", + "sha256": "0171176d463c8fff2c77d88889e8cb4f5d4561e038cb086020fa73970e53f7f1" + }, + "platforms/macos/App/DiskImageEditorModel.swift": { + "bytes": 34667, + "mode": "0644", + "sha256": "cb19a735cfdaa8ded88d9026d3da711531c65a8769fbc2338afb1450be84fe22" + }, + "platforms/macos/App/DiskImageEditorView.swift": { + "bytes": 22239, + "mode": "0644", + "sha256": "312f15ad256aaed1d368a9a890a3fbcb37401d9e05eb9ed1a5a7347a1d8d0557" + }, + "platforms/macos/App/DisplayShader.txt": { + "bytes": 1421, + "mode": "0644", + "sha256": "c4eb112a543102ef4feb41c79211f90579aa724772fc04e808f43aafcb82eb31" + }, + "platforms/macos/App/EmulatorDisplay.swift": { + "bytes": 14850, + "mode": "0644", + "sha256": "1d5a9926ec31d3b3c51d3c43c6f364d170786554cf5104542d7f2113cae15eb2" + }, + "platforms/macos/App/GraphicsPreviewModel.swift": { + "bytes": 6919, + "mode": "0644", + "sha256": "eff7f452ab3718c58cc4932dd2e969c2038fbf183ad3ca1038603cc2c44cc259" + }, + "platforms/macos/App/GraphicsPreviewView.swift": { + "bytes": 9939, + "mode": "0644", + "sha256": "fd7924c4e38b7d7ccc3d21e0a72ce03d962c3d6b93aa78cd8645cfa1dd6765df" + }, + "platforms/macos/App/HardDiskControlsView.swift": { + "bytes": 15595, + "mode": "0644", + "sha256": "4f8c9d44e583b5774b11c6eefa2adae9d17beb2d7ea2d6a1c7a20a4856a25c80" + }, + "platforms/macos/App/HardDiskFiles.swift": { + "bytes": 6208, + "mode": "0644", + "sha256": "4726aec5467e788799f623ca3d0e195383fe7a05788160a65bf51d6ebd50eda5" + }, + "platforms/macos/App/HardwarePresentation.swift": { + "bytes": 14372, + "mode": "0644", + "sha256": "1181072eeb719fb8f99ea89da655ea38cf3351198912037783595e79337c8124" + }, + "platforms/macos/App/Info.plist": { + "bytes": 1958, + "mode": "0644", + "sha256": "adf9b2a17d07c6d9b0b09bf7babeb3a276fe671ad3655913889cc6360c0c19d4" + }, + "platforms/macos/App/InputControlsView.swift": { + "bytes": 9931, + "mode": "0644", + "sha256": "c1d65d9b6e9250b9d924f0248640ded133c59452c8fbbace322d2db503c37508" + }, + "platforms/macos/App/InputHub.swift": { + "bytes": 10706, + "mode": "0644", + "sha256": "e6dd053effa720b62778022b0bf80f0b3ce2bac76781889543c326229439476e" + }, + "platforms/macos/App/InputSettings.swift": { + "bytes": 4679, + "mode": "0644", + "sha256": "820875bac5efb7e716a73937ad2f1d8ce6d9ae57fbeac13011fafac6620ad50d" + }, + "platforms/macos/App/InterfaceValidation.swift": { + "bytes": 26452, + "mode": "0644", + "sha256": "44a386dda7db24d78af71236d05b3bd8585346c4219a718e1fb26881ed11bf60" + }, + "platforms/macos/App/MCPAccess.swift": { + "bytes": 37089, + "mode": "0644", + "sha256": "66a872493433962edf4e6472fcf4f0d966320c14c1ee570cb386c50203fca238" + }, + "platforms/macos/App/MCPArchiveAccess.swift": { + "bytes": 8255, + "mode": "0644", + "sha256": "8fd2d046f209445459658abbaff21adf7a06f339d49997474983a956553e6ecb" + }, + "platforms/macos/App/MCPAssembly.swift": { + "bytes": 46875, + "mode": "0644", + "sha256": "35ebc7019127085a3d09a33008fa7ee207b490861662a00d5632230436c8f4f8" + }, + "platforms/macos/App/MCPBASICRun.swift": { + "bytes": 18714, + "mode": "0644", + "sha256": "b0379b3be3b2794bdbde5b33e70b33e422868e02b370925447b0b0976d95f154" + }, + "platforms/macos/App/MCPCMOC.swift": { + "bytes": 141217, + "mode": "0644", + "sha256": "c89b3f354580fd0752c2231c7298ca7261d0f7729de141d34463be8299f86c83" + }, + "platforms/macos/App/MCPCMOCGuest.swift": { + "bytes": 11824, + "mode": "0644", + "sha256": "b3c02fad583d93e8cdea52effb3a8a845c9ead3afb05d6e8b7a10bcfacd0681b" + }, + "platforms/macos/App/MCPCMOCProject.swift": { + "bytes": 12854, + "mode": "0644", + "sha256": "6708525d8f7ed230499709be7678c3ddd807b0be6b277ee839ec99989bd0e7af" + }, + "platforms/macos/App/MCPChatGPTSetup.swift": { + "bytes": 16057, + "mode": "0644", + "sha256": "bb3c0d67d3a7ac1e3c10c98433f82461827039da1f6605033332de563bf046b2" + }, + "platforms/macos/App/MCPCompiledRunIO.swift": { + "bytes": 3077, + "mode": "0644", + "sha256": "999e6589635a192a49de12ee56aea065d4e8a93edb1771d3e5ac0c43b70440d7" + }, + "platforms/macos/App/MCPDebuggerInspection.swift": { + "bytes": 4251, + "mode": "0644", + "sha256": "36611cefca2f101cabb451cca46d955e6247db358d60a862def92cbed22d344d" + }, + "platforms/macos/App/MCPHelpIndex.swift": { + "bytes": 4269, + "mode": "0644", + "sha256": "9a6778a5158380589853c875d8348f4c363b67ecd2eef1edefb1aa5cda28b163" + }, + "platforms/macos/App/MCPMachineStatus.swift": { + "bytes": 4530, + "mode": "0644", + "sha256": "5af349cb795b7a852d3cea3ca6a251d21408d2c452f8b243f9ce83b5f77b1e82" + }, + "platforms/macos/App/MCPPlaytest.swift": { + "bytes": 63916, + "mode": "0644", + "sha256": "d747568bca7cb46bc9ae24eac530ef6ef1b7b98fb0c6d5104798b8d6da2356ef" + }, + "platforms/macos/App/MCPTransport.swift": { + "bytes": 6503, + "mode": "0644", + "sha256": "10e93f413d0e1d6401fb2a25e59a83c1f3d956818d86603117b5184202837424" + }, + "platforms/macos/App/MachineInterface.swift": { + "bytes": 27725, + "mode": "0644", + "sha256": "6634d933fb3038f13c028f0607f7ea1758b32b7d240f044e70f81060948bff62" + }, + "platforms/macos/App/MachineMenuState.swift": { + "bytes": 3227, + "mode": "0644", + "sha256": "8ea7ca3fa1ba23a23cac4f35636f184263af0031a87352ca9cd398987a657ca2" + }, + "platforms/macos/App/MachineModel.swift": { + "bytes": 175829, + "mode": "0644", + "sha256": "7c2f69173168e8db8dc68ecf7f3c0c198af25c83cd455eb566bc2b605e291ff2" + }, + "platforms/macos/App/MachineSettings.swift": { + "bytes": 1020, + "mode": "0644", + "sha256": "2376e54332daaa2c55741b7ca2874b2a32497eb497817d6d46f5e7b3664cbd93" + }, + "platforms/macos/App/MachineSettingsView.swift": { + "bytes": 8554, + "mode": "0644", + "sha256": "4a51686c57196d8646ceb3c75f7246e8db0c03b77adb1c538c8f82508884eaaf" + }, + "platforms/macos/App/ManualLibraryView.swift": { + "bytes": 12943, + "mode": "0644", + "sha256": "dc68b1a59f6029c4c4144f4ff25f0370e7b6effc15c4a7503cf9eeb2f81fb894" + }, + "platforms/macos/App/ManualPageFind.swift": { + "bytes": 7664, + "mode": "0644", + "sha256": "a647370defd2c28a8630459999672672a8205ade03039abfeffb4c7097ee08b9" + }, + "platforms/macos/App/MediaOpenControls.swift": { + "bytes": 2203, + "mode": "0644", + "sha256": "5ea0c600b5a69b95df9154b802d265621cd0434879558b5e40474927c1c12cd0" + }, + "platforms/macos/App/MemoryToolsModel.swift": { + "bytes": 5851, + "mode": "0644", + "sha256": "fd952fcf35744bef1f86d5043012906bcc1f73990d6f5b5d3a30200fd1662b46" + }, + "platforms/macos/App/MemoryToolsView.swift": { + "bytes": 5513, + "mode": "0644", + "sha256": "aac7b8938d5ab54d5a8e181d325c0824ecaefdb6be3c3ec197db84e07c0613a3" + }, + "platforms/macos/App/MetalRenderer.swift": { + "bytes": 10924, + "mode": "0644", + "sha256": "9f6b1c79f252f25fbe5b3ec48bd37209217aa928d6af8b23fe2818ed22dc2068" + }, + "platforms/macos/App/PrinterOutput.swift": { + "bytes": 15215, + "mode": "0644", + "sha256": "da0d52eb4629602afb475efadff5b4fd0f54972d25b4eedfbaad3f19c71fdf5c" + }, + "platforms/macos/App/ProfileControlsView.swift": { + "bytes": 22320, + "mode": "0644", + "sha256": "c6220c4f8ced604ff7ee92e49ada41b72e7cb385532182cd057dbaca21135c24" + }, + "platforms/macos/App/ROMImage.swift": { + "bytes": 1285, + "mode": "0644", + "sha256": "e82ad344ffdf0bf57e41ca8347483388439f1b1871f793bb702a45bb209cf106" + }, + "platforms/macos/App/RecentMedia.swift": { + "bytes": 3176, + "mode": "0644", + "sha256": "249852ef5f77e16cf5ed26f01e36294fe7731995893896009cd4c4ce3b502661" + }, + "platforms/macos/App/ReleaseHistoryView.swift": { + "bytes": 2404, + "mode": "0644", + "sha256": "d78a7a8da2d987c5370a6214c5c618e3934135dec14c62165dcb383033d7c292" + }, + "platforms/macos/App/SecondaryInterface.swift": { + "bytes": 6515, + "mode": "0644", + "sha256": "0e91eb0aaa9f811ca03fc5bf4bad205ec6f45687762194966669c06ebd78952c" + }, + "platforms/macos/App/SoftwareLibraryArtwork.swift": { + "bytes": 13059, + "mode": "0644", + "sha256": "78a15b30c73fd31cf791cf37e404b7c724867e6e982c1da8666d1f571cae728a" + }, + "platforms/macos/App/SoftwareLibraryCatalog.swift": { + "bytes": 38043, + "mode": "0644", + "sha256": "e8630a7baf5fd36788b0b49793debcfb751bb88ee9a2866fa4ac2728ab6a7522" + }, + "platforms/macos/App/SoftwareLibraryInstallFixture.swift": { + "bytes": 21059, + "mode": "0644", + "sha256": "23d626d5b4f07ca6b998b96e382342b99116f1649cb810722c821407e50288ca" + }, + "platforms/macos/App/SoftwareLibraryInstaller.swift": { + "bytes": 24555, + "mode": "0644", + "sha256": "56d7b20a389ba657799e164a360ec0dce169d62738270a537116cd8a1aa72f7a" + }, + "platforms/macos/App/SoftwareLibraryLaunchPlan.swift": { + "bytes": 22655, + "mode": "0644", + "sha256": "db6efdc9ac0054d12ac3253dbc32c0a6d6b737f53fc9162bbd19982de25494bf" + }, + "platforms/macos/App/SoftwareLibraryLaunchView.swift": { + "bytes": 5722, + "mode": "0644", + "sha256": "cce2d7bf7954fcc49f541652f3f680ffd90ee19043cfe4df2132678138e64c5c" + }, + "platforms/macos/App/SoftwareLibraryManual.swift": { + "bytes": 15932, + "mode": "0644", + "sha256": "a837bc19897a93066ad5c33e4e2224450ac57e10a970e5912d370b79c76fda35" + }, + "platforms/macos/App/SoftwareLibraryModel.swift": { + "bytes": 39853, + "mode": "0644", + "sha256": "2156480803dc8cf42a07ae0473ea7da154051c8e3199aea6a88125319021ec17" + }, + "platforms/macos/App/SoftwareLibrarySourceImporter.swift": { + "bytes": 17913, + "mode": "0644", + "sha256": "597f714262f25aae7d167ada48e28add06a1fed6869b2707c80160c2efe750d9" + }, + "platforms/macos/App/SoftwareLibraryState.swift": { + "bytes": 7629, + "mode": "0644", + "sha256": "bc43d62ab42f21c6a31ae179bacd9411f5c465a2b2afddf1271f238712606cc4" + }, + "platforms/macos/App/SoftwareLibraryView.swift": { + "bytes": 45406, + "mode": "0644", + "sha256": "da4469a919e5eb42f0cd7455e3e199c47ab7e7e84f1c0043e61b143fa1176625" + }, + "platforms/macos/App/SourceFind.swift": { + "bytes": 14533, + "mode": "0644", + "sha256": "c9a8e8b2e780a7daeee64ab6897b14035d4d14e93be2e524abfb56295e5990e6" + }, + "platforms/macos/App/StartupDefaults.swift": { + "bytes": 18876, + "mode": "0644", + "sha256": "bd361cd22f1e5e1d7e4acda2ecb63bb9df48f1e6f0985c9461404ef6e404c0fb" + }, + "platforms/macos/App/SystemView.swift": { + "bytes": 31836, + "mode": "0644", + "sha256": "6b88835de1567f079e56362d2472cb8e0183c81fac1ec86a6a52538fc7e2aed7" + }, + "platforms/macos/App/TapeImage.swift": { + "bytes": 1229, + "mode": "0644", + "sha256": "6f7d15f23dacb64b252f64445d8aa29e3053ed4a7e75fd8808f140b25195ff3e" + }, + "platforms/macos/App/TraceModel.swift": { + "bytes": 5568, + "mode": "0644", + "sha256": "153b03560d227890968b784381a66b19df05477632bcd15bc387f2dcc3c2dc99" + }, + "platforms/macos/App/TraceView.swift": { + "bytes": 8100, + "mode": "0644", + "sha256": "d32b681f102350a140a83ba11e3f80558465c52b852b62aeaa8064c9143270ed" + }, + "platforms/macos/App/VCCMacApp.swift": { + "bytes": 33420, + "mode": "0644", + "sha256": "5af5a988aede692b38ec53fa4d3b517baec331b400e8a2a36fb06d54773e20d9" + }, + "platforms/macos/App/WindowPlacement.swift": { + "bytes": 6519, + "mode": "0644", + "sha256": "0120330cd04dbbfbcc06bb2b25caa9d81cf6feb6426fd55fda858e958428655c" + }, + "platforms/macos/Bridge/DiskImageEditorBackend.h": { + "bytes": 3218, + "mode": "0644", + "sha256": "3a37c20d5954647154c4d5e9e1759111765ab662a258d020b4dffffe42a3372a" + }, + "platforms/macos/Bridge/DiskImageEditorBackend.mm": { + "bytes": 54975, + "mode": "0644", + "sha256": "72277344f1da655cb8ca2853b3ff681787032b5378adb07f2d3f59d6dce07faa" + }, + "platforms/macos/Bridge/DriveWireCoWin.h": { + "bytes": 3898, + "mode": "0644", + "sha256": "1cf8e778a868a97df9fdae598bcc877121ef3b1fb9541a4930ffafd14943561b" + }, + "platforms/macos/Bridge/DriveWireEndpoint.h": { + "bytes": 650, + "mode": "0644", + "sha256": "f7b2ba384af8df8ecbfaec703f67ff14da14ba58e9f6674267fc9ec94ce8a730" + }, + "platforms/macos/Bridge/DriveWireShell.h": { + "bytes": 687, + "mode": "0644", + "sha256": "3c3799bc7164e1460711a15a677fd0d32f790dede2e4a3b3458842220e6f573e" + }, + "platforms/macos/Bridge/DriveWireShell.mm": { + "bytes": 15437, + "mode": "0644", + "sha256": "e5877b31c4abc5f28e63097099a37019b9ba48c95b0e203493c7a7c7c076b914" + }, + "platforms/macos/Bridge/DriveWireTCP.mm": { + "bytes": 6860, + "mode": "0644", + "sha256": "534441ac23df19994061c93a1dc84edcb6f595e9eeaa296a21befb179649a81f" + }, + "platforms/macos/Bridge/DriveWireTerminal.h": { + "bytes": 14234, + "mode": "0644", + "sha256": "1a6a13a8edf7e9768f311c7d095f006d4f124d1b14f47fd2874f37f53bcc3ec6" + }, + "platforms/macos/Bridge/MacAudioOutput.h": { + "bytes": 621, + "mode": "0644", + "sha256": "539fb6beb3a7e25480e78fcdd295bfe5e2a19f62650d6049b339f041fc6930b8" + }, + "platforms/macos/Bridge/MacAudioOutput.mm": { + "bytes": 2557, + "mode": "0644", + "sha256": "a516df5912ab3ef40b70beca9d87e9f2c4557b56dd3c90c2b2e269426d9824b8" + }, + "platforms/macos/Bridge/VCCLibraryArchive.h": { + "bytes": 1436, + "mode": "0644", + "sha256": "deee4b24a1c0d7b8b409e0cf1688c9fb7202cf6d5c7bd090e15faa343babc76b" + }, + "platforms/macos/Bridge/VCCLibraryArchive.mm": { + "bytes": 18377, + "mode": "0644", + "sha256": "57b24ffd9d04a5f4d32ba8b8c0904b9bfdd62589bde3d4c6e05edd3d9d278a07" + }, + "platforms/macos/Bridge/VCCMac-Bridging-Header.h": { + "bytes": 143, + "mode": "0644", + "sha256": "f7d6758f52c19962380885b4ce7b7ba52c09f62ec5ce404299e28e7d9217c5cb" + }, + "platforms/macos/Bridge/VCCMachineController.h": { + "bytes": 32254, + "mode": "0644", + "sha256": "1dffe55b4b91a64141c4f4ec8b607da871421dae2e2cea5932190e7af9a15ccf" + }, + "platforms/macos/Bridge/VCCMachineController.mm": { + "bytes": 141524, + "mode": "0644", + "sha256": "f512f63dfb440a7b1234d2b8f4af919f9173df7282037853c77e3934e5977685" + }, + "platforms/macos/Companion/CompanionDiskTransfer.swift": { + "bytes": 1167, + "mode": "0644", + "sha256": "29f54f1af924bc5a72b39e792f0e9e80ff144035466233824d27cf791ad17aba" + }, + "platforms/macos/Companion/CompanionTransport.swift": { + "bytes": 25193, + "mode": "0644", + "sha256": "747a4b0f25508df8d625d702496f140dfa61476b6c2fc021c84d7e2c49252576" + }, + "platforms/macos/Companion/CompanionValidation.swift": { + "bytes": 4822, + "mode": "0644", + "sha256": "1be8f46f2f2b08be05bcfbdf6538a3c3e5a29a8e48ccd1a23d84edd769432664" + }, + "platforms/macos/Companion/SharedSecondaryCards.swift": { + "bytes": 1501, + "mode": "0644", + "sha256": "83eba0dfd96d2c579c6d6b277f004f8929e4e1d70676e2b9cf2b743c9b29e8fe" + }, + "platforms/macos/Companion/VCCCompanionService.swift": { + "bytes": 3259, + "mode": "0644", + "sha256": "2721ba58942499e98d410e656157047a9762c2ca8a7bb14481677b181bf105ed" + }, + "platforms/macos/Companion/VCCDriveWireTransfer.swift": { + "bytes": 13049, + "mode": "0644", + "sha256": "54ffdc2fb45a7c35350c598b83f08d96c8d112ea8819d6e25372020e9dd7dc62" + }, + "platforms/macos/Packaging/copy-development-starter.sh": { + "bytes": 3988, + "mode": "0644", + "sha256": "5d90b24bd2724837f82c157ad6943b1dcb3221b9826e722ca808d02d5a192d8b" + }, + "platforms/macos/Resources/About/ArtworkNotice.txt": { + "bytes": 834, + "mode": "0644", + "sha256": "e0aeab410502f9450831f0a42e8de0755b304182fd59afa66b9663cd017d0cf0" + }, + "platforms/macos/Resources/About/CopyrightNotice.txt": { + "bytes": 752, + "mode": "0644", + "sha256": "7b2203e29a9b72fb51ee10fce854602a1398eed6ad1ba9825c6a7afe4d94f629" + }, + "platforms/macos/Resources/About/DriveWireCredit.txt": { + "bytes": 237, + "mode": "0644", + "sha256": "5b6e99857bf3cc37c0cad54fe99df309d35c7c9479bf01dc507da4c054423b55" + }, + "platforms/macos/Resources/About/GPL.txt": { + "bytes": 35147, + "mode": "0644", + "sha256": "8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903" + }, + "platforms/macos/Resources/About/ROMNotice.txt": { + "bytes": 705, + "mode": "0644", + "sha256": "1b46d86b5ca8a78e22d50221e634ed8dbff5fa937ea24b32d5863cdc89fcbb4c" + }, + "platforms/macos/Resources/About/ThirdPartyNotices.txt": { + "bytes": 5535, + "mode": "0644", + "sha256": "7c8267a0b0aed1084329491ef1b96b9f13f7e9aa1a538b2d9f01c43662662bd6" + }, + "platforms/macos/Resources/About/WindowsAbout.txt": { + "bytes": 998, + "mode": "0644", + "sha256": "63e5e8c141e2d7664fd4df7e3855306eb79ddd0096b3e95a9ebf53a9608db0e7" + }, + "platforms/macos/Resources/About/dezota-dark.pdf": { + "bytes": 2998, + "mode": "0644", + "sha256": "404a436ee173993f6162ed15d9a23fb754961e950a7157278b12240259db2e41" + }, + "platforms/macos/Resources/About/dezota.pdf": { + "bytes": 2998, + "mode": "0644", + "sha256": "8d3fd13012a7343ffc642ef7cf88df0c39f70b2665014484837cf9923d721e80" + }, + "platforms/macos/Resources/About/founder.pdf": { + "bytes": 174748, + "mode": "0644", + "sha256": "07cf92273fb02b26b7b2ce74cdf94988358bd86e5a932606fdb4c5c20f62dd1b" + }, + "platforms/macos/Resources/About/windows-founders.bmp": { + "bytes": 11750, + "mode": "0644", + "sha256": "f53342fcc18bbadd8d4b0c6214716c4d25c059ea973119b32e2f7db38045d47d" + }, + "platforms/macos/Resources/About/windows-vcc.bmp": { + "bytes": 25022, + "mode": "0644", + "sha256": "8457a5569e9ed220b86e396b1350353b1b003fa2ab669e98c6b0ee679d4edf8a" + }, + "platforms/macos/Resources/AppIcon.icns": { + "bytes": 911948, + "mode": "0644", + "sha256": "43f4925c7fe3cf74242c1b44a0ae061ab3c5ebb1274fd9fe011d53997c5c1fd2" + }, + "platforms/macos/Resources/AppIconArtwork.pdf": { + "bytes": 216831, + "mode": "0644", + "sha256": "8c7fd737782afd19a7354d4c62a9fc34b4b5c17563ea8766d9b67a70d6483e1b" + }, + "platforms/macos/Resources/AssemblyReference.json": { + "bytes": 114620, + "mode": "0644", + "sha256": "0a8bd650066cb5a872d9080a06fe6e9e9afbaaf89276b8ac8cf58b4fe02d2f7b" + }, + "platforms/macos/Resources/BASICReference.json": { + "bytes": 134900, + "mode": "0644", + "sha256": "25937ec363954867dbbc86c0250e449ab3b17b6df02a70884eb9fc2f6e8f992d" + }, + "platforms/macos/Resources/Hardware/cassette.pdf": { + "bytes": 14745, + "mode": "0644", + "sha256": "ddef34d2addbb7f5cafc1f42009aeb808841c1eb274d233e497cfb9b690e7e7c" + }, + "platforms/macos/Resources/Hardware/coco-128kb.pdf": { + "bytes": 19827, + "mode": "0644", + "sha256": "786941bcd3aa6fc2e42d944a4809b856a29f4ef6cbd1cc44dc939a05bc976127" + }, + "platforms/macos/Resources/Hardware/coco-2mb.pdf": { + "bytes": 18710, + "mode": "0644", + "sha256": "bd52cc4be4e8781ea7bf9173ac9b3aedbb1cd642fced23e442239186cfdba4c4" + }, + "platforms/macos/Resources/Hardware/coco-512kb.pdf": { + "bytes": 19585, + "mode": "0644", + "sha256": "ccac923e5e365a00156d348c0d4a43877bf3c67156f40456bdee76065c9d6358" + }, + "platforms/macos/Resources/Hardware/coco-8mb.pdf": { + "bytes": 18915, + "mode": "0644", + "sha256": "839168af14e90512a2b775186489ea6143c9f97aee3ab9f074a1e89b3bfd33d7" + }, + "platforms/macos/Resources/Hardware/floppy.pdf": { + "bytes": 10178, + "mode": "0644", + "sha256": "0d8f927898c348e7ecc94f97cf5f1b1a0968e4f787d44e62ab774b6147cacd37" + }, + "platforms/macos/Resources/Hardware/hard.pdf": { + "bytes": 11188, + "mode": "0644", + "sha256": "397edbb53ba0095381257b62a7fc924de087182ce49a022b88e48139c53b6bed" + }, + "platforms/macos/Resources/Hardware/hitachi.pdf": { + "bytes": 25495, + "mode": "0644", + "sha256": "6229684c07d6f6e224a7ddc6d72c6cf331a6e9ed9e935081d12f3f7e6460b0c0" + }, + "platforms/macos/Resources/Hardware/joystick.pdf": { + "bytes": 9990, + "mode": "0644", + "sha256": "e1d4f62ce654a3b8fde4e2759d5efc662a9d47f5ff9340c2d5ff4fde8885f158" + }, + "platforms/macos/Resources/Hardware/layer-000.pdf": { + "bytes": 58202, + "mode": "0644", + "sha256": "a646f3ded1a2a00b44a1d67f2dcd1d594cf0b293cac8d17b82f460c5639e27b3" + }, + "platforms/macos/Resources/Hardware/layer-001.pdf": { + "bytes": 16752, + "mode": "0644", + "sha256": "60812f75312363246d69719247ccd9528b8b31e1080a9d215be57bb5c22ebb2d" + }, + "platforms/macos/Resources/Hardware/layer-002.pdf": { + "bytes": 2195, + "mode": "0644", + "sha256": "42c6001209fb18e587458809d5964daeaecb7a2227a16cfd86549374db3ed623" + }, + "platforms/macos/Resources/Hardware/layer-003.pdf": { + "bytes": 1889, + "mode": "0644", + "sha256": "275f03a52c9accece8dc89f15d0352857e27a80b6f1df61b29d12fd3191fa219" + }, + "platforms/macos/Resources/Hardware/layer-004.pdf": { + "bytes": 1885, + "mode": "0644", + "sha256": "38783aa3cbec1c05d547561e71ea9540f780132dfe5ab2b66fb042031898255c" + }, + "platforms/macos/Resources/Hardware/layer-005.pdf": { + "bytes": 1876, + "mode": "0644", + "sha256": "602827f91a0bafb14be225abe2ca0915664cfd7bcd71f77357e458d499d87d14" + }, + "platforms/macos/Resources/Hardware/layer-006.pdf": { + "bytes": 1878, + "mode": "0644", + "sha256": "fd615910d8b20d2621bd596bccfb2e2615cb8d6a9deced0b551646dc1758a05e" + }, + "platforms/macos/Resources/Hardware/layer-007.pdf": { + "bytes": 11699, + "mode": "0644", + "sha256": "c067fd86dd72909a7e6921f9cb6c53a30128031a27d385964373f1f8275d363b" + }, + "platforms/macos/Resources/Hardware/layer-008.pdf": { + "bytes": 7186, + "mode": "0644", + "sha256": "69812570b55fa987361d9e9690bb1b528b42222344d8b711ef6bc7f5358686f0" + }, + "platforms/macos/Resources/Hardware/layer-009.pdf": { + "bytes": 3211, + "mode": "0644", + "sha256": "bf4ce390feaba6c3db9581636444c8926a7e2717d8b958e94861ef5d86795fed" + }, + "platforms/macos/Resources/Hardware/layer-010.pdf": { + "bytes": 2421, + "mode": "0644", + "sha256": "8dcfc05734515f375e7c47cb0a7a077f187933698e1c2fbc6f110e55d8cc05a9" + }, + "platforms/macos/Resources/Hardware/layer-011.pdf": { + "bytes": 10318, + "mode": "0644", + "sha256": "c75725d3bf3a3d848cf3640c0c20f74f75e3bd0c2270e787c93bb18f66903f4e" + }, + "platforms/macos/Resources/Hardware/layer-012.pdf": { + "bytes": 7743, + "mode": "0644", + "sha256": "3b1f0f986d1839c33da875698a0cc5ea270a16490b4912c3fc98bfa6fb2bc2f7" + }, + "platforms/macos/Resources/Hardware/layer-013.pdf": { + "bytes": 20921, + "mode": "0644", + "sha256": "4bc1f14458e8352c8fa886e6a2d60f17b61c6096481f7ef3755ffb37bfeb84d7" + }, + "platforms/macos/Resources/Hardware/layer-014.pdf": { + "bytes": 12435, + "mode": "0644", + "sha256": "34e74c59430cc4277f3d27900bb466181bb02752ba7c39bc24c299c9fe494e97" + }, + "platforms/macos/Resources/Hardware/layer-015.pdf": { + "bytes": 12416, + "mode": "0644", + "sha256": "5be4cc491810f35ad61a6e23e06a3948b6fdeb3f7851a9b1fded943473913c40" + }, + "platforms/macos/Resources/Hardware/layer-016.pdf": { + "bytes": 12451, + "mode": "0644", + "sha256": "7e0abb1ec18effde37548c82865ae8f4ddc46e4ab963b1712a2ca6e82cd39ce4" + }, + "platforms/macos/Resources/Hardware/layer-017.pdf": { + "bytes": 12542, + "mode": "0644", + "sha256": "3baf73e8e118d4b85d9894ff14248e76bd0d77ed500172480f991b0dfcce5488" + }, + "platforms/macos/Resources/Hardware/layer-018.pdf": { + "bytes": 12429, + "mode": "0644", + "sha256": "d66b995f7d9901be5a6ae8399db79e916ea87770e4aa91d66fa24338060db33a" + }, + "platforms/macos/Resources/Hardware/layer-019.pdf": { + "bytes": 12203, + "mode": "0644", + "sha256": "0f98466c2a09512ddde4242e64257157d41dc83451a56cb5fee7c9e329bce661" + }, + "platforms/macos/Resources/Hardware/layer-020.pdf": { + "bytes": 12251, + "mode": "0644", + "sha256": "a6ae7ef9c6ef06605a2ec86992361f70ce3ee7594deb245b2e027db04b4fcfcf" + }, + "platforms/macos/Resources/Hardware/layer-021.pdf": { + "bytes": 12309, + "mode": "0644", + "sha256": "4d301565247708633d04dd8346a39114adffd313652223180828fb55723c81ec" + }, + "platforms/macos/Resources/Hardware/layer-022.pdf": { + "bytes": 3528, + "mode": "0644", + "sha256": "cbd2da83ad76ee4002eb346fdfdd6b817bec7f49749aeb8654d2e2dd29d3182b" + }, + "platforms/macos/Resources/Hardware/layer-023.pdf": { + "bytes": 2158, + "mode": "0644", + "sha256": "8e2ed43b3a85c2bc4a02254fe71acbfb4daaadd1097be68eab888bbf02d81c9e" + }, + "platforms/macos/Resources/Hardware/layer-024.pdf": { + "bytes": 1136, + "mode": "0644", + "sha256": "a8b6960abdade9668203edeaefc3d4c318bd338de9f3817d1424e310850b6740" + }, + "platforms/macos/Resources/Hardware/layer-025.pdf": { + "bytes": 1884, + "mode": "0644", + "sha256": "edc86f5e69a032a409f8ee7f730d05baaa20b6b84a87ad38b8bf552ef364a4bd" + }, + "platforms/macos/Resources/Hardware/layer-026.pdf": { + "bytes": 1879, + "mode": "0644", + "sha256": "4f3ca8786d7a101912a7c2c45dc4f0f8da3d1087361c4c0d145f89d3a94f71a0" + }, + "platforms/macos/Resources/Hardware/layer-027.pdf": { + "bytes": 1870, + "mode": "0644", + "sha256": "76dcbed12e996315a92dc8e3ff5369b799da450fb099b330bdce797fa4feb35c" + }, + "platforms/macos/Resources/Hardware/layer-028.pdf": { + "bytes": 1873, + "mode": "0644", + "sha256": "cab6d166d01b9c792fb56af19bef4c81ae01134f25a0edeb6539877b876fc5fd" + }, + "platforms/macos/Resources/Hardware/layer-029.pdf": { + "bytes": 2172, + "mode": "0644", + "sha256": "338314ebb46e255093eec5c68139326646628edfc743f2498bb65ebd5c42e64b" + }, + "platforms/macos/Resources/Hardware/layer-030.pdf": { + "bytes": 2158, + "mode": "0644", + "sha256": "9a4bcdd11dc608eb449b26009a5b026400b6408ab99ebcb50056363c25a239ca" + }, + "platforms/macos/Resources/Hardware/layer-031.pdf": { + "bytes": 1136, + "mode": "0644", + "sha256": "2798d1794f82e99215c8446b34a0bf3ccceb465825a62be9be27f9d00e31525d" + }, + "platforms/macos/Resources/Hardware/layer-032.pdf": { + "bytes": 1885, + "mode": "0644", + "sha256": "0985e9dac895220517b435d1f97e87d989cb59b7f1efa5922b42c90caa0319f0" + }, + "platforms/macos/Resources/Hardware/layer-033.pdf": { + "bytes": 1881, + "mode": "0644", + "sha256": "1f032fcdc15a302548378eb3d523759c2f11e172a6ddba42411b63aa4efb8270" + }, + "platforms/macos/Resources/Hardware/layer-034.pdf": { + "bytes": 1872, + "mode": "0644", + "sha256": "03130bb7f9d11f751e72d8df299e437438a68c9c9edd857478c7ccd6c12a0fb7" + }, + "platforms/macos/Resources/Hardware/layer-035.pdf": { + "bytes": 1875, + "mode": "0644", + "sha256": "65f999d02ece090a88dd13045787b472ddca7d5e44bddab814f0d55f00abc9a4" + }, + "platforms/macos/Resources/Hardware/layer-036.pdf": { + "bytes": 2626, + "mode": "0644", + "sha256": "3c8afd1675816ceaea4ae4512e7cbc63ad4eab3908de81fa345cbc3248f6917a" + }, + "platforms/macos/Resources/Hardware/layer-037.pdf": { + "bytes": 3526, + "mode": "0644", + "sha256": "3f2b6855ab6a7f4a13f27a5f51fb3f8b765c4eb6790b160ffcb2d3b53dc50c57" + }, + "platforms/macos/Resources/Hardware/layer-038.pdf": { + "bytes": 2163, + "mode": "0644", + "sha256": "4b80fcc3289c700331b41a764d954adcaff2f322a9126e6541209133dbfc4ebe" + }, + "platforms/macos/Resources/Hardware/layer-039.pdf": { + "bytes": 1130, + "mode": "0644", + "sha256": "3055e08ed01b8b6d4ced1a48e20a4ca5375a0a8a7d64622ca9d76d23a9dd3a7b" + }, + "platforms/macos/Resources/Hardware/layer-040.pdf": { + "bytes": 1885, + "mode": "0644", + "sha256": "e7a3cdc1c972828f2c58f0df01959c01db86cdf924ff9b0d7dd73f2eefb1fc1d" + }, + "platforms/macos/Resources/Hardware/layer-041.pdf": { + "bytes": 1880, + "mode": "0644", + "sha256": "2d5034a204c2efc9f6386db149a0fad6bd944a623d366b9e1ba068b832b02d49" + }, + "platforms/macos/Resources/Hardware/layer-042.pdf": { + "bytes": 1872, + "mode": "0644", + "sha256": "6a2b1569cd3c750adb5348d0d6835e734b8b2cf936030209eecc2a44a04ccd08" + }, + "platforms/macos/Resources/Hardware/layer-043.pdf": { + "bytes": 1873, + "mode": "0644", + "sha256": "78e18af22872688e1658548f46fdce0a685a44f586c3a5572d0b26edcd1c336b" + }, + "platforms/macos/Resources/Hardware/layer-044.pdf": { + "bytes": 1813, + "mode": "0644", + "sha256": "b1d5212958d0b7d1a0a530c3b9398ed6ed9e8eed3d0683e42d109e0dc3cc93d5" + }, + "platforms/macos/Resources/Hardware/layer-045.pdf": { + "bytes": 2193, + "mode": "0644", + "sha256": "b1cc582f0e09e04913ecfb9a3a17e50f2a0b00544096cc9f3ed85093f9227c14" + }, + "platforms/macos/Resources/Hardware/layer-046.pdf": { + "bytes": 3990, + "mode": "0644", + "sha256": "77cbbdde08862d7c42e8c20d81e153f1d13aa5aa3423b7e872ea78c9e99c0252" + }, + "platforms/macos/Resources/Hardware/layer-047.pdf": { + "bytes": 3391, + "mode": "0644", + "sha256": "7c422830faf59302c6bd0b391238e569d8ba7a5b19267db6a1ecc31cff477980" + }, + "platforms/macos/Resources/Hardware/layer-048.pdf": { + "bytes": 2163, + "mode": "0644", + "sha256": "549c68a4fc14e8241687406949f3ab449de07124b9644b65b5126a94c0c9b16c" + }, + "platforms/macos/Resources/Hardware/layer-049.pdf": { + "bytes": 1132, + "mode": "0644", + "sha256": "883bf0df6f0c7050db2db10601df6098cf2cf6b8e07d9a4a238776cdb8ab0a02" + }, + "platforms/macos/Resources/Hardware/layer-050.pdf": { + "bytes": 1885, + "mode": "0644", + "sha256": "80d7814253c0d54b063509ff0dad934552d29f991a44b82e794162dbc7007bed" + }, + "platforms/macos/Resources/Hardware/layer-051.pdf": { + "bytes": 1880, + "mode": "0644", + "sha256": "2afc3938c4b3322a834651ffe1e9db33c64898a95323b2e3c6a0bf70c502711c" + }, + "platforms/macos/Resources/Hardware/layer-052.pdf": { + "bytes": 1872, + "mode": "0644", + "sha256": "71b0898d9af39a7c3ca09cad9e0b9e9827310aae121f1f0fc6a28f4828f39088" + }, + "platforms/macos/Resources/Hardware/layer-053.pdf": { + "bytes": 1875, + "mode": "0644", + "sha256": "b27beb1126bcbe45c4eceee7cdd818c390e5051a163c191a01dd13a73374049c" + }, + "platforms/macos/Resources/Hardware/layer-054.pdf": { + "bytes": 1811, + "mode": "0644", + "sha256": "3eb0c7d64bc260230254e101c4c9f8a58dbf1ed6025a134dc7581f0bfba15a3e" + }, + "platforms/macos/Resources/Hardware/layer-055.pdf": { + "bytes": 2193, + "mode": "0644", + "sha256": "6395fde5e7be7cf687793fee6198cf3fdeb24c3d23711ac0e54674263bdd477a" + }, + "platforms/macos/Resources/Hardware/layer-056.pdf": { + "bytes": 4217, + "mode": "0644", + "sha256": "1fa37ff89611fa21d621a09313fd3d9df9663e3b1235e197ca34dbca8858b5b0" + }, + "platforms/macos/Resources/Hardware/layer-057.pdf": { + "bytes": 3861, + "mode": "0644", + "sha256": "26d90c4c87ba7164db62048588c6716ed0c1af09c49dbfe5cda47730b2711093" + }, + "platforms/macos/Resources/Hardware/layer-058.pdf": { + "bytes": 3531, + "mode": "0644", + "sha256": "a8d94f2a5357b441467b38cf508ffc2b5f5607688759b807a0f344fba850c04b" + }, + "platforms/macos/Resources/Hardware/layer-059.pdf": { + "bytes": 2160, + "mode": "0644", + "sha256": "d461f89d92b423710b285b0e3c24d14a1683cc8a5084aee2d59426b5d5de826b" + }, + "platforms/macos/Resources/Hardware/layer-060.pdf": { + "bytes": 1133, + "mode": "0644", + "sha256": "28fbf9fd914687020a8b9307b0b8eabefa651dac93cdfaf43e37e70e2ebfe9d8" + }, + "platforms/macos/Resources/Hardware/layer-061.pdf": { + "bytes": 1884, + "mode": "0644", + "sha256": "98c669743ecfc72721c85b64274be840275db891cc50d215353f92eb1fdae950" + }, + "platforms/macos/Resources/Hardware/layer-062.pdf": { + "bytes": 1879, + "mode": "0644", + "sha256": "1f52bc72c4caeace870211c46bc5f1d01bb3241a2e8c8dc9fb4eafc3c50bd34b" + }, + "platforms/macos/Resources/Hardware/layer-063.pdf": { + "bytes": 1870, + "mode": "0644", + "sha256": "ff150089655c2be7ff6d12f87f1301768815524b9d4e71e51b812b4d7da31dbb" + }, + "platforms/macos/Resources/Hardware/layer-064.pdf": { + "bytes": 1873, + "mode": "0644", + "sha256": "2eeb8e40758cbec14d180fa02883640807c8d2856974fdda3b5299f2ef5233b4" + }, + "platforms/macos/Resources/Hardware/layer-065.pdf": { + "bytes": 1814, + "mode": "0644", + "sha256": "08ace2d1dcb860dbf517ac51d8cd5fec9a8482d4d982eab39c41d3f737d6f6bf" + }, + "platforms/macos/Resources/Hardware/layer-066.pdf": { + "bytes": 2196, + "mode": "0644", + "sha256": "7fd65fa455fcc70721bed6580e66fa6398777b30088f80024809111fc389a9f5" + }, + "platforms/macos/Resources/Hardware/layer-067.pdf": { + "bytes": 4336, + "mode": "0644", + "sha256": "ced6c9e1ec2fd37ddb15ae3fc4ab5fed6157efd923a8ca95fef2c8b9b6e93c94" + }, + "platforms/macos/Resources/Hardware/layer-068.pdf": { + "bytes": 4079, + "mode": "0644", + "sha256": "209686d7a6d6ec8dcd5da3e8d632979da8669984e46728996fa1c87e773f7674" + }, + "platforms/macos/Resources/Hardware/layer-069.pdf": { + "bytes": 2162, + "mode": "0644", + "sha256": "2ff11323c41d425fb3ac0521570b38222aa0747c4f6038a9f82270c9867223cd" + }, + "platforms/macos/Resources/Hardware/layer-070.pdf": { + "bytes": 1130, + "mode": "0644", + "sha256": "eeb68d329124893754a6fe372263964d7e46ec79b380fc24c255a25bb5eb73a4" + }, + "platforms/macos/Resources/Hardware/layer-071.pdf": { + "bytes": 1887, + "mode": "0644", + "sha256": "58086b10a62a515068a811cf27d31ba6d83f9e682c96ad6ca3d85fca6b009a78" + }, + "platforms/macos/Resources/Hardware/layer-072.pdf": { + "bytes": 1881, + "mode": "0644", + "sha256": "b655539a3597af0a22ccac1f23caf29a78de6d9d4ef97da3aeed2c9a82df6dbb" + }, + "platforms/macos/Resources/Hardware/layer-073.pdf": { + "bytes": 1874, + "mode": "0644", + "sha256": "f6d8baa2626284022e032e082049eef62bdfa1a7695f6ceb88cfc81fae1c766c" + }, + "platforms/macos/Resources/Hardware/layer-074.pdf": { + "bytes": 1877, + "mode": "0644", + "sha256": "f694e9d2b15f6646fbcc0bcd190422a6a4e16595316174fe6a29cfb5792e5d28" + }, + "platforms/macos/Resources/Hardware/layer-075.pdf": { + "bytes": 1814, + "mode": "0644", + "sha256": "4d48beb9a08dbab3e494b7b354a54d4c343994cb3051b2295b7f35dd8c89ab3d" + }, + "platforms/macos/Resources/Hardware/layer-076.pdf": { + "bytes": 2201, + "mode": "0644", + "sha256": "f512ea4bc96b28c1ce20a420d5e691113ae183e21b933ba70a8108ae733886d1" + }, + "platforms/macos/Resources/Hardware/layer-077.pdf": { + "bytes": 4235, + "mode": "0644", + "sha256": "a21bf758588f6b5c560f79abdca76aaaeb6be4fcb786543b4777c305800fd829" + }, + "platforms/macos/Resources/Hardware/layer-078.pdf": { + "bytes": 3838, + "mode": "0644", + "sha256": "7ac4f5f71f18cbb7e325e68e450aaab5414761d997133dc60bb260d0a9aa6510" + }, + "platforms/macos/Resources/Hardware/layer-079.pdf": { + "bytes": 23583, + "mode": "0644", + "sha256": "7b78b605d09c21811af20cfbfc8963284b5ef9a02bc9f2f1f9a053db98d31ee5" + }, + "platforms/macos/Resources/Hardware/layer-080.pdf": { + "bytes": 29267, + "mode": "0644", + "sha256": "abb452532e8a313c296e242d9a0c0df13d0ef927258d8f968c4a46947922bd28" + }, + "platforms/macos/Resources/Hardware/layer-081.pdf": { + "bytes": 1228, + "mode": "0644", + "sha256": "c6f74c38e22d72fdd48972c2221c0b7af6760c442bb522bb0b2203c71bd1cbd1" + }, + "platforms/macos/Resources/Hardware/layer-082.pdf": { + "bytes": 2354, + "mode": "0644", + "sha256": "2a422d032ce6847c432aa82a1508662e3584a311bfcb017e8bce8a23e1ebcf0b" + }, + "platforms/macos/Resources/Hardware/layer-083.pdf": { + "bytes": 2356, + "mode": "0644", + "sha256": "ca25cea2b8d0b6bf12763d6051c4ac970efdee004a6c6daa0430f5fbbece8916" + }, + "platforms/macos/Resources/Hardware/layer-084.pdf": { + "bytes": 2348, + "mode": "0644", + "sha256": "0ee15efe483f2d68c202e471e364b3a68b7b2e1953941ff4138daedf24460eca" + }, + "platforms/macos/Resources/Hardware/layer-085.pdf": { + "bytes": 2363, + "mode": "0644", + "sha256": "70941f45e5c8423e29f03a4a038d69a4209298e69267042fb067abcdd0b2e460" + }, + "platforms/macos/Resources/Hardware/layer-086.pdf": { + "bytes": 1077, + "mode": "0644", + "sha256": "eb7e522ae7957326154659551af58339ab5d11382749e31c2784ee2c9c66a5e9" + }, + "platforms/macos/Resources/Hardware/layer-087.pdf": { + "bytes": 16511, + "mode": "0644", + "sha256": "525e5018522301abb2421821446f3280fb5aec08be9ce99ad451062c3db8dc17" + }, + "platforms/macos/Resources/Hardware/layer-088.pdf": { + "bytes": 12498, + "mode": "0644", + "sha256": "859546f57997de97c3862abe5ec3e54708f9f48f00c091ecfc1c4807a5baf46e" + }, + "platforms/macos/Resources/Hardware/layer-089.pdf": { + "bytes": 11304, + "mode": "0644", + "sha256": "a95a2716db41c3e363761bf4370d5b8389a6b1e18aae3e95a8c76e78463d26b8" + }, + "platforms/macos/Resources/Hardware/layer-090.pdf": { + "bytes": 11774, + "mode": "0644", + "sha256": "767a86ce363892cd0a46c79479d48b0fed6a3335c2f3fbb6e651b62e5300ce58" + }, + "platforms/macos/Resources/Hardware/layer-091.pdf": { + "bytes": 11151, + "mode": "0644", + "sha256": "9709a0b4234d8809b1f09c64b984af7802ac180ffdc5f05bdfe795d2611d038f" + }, + "platforms/macos/Resources/Hardware/layer-092.pdf": { + "bytes": 11871, + "mode": "0644", + "sha256": "4bdcd51283316fc66570e568bb62d709909dc93ec56c76442692bedd0a3f486d" + }, + "platforms/macos/Resources/Hardware/layer-093.pdf": { + "bytes": 1722, + "mode": "0644", + "sha256": "2425cfa2e9085909a188a3f482a4013900cbe781a11c263a3c823336d4efd269" + }, + "platforms/macos/Resources/Hardware/layer-094.pdf": { + "bytes": 1724, + "mode": "0644", + "sha256": "7497b62e572d05fc9869fae604b8cb7446410e8b5f6e93c813764957116d652e" + }, + "platforms/macos/Resources/Hardware/layer-095.pdf": { + "bytes": 1722, + "mode": "0644", + "sha256": "a0c03c0597758bc2fde9b6970f819e54d5b2bab5d9c340dd9ada8f000bad8261" + }, + "platforms/macos/Resources/Hardware/layer-096.pdf": { + "bytes": 1722, + "mode": "0644", + "sha256": "e9f304ea92e3469e3dad827ee1631f4e35dd152bb472da0a037a2aea2d10994d" + }, + "platforms/macos/Resources/Hardware/layer-097.pdf": { + "bytes": 16531, + "mode": "0644", + "sha256": "6ecd9b717bc8fc7548311567d4d7c692064381a2e9af95a87c390aa90d582519" + }, + "platforms/macos/Resources/Hardware/layer-098.pdf": { + "bytes": 12515, + "mode": "0644", + "sha256": "6c3a120fba4f8f3ff8a4c3093dc095d14606150943b6e5514eac50411785fd81" + }, + "platforms/macos/Resources/Hardware/layer-099.pdf": { + "bytes": 11323, + "mode": "0644", + "sha256": "42303100f8079425be70a8f3967281dcd059914a01a2e6f741e2f5316138ee7f" + }, + "platforms/macos/Resources/Hardware/layer-100.pdf": { + "bytes": 11790, + "mode": "0644", + "sha256": "65b3ab06c41ee474ffff1ecc25f453ca4d6b26f1eb285c94ede322ccc7bc66f2" + }, + "platforms/macos/Resources/Hardware/layer-101.pdf": { + "bytes": 11134, + "mode": "0644", + "sha256": "3662d5cbb1f1677e3be8677115bc6c62ce73657024f959c4ed20aabf079a8fa1" + }, + "platforms/macos/Resources/Hardware/layer-102.pdf": { + "bytes": 11901, + "mode": "0644", + "sha256": "477f8013b0aad44c00403bddeb17ed17b3e97f0597d88e01d303a4eccdd09f8e" + }, + "platforms/macos/Resources/Hardware/layer-103.pdf": { + "bytes": 1724, + "mode": "0644", + "sha256": "49f33891e5f8c9f4263ec8d1d4c64815fde1749b3bb51c09a1fa9907812b9570" + }, + "platforms/macos/Resources/Hardware/layer-104.pdf": { + "bytes": 1724, + "mode": "0644", + "sha256": "66fd48116ba7fc803a21e344081206e66b9af9eca3d8ed5b11adbbfa2290621a" + }, + "platforms/macos/Resources/Hardware/layer-105.pdf": { + "bytes": 1724, + "mode": "0644", + "sha256": "a8a2b3ddb7026672365297ae3a84e8bb1d0c505eaf48f63cf433431933d04d78" + }, + "platforms/macos/Resources/Hardware/layer-106.pdf": { + "bytes": 1724, + "mode": "0644", + "sha256": "7d7712e834304295e84a0063c0efefc6fae126794e3d4e1838f7a40a3be09184" + }, + "platforms/macos/Resources/Hardware/layer-107.pdf": { + "bytes": 16525, + "mode": "0644", + "sha256": "a03b8b22fc9086aeeb07cafb9520a3c35f40eb32461de88824618a382059a878" + }, + "platforms/macos/Resources/Hardware/layer-108.pdf": { + "bytes": 12448, + "mode": "0644", + "sha256": "52469a32ffe958d1782338c9edaa2de3a0ef468098c11dd178bfa9cd6d6e8b4b" + }, + "platforms/macos/Resources/Hardware/layer-109.pdf": { + "bytes": 11307, + "mode": "0644", + "sha256": "292796e367f996b1fc915d413a08a1313acdb8d28d135dd2f6c27125171528f4" + }, + "platforms/macos/Resources/Hardware/layer-110.pdf": { + "bytes": 11708, + "mode": "0644", + "sha256": "903e0263c9b911cf98a1a50af737146f2cc8212cf781e5a8796e8a432bd990c8" + }, + "platforms/macos/Resources/Hardware/layer-111.pdf": { + "bytes": 11121, + "mode": "0644", + "sha256": "03334e5cfac04e245d1c28b04fa943c3d8c13e2eb16ee747efd92c515d8ba51d" + }, + "platforms/macos/Resources/Hardware/layer-112.pdf": { + "bytes": 11914, + "mode": "0644", + "sha256": "6f707a0e79d7b49bff2805ea870caa6de30d05cf85fe9e7b710fc6d709bec11e" + }, + "platforms/macos/Resources/Hardware/layer-113.pdf": { + "bytes": 1718, + "mode": "0644", + "sha256": "0d52a2bc3fe299af643b3863bc41153c97403679dcd53642ddebfbb6dbd7e9e1" + }, + "platforms/macos/Resources/Hardware/layer-114.pdf": { + "bytes": 1720, + "mode": "0644", + "sha256": "c21c2b4c7038af023ab45c11e42246eaa09ad231dd75a1436ee54ff386b90c35" + }, + "platforms/macos/Resources/Hardware/layer-115.pdf": { + "bytes": 1720, + "mode": "0644", + "sha256": "ec524593d3180bc2f212f179ccddb87b44145e59d9040df24fa9f38e6571ce29" + }, + "platforms/macos/Resources/Hardware/layer-116.pdf": { + "bytes": 1720, + "mode": "0644", + "sha256": "e38b00a2031930b3f98da978932ce3d0549e9ea93ff04fe4cf368f5d35bbd3dc" + }, + "platforms/macos/Resources/Hardware/layer-117.pdf": { + "bytes": 16565, + "mode": "0644", + "sha256": "13ba5ef8bee321f70fd1cbe92e910ed621fd7df27f8e2447393566f8e8788382" + }, + "platforms/macos/Resources/Hardware/layer-118.pdf": { + "bytes": 12542, + "mode": "0644", + "sha256": "5806b41fdfbbf6191bc70c09715370fcb3ab01120d18486ab93f74c334f79a57" + }, + "platforms/macos/Resources/Hardware/layer-119.pdf": { + "bytes": 11366, + "mode": "0644", + "sha256": "237b7c3ef632007a117b90c6df34c37d9a88f3d23ea2f2a4531c647f3eafb3e5" + }, + "platforms/macos/Resources/Hardware/layer-120.pdf": { + "bytes": 11752, + "mode": "0644", + "sha256": "9e2be9986835453b2756644feff657f3a94abc0ea075ea80bdaced6d31dfad39" + }, + "platforms/macos/Resources/Hardware/layer-121.pdf": { + "bytes": 11122, + "mode": "0644", + "sha256": "17fd7becefdbdbc2888a2166c61b423f5bfe5021756732401c70f356b468c2af" + }, + "platforms/macos/Resources/Hardware/layer-122.pdf": { + "bytes": 11936, + "mode": "0644", + "sha256": "7a89f523f13f7052cac183a304abc12154063b79c1f56d85dad95c5a89f6f6dd" + }, + "platforms/macos/Resources/Hardware/layer-123.pdf": { + "bytes": 1719, + "mode": "0644", + "sha256": "137c8f0db12129fa63393e05bf6d9c0c77e7423176db2e67e5d996901350bb09" + }, + "platforms/macos/Resources/Hardware/layer-124.pdf": { + "bytes": 1720, + "mode": "0644", + "sha256": "f88b8fd250e10b243d6e157d94b960ea6984da09211642b709b094ffe203635f" + }, + "platforms/macos/Resources/Hardware/layer-125.pdf": { + "bytes": 1720, + "mode": "0644", + "sha256": "8bec38327db11046e1b41bbd6c5c1bfa7cd99d9010f44efcf736b32e2ce3ebfd" + }, + "platforms/macos/Resources/Hardware/layer-126.pdf": { + "bytes": 1721, + "mode": "0644", + "sha256": "2b16f2481b04d89d9f01ba404ee373d5a2d5f4fab7dfaff520ca33bf6f33045d" + }, + "platforms/macos/Resources/Hardware/layer-127.pdf": { + "bytes": 14593, + "mode": "0644", + "sha256": "f39af00152f7a56d861dc30c255deb0d3ec548aae42dfd5671ab2634a5249b28" + }, + "platforms/macos/Resources/Hardware/layer-128.pdf": { + "bytes": 8081, + "mode": "0644", + "sha256": "c2d9cb566ade385e14c5e551f3e53d3dde532b0eebffe0c68dd024af3297542e" + }, + "platforms/macos/Resources/Hardware/layer-129.pdf": { + "bytes": 8358, + "mode": "0644", + "sha256": "616e3d2761c2cf7df53ed056e90ec44d1c0f7a91aabad0a9c5e7f5dcb678a361" + }, + "platforms/macos/Resources/Hardware/layer-130.pdf": { + "bytes": 4261, + "mode": "0644", + "sha256": "e3668e86b144401b9a3f9b05d8ef3ecdff46216902f9344494a4e8bd47eb5b0d" + }, + "platforms/macos/Resources/Hardware/layer-131.pdf": { + "bytes": 4064, + "mode": "0644", + "sha256": "f09da460270b667ebeeb853043b99e64e40da6a9a4da3c56b0ab2e0d0180abd5" + }, + "platforms/macos/Resources/Hardware/layer-132.pdf": { + "bytes": 3187, + "mode": "0644", + "sha256": "c6e2075784ddd0f0a2d77cede397df8a15c357dd1f057122509dbdbf18f0defa" + }, + "platforms/macos/Resources/Hardware/layer-133.pdf": { + "bytes": 3355, + "mode": "0644", + "sha256": "c4b2b07bfed1da36d0aa276cc592a8eaf5122168b09cafd08a13cef9d733c365" + }, + "platforms/macos/Resources/Hardware/layer-134.pdf": { + "bytes": 9179, + "mode": "0644", + "sha256": "92493a34fbde59d5e131f63f34652b8757b22795a2b06139b801f2b86eff63d9" + }, + "platforms/macos/Resources/Hardware/layer-135.pdf": { + "bytes": 183934, + "mode": "0644", + "sha256": "ec5a736737dc3e6d6ef6f325aaba18a6ad412e52ff4cb7ae6638fadca2be471b" + }, + "platforms/macos/Resources/Hardware/layer-136.pdf": { + "bytes": 25343, + "mode": "0644", + "sha256": "93feb14c5490861f2506dd4deb1e04bca0ad6dac55b1cef0cfc3380afe5ecb58" + }, + "platforms/macos/Resources/Hardware/layer-137.pdf": { + "bytes": 24399, + "mode": "0644", + "sha256": "0ce75123e7e429287c77199006219f515b5fd2b4ca851288aa9137d44dc6a541" + }, + "platforms/macos/Resources/Hardware/layer-138.pdf": { + "bytes": 1412917, + "mode": "0644", + "sha256": "25a2143dd68f7389fae591bf030fb71f6d9e475f4dedc3cf1db8c0935b5829d7" + }, + "platforms/macos/Resources/Hardware/layer-139.pdf": { + "bytes": 74706, + "mode": "0644", + "sha256": "00f3481b107b4eb083e4a94b555a9ca62a03bbdd6a04f42577aae53a541c2434" + }, + "platforms/macos/Resources/Hardware/layer-140.pdf": { + "bytes": 1556, + "mode": "0644", + "sha256": "497d93f23e1ec79676ad083f502b5c532edad641809dfe4c9a6ff2b31f00bb6a" + }, + "platforms/macos/Resources/Hardware/layer-141.pdf": { + "bytes": 1755, + "mode": "0644", + "sha256": "eb79c566f0cd226a806b93992a102bcff1519055059bef402cdd515be15fe4cd" + }, + "platforms/macos/Resources/Hardware/layers.json": { + "bytes": 26937, + "mode": "0644", + "sha256": "1426ac70dae356afb83c32007f803b8f69a838776b59679284861458ec80a21a" + }, + "platforms/macos/Resources/Hardware/manual-help.pdf": { + "bytes": 8455, + "mode": "0644", + "sha256": "99d3a922ff2d1cf70310081fbbb4835fa2225a5e53b1c7610b8f08dbf03c34b3" + }, + "platforms/macos/Resources/Hardware/motorola.pdf": { + "bytes": 24295, + "mode": "0644", + "sha256": "a8118d4bfa242ceab5e0a853ce47a5fca4f48789561912eff6410c222f42e395" + }, + "platforms/macos/Resources/Hardware/mpi.pdf": { + "bytes": 9808, + "mode": "0644", + "sha256": "18cc4e66e67cb2d3435c77fd27d911c613c275e00bf5a01161e92f6bcd8b36de" + }, + "platforms/macos/Resources/Hardware/printer.pdf": { + "bytes": 7138, + "mode": "0644", + "sha256": "3a39da6a8d3046b1f05a59e69b9c664a9f096befc929729c5fbc7552fc099678" + }, + "platforms/macos/Resources/Hardware/software-library-shelf.png": { + "bytes": 1577765, + "mode": "0644", + "sha256": "6f16fcaaa0f34da135ee64b21b3ee71728ba0aa6f25733e8e1008e54ee93dbad" + }, + "platforms/macos/Resources/RuntimeTemplates.json": { + "bytes": 283, + "mode": "0644", + "sha256": "32655b557a67ed8ef2429fdc2ae12f12c2445aa064b336b99dd887e4acb8c9df" + }, + "platforms/macos/Resources/SourceProjectSetupPrompt.txt": { + "bytes": 681, + "mode": "0644", + "sha256": "64d0f7ae39d089eb9520466fbe7a2cdfe84d8e3de8eb1697a36950130899e73d" + }, + "platforms/macos/Resources/StarterMedia/Blank Disk.dsk": { + "bytes": 161280, + "mode": "0644", + "sha256": "7732cd06c2e371699425c08ff15345a01de7d8742cf3ea7b1bd17ca5be099612" + }, + "platforms/macos/Resources/StarterMedia/Blank OS9 Header.bin": { + "bytes": 8192, + "mode": "0644", + "sha256": "51c4f627153bec9dd45bdec85f663577bacc224de289b92b939c140a61986c2e" + }, + "platforms/macos/Resources/StarterMedia/Hello Hard Disk.dsk": { + "bytes": 161280, + "mode": "0644", + "sha256": "380d6226d0c4b70a3419bd0960349e82e9b8e09123b25986a603a8a82980c8d9" + }, + "platforms/macos/Resources/StarterMedia/Hello World.cas": { + "bytes": 576, + "mode": "0644", + "sha256": "6627262adc3b88a0a8ad977841bcc9017e22da34d8c097c6b99c252f3f29c864" + }, + "platforms/macos/Resources/StarterMedia/Hello World.dsk": { + "bytes": 161280, + "mode": "0644", + "sha256": "380d6226d0c4b70a3419bd0960349e82e9b8e09123b25986a603a8a82980c8d9" + }, + "platforms/macos/Resources/StarterMedia/README.md": { + "bytes": 4037, + "mode": "0644", + "sha256": "d354e72f8c749b04dc97beb7f6be3d9c5c467f43347b376c13e8345a56c5d2c9" + }, + "platforms/macos/Tests/ArchiveReaderTests.swift": { + "bytes": 16223, + "mode": "0644", + "sha256": "6fe405075ca2073d7e08bdb664fae67d2942979c3fafd7699efeb07fe47423d5" + }, + "platforms/macos/Tests/AssemblyBuildServiceTests.swift": { + "bytes": 13007, + "mode": "0644", + "sha256": "833f65745905b08e5f8176380ebb85ee8e8437c8071484c90cccdc5513d21ecd" + }, + "platforms/macos/Tests/AssemblyDevelopmentTests.swift": { + "bytes": 20449, + "mode": "0644", + "sha256": "3f816ecf01008d5309df4c98c71098f1e792335bc9d5e0f30cd249b7a648d827" + }, + "platforms/macos/Tests/AssemblyReferenceTests.swift": { + "bytes": 10464, + "mode": "0644", + "sha256": "5c3a5b7c246d8f3f7b4586988e1a546bde5ebd4d2346f559afca700b90f0017d" + }, + "platforms/macos/Tests/BASICBridgeTests.swift": { + "bytes": 95121, + "mode": "0644", + "sha256": "f7a99fccdf28e89f9eb1fa23dc5625f2f2852bcc75ab5563f7c75ddccf001a45" + }, + "platforms/macos/Tests/BASICReferenceTests.swift": { + "bytes": 35058, + "mode": "0644", + "sha256": "da193b61dbd97e930d2aa350c8e5f49f62ac3c50a3dcdecc3e4f6f7197a88224" + }, + "platforms/macos/Tests/BASICWorkspaceTests.swift": { + "bytes": 32906, + "mode": "0644", + "sha256": "080967689178a1d38b4607157a734617b87e6284704a5ab2e6530d76b19b3845" + }, + "platforms/macos/Tests/BinaryTests.swift": { + "bytes": 7017, + "mode": "0644", + "sha256": "657940a6db3413f49ddd725eb8f32afe904954c22f5d8d3e0dd4883b16165cd5" + }, + "platforms/macos/Tests/CMOCBuildHistoryTests.swift": { + "bytes": 8470, + "mode": "0644", + "sha256": "97973847ad1145732fc35b7026e65b943e59810be28a2c3001acf6d5f362880e" + }, + "platforms/macos/Tests/CMOCBuildServiceTests.swift": { + "bytes": 149570, + "mode": "0644", + "sha256": "e0fe976afa12b0b97f4eef8f4116e41f50e9e0114b186932190df2add02afff4" + }, + "platforms/macos/Tests/CMOCCallStackIntegrationTests.swift": { + "bytes": 12319, + "mode": "0644", + "sha256": "38594e9441d16d1ea63f1f5f43e1f4444ccdf8121e579b8b038103075472b864" + }, + "platforms/macos/Tests/CMOCCallStackTests.swift": { + "bytes": 9964, + "mode": "0644", + "sha256": "dbe6cc0da89614d7d755a94e75ca03b446fb96a1217299d9fa409016dcb6bff3" + }, + "platforms/macos/Tests/CMOCCompletionEditorTests.swift": { + "bytes": 5589, + "mode": "0644", + "sha256": "3562f3d9b579294e1e7cd65ae9e13afee634a4c6042c02b6a4ca7736ef3b1814" + }, + "platforms/macos/Tests/CMOCCompletionTests.swift": { + "bytes": 10315, + "mode": "0644", + "sha256": "a1656f6158d41493b493fd3824a635a4cf6d490fa843c7dd9347d3119f584fc5" + }, + "platforms/macos/Tests/CMOCDevelopmentTests.swift": { + "bytes": 51528, + "mode": "0644", + "sha256": "c85c2f2fe3d0a87a818aaa6fdd75df87ec3c2114cc57ac96dbb6f43578119b11" + }, + "platforms/macos/Tests/CMOCEditingTests.swift": { + "bytes": 5773, + "mode": "0644", + "sha256": "540a91eac826b221474dd5f5399399912a1b34bef2c53796ff6dcc566d5edaa1" + }, + "platforms/macos/Tests/CMOCFloatingPointIntegrationTests.swift": { + "bytes": 10878, + "mode": "0644", + "sha256": "f76cc0654177efb69e3f45de6b4346eaf2411b2caf1f90dfecf8a2902b10fe15" + }, + "platforms/macos/Tests/CMOCFloatingPointTests.swift": { + "bytes": 5908, + "mode": "0644", + "sha256": "736be95e30df938461fa3b5bd410ba560e7f7db23de5e2061589301c4fa862f6" + }, + "platforms/macos/Tests/CMOCImportedProjectTests.swift": { + "bytes": 14393, + "mode": "0644", + "sha256": "5ba6d00f3e2270a0a75b0a0dc7d0a3f1f7e458c8bbd1452a7fbccdef4822c197" + }, + "platforms/macos/Tests/CMOCNavigationTests.swift": { + "bytes": 22825, + "mode": "0644", + "sha256": "049b38ed90d114e7383f8a00d8fae0f79d9821c2989f839b84147a9067ced453" + }, + "platforms/macos/Tests/CMOCOwnedCallContextTests.swift": { + "bytes": 15332, + "mode": "0644", + "sha256": "1176189ab7fb8843aed00057ccc0264d1a0fb7ed2eef507d7895b7e17db5c9d1" + }, + "platforms/macos/Tests/CMOCProjectIndexTests.swift": { + "bytes": 15971, + "mode": "0644", + "sha256": "e0ae767ec06aafc7ab87d2a066bb7e22af926cac6a54f647f1b73906adca1953" + }, + "platforms/macos/Tests/CMOCProjectInputTests.swift": { + "bytes": 9537, + "mode": "0644", + "sha256": "552c2f3f15bcacd9dc8c784a7b6de179629e16a68368d1f1cd78b6240d5ecaa7" + }, + "platforms/macos/Tests/CMOCSourceDebugTests.swift": { + "bytes": 19851, + "mode": "0644", + "sha256": "5ad14f4c620211c331c984fcd9e3a6eb4d34c01c348cef73a58cbe6e702af24e" + }, + "platforms/macos/Tests/CMOCSourceMapTests.swift": { + "bytes": 79239, + "mode": "0644", + "sha256": "9d6dd01b851c0e4ad5572f492f1b177eb22b0b9beb55a49224c684047702b5e1" + }, + "platforms/macos/Tests/CMOCVariableDebugTests.swift": { + "bytes": 41433, + "mode": "0644", + "sha256": "953e7da020ee55676a5afc666f1b10042ccff56cbd3a6f89771db4b04a8b3a7c" + }, + "platforms/macos/Tests/CMOCVariableTreeIntegrationTests.swift": { + "bytes": 12880, + "mode": "0644", + "sha256": "a7d3256e81b08619a8b99a0fae8c49d68d8a5e4868ea1c13aee5c3e6e3312583" + }, + "platforms/macos/Tests/CMOCVariableTreeTests.swift": { + "bytes": 10128, + "mode": "0644", + "sha256": "2990e60392219dabb9c45957f5db2732f343351c31d7829cb9093fb7b3758af7" + }, + "platforms/macos/Tests/CMOCWorkflowHardeningTests.swift": { + "bytes": 13530, + "mode": "0644", + "sha256": "a92932f0f937b3af6811fce44b2441cb4904210527ccf03650fb098657706b7b" + }, + "platforms/macos/Tests/CMOCWorkspaceRecoveryTests.swift": { + "bytes": 15617, + "mode": "0644", + "sha256": "25aa309ba9f7333072a0909ba7b4c4afb60be3c7d75dd8490570ac55526d7c86" + }, + "platforms/macos/Tests/CartridgePersistenceTests.swift": { + "bytes": 26433, + "mode": "0644", + "sha256": "cc40d5daa5537c8014c281bc16759a78ea13d5a764401645f77eec1e7787a5e4" + }, + "platforms/macos/Tests/CartridgeTests.mm": { + "bytes": 16558, + "mode": "0644", + "sha256": "1a9ee88ad9ca233e1bf5a2fd6d08af6b41390e106212a6bc1d9462793a99c150" + }, + "platforms/macos/Tests/CompanionLibraryTests.swift": { + "bytes": 5740, + "mode": "0644", + "sha256": "05be728de65ea63b20d06df43622153963d76e807c9e4eb9999a880732eec15f" + }, + "platforms/macos/Tests/CompanionStartupTests.swift": { + "bytes": 3016, + "mode": "0644", + "sha256": "72cbc56cb897dd7fb338b7ee98f3e0764b3988f944de00f78ecdf44b24ef7af6" + }, + "platforms/macos/Tests/ControllerTests.mm": { + "bytes": 43081, + "mode": "0644", + "sha256": "9ae361843b9fccbbe9ec9493004bcb3e259f8f0ff7eb11ac674be1e448cd7796" + }, + "platforms/macos/Tests/CoreTests.mm": { + "bytes": 12944, + "mode": "0644", + "sha256": "39ad3cf3b69a086b22285fd2847b013b1e82d9fd5cf8a088e81be73a7c394078" + }, + "platforms/macos/Tests/DebugSourceTests.swift": { + "bytes": 8860, + "mode": "0644", + "sha256": "b99a63ffac0e336e36d4ca6f59a331d1ed0c65a3f98d9c0d6e7270140b601196" + }, + "platforms/macos/Tests/DebuggerCoreTests.mm": { + "bytes": 17455, + "mode": "0644", + "sha256": "4c9b34e91a56c4a2b6d1404a82aff54616cbc553419926fb2484b70ecf6d9356" + }, + "platforms/macos/Tests/DebuggerMMUBridgeTests.swift": { + "bytes": 8386, + "mode": "0644", + "sha256": "4d29d5d84079e561a89a23cc079abe3e753f9b6ffd58a9fb9ab18d3c614cf370" + }, + "platforms/macos/Tests/DebuggerMemoryModelTests.swift": { + "bytes": 5866, + "mode": "0644", + "sha256": "2a75cb58ace0939193a1f314cd949253b381716f979f2a27b68ffecf53806d10" + }, + "platforms/macos/Tests/DebuggerMemoryTests.mm": { + "bytes": 8158, + "mode": "0644", + "sha256": "02919659a108f4abaad23b0b45491ff162b52e7155c4727e906dea73cdb94154" + }, + "platforms/macos/Tests/DebuggerMemoryToolsTests.mm": { + "bytes": 4921, + "mode": "0644", + "sha256": "a781e5ac301a3a9dadd942646913a1d0e8a62a0633aed3a9ada1892ee9ffd241" + }, + "platforms/macos/Tests/DebuggerModelTests.swift": { + "bytes": 7328, + "mode": "0644", + "sha256": "b1eab5b7ae844bbd3fb0bfb1534599a841df377f295281a7fc6252da3da4dfe0" + }, + "platforms/macos/Tests/DebuggerTFMTests.mm": { + "bytes": 5142, + "mode": "0644", + "sha256": "c27ba55f05573c2cf4d2d17d941bb956204055aebe86f1bd0a7b4b98259e90e4" + }, + "platforms/macos/Tests/DebuggerTests.swift": { + "bytes": 6132, + "mode": "0644", + "sha256": "bb0824d407ccf1b7d507108375590eb3459cb9748eaec754aca649f793bdac95" + }, + "platforms/macos/Tests/DebuggerTraceBridgeTests.swift": { + "bytes": 6745, + "mode": "0644", + "sha256": "e3e78430ad22534768959d076b32db7c0cf6cd922f35e15d4d4032bb497c3794" + }, + "platforms/macos/Tests/DebuggerTraceTests.mm": { + "bytes": 7828, + "mode": "0644", + "sha256": "7a86939125de153989a556c22258aacc18954fe03d37f0bc8e88f0d50af40e71" + }, + "platforms/macos/Tests/DisassemblerTests.mm": { + "bytes": 5598, + "mode": "0644", + "sha256": "e64e279313c23273ab70994135fc81eb9d21fe5d428d2ae245809906ef811201" + }, + "platforms/macos/Tests/DiskAutosaveTests.swift": { + "bytes": 15938, + "mode": "0644", + "sha256": "a60e9a40cc244905d817c2a477e2aeb912323378bdadfd4a515729b3b669fca7" + }, + "platforms/macos/Tests/DiskEditorSafetyTests.swift": { + "bytes": 70640, + "mode": "0644", + "sha256": "428ec7a8aa389b70e62818c8fa7b451b0ea40f3bb4d22d94046421ab33da6955" + }, + "platforms/macos/Tests/DiskImageBackendTests.swift": { + "bytes": 48782, + "mode": "0644", + "sha256": "052a60d341c0449293e1ca19ff21608f895399876743af7d080c489d667f92e3" + }, + "platforms/macos/Tests/DiskPersistenceTests.swift": { + "bytes": 14621, + "mode": "0644", + "sha256": "aa2e8fca4869d40b694bb871075f5764b3835edfda44443fb87fd6b8d0f77f75" + }, + "platforms/macos/Tests/Fixtures/DiskEditor/DECB.dsk": { + "bytes": 161280, + "mode": "0644", + "sha256": "f5a0b01e90d3903951327ef862500615278d07b2e143f4b159a5ea27f8f31a50" + }, + "platforms/macos/Tests/Fixtures/DiskEditor/OS9.dsk": { + "bytes": 161280, + "mode": "0644", + "sha256": "1a122760b62853a9d79b35b48ad2d750c83a22784d256f855e08f604b7615c51" + }, + "platforms/macos/Tests/Fixtures/MCPDevelopment/Makefile": { + "bytes": 1251, + "mode": "0644", + "sha256": "ff87bd596ca34ffa768f88614aeacd36c1c1e3fed02dd6eb49edaf49b095c5cf" + }, + "platforms/macos/Tests/Fixtures/MCPDevelopment/export_debug.py": { + "bytes": 4923, + "mode": "0644", + "sha256": "40b705dcb6a33a23771eaba8e9677137bb918961a95731a974bb9872afac876e" + }, + "platforms/macos/Tests/Fixtures/MCPDevelopment/main.c": { + "bytes": 3403, + "mode": "0644", + "sha256": "a1bcb34dba7043cf22501d96238c5f03f8a14109280e33d37bdb5fcbcf3c2f9b" + }, + "platforms/macos/Tests/Fixtures/MCPDevelopment/vccplus-project.json": { + "bytes": 558, + "mode": "0644", + "sha256": "163a74e14d3225547a2d9f0ba32bc3a53e01a1bee565d9cc2f7b18d817239de3" + }, + "platforms/macos/Tests/Fixtures/MCPProjectEvidence/Makefile": { + "bytes": 777, + "mode": "0644", + "sha256": "3ea3450abf91690244fba2aa46b67328ddfed9a190bc22153ccf6eac800eadc4" + }, + "platforms/macos/Tests/Fixtures/MCPProjectEvidence/main.c": { + "bytes": 1025, + "mode": "0644", + "sha256": "f5795e766bf0e8c0ab2d48288aca02f711f60d86e25fb50c2fb48304cd0c67aa" + }, + "platforms/macos/Tests/Fixtures/MCPProjectEvidence/vccplus-project.json": { + "bytes": 473, + "mode": "0644", + "sha256": "fefb433b2484861cbd551e5ba338cd248df27f7bcfa5618e49d56815f089a8da" + }, + "platforms/macos/Tests/Fixtures/ManualC/announcer.c": { + "bytes": 2648, + "mode": "0644", + "sha256": "93fe5d90fb392e18c3e95756fa079c2579a2da88c77fec52b78f57d70369aabe" + }, + "platforms/macos/Tests/Fixtures/ManualC/atlas.c": { + "bytes": 4538, + "mode": "0644", + "sha256": "863167b851cfa752d9b90f8dadba80206025d25417e94c1fc03be67f3f251e79" + }, + "platforms/macos/Tests/Fixtures/ManualC/atlasbackup.c": { + "bytes": 4279, + "mode": "0644", + "sha256": "9ce1bb2dc37d8bae0ad0b8e29f7273db47e25cc88979fbb882b9f7420f939ee0" + }, + "platforms/macos/Tests/Fixtures/ManualC/crew.c": { + "bytes": 1162, + "mode": "0644", + "sha256": "885e2af919dc53d5f4dfafa1232025a850cb9c49ee3bbc611a9a775b0c3de050" + }, + "platforms/macos/Tests/Fixtures/ManualC/descent.c": { + "bytes": 1345, + "mode": "0644", + "sha256": "a839e3add755efbebfeb3a046f686c8a5c4ed619c52569a87208e82c7ea412c2" + }, + "platforms/macos/Tests/Fixtures/ManualC/fieldlog.c": { + "bytes": 1564, + "mode": "0644", + "sha256": "12bdafe3f77909facc7c107299f6c0a9b845a0043cf414eb5b211210bd619412" + }, + "platforms/macos/Tests/Fixtures/ManualC/flightrecorder.c": { + "bytes": 1583, + "mode": "0644", + "sha256": "8e92d1cd4b8fb3439fc4da51e448b4e931920ed4766b560798b383bc789ac72f" + }, + "platforms/macos/Tests/Fixtures/ManualC/flightreport.c": { + "bytes": 1100, + "mode": "0644", + "sha256": "2105e8f3a9c10d0cc6cd76658c78963cf5d19c6ac98c88e1ac30adc55cfac059" + }, + "platforms/macos/Tests/Fixtures/ManualC/flyby.c": { + "bytes": 2593, + "mode": "0644", + "sha256": "32ae1610426665b80c7ceafde6e32621362e763392e7fc96f52cd222f759418b" + }, + "platforms/macos/Tests/Fixtures/ManualC/lander.c": { + "bytes": 4146, + "mode": "0644", + "sha256": "34a67ddf0acd8e6c10c338d080e06afb12a219d3979015c34df9a81547356a61" + }, + "platforms/macos/Tests/Fixtures/ManualC/probe.c": { + "bytes": 4383, + "mode": "0644", + "sha256": "11e59716854af3d25649bb7088b2c08dd1e37a258335596eac6c62f2fb53b22d" + }, + "platforms/macos/Tests/Fixtures/ManualC/returntrip.c": { + "bytes": 2759, + "mode": "0644", + "sha256": "7adb266b8eb648d841eb7592fd55ab356ea9c2eeadd9953e26bd928a80ff87a4" + }, + "platforms/macos/Tests/Fixtures/ManualC/ridge.c": { + "bytes": 4650, + "mode": "0644", + "sha256": "fe072e355c4807ec870ba2db291844ad99923f6e14fc2da9281a8a804b1e29bd" + }, + "platforms/macos/Tests/Fixtures/debugger-source.lst": { + "bytes": 1344, + "mode": "0644", + "sha256": "0dd07b09508112c0c7c211b1f12ea8d99f8dec328b0b0023690a01e1c4c9eb44" + }, + "platforms/macos/Tests/Fixtures/two-page-pmode.bas": { + "bytes": 243, + "mode": "0644", + "sha256": "daeee41d0f4045567a60279e78d5ecfdf806a1ec0ec7b89e6c5b0460a2fd6083" + }, + "platforms/macos/Tests/HardDiskCoreTests.mm": { + "bytes": 8605, + "mode": "0644", + "sha256": "8a37eafe68dac14614b97bf151cd62edbfd44a78a3f774ca6321f3ad630c44b3" + }, + "platforms/macos/Tests/HardDiskTests.swift": { + "bytes": 20454, + "mode": "0644", + "sha256": "52efc5e07e18f781d34b27796a646f19b55c71fca943102f8043897dfada2542" + }, + "platforms/macos/Tests/InputTests.swift": { + "bytes": 19709, + "mode": "0644", + "sha256": "9fa057bfd3c007ef619917ecec21b18085224a872828ee91bead670e47c41bea" + }, + "platforms/macos/Tests/InterfaceTests.swift": { + "bytes": 31328, + "mode": "0644", + "sha256": "bbde253bc363d171cb9698d265a77eec416d138319a9c2f436f81f8a0d0f8c35" + }, + "platforms/macos/Tests/MCPArchiveAccessTests.swift": { + "bytes": 6480, + "mode": "0644", + "sha256": "eb0bc1ed6da4e567afc3418ea292ed3f2e879528d4a46a8dfdd62ca99f78d8de" + }, + "platforms/macos/Tests/MCPCallContextAccessTests.swift": { + "bytes": 35768, + "mode": "0644", + "sha256": "7018a9d03b0abf2b7c6e8d4f761f62ec9aba3ee3a4dabf3581b24317ee28ea61" + }, + "platforms/macos/Tests/MCPDebuggerInspectionTests.swift": { + "bytes": 14009, + "mode": "0644", + "sha256": "c497f8320f7a6964341cec13ea09ed62a1d4eead032f0b258e57275707b2ad19" + }, + "platforms/macos/Tests/MCPPlaytestTests.swift": { + "bytes": 134554, + "mode": "0644", + "sha256": "5747d44d65ee1cfd2d6fccae471513e92765bc349184c7cee09e616fbaec2da9" + }, + "platforms/macos/Tests/MCPProjectRefreshTests.swift": { + "bytes": 17605, + "mode": "0644", + "sha256": "3f2cd52c67a593e1ed985a23f89f69886225a8eb518b3542fcfd66f56646cc3f" + }, + "platforms/macos/Tests/MachineSettingsTests.swift": { + "bytes": 11666, + "mode": "0644", + "sha256": "5a2d7d81efa46889368b5021fa0b1f5d5818653518e7aae745a1bc78fa4b053a" + }, + "platforms/macos/Tests/ManualPageFindTests.swift": { + "bytes": 2824, + "mode": "0644", + "sha256": "4b81b2a2722394c2eaaa2f10f775eb8ba63f112fbb10ae6282990b8b184bff5a" + }, + "platforms/macos/Tests/MemoryToolsModelTests.swift": { + "bytes": 3326, + "mode": "0644", + "sha256": "3fce4d651d63be0c33bfb9e5f1e5eb322cca61b55d33e5a4014818ebe8a1169b" + }, + "platforms/macos/Tests/NativeTests.swift": { + "bytes": 23663, + "mode": "0644", + "sha256": "6c691f8d291dc25e9e09b59ea55645bab731eecf51870fb1d95cb2a5682851a7" + }, + "platforms/macos/Tests/ProfileTests.swift": { + "bytes": 17874, + "mode": "0644", + "sha256": "3e8c33463d7a2b2cc94749cd8af07eb1ab7e034525860be3997b5aba12584745" + }, + "platforms/macos/Tests/SDCBridgeTests.swift": { + "bytes": 4157, + "mode": "0644", + "sha256": "a7b42ed92bac6873f7602c8d4a0f1a2f33cd2f1ad1d28ffe5451d3674b6d8ccd" + }, + "platforms/macos/Tests/SDCCoreTests.mm": { + "bytes": 13692, + "mode": "0644", + "sha256": "505f2063cbb3ef2099e25f859b33ae74e27a0afe411ef6a6acfa2c3f5d362da7" + }, + "platforms/macos/Tests/SDCPersistenceTests.swift": { + "bytes": 7458, + "mode": "0644", + "sha256": "f3e16adaf60235397336bf38a6264d663601a3e0445e5848614c55e69afe4b76" + }, + "platforms/macos/Tests/SoftwareLibraryArchiveTests.swift": { + "bytes": 8557, + "mode": "0644", + "sha256": "27684911f98896f350c879da914d8946860718be5c427a6a1ff3a60ba23dddd9" + }, + "platforms/macos/Tests/SoftwareLibraryArtworkTests.swift": { + "bytes": 12213, + "mode": "0644", + "sha256": "f97bdb49891728cd4884d56a4fa544aeb91d49f0091be89c301a1857e735d126" + }, + "platforms/macos/Tests/SoftwareLibraryBrowseTests.swift": { + "bytes": 22529, + "mode": "0644", + "sha256": "ddac708066479e2d0f50aa0732a442f5e7a61caa50f8ea1f3efae2f4686f12eb" + }, + "platforms/macos/Tests/SoftwareLibraryCuratedLaunchTests.swift": { + "bytes": 17902, + "mode": "0644", + "sha256": "1bd5ec49b060961817af7cc44b66ad5c1dbb94c9f23e0765eec3fcaa4cb8cd8d" + }, + "platforms/macos/Tests/SoftwareLibraryInstallerTests.swift": { + "bytes": 13321, + "mode": "0644", + "sha256": "26c94028fbe3ad421b2fc1d173f9c147942a7ebe09df201c399f366428efb1fe" + }, + "platforms/macos/Tests/SoftwareLibraryLaunchPlanTests.swift": { + "bytes": 16889, + "mode": "0644", + "sha256": "7f86b0cfa4538aff03e06346038175229b423d2b27f590fe3787aa44b2e65268" + }, + "platforms/macos/Tests/SoftwareLibraryMachineLaunchTests.swift": { + "bytes": 23901, + "mode": "0644", + "sha256": "21053ce1c90567242811ae72860ae2c74f9598952d518fd37ce9c12c826d721b" + }, + "platforms/macos/Tests/SoftwareLibraryManualTests.swift": { + "bytes": 9575, + "mode": "0644", + "sha256": "a8cb39a16209f5d4e50bf59d08e3d1a1e69beadc2ca408b190fa6a5c0dec75c8" + }, + "platforms/macos/Tests/SoftwareLibraryPublishedGameTests.swift": { + "bytes": 29275, + "mode": "0644", + "sha256": "5516783ed1333b1350d6618d35ba81b58caaa3e602bb5c90249ee8ccc2831a12" + }, + "platforms/macos/Tests/SoftwareLibrarySourceImporterTests.swift": { + "bytes": 14990, + "mode": "0644", + "sha256": "456c6002ba0bf0047a68f37ba0af04a5f63936e27a4e7676450e308647ab7321" + }, + "platforms/macos/Tests/SoftwareLibraryTests.swift": { + "bytes": 30622, + "mode": "0644", + "sha256": "33521d88857c6f033cdcb1e90d4f1cabdbaa32b482b97e4cb34c6d65e1e7fb0d" + }, + "platforms/macos/Tests/SourceFindTests.swift": { + "bytes": 25621, + "mode": "0644", + "sha256": "15b8a2b63f510a9617bf7930f9d15907c152d60beaeb74a4b38719a1b4d4de93" + }, + "platforms/macos/Tests/StartupTests.swift": { + "bytes": 46268, + "mode": "0644", + "sha256": "66fdad573aa6cef00e8c2f59bae630fca74e29d9f2efc07cf70c1533293bc55a" + }, + "platforms/macos/Tools/MCP/MCPGuestTools.h": { + "bytes": 2219, + "mode": "0644", + "sha256": "85c13429e98581b679c8410b03724860fedf00de962de63bea3b19e165ec6a3c" + }, + "platforms/macos/Tools/MCP/MCPProjectTools.h": { + "bytes": 24058, + "mode": "0644", + "sha256": "f41a931a11bc77464e260f973afd84820a619b6c30abacee343ba879bae40ec2" + }, + "platforms/macos/Tools/MCP/main.mm": { + "bytes": 34960, + "mode": "0644", + "sha256": "433b87264f4bd7b29cc598f38a56e698e5cd5583a210ef2eb06b680184dcf3d7" + }, + "platforms/macos/Tools/MCP/test-helper.py": { + "bytes": 69972, + "mode": "0644", + "sha256": "ce1aca493fc34683852f112394b88606e4f27807f098ec3a785c4601a43b8d52" + }, + "platforms/macos/Tools/Playtest/main.mm": { + "bytes": 44495, + "mode": "0644", + "sha256": "bea1178f6ac9bef7c8a0d43cabfa4cc1bcf623a471b2c3229d59b4cca2747eb7" + }, + "platforms/macos/Tools/bundle-manual-library.py": { + "bytes": 4772, + "mode": "0644", + "sha256": "272e4b4ecbcf677b00a237c64c65b807c11df95c2f0e85c02d60c6a21bd0ce1d" + }, + "platforms/macos/Tools/make-orchestra-label.swift": { + "bytes": 5212, + "mode": "0644", + "sha256": "6a250f3d1a35a6c8248090a3864a5f4ac79886272c8916beb5eaf31872c3aff9" + }, + "platforms/macos/Tools/make-os9-data-header.py": { + "bytes": 1837, + "mode": "0644", + "sha256": "d2868aab0267cb7c4bb95f3f0f53e63c298f31f8717e9a692b7befb8b9f45cbf" + }, + "platforms/macos/Tools/make-printer-badge.swift": { + "bytes": 5059, + "mode": "0644", + "sha256": "1935ec8e0651fec0d75e04356cd439a5e7768aba92f5eec014a94973928db7bd" + }, + "platforms/macos/Tools/make-tp10-printer.py": { + "bytes": 3776, + "mode": "0644", + "sha256": "34ba8b1e274a5a3925e3445045a8bedd7886cb13fafc10e7efa21c2d90b85e29" + }, + "platforms/macos/Tools/prepare-about.py": { + "bytes": 1249, + "mode": "0644", + "sha256": "62e2ac19dd31a311934e913076f4017cb6c030a3e2e655f683b749dfc8a8c247" + }, + "platforms/macos/Tools/prepare-development-templates.py": { + "bytes": 2624, + "mode": "0644", + "sha256": "a03163ef3c20bf556f51a2ff35415712070452f1843bf0edce2db95d642e059f" + }, + "platforms/macos/Tools/prepare-hardware.py": { + "bytes": 21115, + "mode": "0644", + "sha256": "d513a2f2f74611b8cfd05dac520ad23956d432bad84bab75f5d3b81af39f2fc2" + }, + "platforms/macos/Tools/prepare-nitros9.py": { + "bytes": 9898, + "mode": "0644", + "sha256": "e89c62748e14b121426cb98204d7b4fef9ee2ba6189e10b905b3f7e355720f64" + }, + "platforms/macos/Tools/prepare-toolchain.py": { + "bytes": 6804, + "mode": "0644", + "sha256": "b19428b17e91214ba5b36c9d6a1bce8143828e699d56f405b3df00c2568279f6" + }, + "platforms/macos/Tools/test_development_templates.py": { + "bytes": 3217, + "mode": "0644", + "sha256": "603a1ba40e55e094786c298b17137879ca3255098fcbdc49fbc4c2af25de01da" + }, + "platforms/macos/Tools/update-fd502-artwork.py": { + "bytes": 4174, + "mode": "0644", + "sha256": "2c86f35bc0d0d0f898583a4bc8f1dc5004ac065b2f55df41976cd50e90533c97" + }, + "platforms/macos/UITests/InteractionTests.swift": { + "bytes": 295365, + "mode": "0644", + "sha256": "b45abb2d13fa0c7301230299f0459f966ab8869a5ca381dda1b74811ee2ab439" + }, + "platforms/macos/VCC.xcodeproj/project.pbxproj": { + "bytes": 175127, + "mode": "0644", + "sha256": "e770d37c41d2b7ee1c746a347282ced40ebc2a2a3dc8d5abb0ad3e181ef1f868" + }, + "platforms/macos/VCC.xcodeproj/xcshareddata/xcschemes/VCCCoreChecks.xcscheme": { + "bytes": 2337, + "mode": "0644", + "sha256": "1a6c3863d4e4494202fb9702e6c86e4a500f507e03276788bfe997a2f1e03278" + }, + "platforms/macos/VCC.xcodeproj/xcshareddata/xcschemes/VCCMac.xcscheme": { + "bytes": 2325, + "mode": "0644", + "sha256": "0fc8e048b6c0dbbe492138283e74e67b167ae27f03bb60e89995ddf697fdc3db" + }, + "platforms/macos/VCC.xcodeproj/xcshareddata/xcschemes/VCCUITests.xcscheme": { + "bytes": 2446, + "mode": "0644", + "sha256": "41bc86e0fc2acff458cac416a88a2ad8ac79669fa0d9e18b4f7773535a90d582" + }, + "platforms/windows/Audio.cpp": { + "bytes": 10080, + "mode": "0644", + "sha256": "596067306df511798bd2ae9564179245c9e0416e18c4c2db877b8dc0ab593f9d" + }, + "platforms/windows/Build.bat": { + "bytes": 347, + "mode": "0644", + "sha256": "ee40aaad619bfd71319086a6713913ea41dd9fa8b307a8b29fef0f7fc8f3533a" + }, + "platforms/windows/BuildAll.bat": { + "bytes": 423, + "mode": "0644", + "sha256": "5190860cd1e155f81c9b23d66b87073d711cfd07d028ca46634fbe349f72a909" + }, + "platforms/windows/BuildClean.bat": { + "bytes": 292, + "mode": "0644", + "sha256": "a6a02a78886511c016664b7289c4056cbf629b4017ff9877d4ec009cf947607a" + }, + "platforms/windows/Cassette.cpp": { + "bytes": 15743, + "mode": "0644", + "sha256": "a653cb3834691fa4ad487356544c80284d81f5cc4344ea8c0fc72fbc0eb7cab8" + }, + "platforms/windows/Cassette.h": { + "bytes": 1759, + "mode": "0644", + "sha256": "1a1c102296515a29e9359fe5e70852463cfb0ba6ea5e02b801a41a975a259a6a" + }, + "platforms/windows/CommandLine.cpp": { + "bytes": 10766, + "mode": "0644", + "sha256": "e552034742b17429f425124e0224ac9d147f949a507f7f345b055377e18c1957" + }, + "platforms/windows/CommandLine.h": { + "bytes": 1867, + "mode": "0644", + "sha256": "caa2f14149f9765ed1e52c7eea07d5a182b6e5778dad47f155095d85f46e64bc" + }, + "platforms/windows/CopyFiles.bat": { + "bytes": 349, + "mode": "0644", + "sha256": "45dde24f379b1e706d5c412d25eef45564deca47041327516d157bc48108e845" + }, + "platforms/windows/Debugger.cpp": { + "bytes": 11102, + "mode": "0644", + "sha256": "9714dd6b895942316f1daca7fcd12d08199a6244980d1171252e2b7dd0093623" + }, + "platforms/windows/Debugger.h": { + "bytes": 5813, + "mode": "0644", + "sha256": "413d447574a2c54b0b4c049f7a62c8401f970d1c0293516eb5436ae20ecb5f58" + }, + "platforms/windows/DebuggerUtils.cpp": { + "bytes": 4017, + "mode": "0644", + "sha256": "073c782df0dd1b508b5ce8430b502da48c5ceaecf4c957092da40e6c3bdb69c6" + }, + "platforms/windows/DebuggerUtils.h": { + "bytes": 2221, + "mode": "0644", + "sha256": "868ec53226cad5655a0bfaa31864e3f9a604562577e0375e1402840c0b926690" + }, + "platforms/windows/DirectDrawInterface.cpp": { + "bytes": 16556, + "mode": "0644", + "sha256": "75cf81ea3d5f2565de224774677cec291fdc905b59593d4cffbfd549366b9e1b" + }, + "platforms/windows/DirectDrawInterface.h": { + "bytes": 1551, + "mode": "0644", + "sha256": "456a70ded18f8e4c796f7438611e31a89598cfe6bcfee18383aced6d50c927cf" + }, + "platforms/windows/DirectX.cpp": { + "bytes": 19109, + "mode": "0644", + "sha256": "8a896b926005f3f3595d969b4ed0c2076a6d38cd13a71f5582a71e1e5cbe6ac5" + }, + "platforms/windows/DirectX.h": { + "bytes": 2265, + "mode": "0644", + "sha256": "26127a8683e1d9386abdcd48652762992bc9f7511ff00c7d29a80f5832dbff45" + }, + "platforms/windows/Disassembler.cpp": { + "bytes": 38148, + "mode": "0644", + "sha256": "7821f5cc289d4ae55221c2af00ae91973a9004888fe82dd1e224dd5dbaba5525" + }, + "platforms/windows/Disassembler.h": { + "bytes": 1033, + "mode": "0644", + "sha256": "f91cbc8011d2e81dd86fa831f2db39374a18a111897a395ae8cab4002f0540f8" + }, + "platforms/windows/ExecutionTrace.cpp": { + "bytes": 44906, + "mode": "0644", + "sha256": "3b85399d9e114cd2b4b3583472b851735879ceaaac58df41edca870c03a1e163" + }, + "platforms/windows/ExecutionTrace.h": { + "bytes": 994, + "mode": "0644", + "sha256": "0eb1510fa6bcdf9ef5bc30d384a3f67315acfbcdfa2473a1f08a371c2da3a5e8" + }, + "platforms/windows/FD502/becker.cpp": { + "bytes": 9004, + "mode": "0644", + "sha256": "5f72222796bf082ed3aa1439d35edf0f8c7e084c14bd3080ce77d8431df72064" + }, + "platforms/windows/FD502/becker.h": { + "bytes": 409, + "mode": "0644", + "sha256": "3d2b2d8ad41c018883dba5df47a689a593a1e9fd75ef1e2b258b0ee67f308a9c" + }, + "platforms/windows/FD502/defines.h": { + "bytes": 1104, + "mode": "0644", + "sha256": "e1ccf94eab5bd3698e0a07c1524f62396ca6cdd1909281338314d009b96c3851" + }, + "platforms/windows/FD502/distortc.cpp": { + "bytes": 3367, + "mode": "0644", + "sha256": "abfacdd0b6ffa7f556087ce63051aa0ede050e7ea04c9a52bd5d61b2924c6e13" + }, + "platforms/windows/FD502/distortc.h": { + "bytes": 933, + "mode": "0644", + "sha256": "3e8a1840eda7df95a0e194417a10743a23ede5625c4fa41c427b96e3fcbf1da7" + }, + "platforms/windows/FD502/fd502.cpp": { + "bytes": 23551, + "mode": "0644", + "sha256": "985a968fb7b886d31914ab36244a27b7742e08ef263850dc978c264479977ec0" + }, + "platforms/windows/FD502/fd502.h": { + "bytes": 1325, + "mode": "0644", + "sha256": "0b11e47c678b2c9f7e462ca282a30698748736a99304a3e55a02749ecbcd783f" + }, + "platforms/windows/FD502/fd502.rc": { + "bytes": 6892, + "mode": "0644", + "sha256": "76a0f712018bd478fb64216160a79016dc40fc4005ad163cd31f95f5465f8afe" + }, + "platforms/windows/FD502/fd502.vcxproj": { + "bytes": 5826, + "mode": "0644", + "sha256": "77ec9f15dc5b2d0302e8208b348e8b55d3c5215de2c5cfc467763e0d6e1961df" + }, + "platforms/windows/FD502/fdrawcmd.h": { + "bytes": 11697, + "mode": "0644", + "sha256": "aab4138791ad5bd30d42c34c7955e74cc5d9fc16692b7af805f746e93680e97f" + }, + "platforms/windows/FD502/logger.h": { + "bytes": 92, + "mode": "0644", + "sha256": "1a46758c8af3678640e046249fee4085f107367c7244ed5ab0ee9b785851e480" + }, + "platforms/windows/FD502/resource.h": { + "bytes": 2318, + "mode": "0644", + "sha256": "3d3921eb6efb6ca535b615a4711ab17caca540ab913ae590e8738f44f0c06f38" + }, + "platforms/windows/FD502/wd1793.cpp": { + "bytes": 43858, + "mode": "0644", + "sha256": "b36cd832dff6467f897afc14f7c7e3db1a9506e192e8ea6871253f6b14e60ab8" + }, + "platforms/windows/FD502/wd1793.h": { + "bytes": 4549, + "mode": "0644", + "sha256": "18e54520ae8662af893240f90831c030c0ed12b574f2b3d1f174d8998820e038" + }, + "platforms/windows/GMC/Cartridge.cpp": { + "bytes": 2404, + "mode": "0644", + "sha256": "50d3c0dcfb68f1e3b631ee2c67337c2a0766746fe6bf44042035ff0f9c46f15d" + }, + "platforms/windows/GMC/Cartridge.h": { + "bytes": 1960, + "mode": "0644", + "sha256": "63fc197347112d3bb8b0486e8b3fee13e7e2ec1d30fdb7552842b1ea95577ae5" + }, + "platforms/windows/GMC/CartridgeTrampolines.cpp": { + "bytes": 2431, + "mode": "0644", + "sha256": "10cee1997242e420409fd4bcfe6e5214f113227dce4da3ff295e14f21425348f" + }, + "platforms/windows/GMC/CartridgeTrampolines.h": { + "bytes": 727, + "mode": "0644", + "sha256": "1656ab4cc2e45014cacefdc6e02a4607b30b4f696ce6b7a3ff99a22ed0d9a68b" + }, + "platforms/windows/GMC/Configuration.cpp": { + "bytes": 1080, + "mode": "0644", + "sha256": "d6a4001f12312b654fe2a06bd16a46e53d5c6df9d0f47958f248c6eaa386a5de" + }, + "platforms/windows/GMC/Configuration.h": { + "bytes": 412, + "mode": "0644", + "sha256": "09302a4b3daea2d8c5a4f3579e3e76a02f22853cd074f27c4683fa2fc3b40dec" + }, + "platforms/windows/GMC/GMC.h": { + "bytes": 335, + "mode": "0644", + "sha256": "511af901ed6b223f11b7a4610f575352d4673d652436f75d426878220129a6c5" + }, + "platforms/windows/GMC/GMC.rc": { + "bytes": 2816, + "mode": "0644", + "sha256": "9f683936de2ac31e183152556a888d24b29f60cfb61e5aa6fd8b086774352cbb" + }, + "platforms/windows/GMC/GMCCartridge.cpp": { + "bytes": 2463, + "mode": "0644", + "sha256": "0bbf55321cb08c4e1cd34b351cba3cd80672977b1d172ae33508b3ce8268cb80" + }, + "platforms/windows/GMC/GMCCartridge.h": { + "bytes": 915, + "mode": "0644", + "sha256": "a235e94fd48b853af7b480fb9d8d4a29b6ecf51a0a8da18e37d2e35d26866621" + }, + "platforms/windows/GMC/ROM.cpp": { + "bytes": 1171, + "mode": "0644", + "sha256": "f88a87902ce608e02205e9013edb226d4273bd68ec44675774eb33502657749e" + }, + "platforms/windows/GMC/ROM.h": { + "bytes": 765, + "mode": "0644", + "sha256": "5cb6dd60cb546f43dc2f58684c4452f74d18847e71e0a90a29312180218bcd16" + }, + "platforms/windows/GMC/gmc.vcxproj": { + "bytes": 5613, + "mode": "0644", + "sha256": "2798ae253e2cad4fa57f60ae95d6af07a3ddc54d4be1114a9a73cbec49f479e1" + }, + "platforms/windows/GMC/gmc.vcxproj.filters": { + "bytes": 2145, + "mode": "0644", + "sha256": "efc61510f2f90627681eccb4db9672c7c0016103e80118c2d9320dfe36be08b4" + }, + "platforms/windows/GMC/main.cpp": { + "bytes": 1821, + "mode": "0644", + "sha256": "6c0a3aac044a5fb338926f446b6d83f4cd86dd4ebbfdd05ee3dad0cc8bb08a14" + }, + "platforms/windows/GMC/resource.h": { + "bytes": 554, + "mode": "0644", + "sha256": "59107c1b0a47ead147c11ca87d1fbef6ea5445b8bbbc342266edf744139ef7e3" + }, + "platforms/windows/GMC/sn76496.cpp": { + "bytes": 13525, + "mode": "0644", + "sha256": "e024305a92213f19ca35fb121dddd98566f33f1bf0ff6952be1622b74dec9b6b" + }, + "platforms/windows/GMC/sn76496.h": { + "bytes": 1990, + "mode": "0644", + "sha256": "0b033d766eb31aeef0099b98b621c4053efd21a2fe4e3264cedff48d384dc740" + }, + "platforms/windows/HardDisk/ReadMe.txt": { + "bytes": 1620, + "mode": "0644", + "sha256": "dd7d5e37b15186da8720a2368bc5aed69a336abe464cf96c08fd29d1e77a9a1a" + }, + "platforms/windows/HardDisk/cc3vhd.cpp": { + "bytes": 8160, + "mode": "0644", + "sha256": "e212c5ae8f1e6b37e6c6b1bbd4a76ac513f786046a5e99c2683550286cbac88a" + }, + "platforms/windows/HardDisk/cc3vhd.h": { + "bytes": 1561, + "mode": "0644", + "sha256": "a6f4d608a15f77aa42989407b92ae7ae83c3bc8601c50bfd20b2d69a9ae0581c" + }, + "platforms/windows/HardDisk/harddisk.cpp": { + "bytes": 13004, + "mode": "0644", + "sha256": "63d517913033bb95afc61760c72c1e621fd92acd18dd5997416d384d3b20aa50" + }, + "platforms/windows/HardDisk/harddisk.h": { + "bytes": 932, + "mode": "0644", + "sha256": "35fe481468cc91384c2057133c66d8514aac8a5f228c0c68eac1f1db092ebbf0" + }, + "platforms/windows/HardDisk/harddisk.rc": { + "bytes": 4463, + "mode": "0644", + "sha256": "336002e4dd982dab8df3b89ef6fcca0f903ac403a9ca5031e94706982c92cbf8" + }, + "platforms/windows/HardDisk/harddisk.vcxproj": { + "bytes": 5335, + "mode": "0644", + "sha256": "638efa6721c77c4a16c192bac4605a350f1fc653ae2fd02956b2cd0a90fb8b9b" + }, + "platforms/windows/HardDisk/resource.h": { + "bytes": 1580, + "mode": "0644", + "sha256": "dec378267356cc83c8e818ef9f7f5344606ce0b8805b9b3c0e6483bc6c809a13" + }, + "platforms/windows/MMUMonitor.cpp": { + "bytes": 9484, + "mode": "0644", + "sha256": "640b3222f9c85704c0407e22f6a773fe482d0355c9fe67f08c307dada3761d50" + }, + "platforms/windows/MMUMonitor.h": { + "bytes": 1037, + "mode": "0644", + "sha256": "4baf1a34cc35122acde4d8549ea5557fd42b99fded5379e4119ffab0aeab97c1" + }, + "platforms/windows/MemoryMap.cpp": { + "bytes": 54875, + "mode": "0644", + "sha256": "96c3cdc1c82d6fbd7f5c72efcfaa05e71dfd7651e581e83125ff95cc464bc670" + }, + "platforms/windows/MemoryMap.h": { + "bytes": 4584, + "mode": "0644", + "sha256": "495effc33097defac70eac83c50be422365d6b51e0d02756425b180de6cb8575" + }, + "platforms/windows/OpCodeTables.cpp": { + "bytes": 14748, + "mode": "0644", + "sha256": "500683d5b4b8c08fdb42c572f84e927531d0df053557abec1053f95eb1f10d72" + }, + "platforms/windows/OpDecoder.cpp": { + "bytes": 10303, + "mode": "0644", + "sha256": "dfe6c99ddac283350ea3d7daa05add58834ba0cc62f1091336c6fdab784d3ec8" + }, + "platforms/windows/OpDecoder.h": { + "bytes": 2837, + "mode": "0644", + "sha256": "623376678650a9474f67ef6a6362ca797fed5ec933c5e8ab738a276c4970d232" + }, + "platforms/windows/OpenGL.cpp": { + "bytes": 25404, + "mode": "0644", + "sha256": "dd8f546d2536212ced019fb248e42a5912c91d60bee2504965e5f1a08cf14f1b" + }, + "platforms/windows/OpenGL.h": { + "bytes": 3313, + "mode": "0644", + "sha256": "33714f70cac84d03c9c8ea6745689b4588b7afcb387eb997d759e1fff061ba7f" + }, + "platforms/windows/OpenGLFont.h": { + "bytes": 1553, + "mode": "0644", + "sha256": "b42d1995bcee51b0987e7151144a58981eb9ceb1b8b5b516b00c826ebf5d38f4" + }, + "platforms/windows/OpenGLFontConsola.cpp": { + "bytes": 11341, + "mode": "0644", + "sha256": "9134b831605c3a091b6ca1e9d7bd4c3ac5505844e872f3f6ad08c0144fb10c43" + }, + "platforms/windows/OpenGLFontConsola.h": { + "bytes": 968, + "mode": "0644", + "sha256": "3a6c80af97abd59c08f04699632be9f88912924bde9e6994c404fc04ae505328" + }, + "platforms/windows/PrinterWin.cpp": { + "bytes": 2577, + "mode": "0644", + "sha256": "8b111b25eca9e3325bb42f7773d692a381b96f0429524c5be6039016a1ba6e04" + }, + "platforms/windows/ProcessorState.cpp": { + "bytes": 13434, + "mode": "0644", + "sha256": "4eee0a682ab051e5843cd8db6d36486b0bbcff423dd4e50545ba9f39c6e8f56b" + }, + "platforms/windows/ProcessorState.h": { + "bytes": 1045, + "mode": "0644", + "sha256": "bbc3cded099ff4e9eb4b1705adf337845fffa5de07ad450b288e9f9aad472874" + }, + "platforms/windows/Ramdisk/Ramdisk.cpp": { + "bytes": 2733, + "mode": "0644", + "sha256": "f0ee7a76ef07aab3793a3a19f7be7a29bc0f9bc412a4b790cdfa5daef5ff4749" + }, + "platforms/windows/Ramdisk/Ramdisk.rc": { + "bytes": 2835, + "mode": "0644", + "sha256": "5190042120cea497a4adad69d58c3a4a052da886788b9d9204437308dd16f276" + }, + "platforms/windows/Ramdisk/Ramdisk.vcxproj": { + "bytes": 5211, + "mode": "0644", + "sha256": "a7f5fc09bd8dd2db2cde2c7248094d1f90dd2ba0bf3db91bb3efb96a0c141893" + }, + "platforms/windows/Ramdisk/defines.h": { + "bytes": 497, + "mode": "0644", + "sha256": "b84b9ee3338bf72b4e600d18f95dd59c7b62cbdd86f267b48aab195840cf680d" + }, + "platforms/windows/Ramdisk/resource.h": { + "bytes": 522, + "mode": "0644", + "sha256": "46a3eb67946e558bf28d846dc5a3823459cb1420d080e1bbf08fcee1ff11c001" + }, + "platforms/windows/Screenshot.cpp": { + "bytes": 3016, + "mode": "0644", + "sha256": "97426cf4ddacd9dde6538403bc890b9b1159d38f25c3042aaa708839385102d5" + }, + "platforms/windows/Screenshot.h": { + "bytes": 1130, + "mode": "0644", + "sha256": "a1d6e65f06395ddf2ebf30b56b348874a7adfbfc7a50d6c832153e584c8cfeba" + }, + "platforms/windows/SourceDebug.cpp": { + "bytes": 17400, + "mode": "0644", + "sha256": "304abe39f7eaf35b6e97c200e5b12ce10fe372b4748a69ef665222a103c31d97" + }, + "platforms/windows/SourceDebug.h": { + "bytes": 1037, + "mode": "0644", + "sha256": "ca0b113a66e1b022dd743ef4861bd8c20c07ecbbdab3758378fd4a7d74e4a25a" + }, + "platforms/windows/SuperIDE/IdeBus.cpp": { + "bytes": 9239, + "mode": "0644", + "sha256": "4c1fd3a31fe0fa237dabd63168238ab6190954344c012af27bd8550b51a19077" + }, + "platforms/windows/SuperIDE/IdeBus.h": { + "bytes": 2323, + "mode": "0644", + "sha256": "a6c15f1976e3100e1c7ebb7da31fa5bb883829cbef592f77b8af83e4d820b878" + }, + "platforms/windows/SuperIDE/SuperIDE.cpp": { + "bytes": 10277, + "mode": "0644", + "sha256": "8fbd3a5180a6890f496128cf4f6ad2c999a85b6a9c263fe38c24b059942722f0" + }, + "platforms/windows/SuperIDE/SuperIDE.h": { + "bytes": 0, + "mode": "0644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "platforms/windows/SuperIDE/SuperIDE.rc": { + "bytes": 4038, + "mode": "0644", + "sha256": "30e2d2a15c073c4c7d7a3fad29ad6fadc043ae4050907db62bd471eb2fb6ab3b" + }, + "platforms/windows/SuperIDE/SuperIDE.vcxproj": { + "bytes": 5375, + "mode": "0644", + "sha256": "60fb3989c54a722954dee540b138088953edf184be90c28ac27f154ae1985f57" + }, + "platforms/windows/SuperIDE/resource.h": { + "bytes": 746, + "mode": "0644", + "sha256": "ca6a7d0ab7b31111b93df81c468841a8c03ca2c6ba067a643edb8e51b79a82c6" + }, + "platforms/windows/Vcc.cpp": { + "bytes": 35607, + "mode": "0644", + "sha256": "395315796013920ffb538fc1f786997175f7737e385dc13bf6c14b975355477a" + }, + "platforms/windows/Vcc.h": { + "bytes": 1613, + "mode": "0644", + "sha256": "9d069f8afd18eea773044dbb2535f795e0fff898f6bc8130c55d9e06fbef3f1b" + }, + "platforms/windows/Vcc.rc": { + "bytes": 37071, + "mode": "0644", + "sha256": "6fb7f180864f298968e04a3d6ca7599c54d8568815a3805252a4661ceeb6fcdb" + }, + "platforms/windows/Vcc.sln": { + "bytes": 8934, + "mode": "0644", + "sha256": "97f53cca6b4cfda016a6603123a1dc34bd8943eff245daba2c8831fd04f90664" + }, + "platforms/windows/Vcc.vcxproj": { + "bytes": 16481, + "mode": "0644", + "sha256": "7d0ff94ee5a23d3284f3f91c94bbcc0d99e5243a10352914f62b4e12ea1d9c90" + }, + "platforms/windows/Vcc.vcxproj.filters": { + "bytes": 12292, + "mode": "0644", + "sha256": "1c29a6cbf1142914b81baac3bba3d803f5e7770f54b1379c36a5943278fb6dbf" + }, + "platforms/windows/Vcc.vcxproj.user": { + "bytes": 162, + "mode": "0644", + "sha256": "24b3a4255f866764e90db81d7f5f6d68a114a650d4715b73ae25d93e1f0fc982" + }, + "platforms/windows/_xDebug.cpp": { + "bytes": 1259, + "mode": "0644", + "sha256": "959f03e20d77a5ad7d0d5106bab3c709cac7bea58558f5308f54cbd323a11b62" + }, + "platforms/windows/acia/ReadMe.txt": { + "bytes": 14593, + "mode": "0644", + "sha256": "6c76dc8419503a0ba758b133bc214215dfbf5cbd27df13322cd4cb588b140e0c" + }, + "platforms/windows/acia/acia.cpp": { + "bytes": 19618, + "mode": "0644", + "sha256": "679cc71981ca5c3353d8049ed4068d2e3798c19d359c82f3e50e317eb8757148" + }, + "platforms/windows/acia/acia.h": { + "bytes": 3411, + "mode": "0644", + "sha256": "5b4c9ef9f26633c064ddeefe03456ee455250d08cbda681ba9f988c77bbe661b" + }, + "platforms/windows/acia/acia.rc": { + "bytes": 4288, + "mode": "0644", + "sha256": "16d72613693bb7030bd4024bb29dc807d59315cb608d3fbee5a1d11f9ea29df1" + }, + "platforms/windows/acia/acia.vcxproj": { + "bytes": 6879, + "mode": "0644", + "sha256": "96ced843cc70257f67f68e14acffef824f03a72b91cde9afa67e01cdb62b1869" + }, + "platforms/windows/acia/console.cpp": { + "bytes": 19761, + "mode": "0644", + "sha256": "b2813bc68ee44dacb2ad1d86be5bcaae853511a3bd5245b4d3fe72c3f14d9b13" + }, + "platforms/windows/acia/file.cpp": { + "bytes": 4075, + "mode": "0644", + "sha256": "ebc3ce8641187c07ade782d0cfaeb1b8bc300727399a9f1280b20e76580efbee" + }, + "platforms/windows/acia/resource.h": { + "bytes": 1096, + "mode": "0644", + "sha256": "7e583780ba44728bab298c2adc3387c639594ad54a6f12aa86bdad3652dd0f73" + }, + "platforms/windows/acia/sc6551.cpp": { + "bytes": 10220, + "mode": "0644", + "sha256": "d746102635745b16a23c761461ee4ee04c7ba0ed9d74f1dcb6fb9b48bec59681" + }, + "platforms/windows/acia/sc6551.h": { + "bytes": 2519, + "mode": "0644", + "sha256": "14c6a725a1d2d2d6879ab148d471883e6b4b7608624f91918761b1926b79cd0d" + }, + "platforms/windows/acia/tcpip.cpp": { + "bytes": 3711, + "mode": "0644", + "sha256": "8170fefcd73ec7c5760b81a39a66c6afdf8589ccea18aa74b8f893622295e432" + }, + "platforms/windows/acia/wincom.cpp": { + "bytes": 6004, + "mode": "0644", + "sha256": "5bb09c9371415c1fda3c646800c63feca16b4dd9455d6c57a0325528f0300232" + }, + "platforms/windows/audio.h": { + "bytes": 1263, + "mode": "0644", + "sha256": "54696660e27ae75b070f99b310d0c6b446f674f1313713e97dfa1e61b7f781bd" + }, + "platforms/windows/becker/becker.cpp": { + "bytes": 16710, + "mode": "0644", + "sha256": "57af6d1ea85697160262a9f3142432e1ae46d1142eecab1e27c2357df22c517f" + }, + "platforms/windows/becker/becker.h": { + "bytes": 397, + "mode": "0644", + "sha256": "65737c02a0a16383916c919fbcafcbd94ba44e36f7829747d2cf8a1a884ab399" + }, + "platforms/windows/becker/becker.rc": { + "bytes": 3776, + "mode": "0644", + "sha256": "fd6fd58451cc58935c7e763b1605735de9f79747c95f87bd5657d0beb65a8bc8" + }, + "platforms/windows/becker/becker.vcxproj": { + "bytes": 6698, + "mode": "0644", + "sha256": "bde343f9d1bcff6deabc2c8acb639a85e3e1ccd753648da16780f2066e4a64a4" + }, + "platforms/windows/becker/resource.h": { + "bytes": 697, + "mode": "0644", + "sha256": "b1b2a17efd2841fed991366d0e15434d9106c275c01e6335aa97d58377c1ef3e" + }, + "platforms/windows/coco3.cpp": { + "bytes": 37624, + "mode": "0644", + "sha256": "cd3179a0517dde001bf21086d7768d4e8cc9c2dfc112ef4906d4d4e476d570f3" + }, + "platforms/windows/coco3.h": { + "bytes": 1583, + "mode": "0644", + "sha256": "8df833c5ed38e866e679b10bbe31cf04ef1c093105822c48624570cd0ab76b87" + }, + "platforms/windows/config.cpp": { + "bytes": 61232, + "mode": "0644", + "sha256": "605405db229d8bf6e25fe1404e21fe55f2ac77bdb9464f622d9aef6d336ddaa2" + }, + "platforms/windows/config.h": { + "bytes": 2243, + "mode": "0644", + "sha256": "ad5c7bb2e3f1dffba86b23c133483fbe714903771c98d161e16235232f811949" + }, + "platforms/windows/defines.h": { + "bytes": 5667, + "mode": "0644", + "sha256": "c10a15d7831d64dc2925f264bced0f8af03d27a6fb808b7ba5391f9a17ae9309" + }, + "platforms/windows/joystickinput.cpp": { + "bytes": 16853, + "mode": "0644", + "sha256": "4a602bd536a37cf87cafdefe08e3027c34bd63c595fc22ea6c3f1d9434131e96" + }, + "platforms/windows/joystickinput.h": { + "bytes": 2115, + "mode": "0644", + "sha256": "70bad1be04a12167495bf278132f7b0af167c2c84a5f9060a65d2d994213b02a" + }, + "platforms/windows/keyboard.cpp": { + "bytes": 15987, + "mode": "0644", + "sha256": "e21dd1e9883c5a1cece914d2bfa53a266140e856e4ae51971796bc6a088be67d" + }, + "platforms/windows/keyboard.h": { + "bytes": 2240, + "mode": "0644", + "sha256": "dc436f29e502f62042631980c4843598096fb8d134f607edacaaeb1ea0383e4c" + }, + "platforms/windows/keyboardEdit.cpp": { + "bytes": 26647, + "mode": "0644", + "sha256": "d8f76fc1c1d6ead39c86765f1a1fa2959a1855ef3b9d8b32a5c2518e18ce583f" + }, + "platforms/windows/keyboardEdit.h": { + "bytes": 1675, + "mode": "0644", + "sha256": "edb1d03f13da08ed74ef2e1fb52811bb85c87eec8a85c34e51d809aef7eeeaa5" + }, + "platforms/windows/keyboardLayout.cpp": { + "bytes": 36606, + "mode": "0644", + "sha256": "350a450e16d02413817f35524642dc5fbf828dfa8382781613dd1de18c7b6968" + }, + "platforms/windows/keyboardLayout.h": { + "bytes": 1687, + "mode": "0644", + "sha256": "e108b4b084effb114445649f63de32d9b563dd2af67db79e09d69b2fd83eafa9" + }, + "platforms/windows/keynames.h": { + "bytes": 14298, + "mode": "0644", + "sha256": "01e0153276b7f7d732489aa4b80863f4bc2c5a5c3cd304c4e96a882e698dd16c" + }, + "platforms/windows/libcommon/libcommon.vcxproj": { + "bytes": 7044, + "mode": "0644", + "sha256": "c893fb703982350e866a79c1a004f02f7a72f01abfe27a886360d295b0902657" + }, + "platforms/windows/libcommon/vcc/bus/CartridgeInterface.txt": { + "bytes": 7271, + "mode": "0644", + "sha256": "543da6688b34217741550b3dd4572381f4c97dfb7e2c444e40a0bcaf4d77b00a" + }, + "platforms/windows/libcommon/vcc/bus/CartridgeMenuSystem.txt": { + "bytes": 2642, + "mode": "0644", + "sha256": "40fedd54fcf0016bb381f040d9eac121c05a105f20b5f8d202112a37935d31ca" + }, + "platforms/windows/libcommon/vcc/bus/basic_cartridge.cpp": { + "bytes": 2337, + "mode": "0644", + "sha256": "f9b4d8a5df1d13b331defa6187bc39ba4b9847da9ceb60f2b213731653a52d16" + }, + "platforms/windows/libcommon/vcc/bus/basic_cartridge.h": { + "bytes": 1979, + "mode": "0644", + "sha256": "3c5831df97af295b4db0878ab630db88fbe867f176427c8e40407234c265a3e0" + }, + "platforms/windows/libcommon/vcc/bus/cartridge.h": { + "bytes": 2314, + "mode": "0644", + "sha256": "044e23e31c90c1ee99a50add76af83d32ddbb85b767ba1e2243b8e0a2d803b58" + }, + "platforms/windows/libcommon/vcc/bus/cartridge_callbacks.h": { + "bytes": 1546, + "mode": "0644", + "sha256": "1c3904760e19c3a349e28d324c6155a0aa5eeb3234b54b7e34cae13870a77a84" + }, + "platforms/windows/libcommon/vcc/bus/cartridge_loader.cpp": { + "bytes": 8074, + "mode": "0644", + "sha256": "769100a5bc7222fb50e9124e52d4103ea179dc7c1405f3d8843622109248133f" + }, + "platforms/windows/libcommon/vcc/bus/cartridge_loader.h": { + "bytes": 2910, + "mode": "0644", + "sha256": "955e397902ecc5e90e5a91997bc78cce50101e99defdcee50413571d9d6af3b0" + }, + "platforms/windows/libcommon/vcc/bus/cartridge_menu.cpp": { + "bytes": 4292, + "mode": "0644", + "sha256": "3329519720653d55d1f9e0dea73087213ad44ccf35ee2f48590439be17987c10" + }, + "platforms/windows/libcommon/vcc/bus/cartridge_menu.h": { + "bytes": 3209, + "mode": "0644", + "sha256": "87fd4743f5768985c0ad235d01baa6b39c9159cca7aa3d0f50b1fddcfa7a9d38" + }, + "platforms/windows/libcommon/vcc/bus/cartridge_menuitem.h": { + "bytes": 1648, + "mode": "0644", + "sha256": "f5cbd3dde46b6a7fd93f59c298a2c60b8a2653a4df7e1c46deebb11cf0215a85" + }, + "platforms/windows/libcommon/vcc/bus/cartridge_messages.h": { + "bytes": 4196, + "mode": "0644", + "sha256": "ca22d6ee2649c7333a2da25ca91c04b62f045a6d836a6e4a63efc554e626ddfc" + }, + "platforms/windows/libcommon/vcc/bus/cpak_cartridge.cpp": { + "bytes": 5399, + "mode": "0644", + "sha256": "f76f7bff0cf0c6b715ed0930d404cf199c923c70b5258ed2a959acbedb0ed1e4" + }, + "platforms/windows/libcommon/vcc/bus/cpak_cartridge.h": { + "bytes": 3170, + "mode": "0644", + "sha256": "9be946b5412c382ad74a3668528baef04f378886adea89dcfdfe569d9ab4b47b" + }, + "platforms/windows/libcommon/vcc/bus/cpak_cartridge_definitions.h": { + "bytes": 2810, + "mode": "0644", + "sha256": "4eb676cffde45492211247ac378570ecc55e1ec51b7fbae6c684da947375443e" + }, + "platforms/windows/libcommon/vcc/bus/null_cartridge.h": { + "bytes": 1127, + "mode": "0644", + "sha256": "843a984736d59c2d2f49713a3fa80d259b626abe17b57393584e39a09616155a" + }, + "platforms/windows/libcommon/vcc/bus/plugin_callbacks.h": { + "bytes": 2266, + "mode": "0644", + "sha256": "b6336452312ffef78ba529ca3da64686fc45146442cab246e1bec1eb7fadc976" + }, + "platforms/windows/libcommon/vcc/bus/proxy_msgwin.cpp": { + "bytes": 3018, + "mode": "0644", + "sha256": "e531789da5eeed53082362aace133a545f44249b03d48aed0906b80414e78f90" + }, + "platforms/windows/libcommon/vcc/bus/proxy_msgwin.h": { + "bytes": 2132, + "mode": "0644", + "sha256": "9d1451696a6669e7e682e94b6a9a70a1024ee39ba4b791be801a5391965e082e" + }, + "platforms/windows/libcommon/vcc/bus/rom_cartridge.cpp": { + "bytes": 2394, + "mode": "0644", + "sha256": "5c4d45314fddd016bea44c5635aa6d89ee089b5a0c1275814beb73e7eca9de5b" + }, + "platforms/windows/libcommon/vcc/bus/rom_cartridge.h": { + "bytes": 2201, + "mode": "0644", + "sha256": "4a0fb16d5658e5414ae766f8f8048e23efb547d160f63da274996a441de63d81" + }, + "platforms/windows/libcommon/vcc/devices/cloud9.cpp": { + "bytes": 4708, + "mode": "0644", + "sha256": "9a1212e2799d25fb9c6af659dc619b892c5f64be524e7f71189c7fa05d9d2893" + }, + "platforms/windows/libcommon/vcc/devices/cloud9.h": { + "bytes": 555, + "mode": "0644", + "sha256": "6ebb82641d94f4d08e8298102951530e5998b3b5713e661b23124d344656a6ea" + }, + "platforms/windows/libcommon/vcc/util/DialogOps.cpp": { + "bytes": 8639, + "mode": "0644", + "sha256": "476ab8435c5ec0e07e0234476fd44369d841f3dcd159fed71ce4331d68cf3044" + }, + "platforms/windows/libcommon/vcc/util/DialogOps.h": { + "bytes": 3408, + "mode": "0644", + "sha256": "e816fe08861c01d82c3be05f6a037bdb1cdb7c281eefb21a0b05a7a7e3b73019" + }, + "platforms/windows/libcommon/vcc/util/FileOps.cpp": { + "bytes": 3751, + "mode": "0644", + "sha256": "9cbda3ff3fcd0944d3c1dfefd8c8f125f74d765ed8598724fff8affc090e71db" + }, + "platforms/windows/libcommon/vcc/util/FileOps.h": { + "bytes": 1207, + "mode": "0644", + "sha256": "cb217e67274bd5ebb4bd3c45060ee02752859764e0ccb46dde742b08f0d412fd" + }, + "platforms/windows/libcommon/vcc/util/coreutil.cpp": { + "bytes": 1936, + "mode": "0644", + "sha256": "747530d7ee65a6937e5c18e35e497496342d99188854caae4ca6412b9b8006ad" + }, + "platforms/windows/libcommon/vcc/util/coreutil.h": { + "bytes": 1502, + "mode": "0644", + "sha256": "6f171e2708a79354894f91826edb87cd67a75334356f5044f7795a91a44cd952" + }, + "platforms/windows/libcommon/vcc/util/critical_section.h": { + "bytes": 1862, + "mode": "0644", + "sha256": "e50dff9ac622e9550c68d8a0fa68096507ce6e93fe8715bc907fba94778bec9d" + }, + "platforms/windows/libcommon/vcc/util/filesystem.cpp": { + "bytes": 873, + "mode": "0644", + "sha256": "9272acf3278af4a5fe36181317bc5edc6aa6ed37a575d1ca5dc9a3e295fea613" + }, + "platforms/windows/libcommon/vcc/util/filesystem.h": { + "bytes": 203, + "mode": "0644", + "sha256": "ece541d86869a4ea0fb7aceee5dd7e431dd6fa8c7fb8932cf061c503b37ddb8a" + }, + "platforms/windows/libcommon/vcc/util/fileutil.cpp": { + "bytes": 4993, + "mode": "0644", + "sha256": "ffa90448094c35a33420c9ef21c6fc4f0f56eacd4f48a3529967eb58ac9503ed" + }, + "platforms/windows/libcommon/vcc/util/fileutil.h": { + "bytes": 5509, + "mode": "0644", + "sha256": "744a11e231d3722545a5a4aebdf9157104446c8666da3f9a706f80538c755987" + }, + "platforms/windows/libcommon/vcc/util/limits.h": { + "bytes": 1004, + "mode": "0644", + "sha256": "e84527b10d4ed2bef369c82cb13e2cec545ed102751d49720f700319ebcb9477" + }, + "platforms/windows/libcommon/vcc/util/logger.cpp": { + "bytes": 2354, + "mode": "0644", + "sha256": "59ad37b273e1fd3db251d9714eca35497477eb1236075afdce57048424689009" + }, + "platforms/windows/libcommon/vcc/util/logger.h": { + "bytes": 1291, + "mode": "0644", + "sha256": "3d5e9ae80aa89c73a768252b310135aababdcb43d1d729fee948b55d0727c9a6" + }, + "platforms/windows/libcommon/vcc/util/settings.cpp": { + "bytes": 2718, + "mode": "0644", + "sha256": "3b520e78c2328ef1392ea2d13947608c08f1af3ec27f5e168a176a3a090fb4c9" + }, + "platforms/windows/libcommon/vcc/util/settings.h": { + "bytes": 2512, + "mode": "0644", + "sha256": "1a257425799d4c9cadc71a8f23597826b86fe473c503fd85d2a24c58a2d42240" + }, + "platforms/windows/libcommon/vcc/util/textutil.h": { + "bytes": 3484, + "mode": "0644", + "sha256": "55e906f58622f542e5107ccff1f8d356fa209a6b712f1b6283d946aefb320e92" + }, + "platforms/windows/memdump.cpp": { + "bytes": 2674, + "mode": "0644", + "sha256": "feccdd71f9f3136035e4fa13907297873ab4d6c5d2cb049235fa34f2ae957011" + }, + "platforms/windows/memdump.h": { + "bytes": 1078, + "mode": "0644", + "sha256": "6981ab66b679ce5722bdc1c61c5118d1e873850ab59eda6bc13c1c5c43c0010f" + }, + "platforms/windows/mpi/configuration_dialog.cpp": { + "bytes": 8620, + "mode": "0644", + "sha256": "906a8383a80da310d5338c9368c36c44c042b25346e300911dda3850548cdda6" + }, + "platforms/windows/mpi/configuration_dialog.h": { + "bytes": 2068, + "mode": "0644", + "sha256": "47b53cab1e7540fb30a74fac8114b4612a5a1e511d6cffa98ce1125c5c096a45" + }, + "platforms/windows/mpi/mpi.cpp": { + "bytes": 3454, + "mode": "0644", + "sha256": "a49d21aafbcb8ed9fdcb5c4567e64fab7f83622da9f53a75fca3d1c4c90c2d0f" + }, + "platforms/windows/mpi/mpi.h": { + "bytes": 1116, + "mode": "0644", + "sha256": "19cabd0d0cfbba4ecb1b1327277b1e0c3ea2800031cb1bac1ea694aba2fa983b" + }, + "platforms/windows/mpi/mpi.rc": { + "bytes": 5308, + "mode": "0644", + "sha256": "7dbfb455509454434f3dc379979bcf840031bcee10007c79b201cc1afa476779" + }, + "platforms/windows/mpi/mpi.vcxproj": { + "bytes": 5543, + "mode": "0644", + "sha256": "feafd8ee3425f34041862b087a54f0b5717b72063374613a2f9378c0f50ec154" + }, + "platforms/windows/mpi/multipak_configuration.cpp": { + "bytes": 3040, + "mode": "0644", + "sha256": "2d51110fb72f8d7d9e42cf02d6bb87da88e71e11b9493de59383ce685b4c3556" + }, + "platforms/windows/mpi/multipak_configuration.h": { + "bytes": 1844, + "mode": "0644", + "sha256": "ea6332ca9366917fa6553d8eaeb537057aa0eba0a50b3eb34959079217c6a4d8" + }, + "platforms/windows/mpi/multipak_supervisor.cpp": { + "bytes": 4210, + "mode": "0644", + "sha256": "b2651865372f37ec57083856023f7ca0339f7b7fffc2985b7c0954025ce7d1c0" + }, + "platforms/windows/mpi/multipak_supervisor.h": { + "bytes": 2451, + "mode": "0644", + "sha256": "60357193d1735e223ca9e7afeac5c62aaa84af4332519ff732d528455cd43b7c" + }, + "platforms/windows/mpi/resource.h": { + "bytes": 1505, + "mode": "0644", + "sha256": "cbc48a4caf16496ef1c1743a11a3e838a5d6c26dde718e2bdb7510b0faacc875" + }, + "platforms/windows/orch90/orch90.cpp": { + "bytes": 3840, + "mode": "0644", + "sha256": "2621bc4f658827ff4965622f2afb65ff22611a9cd8d0359dc80ab77981560538" + }, + "platforms/windows/orch90/orch90.rc": { + "bytes": 3104, + "mode": "0644", + "sha256": "37b8b054561412f7f333bfdee5e84c0b54dd1b3c8403dcd10fd9a99e0423b571" + }, + "platforms/windows/orch90/orch90.vcxproj": { + "bytes": 5210, + "mode": "0644", + "sha256": "77b1d7246617214eccf807a32f6edc77fa74c57a4c24a1651c1059bcbf06fd17" + }, + "platforms/windows/orch90/resource.h": { + "bytes": 563, + "mode": "0644", + "sha256": "d56221e69abad58a1b0c596a7c3754d4ef5ac6ab02bba0235d4e317fe30e4acb" + }, + "platforms/windows/pakinterface.cpp": { + "bytes": 15240, + "mode": "0644", + "sha256": "9e32428e2328f41fa43132faadcf97ff093c1b59048bacec7de4806b7aba6753" + }, + "platforms/windows/pakinterface.h": { + "bytes": 1742, + "mode": "0644", + "sha256": "cec4e1877dc40dd1728f0a66fc56ff8c515b3ed41b2f6d1fa90cdf22ece9b61d" + }, + "platforms/windows/pakrouter.cpp": { + "bytes": 8225, + "mode": "0644", + "sha256": "692fa233b9906b8d2d3ad49647537b4909a4987f4cc974c6e7d0199f140df43b" + }, + "platforms/windows/pakrouter.h": { + "bytes": 5147, + "mode": "0644", + "sha256": "4ff6a4a9ba16053057bee1e72270a0d64fe28708fc1d9af470f7f2870e4b6e23" + }, + "platforms/windows/quickload.cpp": { + "bytes": 3086, + "mode": "0644", + "sha256": "d5809065fda83be2b12ba0212c7ef94d6020fd97750a529918fdac53fb9a66c7" + }, + "platforms/windows/quickload.h": { + "bytes": 923, + "mode": "0644", + "sha256": "8d8c706756fe3bea6b3072abd78d214e58c012c58f43647d1c49cf387440f53a" + }, + "platforms/windows/resource.h": { + "bytes": 21184, + "mode": "0644", + "sha256": "3edd42495f5c0b4e145cb9f006dbfca4d68331861267568564d0ee6ac72ff7ca" + }, + "platforms/windows/resources/3guys.bmp": { + "bytes": 11750, + "mode": "0644", + "sha256": "f53342fcc18bbadd8d4b0c6214716c4d25c059ea973119b32e2f7db38045d47d" + }, + "platforms/windows/resources/Keyboard.ico": { + "bytes": 3638, + "mode": "0644", + "sha256": "99dfbcb36dbe84f256f283be90e90917c719093e4d49ea8911aeff242bcd8448" + }, + "platforms/windows/resources/binfile.ico": { + "bytes": 4846, + "mode": "0644", + "sha256": "210a27099720d32689777dea1d8b1d25807690d36cedf7f6aa6929db829d2006" + }, + "platforms/windows/resources/composite.ico": { + "bytes": 766, + "mode": "0644", + "sha256": "c11302fd0407d222d2199f0b369d8feb9d8bfdc309ea7e172e7f643989bcc851" + }, + "platforms/windows/resources/consola.bmp": { + "bytes": 101622, + "mode": "0644", + "sha256": "fad7eeb15c95f589ae4484f02ed99f47782b388d0cff0db9b9478238fd3e571a" + }, + "platforms/windows/resources/cursor1.cur": { + "bytes": 326, + "mode": "0644", + "sha256": "bf79bffdba70f456cb406fd1ece8652750363b94188510b5d73f36c8ea6e7ae9" + }, + "platforms/windows/resources/hitachi.ico": { + "bytes": 766, + "mode": "0644", + "sha256": "ec9fdce7fca781494969a1c11ca37d1bb322c20151a325119279baf0d9f00893" + }, + "platforms/windows/resources/ico00004.ico": { + "bytes": 766, + "mode": "0644", + "sha256": "c3cb4fc29f7577919ab38b62fcd833323f659ac3fbed4e11b81947dcdf63009a" + }, + "platforms/windows/resources/icon1.ico": { + "bytes": 4846, + "mode": "0644", + "sha256": "04a7692dd7a342c3b5523921613736982db312aab92c7652ef4d5725f20d3067" + }, + "platforms/windows/resources/joystick.ico": { + "bytes": 766, + "mode": "0644", + "sha256": "e4ccd17b83d0e7a4d090bbb7e35355d4f5f791abcaa802b181d7d46be91192b1" + }, + "platforms/windows/resources/moto.ico": { + "bytes": 766, + "mode": "0644", + "sha256": "5f9a096cfae48dc197299eefdeef4fa58d97e438fc9c764dc88fc4d90e962a09" + }, + "platforms/windows/resources/mouse.ico": { + "bytes": 766, + "mode": "0644", + "sha256": "2a4900dd6ea22da1443dec3bdd8ae25e4bf6ce8cbaab4fa63961b562d9f95139" + }, + "platforms/windows/resources/progpack.ico": { + "bytes": 1078, + "mode": "0644", + "sha256": "d3bf669aff7ebd2a9cfa082bf9310d01209907b178f83693a8b7e5812cbefd5c" + }, + "platforms/windows/resources/rgb.ico": { + "bytes": 766, + "mode": "0644", + "sha256": "9dc3e20e8d771c867fc20c16707d967b55fe019619decce8c54a8c5f82d49572" + }, + "platforms/windows/resources/speaker1.bmp": { + "bytes": 1334, + "mode": "0644", + "sha256": "54ed7fe78f46b59051725b9e4bb2dbfb49388b728d71d7cb9719652179ea5915" + }, + "platforms/windows/resources/speaker2.bmp": { + "bytes": 1334, + "mode": "0644", + "sha256": "514083702c1eee31478963b6fc88fb4cb3000de8a75c359e68840fcc4a4a9a24" + }, + "platforms/windows/resources/vcc.bmp": { + "bytes": 25022, + "mode": "0644", + "sha256": "8457a5569e9ed220b86e396b1350353b1b003fa2ab669e98c6b0ee679d4edf8a" + }, + "platforms/windows/sdc/clock.txt": { + "bytes": 236, + "mode": "0644", + "sha256": "fde7b10df111b2402b5e6c32db4cebbd8e119783f4746f7e33c5a86d4ec239df" + }, + "platforms/windows/sdc/resource.h": { + "bytes": 2270, + "mode": "0644", + "sha256": "0a4a329ec5804ac60636b2ce47646d8c002ee4b3653c338d67cd341c4dd3ade3" + }, + "platforms/windows/sdc/sdc.cpp": { + "bytes": 83114, + "mode": "0644", + "sha256": "09412a77338835b3c9f14f07a6598f9f545e83d8d3659506c51c200b63a4e6b7" + }, + "platforms/windows/sdc/sdc.h": { + "bytes": 5549, + "mode": "0644", + "sha256": "80038e0b81c2b0e9d084bfee1cf3f0025854ddf03a9d8c9f1cd972e4c57b9528" + }, + "platforms/windows/sdc/sdc.rc": { + "bytes": 5544, + "mode": "0644", + "sha256": "3561f4c96fa04e3b9ac11cf0fced657cdbb1766c1b265d981a69dbcb9492bd2a" + }, + "platforms/windows/sdc/sdc.vcxproj": { + "bytes": 5538, + "mode": "0644", + "sha256": "2b10567a3deaa55e161ab39c3b5145f4a36b2a0c33aa187b848b5757b2b7b18f" + }, + "platforms/windows/sdc/write_flash.txt": { + "bytes": 2794, + "mode": "0644", + "sha256": "0b063cc11c8f1ea8ef3e19e0e3d9ded11921fe47eda09c9a1c9aa2736aa0c82b" + }, + "platforms/windows/speaker.ico": { + "bytes": 1078, + "mode": "0644", + "sha256": "0534f79950b232e4ab4124730117c666609729634622baac1f0dc81704074975" + }, + "platforms/windows/ssc/ssc.vcxproj": { + "bytes": 5415, + "mode": "0644", + "sha256": "2f2678b45d80ee49642cbfafeb6c92fd4fc765e6ce19cebc466967f5bb9ff476" + }, + "platforms/windows/ssc/ssc_dll.cpp": { + "bytes": 7863, + "mode": "0644", + "sha256": "d938f6cc7af2cfdbfd9ccaddb7553567b2b0a6de7ec11b139e2a90ddbe9e1f51" + }, + "platforms/windows/ssc/ssc_dll_legacy.cpp": { + "bytes": 7066, + "mode": "0644", + "sha256": "30aaff84c6ad94a0a39113f31cc10c2baa9768d2498f67d60f4c130fee05cd8e" + }, + "platforms/windows/ssc/ssc_dll_universal.cpp": { + "bytes": 9246, + "mode": "0644", + "sha256": "cbaa755c15f5bf831e1f39cec882f6c6b628ce8202f84a15b6330fa26b49cd9b" + }, + "platforms/windows/ssc/test/.gitattributes": { + "bytes": 34, + "mode": "0644", + "sha256": "3bd9505d2038ebf7b4a436e08daf01d454b7493f44cf4839f4631357dc5b5676" + }, + "platforms/windows/ssc/test/real_rom_capture.wav": { + "bytes": 88244, + "mode": "0644", + "sha256": "f1be734a7a7b2a6144d63151ca296e037fd23f89591bc34b186be3e261fa1548" + }, + "platforms/windows/ssc/test/real_rom_test.cpp": { + "bytes": 8525, + "mode": "0644", + "sha256": "874d525d31699df51ba7a4ca23d83bea2a253bbbf9f2cff86ef34c1a56ed209c" + }, + "platforms/windows/ssc/test/real_sp0256_speech.wav": { + "bytes": 171480, + "mode": "0644", + "sha256": "57b354f3fc9f3961e084bf7f3a9c20ddabaefca1f903cacd9ee9d6673f3d1b82" + }, + "platforms/windows/ssc/test/real_sp0256_speech_test.cpp": { + "bytes": 5167, + "mode": "0644", + "sha256": "52b7394583d97c6bb939aec5e17718c558601961348a796faaa4399ad9eb5fd9" + }, + "platforms/windows/ssc/test/run_tests.sh": { + "bytes": 1532, + "mode": "0644", + "sha256": "a4db623102a63048ab396a3053ed01083459a745b800d737234613b825bafc6c" + }, + "platforms/windows/throttle.cpp": { + "bytes": 3212, + "mode": "0644", + "sha256": "f45e5859f6af68ade2f6773c31266d7acbca946c4772b2aa4d0da5f754bf5007" + }, + "platforms/windows/throttle.h": { + "bytes": 978, + "mode": "0644", + "sha256": "e5b44d82a96bb6bc79592b4ea51cdfcc96b6dc58fe30325e758eafbb70920627" + }, + "platforms/windows/vcc-base.props": { + "bytes": 2558, + "mode": "0644", + "sha256": "0b423495b177b88c075fcee79e61601539402da53f04b77a47306ecb9032e05a" + }, + "platforms/windows/vcc-debug.props": { + "bytes": 1064, + "mode": "0644", + "sha256": "58625e1cbcc0883e51c6eed8e93cb0d7c44a557c65701de49e1d311e81dddf6d" + }, + "platforms/windows/vcc-legacy.props": { + "bytes": 911, + "mode": "0644", + "sha256": "f5c174ef491a14cd92d314b808681897c02998e730b62ac1db626ee3fa70cdfd" + }, + "platforms/windows/vcc-release.props": { + "bytes": 950, + "mode": "0644", + "sha256": "47e899c9a81f67ccb8e855fb24ea33200627327b78b1b49c662dff2f2e0079ce" + }, + "platforms/windows/xDebug.h": { + "bytes": 602, + "mode": "0644", + "sha256": "1f7a8a0c2d536731fce939fa9c687dd8abd909969403a186389caad5eb617066" + }, + "platforms/windows/xsid/xsid.vcxproj": { + "bytes": 4761, + "mode": "0644", + "sha256": "8b4b68b9ba89e2bad2e6ae0368b349ba102a03021234ab2f23c6d885098b2cd8" + }, + "platforms/windows/xsid/xsid_vcc_hifi.c": { + "bytes": 13421, + "mode": "0644", + "sha256": "237bf5df6a618a80824988e436cf40377c6345f967810561b1d7f15e0fb98075" + }, + "sdk/cmoc/bank/bank.c": { + "bytes": 4967, + "mode": "0644", + "sha256": "555541db6cce963176ac6d13d13d27fb1417d768de7dbff47bc6059068f6b3ed" + }, + "sdk/cmoc/compat/cassette.c": { + "bytes": 8572, + "mode": "0644", + "sha256": "77250999466d3621f704ad4c0bcad06d09bde7b0b09d861ed6a1f72e96fe3af5" + }, + "sdk/cmoc/compat/ctype.c": { + "bytes": 632, + "mode": "0644", + "sha256": "92c28baf2c7fa43517ee05e9a1c088d628e8390a6ff00c5c9c5ef5d60a874e2c" + }, + "sdk/cmoc/compat/directory.c": { + "bytes": 3692, + "mode": "0644", + "sha256": "15eb50cc0fa54811088ba552f67a9c014ff7834b81a15f54679decf926acf059" + }, + "sdk/cmoc/compat/disk-internal.h": { + "bytes": 830, + "mode": "0644", + "sha256": "b742aeaee29805ff740b3fca9bf2c971ccba7d928227373272fa0fb2aaea60da" + }, + "sdk/cmoc/compat/fileformat.c": { + "bytes": 1162, + "mode": "0644", + "sha256": "cb4da81441c1771116d5202cee8d8bebdf2b751a9d64c3516de7bd13ad584b6b" + }, + "sdk/cmoc/compat/fixed.c": { + "bytes": 2551, + "mode": "0644", + "sha256": "2ea7dc96bf3d0c076f7a93cdbfbb8537d52ed3ffd45017c9ae3415752afe8eca" + }, + "sdk/cmoc/compat/format-internal.h": { + "bytes": 395, + "mode": "0644", + "sha256": "fe1dbb2bb5a796d82ffa1680c979d17bb75a963e1626d2454fde98194025d1e1" + }, + "sdk/cmoc/compat/format.c": { + "bytes": 5896, + "mode": "0644", + "sha256": "b17515322b804e4fd375d94d0b8ce8099aad714ef331f05363d27839234110ba" + }, + "sdk/cmoc/compat/heap.c": { + "bytes": 1814, + "mode": "0644", + "sha256": "95120fbf03a188abc96b811dc88548e9f3680366e692e411bcb764ce1fca887d" + }, + "sdk/cmoc/compat/include/ctype.h": { + "bytes": 373, + "mode": "0644", + "sha256": "773bbec311574f3efc9424b2d46ff0c81ab6716da58f428e2597bcb584391ac5" + }, + "sdk/cmoc/compat/include/disk.h": { + "bytes": 250, + "mode": "0644", + "sha256": "bed9e09074d3947206ee6c3232b6c2093ddeba4bb902532b37d294a80ff93203" + }, + "sdk/cmoc/compat/include/errno.h": { + "bytes": 222, + "mode": "0644", + "sha256": "0ef44d665b154887d3c57e864614d564434f0b66e56cdca5cd429b47c1c05cd6" + }, + "sdk/cmoc/compat/include/limits.h": { + "bytes": 617, + "mode": "0644", + "sha256": "10a16359d739e7d89798046b5ae2e76374c559cca1d1aa8ddca966fb34f786a2" + }, + "sdk/cmoc/compat/include/stddef.h": { + "bytes": 216, + "mode": "0644", + "sha256": "def2defd138c4b8b9f5f6cfc3aea55cb54a53a6a76a0836e5bea9176fbc2c45e" + }, + "sdk/cmoc/compat/include/stdint.h": { + "bytes": 1023, + "mode": "0644", + "sha256": "e80c898d695dfca1653ae89558bc24398fc6d6af3fd1dce8eb7a4d101b157964" + }, + "sdk/cmoc/compat/include/stdio.h": { + "bytes": 4103, + "mode": "0644", + "sha256": "085e609ec1a86c66027f491c2a839b8a657029eef485a2c587b8b14f9a8728e3" + }, + "sdk/cmoc/compat/include/stdlib.h": { + "bytes": 1287, + "mode": "0644", + "sha256": "46b8fa9856438377b9aab4c79b562538a268f8ac4336316aa15d84bf522713c2" + }, + "sdk/cmoc/compat/include/string.h": { + "bytes": 628, + "mode": "0644", + "sha256": "f1a047d77852bffdc6510c9f8ce5a5a18d05fcbfa81f1a4aec4f3ed9f94d8787" + }, + "sdk/cmoc/compat/printer.c": { + "bytes": 1157, + "mode": "0644", + "sha256": "66e6eee3ab980e2e21a30e38c4a96caad361718866059b66e319d651349d26ca" + }, + "sdk/cmoc/compat/streams.c": { + "bytes": 26367, + "mode": "0644", + "sha256": "c50cb992803bcd13fc7d77761a1b60d4e5a615b2643c6e8ada61b089dc6cbccd" + }, + "sdk/cmoc/compat/strto.c": { + "bytes": 2656, + "mode": "0644", + "sha256": "93285dfa4f529dab0c19b1c1307d00f8084b166894cf060079a92070e655bba6" + }, + "sdk/cmoc/compat/tests/check.py": { + "bytes": 1878, + "mode": "0644", + "sha256": "875d24799d9af6ba0753df82689ef00e5b6e571306ee6bcd271f50f83b1ba7a0" + }, + "sdk/cmoc/compat/tests/compat-check.c": { + "bytes": 4956, + "mode": "0644", + "sha256": "e96d3d400f5f798b0edf038d0da93fecefe0a66b4e59fbafea07992078a0e893" + }, + "sdk/cmoc/compat/tokenize.c": { + "bytes": 551, + "mode": "0644", + "sha256": "a5b423350908520eaa9a8b935c4cd8c461378dc34aafd2089179b065b4690e22" + }, + "sdk/cmoc/gime/gime.c": { + "bytes": 6191, + "mode": "0644", + "sha256": "3a4ec27d3bc19cf59b1bcf23ae9ccb89aa308731e97ec12ef9609516c323859d" + }, + "sdk/cmoc/include/vcc/bank.h": { + "bytes": 1572, + "mode": "0644", + "sha256": "4387375ec87bf8deaac4edb267f6ec31eb40d09c94c6eb95b1284eaa9d88f47c" + }, + "sdk/cmoc/include/vcc/cassette.h": { + "bytes": 1157, + "mode": "0644", + "sha256": "27f04685d4efa75b245452b24eb34b4634b6bc792ec1e33d523a98954ab25882" + }, + "sdk/cmoc/include/vcc/decimal.h": { + "bytes": 786, + "mode": "0644", + "sha256": "3f19d2f2e71391049efb7e6751cf19b3f46c4ea67d9408e99306dff980cbd768" + }, + "sdk/cmoc/include/vcc/gime.h": { + "bytes": 1611, + "mode": "0644", + "sha256": "66f602fd1a48fe92bb1971c2598f437e9ed8ea895cc11226fd929eaaca999907" + }, + "sdk/cmoc/include/vcc/input.h": { + "bytes": 1458, + "mode": "0644", + "sha256": "86bfa1f370e0f965867572b106bda98673d1b61e9db83b2e7bbb763eec87bfe7" + }, + "sdk/cmoc/include/vcc/orch90.h": { + "bytes": 2628, + "mode": "0644", + "sha256": "d6e05ba827ec3954f25bee74d32068d40e474b88ecf5539ceb2588d4cb5f574a" + }, + "sdk/cmoc/include/vcc/printer.h": { + "bytes": 693, + "mode": "0644", + "sha256": "e36325abbacd45bd6eaf4602fa3b5e8cb7d7560f43c0558595695614651197dc" + }, + "sdk/cmoc/include/vcc/sdc.h": { + "bytes": 2170, + "mode": "0644", + "sha256": "3f6267ae8a60169cae0c9e61282633524189b34af2467bb5bf839a386ccbb8dc" + }, + "sdk/cmoc/include/vcc/ssc.h": { + "bytes": 6369, + "mode": "0644", + "sha256": "4fc3c75c07584e95cba09a6762f279f687a0a27c6ddd605b2b8f781ecbb8efaf" + }, + "sdk/cmoc/input/input.c": { + "bytes": 2662, + "mode": "0644", + "sha256": "47ff63ac62ac0ea090c1e780f65bb9ae18f21ed9117f6ce8ebf155c73b1a53d4" + }, + "sdk/cmoc/orch90/background.c": { + "bytes": 4365, + "mode": "0644", + "sha256": "2b3b2664feca290a3bad9f1e223bd56b205d3ab7829f6760808e061b7cbbb535" + }, + "sdk/cmoc/orch90/play.c": { + "bytes": 960, + "mode": "0644", + "sha256": "52ce491e7994dd4f4db49b6b412c00b22c384dd85eb94a0b94820f846f1c4fd9" + }, + "sdk/cmoc/orch90/write.c": { + "bytes": 262, + "mode": "0644", + "sha256": "ce711c096746ca0ead1eeb882bdcdaa82191a72afc3216e89b1c885c8d46675a" + }, + "sdk/cmoc/sdc/sdc.c": { + "bytes": 8634, + "mode": "0644", + "sha256": "18f639a446829b362239dd6e4a6637810098256700023504bf1609ac70a38338" + }, + "sdk/cmoc/ssc/effect.c": { + "bytes": 1811, + "mode": "0644", + "sha256": "b39f18d1fa995ca13e61016b5a040759effd699bc600473747a7bd8651cf713c" + }, + "sdk/cmoc/ssc/internal.h": { + "bytes": 320, + "mode": "0644", + "sha256": "d30c7748decf7e92e6ffa87ee32bcd4402e7a2caac5255fde46741885a4d602b" + }, + "sdk/cmoc/ssc/phrase.c": { + "bytes": 2239, + "mode": "0644", + "sha256": "a8d5bb5c4e01ec41b8fdcfb1e971dcdb7de6ae730bad775a2d223170273a8647" + }, + "sdk/cmoc/ssc/port.c": { + "bytes": 1122, + "mode": "0644", + "sha256": "32f182f9157f9d95a8a73214dbdb9b77b843140ccc3b29fd27732e2adf625d07" + }, + "sdk/cmoc/ssc/route.c": { + "bytes": 1537, + "mode": "0644", + "sha256": "d5f21c66e54c3a4f7b173a9447119c5dd4bf3cee5c1504ad0ff52767b2803c75" + }, + "sdk/cmoc/ssc/stored.c": { + "bytes": 2912, + "mode": "0644", + "sha256": "7f0f31785d91a716a04093c4ffe895f1fddaad4d0f3f02604fc24822883fb051" + }, + "src/core/AudioBuffer.h": { + "bytes": 2655, + "mode": "0644", + "sha256": "693f83fe8cb86e27b10903b471ef4046d65f9d98e3eddda1262bd606119b30ae" + }, + "src/core/BasicProgram.cpp": { + "bytes": 15488, + "mode": "0644", + "sha256": "f457a3d651a36dd4a93b00db836f6fd56b0b5fb15e0b5c877482847a78719de9" + }, + "src/core/BasicProgram.h": { + "bytes": 1694, + "mode": "0644", + "sha256": "83eb25543f5a92c42d0db2b93032a3d76904b6a2dae7d41ff9b0bfd26856a816" + }, + "src/core/BinaryImage.h": { + "bytes": 2107, + "mode": "0644", + "sha256": "a2e7a74556f93fd52701a8d722b3be47107c31ef8e8a2efadb0ddc7c707778f7" + }, + "src/core/BuildConfig.h": { + "bytes": 3860, + "mode": "0644", + "sha256": "002ef1785de3f20a4e7e7c7224065e355d18407bbe9afe840c21e236696bebd8" + }, + "src/core/CassetteDeck.cpp": { + "bytes": 8069, + "mode": "0644", + "sha256": "a63427ed2fa2e321967e7f1d9f871a20e86b847d7fdee70b15a74c0bac633546" + }, + "src/core/CassetteDeck.h": { + "bytes": 1744, + "mode": "0644", + "sha256": "e7671e28c59c56d2b5c6a49eaa546b91cc8587b68458ee1750b3de7bf847081e" + }, + "src/core/CpuCommon.h": { + "bytes": 1910, + "mode": "0644", + "sha256": "05820d6fa3a847d9fc4ea2d43d37bfb6d6b86c2b18d08cbeeeea176e75fa2b7c" + }, + "src/core/CpuHost.cpp": { + "bytes": 3019, + "mode": "0644", + "sha256": "8ba8cd73022e6077a2e32858574995308f77e2b9dea7f425efd566a8f0da1c61" + }, + "src/core/CpuHost.h": { + "bytes": 1923, + "mode": "0644", + "sha256": "58828eed94b8c92e28750e9f6a3448c6752b25f1b7485a379ddbfd93829d4a44" + }, + "src/core/CpuMemory.cpp": { + "bytes": 984, + "mode": "0644", + "sha256": "2285ad261f89ecbb9f40f9341dbb59edcc81e5348c5ab9d8d39a8687d816431d" + }, + "src/core/CpuMemory.h": { + "bytes": 862, + "mode": "0644", + "sha256": "9e97eb89d94a3f0a5064f3af00dabc3efe8b80aba56a42a796a0ad0098ae7191" + }, + "src/core/DebugDisassembler.cpp": { + "bytes": 13540, + "mode": "0644", + "sha256": "84763c0659f524e7e4273d9896f41c2526bd64dbc8a32418567af3d7ec31dbc8" + }, + "src/core/DebugDisassembler.h": { + "bytes": 1445, + "mode": "0644", + "sha256": "f90114cc86cb4098ea1470dcc33b4382516826767224262c56b9cb7e23d5532c" + }, + "src/core/DisplayNone.h": { + "bytes": 2812, + "mode": "0644", + "sha256": "704c85a09218f02bd184ef797d229fb0080ad81060da511ab769c00cb0982750" + }, + "src/core/DisplayNull.h": { + "bytes": 2382, + "mode": "0644", + "sha256": "5689e30e15bc37026344f7e46d0d511666e43714c458ef671f610b1fa5791671" + }, + "src/core/Event.cpp": { + "bytes": 12194, + "mode": "0644", + "sha256": "f9bb6642c1ec8dc94276bb6ec200182f443de73442957ee079a226ad7159ffb1" + }, + "src/core/Event.h": { + "bytes": 3824, + "mode": "0644", + "sha256": "3efb44658ca5abdd1afe43bc103f4a046bb1657fa84e0e519d86c17d6b48b0a3" + }, + "src/core/FramePacing.h": { + "bytes": 1554, + "mode": "0644", + "sha256": "2e3ef05c7fac6e51b2fcb9e5ea539bb6c32ca5f02b4d8452dffddb16f99af011" + }, + "src/core/FrameRunner.cpp": { + "bytes": 1011, + "mode": "0644", + "sha256": "5a240ff848baee1c440802c4c151419904c64167a4f27411bfbfdde7c69eb3e9" + }, + "src/core/FrameRunner.h": { + "bytes": 546, + "mode": "0644", + "sha256": "cbb8f2613133c1e1a365ae08aeafda1df4346615c2e8d47e4c63a78fedb2c2e2" + }, + "src/core/IDisplay.h": { + "bytes": 4556, + "mode": "0644", + "sha256": "ac5351304579b74f0e6a08667d489dbcb16a9794b4d527edaa849cd348b4aa24" + }, + "src/core/IDisplayDebug.h": { + "bytes": 1493, + "mode": "0644", + "sha256": "54f943cd62347a53ed3e7569300e9816fd2b02ba1c158528fe3329458a1c14c3" + }, + "src/core/Interrupts.h": { + "bytes": 1397, + "mode": "0644", + "sha256": "1a423c70561361ebb39d17eb6f13011d472ffdb6445a693c4c8217339563153d" + }, + "src/core/JoystickState.h": { + "bytes": 2071, + "mode": "0644", + "sha256": "ff7b09e0f0a6a7bb0dcb00706a62929099a2d40be34cf45cc1729f8daa17e3e7" + }, + "src/core/KeyboardMatrix.h": { + "bytes": 628, + "mode": "0644", + "sha256": "430507bbade872b18dbe5302c6f5a6b97616bf41b7d3deeec4df53d9e689d277" + }, + "src/core/MachineDefs.h": { + "bytes": 3153, + "mode": "0644", + "sha256": "0e5a7c58dcd0fa8d244cfe84e7741ed6e8eb4840d6ded5d2292aa3ee19fa08a1" + }, + "src/core/MachineHost.cpp": { + "bytes": 3800, + "mode": "0644", + "sha256": "fbc36f20c8723c40fb19037600aafb492ee5edf05ae5afef6ed27150866c5704" + }, + "src/core/MachineHost.h": { + "bytes": 2030, + "mode": "0644", + "sha256": "dc008ed868e23b19e58882fcb3897696ff28ec376ec485cd0d5bdd6870244ba9" + }, + "src/core/MachineSession.cpp": { + "bytes": 131652, + "mode": "0644", + "sha256": "3e19e72ed3660dec9359895fbaf700bd8b5fae641fd4648da9da9f41bd279810" + }, + "src/core/MachineSession.h": { + "bytes": 16328, + "mode": "0644", + "sha256": "c87dbd2676fe3fa27ab84c1123c07f9ad12840cab41b868c27654b78a719a2b4" + }, + "src/core/OpCodeTables.h": { + "bytes": 56014, + "mode": "0644", + "sha256": "ffee8b8e801b6822c5f72ea699b4c0841ff636ba931fda681ef4ee47a692dcab" + }, + "src/core/PrinterCapture.h": { + "bytes": 1892, + "mode": "0644", + "sha256": "84a7b8c48fb19d521a69b24ddcc999cb54e1d501435818c201690fdf226df947" + }, + "src/core/VideoHost.cpp": { + "bytes": 944, + "mode": "0644", + "sha256": "6cb2ac40fa8f294614a28678a3a68aecaf5c90d3bb8c9fd3699bf9488d84f12e" + }, + "src/core/VideoHost.h": { + "bytes": 3056, + "mode": "0644", + "sha256": "8a8e5462c9cc5ca8c96ec84ee2ec78d9ebddb0ece0b2e83c50c99f1928fe38b0" + }, + "src/core/VideoRegisters.cpp": { + "bytes": 1561, + "mode": "0644", + "sha256": "5e0702eb0e4e568f0ff2b7cc397d5a3ee4db3856de6b9bf04c663654e416e149" + }, + "src/core/VideoRegisters.h": { + "bytes": 298, + "mode": "0644", + "sha256": "4effbc6e052fcf20bcc0aedf5d6a24d651d5479d03aa3c04ea38ec94c181ec0e" + }, + "src/core/cc2font.h": { + "bytes": 8026, + "mode": "0644", + "sha256": "a1b4c3188c7c286caffb0799d9dc209c8ab44f5d144915fb2344580c205f7814" + }, + "src/core/cc3font.h": { + "bytes": 17694, + "mode": "0644", + "sha256": "77e0fda244b629e12b3f3e895606b7a5fd3cd3cad7687493eccf0f50732d50de" + }, + "src/core/hd6309.cpp": { + "bytes": 161907, + "mode": "0644", + "sha256": "7e85d2955cff6405d420bee996b304b6ea7d55264041915bffffbe31ac6923cb" + }, + "src/core/hd6309.h": { + "bytes": 1311, + "mode": "0644", + "sha256": "09cc901e945c7574b7afed965be2d85384c51aa0d4c89dc5019086cff2c2afe4" + }, + "src/core/hd6309defs.h": { + "bytes": 16449, + "mode": "0644", + "sha256": "f6b05aa295eaecf637ae19539be335551e3a5bdb49a6b6f5cd5c337cd844de9f" + }, + "src/core/iobus.cpp": { + "bytes": 4384, + "mode": "0644", + "sha256": "8cbdce436a13ac9b96dc7c24692ebc5a3d3192d0dcc7f93e41645d28bf4ff911" + }, + "src/core/iobus.h": { + "bytes": 944, + "mode": "0644", + "sha256": "80b5825e41a573dc64f8e74b4106fbca6684464b460ac2b895f8fdf462d677eb" + }, + "src/core/mc6809.cpp": { + "bytes": 80876, + "mode": "0644", + "sha256": "0fb65c0b15aa592d4c8272517cf59740a35ce537c1c72d1d38b372a98bdf9369" + }, + "src/core/mc6809.h": { + "bytes": 1313, + "mode": "0644", + "sha256": "270518498b54b0a0a8195d8fc7f8f9b3b3b6f54ef496b7e597ad2b9500ef5e60" + }, + "src/core/mc6809defs.h": { + "bytes": 9950, + "mode": "0644", + "sha256": "baf4414a44db04b6a122d3ebbc8e600bcf897a0c6eec9dd990c0b162aeefd027" + }, + "src/core/mc6821.cpp": { + "bytes": 9860, + "mode": "0644", + "sha256": "103d243f1f2fffa6d67b1a1c179f0213be7194880d9938ddea589c214f0da245" + }, + "src/core/mc6821.h": { + "bytes": 2227, + "mode": "0644", + "sha256": "165904bdcbedd56d8c5dbad8cb90c3387ce3dd3b15d7f71d0c3bde9faf8b658d" + }, + "src/core/tcc1014graphics.cpp": { + "bytes": 611489, + "mode": "0644", + "sha256": "24aa565e1e5f426f4dce92896e0c741110701fa52f627675b8b3b47f57d3e969" + }, + "src/core/tcc1014graphics.h": { + "bytes": 10675, + "mode": "0644", + "sha256": "35d20c65a2c57126196b0ede7b31986f80158fbdbb623449b7ce522b3368a5fd" + }, + "src/core/tcc1014mmu.cpp": { + "bytes": 13395, + "mode": "0644", + "sha256": "6eab0f7e808b058d0d11226bb2756c691e2693f010e1c889b592210377a2ad0d" + }, + "src/core/tcc1014mmu.h": { + "bytes": 3263, + "mode": "0644", + "sha256": "519b5da413aa3143382d47c74b07fa4dc2243023d46938ee217f201812e8ee9e" + }, + "src/core/tcc1014registers.cpp": { + "bytes": 11675, + "mode": "0644", + "sha256": "c8ac156ffeb4feff455ff2bb87c41f1623c41c502430a970b7a0dd3aab298979" + }, + "src/core/tcc1014registers.h": { + "bytes": 1347, + "mode": "0644", + "sha256": "b5dcefe7a5c75205a34c9207b4674cf94526ad249cc3aad2d0cc310989f0b34b" + }, + "src/devices/CartridgeDevice.h": { + "bytes": 7766, + "mode": "0644", + "sha256": "d18e338c9c517a69c7e99c67211b83955c0d8a50980a61df9d1eac3dbf3834b8" + }, + "src/devices/DriveWireDevice.cpp": { + "bytes": 8790, + "mode": "0644", + "sha256": "9362d937e9cbff179f8cbf2d381fba5228f8cd7c216a7a476d63eeeb33ad2fe1" + }, + "src/devices/DriveWireDevice.h": { + "bytes": 1308, + "mode": "0644", + "sha256": "fb96879f9eb4b3df6d073ad97b97ae050708624c04eb32ec139c045fb6237a3f" + }, + "src/devices/DriveWireTransport.h": { + "bytes": 998, + "mode": "0644", + "sha256": "9e732a4a4a15c804637846f41962cd56d8becace860f779158242dcd6440677d" + }, + "src/devices/FD502/DiskImage.cpp": { + "bytes": 18086, + "mode": "0644", + "sha256": "7bf4fb80cf001116f53deacc2f6733392defd07c4125b7784b662c391ed94534" + }, + "src/devices/FD502/DiskImage.h": { + "bytes": 2907, + "mode": "0644", + "sha256": "a2c5522bfe8cdc144ee28feff8923268293a009bd540139623ed91dae4308765" + }, + "src/devices/FD502/Fd502Device.cpp": { + "bytes": 11401, + "mode": "0644", + "sha256": "1155c6608dc0e6fffa1ed872f38b58d54cc2c8ec8eede1be767c365a9d369140" + }, + "src/devices/FD502/Fd502Device.h": { + "bytes": 2918, + "mode": "0644", + "sha256": "d6078ba8ccfab8c4c395525bf9c73e5a1fb813d68013fb0a3f443649e3b7bf6c" + }, + "src/devices/HardDisk/HardDiskDevice.h": { + "bytes": 7411, + "mode": "0644", + "sha256": "862e786a1209fd8f7bdc9c1f027d6a5c24fa697d857a5a1a5a0ecd096154c72e" + }, + "src/devices/HardDisk/VirtualClock.h": { + "bytes": 3080, + "mode": "0644", + "sha256": "b285ed53cb0a4349f20c8dc2d2a683e7d2082289c085990660be743b948f7700" + }, + "src/devices/Orchestra90Device.h": { + "bytes": 1645, + "mode": "0644", + "sha256": "aa63234b8ebabd513e47bb381e7a9fc4749b8f82124881aef78b65932273bf10" + }, + "src/devices/RamDiskDevice.h": { + "bytes": 934, + "mode": "0644", + "sha256": "f0009bb3a30b2f388ef658f996d8ce13c72407d6ec9f711fcc9cf087cb94d955" + }, + "src/devices/Ramdisk/memboard.cpp": { + "bytes": 1507, + "mode": "0644", + "sha256": "9b21e57e0fe22ba4da898f69e38df874c1602829e1f7842cc30ecb9e776120b3" + }, + "src/devices/Ramdisk/memboard.h": { + "bytes": 1873, + "mode": "0644", + "sha256": "cc04cfa6dfad2242a70df8208f416cc7d8ab60cee0d0a1eb606672a79b570809" + }, + "src/devices/RomCartridge.h": { + "bytes": 1107, + "mode": "0644", + "sha256": "a97cca8efcf53f2372e02124568fe2d5b21d38c4ee70466264cd7b0cdc0a3f81" + }, + "src/devices/SDCDevice.cpp": { + "bytes": 39096, + "mode": "0644", + "sha256": "76e3cdebc3630f3744c2a8bf23311c5178099e13a68a0c6f02d76355667ef034" + }, + "src/devices/SDCDevice.h": { + "bytes": 1695, + "mode": "0644", + "sha256": "5ead4fb27ecd368757a033a9bb4a566c677bae8073b86a1c663e9338f2cb69c0" + }, + "src/devices/SpeechSoundDevice.h": { + "bytes": 1957, + "mode": "0644", + "sha256": "ed71b900df181e7547d925c44a82af45b1ba4f375a755bc07433d08bc6513b00" + }, + "src/devices/ssc/LICENSE": { + "bytes": 1639, + "mode": "0644", + "sha256": "ea3bce8de34d611ba6152c8879ab800377074f7ec476f92da8d38ebdabdc9bc4" + }, + "src/devices/ssc/ay8913.cpp": { + "bytes": 4804, + "mode": "0644", + "sha256": "c0fae876eb208187b583cb6cb491e73d23d07ae31ec2ae4b08d6ae96bd6a604a" + }, + "src/devices/ssc/ay8913.h": { + "bytes": 3422, + "mode": "0644", + "sha256": "341215634319d0379d1a0acc7dc83b75dfb3118ab56a40cdf0986fc0ca9630c1" + }, + "src/devices/ssc/sp0256.cpp": { + "bytes": 24220, + "mode": "0644", + "sha256": "933b2bac1a7a2a52a498a63d204f2781771e2c8e088fee131dfd811e60d2990e" + }, + "src/devices/ssc/sp0256.h": { + "bytes": 3958, + "mode": "0644", + "sha256": "4b049caece788168465df904dde1d6659057e4b32b8d0a9a02df2024dab1cd30" + }, + "src/devices/ssc/ssc_core.cpp": { + "bytes": 9216, + "mode": "0644", + "sha256": "eabe2cd224d1e173bf2556e59cbc604cbb8489f7d99ef8a560e5a1b588302025" + }, + "src/devices/ssc/ssc_core.h": { + "bytes": 6799, + "mode": "0644", + "sha256": "5d101829ee9a441cc08e10f72e4030f545f9c07c07e4f6ef8100cf90f96b8da2" + }, + "src/devices/ssc/test/smoke_ay8913.cpp": { + "bytes": 3745, + "mode": "0644", + "sha256": "303ee53535fdf1eead401dbdd6aeeac24ebeaad7473d525a115b28809ca4f025" + }, + "src/devices/ssc/test/smoke_cpu.cpp": { + "bytes": 1741, + "mode": "0644", + "sha256": "7dc5918876ed007dba8f38087dfe40861bd2c70fd792854c23a9a84a5df59060" + }, + "src/devices/ssc/test/smoke_sp0256.cpp": { + "bytes": 1789, + "mode": "0644", + "sha256": "3e9a4d9cf08972162c6ff008355b7a2b8b26210f6cb5991808c731251bfbc040" + }, + "src/devices/ssc/test/smoke_ssc_core.cpp": { + "bytes": 2496, + "mode": "0644", + "sha256": "cc411e421dd0377636d623d435741fe2a786af940f75ff5c2260d058b8691431" + }, + "src/devices/ssc/tms7000.cpp": { + "bytes": 29942, + "mode": "0644", + "sha256": "fb952c832e4f06543409c87743a8380bf237d10892ccc9c48a9e0a1d6cf5688e" + }, + "src/devices/ssc/tms7000.h": { + "bytes": 8201, + "mode": "0644", + "sha256": "8a4d946b490c7ca8d316ddaeeb992c7a2054791ba869262288dbecd93d21ae83" + }, + "tests/core/AudioCassetteChecks.cpp": { + "bytes": 13719, + "mode": "0644", + "sha256": "e1d4f4ba247d55de1fdad59f45f9fd5f69954c7b1f89659cd39c750f6cef31d6" + }, + "tests/core/BasicProgramChecks.cpp": { + "bytes": 9296, + "mode": "0644", + "sha256": "49a23d1c1a021c5cab8a530ca080c898c28c612651b2af5941f61e0e453466eb" + }, + "tests/core/BinaryChecks.cpp": { + "bytes": 37625, + "mode": "0644", + "sha256": "fd30c01d9d87a32040757daf386ece974e2da659cf9e4d5bf586820afe7178ef" + }, + "tests/core/CoreChecks.cpp": { + "bytes": 7237, + "mode": "0644", + "sha256": "bba52ad9d1c006e8f612ef5ce4e41d532431597f99daa2ae7b46402871052ffe" + }, + "tests/core/CoreChecks.h": { + "bytes": 2915, + "mode": "0644", + "sha256": "ee5e0df2dcdb0c0ee4c6cccefff9e0bc4d983def75997d526d91e8541c3fc27b" + }, + "tests/core/CpuChecks.cpp": { + "bytes": 14917, + "mode": "0644", + "sha256": "7b34fa05e42228013976fb4c78e177351f6068b4ef8393cb34b4ff5b969a5a8f" + }, + "tests/core/FloppyChecks.cpp": { + "bytes": 27033, + "mode": "0644", + "sha256": "fa3a016a771aacc72f9cadd8d5fdc043a9b039688f61aa0440166d40ac699dea" + }, + "tests/core/JoystickChecks.cpp": { + "bytes": 8083, + "mode": "0644", + "sha256": "af2bd8eb09af12f413d589d5e464fe165601c8fd7a748ab59bbb4a5e95afeabf" + }, + "tests/core/MachineChecks.cpp": { + "bytes": 12458, + "mode": "0644", + "sha256": "c13051cff64d380cb4367bb3f4205e583a1144c8d5e9d59acac3a6fcc261cbc0" + }, + "tests/core/RomBootCheck.cpp": { + "bytes": 50520, + "mode": "0644", + "sha256": "28b522b38145d4fe2fccfb340e4a80facffdc3043b03162802bcffecbd75cdab" + }, + "tests/core/SessionChecks.cpp": { + "bytes": 26844, + "mode": "0644", + "sha256": "bd7d99cfc8d49dc9995bc87266e690dacd021225a1d156cbce0fdd546f930962" + }, + "tests/core/TestMachine.h": { + "bytes": 4917, + "mode": "0644", + "sha256": "aa02894ac4c413a0acb31827e184a4a7a49137e8166e306a6ef76d0f03904f05" + }, + "tests/core/TimingChecks.cpp": { + "bytes": 6481, + "mode": "0644", + "sha256": "a1ebe8c4f9cf39ebfe20803486b3bdddf461e1a0aeab083faa0e6188b2a477ef" + }, + "tests/core/VideoChecks.cpp": { + "bytes": 16133, + "mode": "0644", + "sha256": "d2c44e0cf28be6f6b7d0d52add8513c0b1e94792b7e17bd413714fe00f7e572f" + }, + "tests/core/main.cpp": { + "bytes": 6963, + "mode": "0644", + "sha256": "51f94eaaa85718c890d99490cc3787bb80a71bc092bf58bb2e8fcc1d0ada099a" + }, + "tests/macos/InterfaceUIProbe.swift": { + "bytes": 8245, + "mode": "0644", + "sha256": "57b60cea6c5f50b4e746c435c158278aa75b66f327833172d22fcf446d8409f4" + }, + "tests/macos/MediaDragProbe.swift": { + "bytes": 3961, + "mode": "0644", + "sha256": "572e355ae3ae54c6228d7e756c6acd90aec4d7bc5a620c753ab326fa359e239d" + }, + "tests/macos/SoftwareLibraryOwnedRecordProbe.swift": { + "bytes": 1751, + "mode": "0644", + "sha256": "b75bee410b1ae607c2589bd2fd0020c5d4625ea212d9d20b4dd8fd91f3d974ae" + }, + "tests/macos/SustainedChecks.mm": { + "bytes": 7739, + "mode": "0644", + "sha256": "9b84b495bfa69fe45b340ce54a206f72295b5190028647b1db81c5b67e66ab3f" + }, + "tests/macos/audio-game-validation.cpp": { + "bytes": 7273, + "mode": "0644", + "sha256": "0389678992e168d583ec9ba94fcd862bcb81af7a5fc27a67b6afe63e522806c5" + }, + "tests/macos/capture-secondary-windows.py": { + "bytes": 2760, + "mode": "0644", + "sha256": "9ece45d3adc2ccf2549544a77e75a1896b393fc78e2eee796febf1704b20425a" + }, + "tests/macos/catalog-launch-probe.cpp": { + "bytes": 5193, + "mode": "0644", + "sha256": "83f4f37303848eef30476270fc2258a39d19838220741ae92aa1950820f43d9b" + }, + "tests/macos/companion/SignedTransportPeer.swift": { + "bytes": 2384, + "mode": "0644", + "sha256": "e5623e9936ab666afc61d2f9708eb47bd31bcc5a758da815d9389f397f7ebfca" + }, + "tests/macos/companion/TransportChecks.swift": { + "bytes": 9058, + "mode": "0644", + "sha256": "3c5dcce97337b05b137874690afdd895224eae0ec26ad5742b6c6f4efc9285b9" + }, + "tests/macos/companion/ValidationChecks.swift": { + "bytes": 4481, + "mode": "0644", + "sha256": "e3966c1066deaf577d5bb32e13a4f6fc181579d25b6e77da899cd64522a517bf" + }, + "tests/macos/companion/run-transport-checks.sh": { + "bytes": 558, + "mode": "0755", + "sha256": "bed7d286ea0669d3511fbe8979859c46bc1416159d6c831a6d8fa753afc358ce" + }, + "tests/macos/companion/run-validation-checks.py": { + "bytes": 2721, + "mode": "0755", + "sha256": "117cbcc22f2f6b68cc7e678b537f13be7ef555393f6751f60fb864a4172a20c0" + }, + "tests/macos/drivewire-cowin-probe.cpp": { + "bytes": 3480, + "mode": "0644", + "sha256": "b75ca8ee9b95ca1122b5ca75a3bc63629c42f25e8a800f68267e41ff2f11f8b9" + }, + "tests/macos/drivewire-guest-check.py": { + "bytes": 3438, + "mode": "0644", + "sha256": "b442c79bd78eb8683c6806d4574475028a38391e4d7e46e1adcce7fc6c372e7a" + }, + "tests/macos/drivewire-guest.cpp": { + "bytes": 8935, + "mode": "0644", + "sha256": "32fa68a404939cda93abb028487e1e15fe8989ce20369c29ba3dba3e82664180" + }, + "tests/macos/drivewire-shell-probe.mm": { + "bytes": 6333, + "mode": "0644", + "sha256": "c14f8c5dd946d6daf22c03913234abca4025118f2f68f191b3e68b2d4b25a630" + }, + "tests/macos/drivewire-tcp-probe.mm": { + "bytes": 4678, + "mode": "0644", + "sha256": "a0a04797e8fa16019248a21e8ff35a7007ba70d52d495bc6605419cc2694a965" + }, + "tests/macos/drivewire-terminal-probe.cpp": { + "bytes": 5669, + "mode": "0644", + "sha256": "065540bed4f2e044cfc39b2312d1c9d7cfd725d8a729f8bb2566519034418b52" + }, + "tests/macos/fd502-media-probe.cpp": { + "bytes": 7003, + "mode": "0644", + "sha256": "6f4a83bb41d9a1c27dcebd5a8585731f2f2b29d2de5e6ea9bc00eb076bcdc819" + }, + "tests/macos/run-sdc-validation.sh": { + "bytes": 1579, + "mode": "0755", + "sha256": "c2550314435224e7607da6ed962fbaa2b33c7be1548a5630f0c51bdd9e547446" + }, + "tests/macos/run-sustained-check.sh": { + "bytes": 1588, + "mode": "0755", + "sha256": "48551be32f5777043d5533742a729d13a58cbb0636f6cc686a6872990f18052e" + }, + "tests/macos/scripsit-compatibility-probe.cpp": { + "bytes": 3877, + "mode": "0644", + "sha256": "0662d6df0c400784395eb4925fccb2151558851d7f6d9ee8a04eda8ac6a6ad52" + }, + "tests/macos/sdc-validation.cpp": { + "bytes": 10266, + "mode": "0644", + "sha256": "5317feb79906f2628a29fe81c482161c3030cec56204583d82aa5c5a028f5844" + }, + "tests/macos/test_development_starter.py": { + "bytes": 6428, + "mode": "0644", + "sha256": "cf2c5e2201247a5c32df0a44139cae4524f4102bc8cc782d96e0a883371354ef" + }, + "tests/macos/test_nitros9_media.py": { + "bytes": 7137, + "mode": "0644", + "sha256": "56409a37b0734dd7efcca652ea90bc4f8607b9e45eb234757ae103175ff14176" + }, + "tests/toolchain/atlas-backup-demo/check.py": { + "bytes": 6064, + "mode": "0644", + "sha256": "16a19d23425ee0d6ecb495b89c3ff13b60f98ad2c347e82c09c594060c881dfe" + }, + "tests/toolchain/atlas-backup-demo/run.cpp": { + "bytes": 2172, + "mode": "0644", + "sha256": "bde06337a7f0544f8c4ef2f7d9ab1ff919061c3d0d2c9882e82ae6b385d4cbef" + }, + "tests/toolchain/atlas-demo/check.py": { + "bytes": 4159, + "mode": "0644", + "sha256": "0ca753485cf7a1d8e6958e55479ddd736da6e33825be505939c283b8786bec50" + }, + "tests/toolchain/atlas-demo/run.cpp": { + "bytes": 3857, + "mode": "0644", + "sha256": "be0d999ca4398b36c1998837869b34208bb7f0eadcd92d418a692bc28d8be74c" + }, + "tests/toolchain/bank-demo/check.py": { + "bytes": 2156, + "mode": "0644", + "sha256": "27147b8a37e1308ef8b1e740080b2b586f0c1733acbc58f0ff89e965205c4d98" + }, + "tests/toolchain/bank-demo/run.cpp": { + "bytes": 4127, + "mode": "0644", + "sha256": "f70cc8ac6c2593eff581c2c3bf3d56cb2b10ea16994d16cbf16f707449a3b021" + }, + "tests/toolchain/bank/check.py": { + "bytes": 2074, + "mode": "0644", + "sha256": "2eb8b381f7c68670d7b4d618c4413108cb1eadac4f1fcebfecf93e705d7230ec" + }, + "tests/toolchain/bank/qualification.c": { + "bytes": 3325, + "mode": "0644", + "sha256": "85efcd866e88546c174052819c8c86ac383844507bb48a9b6cbd0609704c809f" + }, + "tests/toolchain/bank/run.cpp": { + "bytes": 7315, + "mode": "0644", + "sha256": "3a45e70c8d128f9e303906f3f856c6df050cc547ae46fac2b12d2ee88899e617" + }, + "tests/toolchain/basic-disk-session.h": { + "bytes": 6893, + "mode": "0644", + "sha256": "e56070e1fc2968adfbd640ad4e1b9eb7e74ead624617a177e0a7c811971dc106" + }, + "tests/toolchain/cassette-demo/check.py": { + "bytes": 2675, + "mode": "0644", + "sha256": "80777d2fc7d5cdf79e7162986a11d75d485809a333f6d3f451f92b3433a90f9a" + }, + "tests/toolchain/cassette-demo/qualification.c": { + "bytes": 2885, + "mode": "0644", + "sha256": "755f47402322ddc2a65248209f31a548c3702e3cb18ba5d3d9993d5ee8c7aa85" + }, + "tests/toolchain/cassette-demo/run.cpp": { + "bytes": 8753, + "mode": "0644", + "sha256": "32fa5459d4519924bc2ec1b2e0859482d978a84ab6ecc6d71166484833934608" + }, + "tests/toolchain/expedition-demo/check.py": { + "bytes": 3230, + "mode": "0644", + "sha256": "40fb180e3be0ad3020aff79c268977ad43f74410aede9fec39dbc2692ca50939" + }, + "tests/toolchain/expedition-demo/run.cpp": { + "bytes": 4086, + "mode": "0644", + "sha256": "365ef31be7f12d9fce5519d77e8e01368572e7036f6f85036dfc300699248593" + }, + "tests/toolchain/fixed-decimal/check.py": { + "bytes": 5857, + "mode": "0644", + "sha256": "8ebba705f189bc7b6ba8b6ed126f154787fbe931217ef1af2af0eef6dfbd1a8b" + }, + "tests/toolchain/fixed-decimal/qualification.c": { + "bytes": 2148, + "mode": "0644", + "sha256": "28eb014a22548afbe7fb9131eb834758add8de30eb19b87a386c1491ec305ba8" + }, + "tests/toolchain/fixed-decimal/run.cpp": { + "bytes": 2779, + "mode": "0644", + "sha256": "56547a27f619b919961f25deec1cf58137bd63dc3162bed8e5b11f9825e1f6bd" + }, + "tests/toolchain/float.c": { + "bytes": 270, + "mode": "0644", + "sha256": "d89b5c9e24422540e2ac434f43fc70bae4781aef2b575af7572678fbdff01609" + }, + "tests/toolchain/gime/check.py": { + "bytes": 2809, + "mode": "0644", + "sha256": "6e955b3222596066555b0c3732cfd79ffd59dd4de166543a3abe204ec1794761" + }, + "tests/toolchain/gime/disk.cpp": { + "bytes": 1780, + "mode": "0644", + "sha256": "c586c6ac20ff59eae32d7fe5259be13a4d014be2a671ae94e8e1424b5ad29c96" + }, + "tests/toolchain/gime/disk.py": { + "bytes": 987, + "mode": "0644", + "sha256": "2d9f242c6cbb17f8c4bd92fe82e191037c14a3ee76c351b397b969a2ddd9f873" + }, + "tests/toolchain/gime/qualification.c": { + "bytes": 2827, + "mode": "0644", + "sha256": "2d51398f0795d4a418c7f8c9e10a65114fa74df3ba583fdf6e344a63251d687f" + }, + "tests/toolchain/gime/run.cpp": { + "bytes": 15289, + "mode": "0644", + "sha256": "4a5d72b5787e127fc5e9e2f8433899b3fbfa40b3aeba55cb26c46924bf34495a" + }, + "tests/toolchain/guest-captures.h": { + "bytes": 1977, + "mode": "0644", + "sha256": "f0daf8d52f624fcfbaf13b5510d0c8f16cd8eb830e4d5ceb75fe53ca557a17a8" + }, + "tests/toolchain/heap/check.py": { + "bytes": 1753, + "mode": "0644", + "sha256": "5f7c29728a57e799faa16adfd2f9e3bbc68e56cd59d4d9cd49dd29323883b4e9" + }, + "tests/toolchain/heap/qualification.c": { + "bytes": 4190, + "mode": "0644", + "sha256": "d77a0e5e7654f1f349c7649a6b29a59de8b7613bb24943a0b8a2db0d5b152f19" + }, + "tests/toolchain/heap/run.cpp": { + "bytes": 2839, + "mode": "0644", + "sha256": "422162146865fd1bf7aefdbbe15563ce685a6607fd6c3fc3301eca85310f586f" + }, + "tests/toolchain/hello.c": { + "bytes": 132, + "mode": "0644", + "sha256": "85c5f67b4504983229c765940eda45492beb6cd81f18d57b12b53d4177792e34" + }, + "tests/toolchain/indexed-arguments/check-rule.py": { + "bytes": 1511, + "mode": "0644", + "sha256": "7b5c2a08c59a1a4d54b21d8a27811601d84f7d4be77d15f4654fa0e12b11a672" + }, + "tests/toolchain/indexed-arguments/check.py": { + "bytes": 2216, + "mode": "0644", + "sha256": "1a921c7d801a0b938aca9651695d9ba83099461d2bf5309c0d17c8262c4058fc" + }, + "tests/toolchain/indexed-arguments/optimizer-rule.cpp": { + "bytes": 1781, + "mode": "0644", + "sha256": "571007ed721c09916cd844142a1e56125c06aea7bb09ddb1b0dc3df0c305fad5" + }, + "tests/toolchain/indexed-arguments/qualification.c": { + "bytes": 1969, + "mode": "0644", + "sha256": "7fa79b1fc1ace0947ffb5fbaba0dba8458fec81533ea1ed3ce7b9424d9845cbf" + }, + "tests/toolchain/indexed-subtraction/check.py": { + "bytes": 1739, + "mode": "0644", + "sha256": "8b6bc93a8e21f0c5618b94f27322558a5eabdb9e5f09332da7532a085fb58046" + }, + "tests/toolchain/indexed-subtraction/qualification.c": { + "bytes": 1667, + "mode": "0644", + "sha256": "3c6abd1df4759bcf422afd1f6fb344154135fb70f5c747f5bb39ba64e4a6d1ad" + }, + "tests/toolchain/input-demo/check.py": { + "bytes": 2257, + "mode": "0644", + "sha256": "8dd269fdb7f43a36a8f45d12f02e974af77795356fc3b41c68072e0ad8120472" + }, + "tests/toolchain/input-demo/run.cpp": { + "bytes": 5196, + "mode": "0644", + "sha256": "3121f04b0677f7dd8f5664636d933ea27d5baf19ffb255649577d1365a1db6d1" + }, + "tests/toolchain/input/check.py": { + "bytes": 1916, + "mode": "0644", + "sha256": "debf7de8cd5659331ca500872a3b6f16b4cd12cfef0a5ab226d8d13b0ea95fa5" + }, + "tests/toolchain/input/qualification.c": { + "bytes": 4372, + "mode": "0644", + "sha256": "4fabe830105f728aaa1c9f18442f65af83809c0db105addfe0d337a58182ac3f" + }, + "tests/toolchain/input/run.cpp": { + "bytes": 8556, + "mode": "0644", + "sha256": "9ff8c1f8941b3ce735724612fc03c260784b39fff72df8cc6c506f9ec1db97b1" + }, + "tests/toolchain/logical-negation.c": { + "bytes": 838, + "mode": "0644", + "sha256": "72ee74e115a0381f1c6854e460a05d9e8efadaf62489f58586e34c1d132bf43e" + }, + "tests/toolchain/mission-recorder/check.py": { + "bytes": 5723, + "mode": "0644", + "sha256": "270f2b2fda09c72d9701af393fe4294bed1e3fb544541ac90d8713f825b4b900" + }, + "tests/toolchain/mission-recorder/profiles.cpp": { + "bytes": 1247, + "mode": "0644", + "sha256": "9c1588a459762b7735f32dc7a4e99134186a00cabc9d1034a9e4c5eecb84f0c9" + }, + "tests/toolchain/mission-recorder/run.cpp": { + "bytes": 10292, + "mode": "0644", + "sha256": "d876d5935ae8b3119158bbb993220c0da912b186c5d920c33ccb91d6ca648653" + }, + "tests/toolchain/number-conversion/check.py": { + "bytes": 2335, + "mode": "0644", + "sha256": "5cac0e7f664d6031420d1d58eb2c58ee63df9eb95b533b25ff76c3be7fb0d7cc" + }, + "tests/toolchain/number-conversion/qualification.c": { + "bytes": 4452, + "mode": "0644", + "sha256": "927eb17168ac49cff4dda4f6c723c06fb73c50b85c611c5e0ec678f5eed47996" + }, + "tests/toolchain/orch90-background/check.py": { + "bytes": 2333, + "mode": "0644", + "sha256": "b68201e8baea4591335707666a9dadff1abbd5cf308430adef878eba713ddc3a" + }, + "tests/toolchain/orch90-background/qualification.c": { + "bytes": 5928, + "mode": "0644", + "sha256": "72f06dd3d0c5573b251adaa4c8246147ba7c5466c152a1f309acdc4ff1f9c321" + }, + "tests/toolchain/orch90-background/run.cpp": { + "bytes": 9260, + "mode": "0644", + "sha256": "139ee18c1bdca77bb077c388a87f4200ceb3e88d2b9fbbd274c085711da757fd" + }, + "tests/toolchain/orch90/check.py": { + "bytes": 1183, + "mode": "0644", + "sha256": "fd9979075bfc96a635041374f8fb9c9101c49736048de44775bfc7d6ff9e9277" + }, + "tests/toolchain/orch90/measure.cpp": { + "bytes": 3691, + "mode": "0644", + "sha256": "68123da6bee5ef44f5122a8019aa6cf5fb1037ae737591bf220e030da1684f0a" + }, + "tests/toolchain/orch90/playback.c": { + "bytes": 1465, + "mode": "0644", + "sha256": "fc37a94c6c86f24a9f9ad3251a3d857b46a3f2a393f187f8f3741d970db8722e" + }, + "tests/toolchain/printer-demo/check.py": { + "bytes": 2512, + "mode": "0644", + "sha256": "76dcbe22497a164ec0ef001ffafa6ac43b022ff6a4b55d4faaf19115b184aee5" + }, + "tests/toolchain/printer-demo/qualification.c": { + "bytes": 1351, + "mode": "0644", + "sha256": "684c91d7546c354cc82345c9d6788b380fafb34c93cee2e270180cba39a46ec3" + }, + "tests/toolchain/printer-demo/run.cpp": { + "bytes": 2533, + "mode": "0644", + "sha256": "6faad277bf2f202db073a73f1553b630d11b508abd7f7c8465b22789d560d67c" + }, + "tests/toolchain/run-coco-letters.cpp": { + "bytes": 4185, + "mode": "0644", + "sha256": "a4b4bf08b37f19710ad503ba8a4740c148163d71b647df47fc37183f00344495" + }, + "tests/toolchain/run-compiled.cpp": { + "bytes": 2100, + "mode": "0644", + "sha256": "87f40eaf8472219a873c2408b69ebf667b87a621bd47e3736857683ee8002778" + }, + "tests/toolchain/sdc/check.py": { + "bytes": 3175, + "mode": "0644", + "sha256": "78ab65e01cff51d0a5a49b926e43ae72f35812b85dd3ae367a63ece14ea87338" + }, + "tests/toolchain/sdc/qualification.c": { + "bytes": 5883, + "mode": "0644", + "sha256": "1add704addfda203966ad6d2c61c2ad0a3acddb01c9d822d3de0589044813b77" + }, + "tests/toolchain/sdc/run.cpp": { + "bytes": 4817, + "mode": "0644", + "sha256": "81d772365577d5121ba4b717e648a169f1d5f055efb820dc62b30fcc12834ee0" + }, + "tests/toolchain/ssc-demo/check.py": { + "bytes": 2353, + "mode": "0644", + "sha256": "93ee4296d9669f27e57f653cd35d6a5e3b4ece270abe028203a4ec29caf40700" + }, + "tests/toolchain/ssc-demo/qualification.c": { + "bytes": 3649, + "mode": "0644", + "sha256": "188cf58dacfdb63d4d4c06d35ed1ee8824363ad2b43ed2d32b3d02714bd35c65" + }, + "tests/toolchain/ssc-demo/run.cpp": { + "bytes": 8153, + "mode": "0644", + "sha256": "18e6111f4c25292feeabaaa6593e08f2bf178df14b9990350c4cc71450d18fc3" + }, + "tests/toolchain/ssc/check.py": { + "bytes": 1887, + "mode": "0644", + "sha256": "756174d604fc3fb4da671c2ac585afc84f04ef1bfd624fbb38266bfaaf761ac5" + }, + "tests/toolchain/ssc/qualification.c": { + "bytes": 2877, + "mode": "0644", + "sha256": "357cfa7e98122735ea39d325113d0301d0ab73be73a62607e394f048c7b104fc" + }, + "tests/toolchain/ssc/run.cpp": { + "bytes": 6660, + "mode": "0644", + "sha256": "86a96ac3d31ceb27f462c578dc19d8e6599fc15eae62d87723d9b8c79192b630" + }, + "tests/toolchain/ssc/session.h": { + "bytes": 4706, + "mode": "0644", + "sha256": "701fe207d795ceb5680a9d367c432ed6198257ee3979f7103b826db7fe5fa054" + }, + "tests/toolchain/stream-write-demo/check-returntrip.py": { + "bytes": 3456, + "mode": "0644", + "sha256": "3000185dff78ff454c2f159b6c52470b69b5478b2824ecbb17529b5221333765" + }, + "tests/toolchain/stream-write-demo/check.py": { + "bytes": 2992, + "mode": "0644", + "sha256": "f1ac9bcef0fe45770417d3dfbff37e18f429228d64bd5dd13396709cb9967b59" + }, + "tests/toolchain/stream-write-demo/returntrip.cpp": { + "bytes": 3022, + "mode": "0644", + "sha256": "3eb89a64e81a3016f4a1c4c850afd8d9d6812126878b78c9585166d841fa991b" + }, + "tests/toolchain/stream-write-demo/run.cpp": { + "bytes": 3159, + "mode": "0644", + "sha256": "999031e015c060299f9c2fd0d6e6f8eaae36dde24d9dbc3450100fcfead745f8" + }, + "tests/toolchain/stream-writes/check.py": { + "bytes": 14306, + "mode": "0644", + "sha256": "42202b72544a9fa5bead395b7312255eab9d89f7393a09318c8789bb9045a688" + }, + "tests/toolchain/stream-writes/directory.c": { + "bytes": 3262, + "mode": "0644", + "sha256": "2e99c5a3b942b57b9387d26ca1f2ac355b1f4267d04684e0b234a4f90aff242b" + }, + "tests/toolchain/stream-writes/formatted.c": { + "bytes": 2745, + "mode": "0644", + "sha256": "b79993ef61fd13669b8580d5116c130fe8db4b2e3ef186a4e818c1fd1152ca10" + }, + "tests/toolchain/stream-writes/mixed-rewind.c": { + "bytes": 1249, + "mode": "0644", + "sha256": "1bfe429b15c7f8f447833af357d8126d95a5767a74ecc06eb790399013889a55" + }, + "tests/toolchain/stream-writes/position.c": { + "bytes": 6659, + "mode": "0644", + "sha256": "7bd9d6dfc432e999bb02aac1d06b872b6783f2dbe311a06a2b64d7a7131943a7" + }, + "tests/toolchain/stream-writes/qualification.c": { + "bytes": 6295, + "mode": "0644", + "sha256": "3f09bdaf88be9ecb7a41e2a7ba78b8b4b078c4460c95a14c5bfcc6a80c3a2878" + }, + "tests/toolchain/stream-writes/refuse-fat.c": { + "bytes": 737, + "mode": "0644", + "sha256": "60fb1514d735668c7b0989d38e1237f2749e45be0a338c5f72f260738c8f745d" + }, + "tests/toolchain/stream-writes/run.cpp": { + "bytes": 6412, + "mode": "0644", + "sha256": "ec05822d5b4ee3653df6204c0ae455ed0f8b4de9ce60a29361f0ddadee9bce73" + }, + "tests/toolchain/stream-writes/update.c": { + "bytes": 5939, + "mode": "0644", + "sha256": "c27443dde4a6ea1200b984940943822cdc155759e7e0c0f4175c159b481525ff" + }, + "tests/toolchain/streams/check.py": { + "bytes": 5380, + "mode": "0644", + "sha256": "bc8c2852c0252cdeceafe3661c78249a6f5abe420a327c15c8333d2b2f3c33f0" + }, + "tests/toolchain/streams/qualification.c": { + "bytes": 4601, + "mode": "0644", + "sha256": "34681d5979ac619351e4297eb9f596f3bddb48d504212dbba65283be337ac8fd" + }, + "tests/toolchain/streams/run.cpp": { + "bytes": 4266, + "mode": "0644", + "sha256": "5407af7f72a2ecb160f211e596665d961a2e0c7668f8c2bc58d5757607199e28" + }, + "tests/toolchain/test_cpp_adapter.py": { + "bytes": 3979, + "mode": "0644", + "sha256": "43302b89c5e8a6364cf36fbdc60a2a97a3ae8e4222aa54b70a85b3a7a64c4bea" + }, + "tests/toolchain/test_development_templates.py": { + "bytes": 2598, + "mode": "0644", + "sha256": "177d558ac2fbb0083294ee4a6e76d065002e321e3dcf7e9cb33c4886d37c14d7" + }, + "tests/toolchain/test_runtime_inputs.py": { + "bytes": 2248, + "mode": "0644", + "sha256": "a93c8634fd4cfe3966a9f3a9c822c4ecb01fdce14ddf426533978c82a950d3ef" + }, + "third_party/README.md": { + "bytes": 2710, + "mode": "0644", + "sha256": "5ba09be438b1e5d7664d43e9ba513c3e72fc910e71aa5e5149a8d79af3c60b9b" + }, + "third_party/manifests/astar.json": { + "bytes": 1295, + "mode": "0644", + "sha256": "b33a8fb8d9ffc01cd462f61d3da5017e22710dd875b6358b11205464a326ccf3" + }, + "third_party/manifests/bcontrol.json": { + "bytes": 3566, + "mode": "0644", + "sha256": "fefa57d173942eb2314e20f0557c9ec5d164e36a7073a2e7de808b2c025f4e6f" + }, + "third_party/manifests/bgraph.json": { + "bytes": 13098, + "mode": "0644", + "sha256": "5b2dad39264543b61c00ae089f6b05334ee5743696ce98a79e7c8ff9477aebc4" + }, + "third_party/manifests/bsound.json": { + "bytes": 2934, + "mode": "0644", + "sha256": "78dd3469a2f4d29e11f475d69c519847f217786241e100952d879dac0acf0909" + }, + "third_party/manifests/cardgame.json": { + "bytes": 7654, + "mode": "0644", + "sha256": "111c78000e57810268256df193df81e5916b54cb7587cc43e017eb91dab4a88e" + }, + "third_party/manifests/cmoc-make-dependencies.patch": { + "bytes": 5874, + "mode": "0644", + "sha256": "e21ef9e60c338d660d0716386c40f7ef496f74e08cefb104e66053b89ccc51b8" + }, + "third_party/manifests/cmoc-source-only.patch": { + "bytes": 3821, + "mode": "0644", + "sha256": "b20ec7d762c793c8baf120924f3d3e1b7d7d238bd8950b2e511062da6a6f4614" + }, + "third_party/manifests/cmoc.json": { + "bytes": 101346, + "mode": "0644", + "sha256": "17d6b9a919b95d1b683f44af5dae5f0d2d9d97f0a63b9a023c18417781eb750f" + }, + "third_party/manifests/coco-letters.json": { + "bytes": 5528, + "mode": "0644", + "sha256": "3e8592675aebf0ed4260b4fd538301189ea133818032936815dcc9356a1f3230" + }, + "third_party/manifests/decbfile.json": { + "bytes": 16744, + "mode": "0644", + "sha256": "f9f3f5805b8ad676c6eff040fa50c7f2d8c8b395d9be61fb610ef97e495a2621" + }, + "third_party/manifests/ebitor.json": { + "bytes": 3795, + "mode": "0644", + "sha256": "df3053788d594270b3af76abd479a69503720530dc94a4f236c05d17ead4aa41" + }, + "third_party/manifests/hirestxt.json": { + "bytes": 8852, + "mode": "0644", + "sha256": "765c8e53ac77db4912c647c4791be2133e53623489ba8fc73a349758d6803c1c" + }, + "third_party/manifests/lwtools.json": { + "bytes": 30725, + "mode": "0644", + "sha256": "185dac5ed9a84f237bdbcf23e92c537da468792f124edad6c301f5cab5a87760" + }, + "third_party/manifests/make.json": { + "bytes": 75794, + "mode": "0644", + "sha256": "7c1308c886f4d09b244463dbd45530ce8c7bad9c85e82ab75f01b4522c24def9" + }, + "third_party/manifests/mcpp.json": { + "bytes": 160627, + "mode": "0644", + "sha256": "1c367e09470efe55f5e5991ef920c09b94f4818c42a9c1f01aa9e3575c604565" + }, + "third_party/manifests/perl.json": { + "bytes": 1455647, + "mode": "0644", + "sha256": "db2e5e1f4a7a9756c098ae62aa71947019e116479968a09f89303b6550eccbf2" + }, + "third_party/manifests/toolshed.json": { + "bytes": 11765, + "mode": "0644", + "sha256": "cf3355fa522e6d768e427ec432aed8da91268ddab8e7fb488deaa3fea68b85bd" + }, + "third_party/manifests/wydealloc.json": { + "bytes": 2482, + "mode": "0644", + "sha256": "9360706794c291416823adf9dfe01359c55af0d2a22e9f4fbd22e59526986ec3" + }, + "tools/build_content.py": { + "bytes": 5043, + "mode": "0644", + "sha256": "e5c9e4e68c783ea8a85bab636d702af25174c711fc450c20a33ee5985f07033a" + }, + "tools/catalog/app-schema.sql": { + "bytes": 2834, + "mode": "0644", + "sha256": "ca694620918b35b5775f154262dd3318d90a57ca686ed8d42ecee66c6a0db48c" + }, + "tools/catalog/package.py": { + "bytes": 14932, + "mode": "0644", + "sha256": "3a4685c3598b25ff8bc43930a1a5d3b171ea4fffe8f3db8e71577c23237dfd2d" + }, + "tools/dependencies/fetch.py": { + "bytes": 17751, + "mode": "0644", + "sha256": "c2bb8d533151641dfbfa08b72c9d349c9fa17ac89992df9ac3bd0b4b3a21b3a3" + }, + "tools/dependencies/manifests/cocoroms.json": { + "bytes": 2733, + "mode": "0644", + "sha256": "cc3b9fc10badbeedc9c25a7a156055be9de56e5456b284064569997c3f892d2f" + }, + "tools/dependencies/manifests/legacy-graphics.json": { + "bytes": 1679, + "mode": "0644", + "sha256": "fd8a8d3055b99398d858adfa6efb0939b7a10f06057b171d14115da940825b3d" + }, + "tools/dependencies/tests/test_fetch.py": { + "bytes": 14289, + "mode": "0644", + "sha256": "edef586592f027bcaf06340cacb4383947e7264c13620c870ad58a62f0ae9efe" + }, + "tools/knowledge/archive-library.sql": { + "bytes": 2437, + "mode": "0644", + "sha256": "4e5c1b724c852f316ad818ef41a773755a4938de53c75cbedfd21e99f6fde130" + }, + "tools/knowledge/package_archive.py": { + "bytes": 5865, + "mode": "0644", + "sha256": "3b6f94b0210c6e9b01062e1c40ad1cccc66710e940f62b9abfe8a9ee1ce7fd6e" + }, + "tools/manuals/lookup_resources.py": { + "bytes": 7648, + "mode": "0644", + "sha256": "b2e8e974d1dce5dcad916f9e51a0cd220024fb76d5de485fed6403ac1546de28" + }, + "tools/oss/check.py": { + "bytes": 6690, + "mode": "0644", + "sha256": "bd670075b8406d05bcb23a13b444f98d5a0fab191ca7aef1d8efa3b9fcd45029" + }, + "tools/oss/publication_urls.py": { + "bytes": 1120, + "mode": "0644", + "sha256": "9355734a6b3365ec3882904ab175c9682c35905092fe158eb701e860122a5eea" + }, + "tools/roms/build.py": { + "bytes": 13366, + "mode": "0644", + "sha256": "b318ecc600a600a8c07a734494dbf5ec8d4bcb06b3ad68db23ef41b5bb392af9" + }, + "tools/roms/core_inputs.py": { + "bytes": 1000, + "mode": "0644", + "sha256": "bd739dc674e916ef8a5a8e93df89045d12010ce574bf4f7ae04f38964aee2114" + }, + "tools/roms/stage.py": { + "bytes": 14776, + "mode": "0644", + "sha256": "d609b3f973d6b25066fb071896e69ba30967d5dce74f8a37603cca7749224200" + }, + "tools/roms/tests/test_build.py": { + "bytes": 9277, + "mode": "0644", + "sha256": "9c809929449d6139d4be7ae0cbf19d67091225730279449bbdef13cfb308322e" + }, + "tools/roms/tests/test_stage.py": { + "bytes": 24677, + "mode": "0644", + "sha256": "b6d7c59f754e86e77346e6c14d6ecb695aa32b525b2c7ca55afb093af694756c" + }, + "tools/tests/test_build_content.py": { + "bytes": 14195, + "mode": "0644", + "sha256": "9f54794ec5d3b33cc0237622b19af87284f132e94d8401872dc5b42babd38772" + }, + "tools/toolchain/build-coco-letters.py": { + "bytes": 1886, + "mode": "0644", + "sha256": "c7c3c8482d2903fcd46fa0ceab729a9132d530e9486688b1a29b4cf99ebddb8c" + }, + "tools/toolchain/build-perl.py": { + "bytes": 1931, + "mode": "0644", + "sha256": "b7a72d210df83fab0be7f5667c702f28c80affa176ac5f903857ae5edd447569" + }, + "tools/toolchain/build-runtime.py": { + "bytes": 5528, + "mode": "0644", + "sha256": "aa0de1a3dc18b26b047ca88069d19d2a981e0b5e5ac3251b362313b19a33d2f1" + }, + "tools/toolchain/build.py": { + "bytes": 5747, + "mode": "0644", + "sha256": "072dfd12fbee00c4558fb56cbda0144fef65db505a2f6274737fe0dd22a4f71b" + }, + "tools/toolchain/check.py": { + "bytes": 4647, + "mode": "0644", + "sha256": "6f7dde1c241660538b3945fb550c75114d6ec0fc2748cd4f0feb51ae0c7f1fbf" + }, + "tools/toolchain/cmoc-runtime.sh": { + "bytes": 888, + "mode": "0644", + "sha256": "b83e6ea79da5160cd85f5b7665524f19f717a4a6e76e12e661900dc071a1cea6" + }, + "tools/toolchain/cpp-macos.sh": { + "bytes": 257, + "mode": "0644", + "sha256": "7722bc7b0fc5c1ddd44ca3aa63da1387aa0cb5debe784964e6777f9ec045f32f" + }, + "tools/toolchain/cpp-mcpp.c": { + "bytes": 7501, + "mode": "0644", + "sha256": "2a44cc4021200502e3144f134cd3806c1ed9ffd860d7a9d88f2fea8ec7893684" + }, + "tools/toolchain/patches/README.md": { + "bytes": 8085, + "mode": "0644", + "sha256": "b7a3e3068f2b6ed0abb7b0695abb128a14639a7fe6590504d5d4806928a7c788" + }, + "tools/toolchain/patches/cmoc-add-zero-flags.patch": { + "bytes": 3095, + "mode": "0644", + "sha256": "3941ae548e2e6cf31ed576838eb4bb211047fe2b6d2bf5d13772a342865b97b8" + }, + "tools/toolchain/patches/cmoc-debug-metadata.patch": { + "bytes": 10450, + "mode": "0644", + "sha256": "70e1547200f3bbf4182a03c3456a1d7d275c7d1a3a7bf3b0bb03c13e54681aff" + }, + "tools/toolchain/patches/cmoc-indexed-argument-load.patch": { + "bytes": 1984, + "mode": "0644", + "sha256": "33cb77adf7c4bca6189cd3f34831a9f204359531b631daf9487116e4a82cd403" + }, + "tools/toolchain/patches/cmoc-indexed-byte-subtraction.patch": { + "bytes": 2645, + "mode": "0644", + "sha256": "0e54d09d96f8e67311907351c73d29dd2518fed8348eb7db648eedcd957b23fd" + }, + "tools/toolchain/patches/lwtools-project-inputs.patch": { + "bytes": 10537, + "mode": "0644", + "sha256": "b4c0be753b3d68fead830575d6fa4e407aa0920e93e69ea809bfb28c766a263a" + }, + "tools/toolchain/patches/writecocofile-before-dir.patch": { + "bytes": 1567, + "mode": "0644", + "sha256": "8d8d459ccea4966135d4e65b4a5e8c48898a974243b448c2066db1f158a33025" + }, + "tools/toolchain/perl-launcher.c": { + "bytes": 1179, + "mode": "0644", + "sha256": "e72a89dfaeca4365ecdb11d0d5c75ff7e314907acc66ca7720b1d1b1d1f5383b" + }, + "tools/toolchain/prepare-coco-letters-project.py": { + "bytes": 4980, + "mode": "0644", + "sha256": "514f1e865ad925a9f74ffe7942b362834353097d37699274c9ba49bdba66a436" + }, + "tools/toolchain/runtime_inputs.py": { + "bytes": 1654, + "mode": "0644", + "sha256": "bcfea5c6fbc3439d31ed2495219311a863ca6cbd2b94a6446077c3bde780f2c1" + }, + "tools/toolchain/stage-decbfile.py": { + "bytes": 5267, + "mode": "0644", + "sha256": "662d1f4b6dad6024dfff949ca030d33883ef89ebeaac2dfd664bf9dac796527d" + }, + "tools/toolchain/stage-guest-sdk.py": { + "bytes": 4711, + "mode": "0644", + "sha256": "d114d138c0a472b7b2a41d1ce4423b81a8d59b738a24b8659ea814a1d98a265c" + }, + "tools/toolchain/stage-libraries.py": { + "bytes": 4763, + "mode": "0644", + "sha256": "c04770376d6a3741c604e2ce55b1cfe391553af4d512326d103b53143e8f4895" + }, + "tools/toolchain/stage-perl.py": { + "bytes": 5810, + "mode": "0644", + "sha256": "bca001ddfab037c4d52d9c9e863d06cfd7aaba4ce3c86380f02aacba1a5cf047" + }, + "tools/toolchain/stage-standalone-disk.py": { + "bytes": 4112, + "mode": "0644", + "sha256": "818d910da0302fabf3006d7d91113510102ae83a1769d756ad5fc3d8bcc3723c" + }, + "tools/toolchain/verify-runtime.py": { + "bytes": 20867, + "mode": "0644", + "sha256": "0cbeec7c1fb5b14c9c33e96045ea5c228b2f3ca5a33f130123d4284796a50a73" + }, + "tools/toolchain/verify-sources.py": { + "bytes": 1298, + "mode": "0644", + "sha256": "e7062472943ca987e4d0b59b67af85637f6a031ea9595a9159f62fe8f2499cef" + } + }, + "policy_version": 6, + "recipe_sha256": "0e6716bb6afbf93f2064a5bd724ba6260fb13fe0ece36a4654b92f0b6156d3e7", + "repository": "VCCPlus/VCCPlusOSS", + "schema_version": 1, + "source_history": "Independent distribution history; private Git metadata excluded" +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..bd69418 --- /dev/null +++ b/README.md @@ -0,0 +1,108 @@ +# VCCPlusOSS + +A source distribution of **VCC Plus for Mac**, installed as **VCC Plus OSS**, a native macOS Color Computer emulator derived from VCC. Designed by Brian Holman · Sponsored by Dezota LLC. Original VCC contributors and component credits are retained in the application. + +The portable engine, native interface, device emulation, BASIC/C/assembly workspaces, debugger and MCP services are included. Software and Archive libraries start empty. BASIC and Assembly lookup remain available. The full manual collection, archived publications, software corpus and ROMs are not included. + +## Independent installation + +The app is **VCC Plus OSS.app**, with bundle identifier `com.brianholman.vccplus.oss.mac`. Preferences, application support, cached library artwork and local companion endpoints are separate from VCC Plus. Both editions can be installed on one Mac. They can intentionally open the same user-selected documents; keep separate writable media copies when testing concurrently. No commercial settings or personal media are imported automatically. + +The proprietary software-update client, its service protocol and statistics collection are excluded. Install future OSS versions from this repository's reviewed releases. The engine, devices, development workspaces, debugger, SDK and local MCP services remain available. Downloadable content and external companion applications have their own preparation and trust requirements. The local companion transport is retained with a separate OSS endpoint. A publisher can supply `VCCCompanionTeamIdentifier` in the app Info.plist for mutually trusted, Apple-signed OSS companion builds. Without that setting an ordinary ad-hoc build rejects companion peers; it does not inherit commercial publisher trust or disable signature checks. The emulated DriveWire protocol and local MCP services remain available independently of that cross-app trust setup. + +## Build + +Requires macOS 14 or later, full Xcode with its command-line tools, and Python 3.10 or later for explicit dependency preparation. Both Apple Silicon and Intel are supported build targets. From this directory: + +```sh +export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer +python3 tools/oss/check.py +# Only the filesystem subset is needed for the app/core build. +python3 tools/dependencies/fetch.py --only toolshed +xcodebuild -project platforms/macos/VCC.xcodeproj -scheme VCCMac \ + -configuration Release -derivedDataPath .build/macos \ + CODE_SIGNING_ALLOWED=NO build +``` + +The checked-in project defaults to the shared `source` content profile and local ad-hoc signing. No Apple developer account, Developer ID certificate, notarization service or DMG workflow is required. An unsigned command-line build is shown above; opening the project in Xcode uses its local ad-hoc defaults. + +The dependency preparation step downloads pinned upstream source releases or repository snapshots, verifies their recorded checksums, applies recorded import patches and retains upstream notices. Generated dependency trees are ignored by Git. After preparation, the checked-in Xcode project also opens directly in Xcode and compilation can run offline. The shared source profile builds lookup from `BASICReference.json` and `AssemblyReference.json`, stages the source prompt selected by `RuntimeTemplates.json`, and does not discover maintainer datasets or ROMs. The full-manual tree is not needed. They generate two empty SQLite libraries from the included schemas. No SQLite database is stored in this repository. + +The source checkout contains no ROMs. You can supply your own CoCo 3 system ROM through **Open ROM…**, or explicitly reconstruct the qualified system and Disk BASIC ROMs from external assembly sources: + +```sh +python3 tools/dependencies/fetch.py --only cocoroms lwtools +python3 tools/roms/build.py --output .build/roms \ + --bundle-output .build/SourceROMBundle +xcodebuild -project platforms/macos/VCC.xcodeproj -scheme VCCMac \ + -configuration Release -derivedDataPath .build/macos-with-roms \ + VCC_SOURCE_ROM_DIR="$PWD/.build/SourceROMBundle" CODE_SIGNING_ALLOWED=NO build +``` + +Preparation downloads pinned source inputs explicitly; assembly and app compilation then run offline. The builder uses fresh assembly-only inputs, builds a minimal LWASM when needed, and checks all four reconstructed outputs against recorded sizes and hashes. Only the CoCo 3 system and Disk BASIC ROMs enter the optional app bundle, with source provenance and original-firmware notices. These are reconstructed upstream firmware. Isolated UI-test products omit ROMs even when a bundle is selected. Without an optional bundle the source build remains ROM-free. SDC, RGB-DOS, DriveWire and optional math ROMs are excluded; users may supply compatible ROMs separately. The ROM-free diagnostic and synthetic core checks require none. + +## C and assembly tools + +Build the reviewed toolchain from the prepared upstream sources and included patches, without private ROMs or disk-driver inputs: + +```sh +python3 tools/dependencies/fetch.py +python3 tools/toolchain/verify-sources.py +python3 tools/toolchain/build-runtime.py --output .build/runtime --architectures arm64 x86_64 +mkdir -p platforms/macos/LocalResources +cp -R .build/runtime/Toolchain platforms/macos/LocalResources/SourceToolchainBundle +``` + +Then rebuild the app with its default source profile. `VCC_SOURCE_TOOLCHAIN_DIR` can explicitly select another source-only runtime directory; private runtime inputs are rejected. This bundles CMOC, LWTools, mcpp, Make, Perl and reviewed libraries. Use only your host architecture for a smaller local build. The source-built runtime retains compiler correctness fixes and debug metadata. Run the toolchain build in a fresh output directory; it never downloads dependencies during compilation. Without staging it, the emulator still builds and the development workspaces explain that compiling requires the toolchain. Installed supported C workflows use the bundled tools; building those tools from source requires developer tools. + +## Validate + +```sh +xcodebuild -project platforms/macos/VCC.xcodeproj -scheme VCCCoreChecks \ + -configuration Release -derivedDataPath .build/checks CODE_SIGNING_ALLOWED=NO build +.build/checks/Build/Products/Release/VCCCoreChecks +xcodebuild -project platforms/macos/VCC.xcodeproj -scheme VCCMac \ + -destination 'platform=macOS,arch=arm64' -derivedDataPath .build/tests \ + CODE_SIGNING_ALLOWED=NO test +``` + +The default test command is ROM-free and reports optional-input skips. To exercise the ROM-backed disposable-playtest checks after the assembly preparation above, select the same bundle for the separate XCTest build: + +```sh +xcodebuild -project platforms/macos/VCC.xcodeproj -scheme VCCMac \ + -destination 'platform=macOS,arch=arm64' -derivedDataPath .build/tests-with-roms \ + VCC_SOURCE_ROM_DIR="$PWD/.build/SourceROMBundle" CODE_SIGNING_ALLOWED=NO test +``` + +The playtest tests inspect the ROM pair selected in the actual built app. Extra-firmware and separately staged compiler fixtures remain optional; a skipped check is not a compatibility pass. + +Use `arch=x86_64` for Intel execution; on Apple Silicon this uses Rosetta and does not establish physical Intel qualification. Core checks run serially. Additional offline authored regressions can run with: + +```sh +python3 -m unittest discover -s tools/tests -p test_build_content.py +python3 -m unittest discover -s tools/dependencies/tests +``` + +These do not fetch or execute downloaded programs. Optional tests requiring externally supplied ROMs, datasets or toolchains report skips. Desktop interaction tests require their separate isolated scheme and an idle desktop; ordinary validation does not launch the normal app or alter personal media. + +## Local app and ZIP distribution + +Xcode's **Sign to Run Locally** (ad-hoc identity `-`, empty development team) works without an Apple developer account. These project defaults build the source edition; no Developer ID certificate, Apple upload, notarization or DMG tooling is part of the workflow. Keep an app intended for distribution separate from your build/test products, and review its source-profile resources before creating a ZIP. A ZIP release and its checksum require their own completed validation; this source repository does not establish that a particular downloaded binary has been qualified. + +A downloaded ad-hoc app may carry macOS quarantine. After verifying the app's origin and any published checksum, the recipient can remove quarantine from that particular extracted app: + +```sh +xattr -dr com.apple.quarantine "/path/to/VCC Plus OSS.app" +``` + +This does not notarize the app or verify its contents. Locally built apps normally need no quarantine removal. System-wide security settings do not need to change. + +## Source and notices + +The original project is [VCCE/VCC](https://github.com/VCCE/VCC). Its `COPYING` and `license.txt` are retained unchanged, together with the original contributor credits in About. This distribution has its own source history; the upstream repository remains the reference for original VCC. + +`src/core` and `src/devices` contain shared implementation; `platforms/macos` owns the native host. Retained Windows sources are the original host, not a completed VCC Plus Windows edition. `sdk`, `examples` and `tools/toolchain` support guest development. Reviewed upstream locations, license inventory, source hashes and import patches are in `third_party/manifests`; complete dependency source and original notices are fetched into ignored directories. + +Application source is GPL-3.0-or-later; see [COPYING](COPYING). Third-party files and artwork retain their own notices and terms. The original artwork notice in `platforms/macos/Resources/About/ArtworkNotice.txt` applies to the unchanged artwork. Production artwork sources and [artwork attribution](docs/media/ATTRIBUTION.md) are retained under `docs/media`. Required dependency provenance includes supplemental legacy-graphics metadata under `tools/dependencies/manifests`. + +`EXPORT.json` records the distribution policy and file fingerprints. This repository has an independent history beginning with its source export. Source refreshes occur at selected milestones and are reviewed as ordinary diffs; routine product releases do not automatically update this repository. The private originating revision and local validation evidence are retained outside this repository by the maintainer. Sanitized technical evidence supporting the paper is selected separately under `docs/`; it is not an internal development transcript. No private repository connection or credentials are required to build this distribution. diff --git a/RELEASES.md b/RELEASES.md new file mode 100644 index 0000000..2e31f5d --- /dev/null +++ b/RELEASES.md @@ -0,0 +1,285 @@ +# VCC Plus release history + +> VCC Plus OSS retains the shared emulator and development capabilities. This calendar also describes prepared software collections, the full manual library, and separately distributed companion applications. Those payloads are not bundled with the OSS source edition; compatible user-supplied content and external applications have their own preparation requirements. + +Current version **3.6.2** + +## 3.6.2 — Curated Games and Personal Profiles + +November 11, 2026 + +**Start with a ready-to-play game.** The Software Library opens in Getting +Started with Bone Quest, Capital Quest and Quadrapassel. Each game uses its +verified memory, +video and disk setup, performs a Cold Restart and enters DOS automatically. +Bone Quest and Capital Quest use 512 KB and appear in Education and Games; +Quadrapassel uses 128 KB. Capital Quest includes its expanded quit controls, +while earlier installed editions and their saved disks remain available. Curated +titles lead their categories alphabetically. Existing programs, +unsaved media and writable game disks retain their restart and save safeguards. + +Read each game's verified PDF in the native reader, visit its online manual, +or choose Open Source to create a personal C project. Opening source preserves +the current CoCo and does not build or run the project. Project authorship, +licenses, repository links and corresponding library sources are distinct from +Color Computer Archive attribution. The twelve app manuals include the current +Library workflow and screenshots; website editions include search, examples and +individual PDF downloads. + +**Develop and test joystick-controlled programs.** Project MCP connections can +control both standard analog joystick ports, combine axes and buttons with +keyboard input, and inspect delivered input in disposable playtests. Read-only +shared-machine diagnostics help distinguish controller setup from guest input. +The bundled CMOC toolchain also corrects indexed argument loading. Finder disk +insertion offers No Reset, Soft Reset or Cold Restart independently of whether +the machine remains paused or runs afterward. + +**DriveWire remembers your personal setup.** The paired DriveWire for VCC Plus +3.6.2 opens its last-used personal profile automatically. Begin with an editable +Default profile, optionally create named profiles, and switch explicitly without +losing the connection and disk settings you chose. Recovery copies protect +unsaved disk bytes, while busy transfers and editing guard profile changes. +Its separate, unnumbered companion guide covers the new workflow on the website +and in a standalone PDF. Both apps retain matching product versions and +independent build numbers. + +## 3.6.1 — Hard-Drive Editing and Sound Reliability + +November 11, 2026 + +**Edit hard-drive images.** Virtual Hard Disks now offers **Edit…** beside HD0 +and HD1. Browse OS-9 volumes and numbered HDB-DOS disks through the same native +Disk Image Editor used for floppies. A Volume picker distinguishes the filesystems +inside a combined image. Larger OS-9 allocation clusters are supported, while +other volumes, supplementary bytes and declared external boot regions are preserved. + +Mounted editing captures the current disk, pauses and locks the CoCo, and keeps +changes in a private working copy. Applying edits requires an explicit restart. +Write protection, temporary changes, source-file conflicts, Undo/Redo and +separate-copy exports retain their existing safeguards. The updated manuals show +the hard-drive controls and explain volume selection and supported layouts. + +**Quiet games with sound cartridges connected.** The native audio path now +honors the CoCo sound-enable control and analog source selector. This fixes the +reproduced Quadrapassel splash-screen buzz with Speech/Sound and Orchestra-90 +connected, without changing the game. Normal game effects, cartridge speech and +music, cassette sound, single-bit sound and independent Orchestra-90 stereo are +preserved. + +This release is paired with **DriveWire for VCC Plus 3.6.1 — System View and Disk +Tools**, including its System/Full presentation, serial-command reliability fixes, +shared editor improvements and branded installer. Both apps retain independent +build numbers and matching product versions. + +## 3.6.0 — DriveWire for VCC Plus Integration + +November 11, 2026 + +Use DriveWire for VCC Plus as a separate companion for a real Color Computer. +Both apps share the same native Disk Image Editor and Software Library interface. +DriveWire's library is restricted to disk images and uses the catalog, verified +installations and supporting content maintained by VCC Plus, with no second +catalog to update. Companion startup leaves the emulator and its media alone. + +In Floppy Disks, **Actions → Send a Copy to DriveWire…** sends the mounted disk's +current in-memory contents to an already connected DriveWire serial session. +Choose DW0–DW3 and review the target before sending. Copying does not pause or +restart the emulator, change its save mode, or mark unsaved source changes saved. +DriveWire asks permission for the receiving connection and retains the previous +disk's current bytes as a recovery copy before replacement. + +The shared editor preserves private working copies, Undo/Redo, source-conflict +checks and write protection. DriveWire suspends access to the edited drive and +requires an explicit apply; the real CoCo must be reset before using the changed +filesystem again. Both apps keep separate windows, sessions and build numbers, +with matching public versions and coordinated releases. + +Updated manuals explain the companion workflow, permission lifetime and recovery. +DriveWire includes its own help through the same manual reader and rendering tools. + +## 3.5.5 — Disk Image Editor + +November 10, 2026 + +Explore and edit Disk BASIC and OS-9 floppy images in a native Mac window. +Open the editor beside a mounted floppy or inspect a separate disk image. +Browse detailed directories, import and export files, rename and delete entries, +create OS-9 folders, move files between them by dragging or using Move To…, +and undo or redo edits. The status bar reports total, used +and free filesystem space. OS-9 File Information brings owner/public permissions, +single-access settings and group/user ownership together in one sheet. + +Mounted disks pause and lock the CoCo while a private working copy is edited. +Applying changes requires an explicit restart; cancellation preserves the disk. +External changes and write protection remain guarded. Supported larger raw Disk +BASIC images preserve supplementary tracks unchanged, outside the editable +filesystem. Finder opening offers editing or insertion into a chosen floppy +with Keep current state, Pause or Run. + +Updated manuals explain the editor, Archive Library reading and code copying, +and the expanded MCP development workflow. Book 12 follows the real +CoCoCapitalQuiz project from its detailed prompt through building and playtesting. + +## 3.5.0 — Robust Gaming Development with MCP + +November 9, 2026 + +Build, debug and playtest substantial CoCo games with an AI assistant using the +installed VCC Plus application. Approved custom Make projects use the bundled +toolchain, declared build configurations and supporting files. + +Bank-aware debugging verifies source, executable bytes and physical RAM mappings. +Stop at mapped C statements or verified function entries, including assembly +routines, then inspect registers, shared globals and bounded program memory. +Unavailable source lines and unsupported local frames remain clearly identified. + +Disposable 512 KB MC6809 or HD6309 playtests run separately from your personal +CoCo. Inspect actual 6309 mode and MD state. Hold physical key combinations, +including punctuation, for measured video fields; capture the game screen or +bounded guest audio; cold-restart +with saved disk contents, and resume retained test disks across connections and +app updates. Each resumed run uses a new writable copy and preserves its original. +Scoped MCP connections retain project review, artifact identity and retry +safeguards throughout the development workflow. Inspect declared project inputs, +reuse verified dependency caches, and review scope or recipe refreshes in the +native workbench without discarding editor drafts. Failed builds retain paged +compiler/linker output and actionable diagnostics. + +Verified ordinary and banked debug evidence distinguishes typed C stops from +symbol-only inspection. Graphics capture supports declared custom GIME canvases +and page/stride identity. Startup reports pollable progress and cancellation; +request-budget reporting and reserved cleanup keep owned test disks recoverable. + +## 3.4.0 — The Archive Release + +November 5, 2026 + +Explore the Color Computer's published history from inside VCC Plus. The Archive +Library provides offline browsing and search across 4,727 publications and more +than 237,000 page or section locations. + +Select a title or search result to open its PDF, image or text in the reader. +Downloads report progress, verified files reopen offline, and citations preserve +Color Computer Archive attribution. Reviewed listings can be copied or opened in +a development workspace. Assistants can search the same index through MCP. + +## 3.3.1 — Interactive Development + +November 2, 2026 + +Review a program, start a run and let a connected assistant help playtest it. +Interactive controls support BASIC, C and assembly programs. + +Machine-readiness checks, multi-file change review and debugger inspection give +the assistant a clearer view of the current project and running machine. +Book 12, Vibe Coding with ChatGPT, teaches the complete workflow. + +## 3.3.0 — Connected to ChatGPT + +October 26, 2026 + +Connect ChatGPT to the BASIC, C and assembly workspaces through the bundled +local MCP helper. Share a project, ask for an explanation, review proposed edits, +build a program and inspect its results. + +Connections are scoped to the selected workspace. Users review proposed changes +and retain control over program execution. + +## 3.2.1 — Programming the Whole Machine + +October 19, 2026 + +Build C programs that use graphics, joystick input, banked memory, disk files, +cassette, printing, Orchestra-90 and Speech/Sound. + +Worked projects put the APIs into practice through landers, field logs, record +keeping, sound and persistent storage. + +## 3.2.0 — Learn Your Color Computer + +October 12, 2026 + +The eleven-book Manual Library takes readers from their first BASIC program +through C, assembly, CoCo 3 hardware and NitrOS-9. + +Read offline, search across the books, find text on a page and open examples in +the development workspaces. Tested exercises connect each lesson to the emulator. + +## 3.1.1 — Explore the Software Library + +October 5, 2026 + +Browse and search thousands of software releases preserved by Color Computer +Archive. Install verified downloads, consult supporting manuals and artwork, +and use recommended launch setups where available. + +Installation management and broader disk-image support make the historical +collection easier to explore. + +## 3.1.0 — CoCo Development Studio + +September 28, 2026 + +Write, build, run and debug programs in native BASIC, C and assembly workspaces. +Bundled compilers and assemblers support development directly in VCC Plus. + +Multi-file C projects, source breakpoints, stepping, variables and watches bring +the editor and running CoCo together. Draft recovery and independent example +documents support everyday editing. + +## 3.0.0 — The Mac Release + +September 21, 2026 + +VCC Plus brings native Color Computer emulation to Apple Silicon and Intel Macs +running macOS 14 or later. Both 6809 and 6309 processors are supported. + +A Metal display, native menus, audio, controllers, disk and cassette handling, +cartridges and Multi-Pak form the everyday emulator. The illustrated System desk +and focused Display view share one running machine. System profiles and personal +starter media simplify getting started. + +## 3.0 Beta 2 — A Complete Virtual CoCo + +September 14, 2026 + +Expand into Hard Drive BASIC, NitrOS-9 and CoCo SDC workflows. Orchestra-90, +Speech/Sound and printer capture extend the virtual hardware. + +Personal profiles and writable starter media preserve useful setups and work +between sessions. + +## 3.0 Beta 1 — Everyday Use + +September 7, 2026 + +Load programs from floppy disks and cassette, configure cartridges and use +controllers. Remembered media assignments and automatic writable-image saving +support repeated use. + +Refinements to resizing, keyboard focus, audio stability and media safeguards +make the native application more comfortable to use. + +## 3.0 Developer Preview — First Native Mac Build + +August 31, 2026 + +Boot a CoCo ROM, reach BASIC, type commands and hear sound through the native +Mac host. Both processor engines run through the portable emulator core. + +The preview establishes the display, input and execution paths needed for +testing familiar CoCo programs. + +## Project kickoff + +August 24, 2026 + +Review Windows behavior, plan the native Mac architecture and begin extracting +the portable emulator core. + +## Windows VCC 2.1.9.3 — Upstream Baseline + +August 21, 2026 + +The Windows release provides the starting point for this development calendar. +VCC Plus preserves the original project's contributors and component credits. diff --git a/docs/WHITE_PAPER_EVIDENCE.md b/docs/WHITE_PAPER_EVIDENCE.md new file mode 100644 index 0000000..d97441b --- /dev/null +++ b/docs/WHITE_PAPER_EVIDENCE.md @@ -0,0 +1,34 @@ +# White-paper technical evidence + +These selected records support the paper’s architecture, debugging, defect and validation references. They preserve cited paths while excluding the broader product manuals, screenshots, planning chronology and coordination records. An extract is a subset, not the complete original document. Historical configurations and limitations apply to their recorded results. + +- [docs/development/ASSEMBLY_WORKSPACE.md](development/ASSEMBLY_WORKSPACE.md) +- [docs/development/BASIC_WORKSPACE.md](development/BASIC_WORKSPACE.md) +- [docs/development/CMOC_BENCHMARKS.md](development/CMOC_BENCHMARKS.md) +- [docs/development/CMOC_INDEXED_ARGUMENT_LOAD.md](development/CMOC_INDEXED_ARGUMENT_LOAD.md) +- [docs/development/CMOC_RELEASE_QUALIFICATION.md](development/CMOC_RELEASE_QUALIFICATION.md) +- [docs/development/CMOC_RUNTIME.md](development/CMOC_RUNTIME.md) +- [docs/development/CMOC_SOURCE_DEBUGGING.md](development/CMOC_SOURCE_DEBUGGING.md) +- [docs/development/MCP_AUDIO_CAPTURE.md](development/MCP_AUDIO_CAPTURE.md) +- [docs/development/MCP_BANKED_PLAYTEST.md](development/MCP_BANKED_PLAYTEST.md) +- [docs/development/MCP_BUILD45_VALIDATION.md](development/MCP_BUILD45_VALIDATION.md) +- [docs/development/MCP_CALL_CONTEXT.md](development/MCP_CALL_CONTEXT.md) +- [docs/development/MCP_DEBUG_EVIDENCE.md](development/MCP_DEBUG_EVIDENCE.md) +- [docs/development/MCP_PLAYTEST_PROCESSORS.md](development/MCP_PLAYTEST_PROCESSORS.md) +- [docs/development/MCP_PROJECT_RELIABILITY.md](development/MCP_PROJECT_RELIABILITY.md) +- [docs/development/REPOSITORY_LAYOUT.md](development/REPOSITORY_LAYOUT.md) +- [docs/macos/AUDIO_CASSETTE.md](macos/AUDIO_CASSETTE.md) +- [docs/macos/AUDIO_ROUTING.md](macos/AUDIO_ROUTING.md) +- [docs/macos/CARTRIDGES.md](macos/CARTRIDGES.md) +- [docs/macos/CPU_CORE.md](macos/CPU_CORE.md) +- [docs/macos/DEBUGGER.md](macos/DEBUGGER.md) +- [docs/macos/DEBUGGER_MEMORY_TOOLS.md](macos/DEBUGGER_MEMORY_TOOLS.md) +- [docs/macos/DEBUGGER_TRACING.md](macos/DEBUGGER_TRACING.md) +- [docs/macos/FLOPPY_CORE.md](macos/FLOPPY_CORE.md) +- [docs/macos/GRAPHICS_CORE.md](macos/GRAPHICS_CORE.md) +- [docs/macos/HARD_DISKS.md](macos/HARD_DISKS.md) +- [docs/macos/MACHINE_CORE.md](macos/MACHINE_CORE.md) +- [docs/macos/MAC_CONTROLLER.md](macos/MAC_CONTROLLER.md) +- [docs/macos/NATIVE_BOOT.md](macos/NATIVE_BOOT.md) +- [docs/macos/PORTING_PLAN.md](macos/PORTING_PLAN.md) +- [docs/macos/TIMING_RELIABILITY.md](macos/TIMING_RELIABILITY.md) diff --git a/docs/development/ASSEMBLY_WORKSPACE.md b/docs/development/ASSEMBLY_WORKSPACE.md new file mode 100644 index 0000000..ef7853c --- /dev/null +++ b/docs/development/ASSEMBLY_WORKSPACE.md @@ -0,0 +1,51 @@ +# Assembly Development + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +Open **Develop → Assembly Development…** at a CoCo 3 BASIC prompt. The first document is Hello World — Earth or Mars. You can run it before saving a file or creating a disk. + +## Working with several files + +Use **File → Open Source…** for a single file with local includes, or **Open Project Folder…** for a folder of sources. Assembly instructions in LWASM normally start after whitespace. Put labels in the left column. Relative filenames and labels keep their original spelling and case. Save your work as ordinary UTF-8 source. Recoverable drafts retain edits separately from saved files. + +The default project entry is `main.asm`. In a project folder, **File → Project Settings…** opens the editable `vccplus-assembly.json` configuration. For an object-linked program, set the entry module, additional modules and your LWLINK script: + +```json +{ + "main": "main.asm", + "modules": ["draw.asm"], + "linkScript": "layout.link" +} +``` + +VCC Plus assembles each module, links the objects and verifies source addresses against the final loaded bytes. Use the listing or native disassembly when a source location is ambiguous. A custom Make recipe can instead declare `makefile`, `target` and `binary`. Review the recipe before allowing it to run with your Mac account’s permissions. Custom recipes produce a runnable/exportable binary and can use the machine debugger. Verified source stops require the native assembly or link workflow. + +## Share an assembly project with a local assistant + +In Assembly Development, choose **File → Local Assistant Access… → Save Assembly Connection…**. The saved connection gives one client access to the current assembly document, including unsaved edits. Configure the client with the bundled helper and the saved connection file. See the local MCP client instructions. + +Build 28 can read the listed files, assemble them with the bundled LWASM, return diagnostics and propose a single-line replacement. Review the current and proposed lines in the access panel. **Apply Edit** updates that buffer and supports the editor’s usual Undo. Assemble the revised source, set a stop on an executable instruction, then choose **Run Shared Build…**. At a verified pause the client can read the mapped source line, instruction bytes, PC, available A and E registers and the text byte at `$0400`. **Revoke Connection** ends access. Selecting another document also ends its grant. + +Build 29 adds **multi-file review**. The assistant can call `propose_project_edits` with one to eight existing shared assembly or include files and up to 16 KiB of UTF-8 replacement source altogether. Open each filename to compare the entire proposed source with its current draft. **Apply All Changes** updates all the drafts together. **Cancel Changes** preserves them. Save writes the updated files. **Undo All Changes** in the access panel restores the previous drafts as one operation while that applied revision is current. If the workspace changes during review, ask the client to reread and propose against the new revision. Native two-file review + +In build 30, start the shared build from the BASIC prompt to play an assembly text game over MCP. After the native launch the assistant can read the screen and send one letter, digit or space at a time. When the program returns to BASIC, the live game controls close. Play an interactive program + +The development client can also call `get_machine_status` for the actual CPU, memory and media state, build and run blockers, and the latest build ID and status. Use `get_run` after a native run to obtain its run ID. At a verified source stop, `get_debug_snapshot` returns registers, the source stop and the readable address ranges. Pass the same run and snapshot IDs to `read_debug_memory` to read up to 256 permitted bytes. Stale snapshots and addresses outside the disclosed ranges are refused. + +Share a direct-assembly project containing up to 32 UTF-8 assembly and include files, up to 64 KiB each and 512 KiB overall. Project includes must resolve inside the shared snapshot. Linked projects and custom Make recipes use the native workbench. Earlier CPU and target qualification + +The assembly regression client exercises a dedicated app launched with `--interface-validation --mcp-assembly-regression --mcp-assembly-fixture EMPTY_DIR --mcp-rom-dir ROM_DIR`. Use a fresh, private directory each time and pass `--helper HELPER --fixture EMPTY_DIR --cpu 6809 --target 6809` to the client. For HD6309, add `--basic-6309 --mcp-assembly-hd6309` to the app and use `--cpu 6309 --target 6309` for the client. The test covers stale proposals, cancellation, whole-project apply and undo, an assembled run after changing both files, snapshot-scoped memory reads, and refusal of an out-of-project include. The optional mismatched combination checks that a 6809 guest refuses HD6309-only code. + +## Verification on November 5, 2026 + +The screen-cell lesson assembled and ran in Disk BASIC, Hard Drive BASIC and CoCo SDC on both emulated processors. The disk export also ran from a Disk BASIC prompt with `LOADM"FIRST":EXEC`. The two-module test checked the linked address of a subroutine and its relocated operand. Follow the reference lesson table to reproduce the seven smaller CPU experiments. + +The 78 focused Xcode tests passed on arm64 and again under x86_64 Rosetta. They cover assembly, BASIC bibliography and profile integration, the shared C build and source-map services, and disk safeguards. All 66 portable core checks also passed on arm64. + +On macOS 27.2 with Xcode 27.2, the isolated native window test stopped before the first instruction, stepped twice, returned keyboard focus to the running CoCo, opened an example in a separate document and resized the editor. The relocated, locally signed development app produced identical binaries with the arm64 and Rosetta x86_64 slices of its embedded assembler. Physical Intel hardware, a macOS 14 installation and a notarized installer were outside this pass. + +- Assembly editor paused after the screen write + +- Quick Reference with LDA selected + +While the editor is open it monitors the active project's files. Before source stepping or continuing it rechecks the project inputs. While a different document is open or the window is closed, a running guest can still reach stops armed for the previously loaded binary. diff --git a/docs/development/BASIC_WORKSPACE.md b/docs/development/BASIC_WORKSPACE.md new file mode 100644 index 0000000..2ba5f5f --- /dev/null +++ b/docs/development/BASIC_WORKSPACE.md @@ -0,0 +1,339 @@ +# BASIC development workspace + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Direct machine operations + +- **Load into CoCo** installs the editor's complete program at a safe BASIC + prompt, without running it. It replaces the existing in-memory program and + prepares a fresh BASIC execution/variable state. The previous running/paused + state of the emulator is preserved; a paused load does not execute guest + instructions until Run or Resume completes the interpreter initialization. + +- **Run** performs the same validated replacement and starts a fresh execution + through the existing ROM interpreter. It does not add a source breakpoint or + require an additional Run action in the emulator. + +- **Read from CoCo** reads the program currently in BASIC memory back into the + editor. This includes changes made through the CoCo's own line editor. It reads + program source, not variable values or a suspended execution checkpoint. + +Load and Run preflight the entire source, ROM, memory mapping, available space +and interpreter state before replacing program memory. They refuse an unsafe +state, such as a program still executing or waiting for INPUT. Mounted disks, +cassettes, cartridges and machine configuration are retained. Existing media +save/export protections remain independent of these program-memory operations. + +Read-back is a canonical listing: keywords use their BASIC spellings, `?` may +become `PRINT`, lines are numbered and sorted, and ROM-inserted separators around +`ELSE` and apostrophe remarks are handled so that reading and reloading preserves +the program. It is not a byte-for-byte copy of the editor's original formatting. +Programs containing unsupported binary/non-ASCII text or damaged line links are +rejected without replacing the editor's contents. + +## BASIC line breakpoints + +Click the gutter circle beside a numbered statement, or use **Toggle BASIC +breakpoint at insertion point** in the toolbar. Breakpoints are explicit; the +sample and a new document start with none. **Run** installs the program and its +breakpoints together, so even its first line can stop before executing. Changes +to the breakpoint set can also attach to an already-loaded matching program. + +At a breakpoint the whole emulator pauses, the source line is highlighted, and +**Continue** resumes without reloading BASIC, clearing variables, unwinding +GOSUB/FOR stacks or closing files. Continue executes the stopped line once before +that breakpoint can stop again. **Run** remains a fresh program transfer, subject +to the existing OK-prompt guard; it is not the Continue action. The main emulator +Resume action can also leave a BASIC stop. + +These are **line-entry breakpoints**. A colon-separated second statement and a +return into the middle of a line do not re-trigger that line's entry breakpoint. +The stepping controls below can stop at those individual statements. + +In Earth or Mars, set a breakpoint on the line that prints `M$` and add +`M$` as a watch. Run the program and select a planet. At the stop, the watch +contains its greeting and the screen still shows the menu. Step once to print +the greeting. Continue to switch back to the usual text colors and return to BASIC. + +The editor checks its source against the tokenized program in CoCo memory. +Editing the source detaches the live mapping immediately and hides the execution +highlight; pending breakpoint numbers apply on the next Run. A core comparison +of the line chain, command dispatcher and memory mapping also detaches when the +guest program or relevant memory changes. Continue rechecks the source and stop +on the emulation queue before resuming. It refuses a stale stop. Explicit CPU +stepping, PC changes, binary loading, resets and configuration replacement also +end the BASIC debugging attachment. Manual machine-code breakpoints are kept +separately. + +Breakpoint selections last for the current editor document/session. New, Open +and Read from CoCo clear them; Renumber clears them after changing the labels so +old breakpoint numbers cannot silently target different code. Source files and +recovery drafts do not currently store breakpoints. Closing the workspace window +alone preserves its model and the paused CoCo session. + +The hook uses the shared command dispatcher at `$ADC6`, with the current line at +`$0068` and input pointer at `$00A6`. The input pointer must identify the line's +first token. The Color, Extended and Disk BASIC dispatch loops have different +entry paths but converge here. The implementation validates the qualified +bundled CoCo 3 interpreter and dispatcher before enabling this behavior; it does +not patch ROM or program bytes. The primary references are the command dispatch +sections in [Color BASIC Unravelled](https://colorcomputerarchive.com/repo/Documents/Books/Unravelled%20Series/color-basic-unravelled.pdf), +[Extended BASIC Unravelled](https://colorcomputerarchive.com/repo/Documents/Books/Unravelled%20Series/extended-basic-unravelled.pdf) +and [Disk BASIC Unravelled](https://colorcomputerarchive.com/repo/Documents/Books/Unravelled%20Series/disk-basic-unravelled.pdf). + +## Statement stepping and Step Over + +At a BASIC breakpoint, **Step Into BASIC statement** (the down-arrow toolbar +button) executes until the next statement the interpreter dispatches. A yellow +highlight identifies its source line; a stronger orange highlight identifies +its next token, including separate statements on the same line. The mapping is +emitted by the tokenizer from the original editor source, preserving spelling, +spacing, CRLF and source order. Highlighting never edits the document or moves +the insertion point. + +**Step Over BASIC subroutine** (the bent-arrow button) follows a `GOSUB` through +its `RETURN`, including recursion and `ON … GOSUB`. Nested `FOR/NEXT` loops are +not mistaken for subroutine calls. An explicit breakpoint inside the call still +wins. On an ordinary statement, Step Over stops at the next statement just like +Step Into. `IF` can dispatch an inline THEN/ELSE command as a separate stop; +expressions themselves are not individually stepped. REM, DATA, skipped branches +and empty separators follow the interpreter's behavior. + +The editor is temporarily read-only while a step is running. **Pause BASIC step** +appears during a wait, and the main emulator Pause action also cancels stepping. +A step pauses automatically after 600 emulated video frames (about ten seconds), +so a nonreturning subroutine or INPUT wait cannot leave an unbounded debugger +operation. Continue resumes the existing execution without reloading. After +cancellation or the limit, stepping becomes available again at the next BASIC +breakpoint; no statement highlight is invented for a mid-statement pause. +Use Show CoCo and Continue to supply input normally. + +END, STOP, and runtime errors that return to BASIC finish a step at the OK prompt. +The emulator remains paused; Continue lets the prompt accept commands or a new +editor transfer. Program, +interpreter or mapping changes cancel an active step and detach its source map. +Changes to the editor after a stop also detach debugging as described above. + +Step Over observes the qualified interpreter's GOSUB frame push at `$AE9D` and +RETURN pop at `$AEDA`, recording and matching frame addresses instead of guessing +from the stack pointer alone. The input-loop entry at `$AC7C` identifies a return +to the prompt. These routines and the dispatcher are guarded against changes; +CoCo 3's normal boot patch to the preceding OK-print routine is outside the guard. +The [Color BASIC Unravelled](https://colorcomputerarchive.com/repo/Documents/Books/Unravelled%20Series/color-basic-unravelled.pdf) +GO, RETURN and command-dispatch listings provide the interpreter reference. + +## Step Out and runtime errors + +**Step Out** runs the current `GOSUB` through its `RETURN`, stopping before the +next mapped statement in the caller. It handles nested and recursive calls and +skips intervening `FOR` frames. Explicit breakpoints still take precedence. The +button is unavailable at top level, in an unrecognized stack, or after a +mid-statement pause. Pause and the same 600-frame execution bound apply. + +The caller walk starts at the interpreter's current dispatch return address, +verifies its BSR/JSR instruction, and walks typed 18-byte FOR and five-byte GOSUB +frames within BASIC's RAM bounds. It verifies the saved caller line/pointer +against the attached source, then matches the exact frame at `$AEDA`. A changed +caller frame cancels Step Out. Different DOS command-loop return addresses are +accepted only when their call into the recognized dispatcher is verified. + +Run now attaches error observation even without a source breakpoint. It still +runs immediately and never adds a default breakpoint. Unhandled errors finish +the ROM's normal reporting and file cleanup, then pause before keyboard input +at the OK prompt. A banner shows the ROM's actual two-character error code and +source line; **Show Line** selects that numbered source row without modifying it. +This is line-level navigation, not a claim to identify the exact faulty +expression. Values that remain in BASIC can be inspected at this stop. + +Choose **Continue** to return to the normal prompt before editing and running a +corrected program. If source edits have already detached debugging, resume the +CoCo from the main window. Continue does not resume the aborted BASIC program. +A new transfer, changed source, reset, or detached source mapping clears the old +error. The last matching error can remain visible after returning to the prompt. + +`ON ERR GOTO` remains under the ROM's control. Handled errors do not produce the +unhandled-error banner or an automatic stop; a breakpoint in the handler still +works. Error observation uses the shared `$AC65` reporting path after the error +code has been printed, rather than intercepting every error before the guest +can handle it. The error routines are guarded alongside command dispatch. + +The additional interpreter references are the +[Disk BASIC Unravelled command-loop and error-driver listings](https://colorcomputerarchive.com/repo/Documents/Books/Unravelled%20Series/disk-basic-unravelled.pdf) +and [Super Extended BASIC Unravelled error-trap listings](https://colorcomputerarchive.com/repo/Documents/Books/Unravelled%20Series/super-extended-basic-unravelled.pdf). + +## Variables and watches + +The collapsible **Variables and Watches** panel reads the stopped BASIC program's +numeric and string variables, DIM arrays, and DEF FN entries. It refreshes at a +BASIC breakpoint, after statement stepping, and at the stepping stop before the +OK prompt. **Refresh BASIC variables** also rereads a safe stop. Continuing, +editing the source, resetting or detaching debugging clears the displayed values. +An arbitrary CPU pause in the middle of INPUT, expression evaluation or string +collection is not a safe BASIC inspection stop. + +Arrays expand into pages of 32 elements. Their displayed bounds are inclusive +and begin at zero; multidimensional indices use the source's order. Strings +preserve case and quote their contents, with nonprinting bytes escaped as +`\xHH`. Numbers decode the interpreter's five-byte floating-point representation. +DEF FN entries are identified but never evaluated. + +**Watches** accepts named variables and array elements with literal, nonnegative +subscripts, such as `A`, `NAME$`, or `M(1,2)`. BASIC identifies names by their first +two characters, so `NAME$` appears as `NA$`. Unknown names say **Not assigned**; +unknown arrays say **Not dimensioned**. Wrong subscript counts and out-of-range +indices are reported separately. Watches do not evaluate expressions, functions, +PEEK or assignments and never create a guest variable. Up to 128 watch names are +remembered with the local workspace recovery draft, independently of breakpoints. + +Inspection copies normal BASIC RAM on the emulation queue without executing +instructions, modifying memory or accessing device registers. It validates the +qualified interpreter, source/program identity, MMU mapping, variable-table +bounds and array descriptors. Strings whose descriptors point outside ordinary +BASIC RAM are shown as unavailable. A malformed table returns an inspection +error instead of guessed values. Asynchronous results are discarded after the +source, machine generation or stopped execution position changes. This is +read-only inspection; editing values and general expression watches are not +implemented. + +## Validation approach + +`BASICBridgeTests` runs against optional, ignored +`platforms/macos/LocalResources/ROMs/coco3.rom` and `disk11.rom`. Tests explicitly +skip the ROM integrations if those files are absent; no proprietary ROM bytes are +checked into the repository. Both guest processors are exercised sequentially +because the retained emulator core is process-global. + +The key independent oracle enters an authored fixture through the actual ROM's +keyboard/tokenizer, captures the tokenized RAM program, then compares it with a +directly loaded version of the same source. The fixture includes strings, +`DATA`, `REM`, apostrophe remarks, `?`, function tokens, `ELSE`, disk commands and +CoCo 3 commands. Reading that program and reloading the returned source must +produce the same bytes. Other checks cover direct execution without queued +keystrokes, preserved media and machine generation, rejected source preserving +the previous program, and unsupported machines rejecting direct writes. Export +checks cover deterministic DSK/CAS output, paused memory/register preservation, +running-program preservation, invalid source/names and unchanged media and +machine generation. Separate core checks load the exported files through the +actual ROM's `LOAD` and `CLOAD`, including programs crossing disk granules and +cassette data blocks; cassette checks use the normal transport rather than fast +loading. + +The BASIC command references maintained by Color Computer Archive are useful +background for command vocabulary and usage: +[Color BASIC, Extended BASIC and Disk BASIC references](https://colorcomputerarchive.com/repo/Documents/BASIC%20Commands/). +Interpreter storage and execution behavior are documented in +[Color BASIC Unravelled](https://colorcomputerarchive.com/repo/Documents/Books/Unravelled%20Series/color-basic-unravelled.pdf). +The bundled Quick Reference provides original local +explanations and examples. These source links do not imply that the external +manuals are bundled with the workspace. + +### Initial validation — November 4, 2026 + +The 13 focused native tests passed on both Apple Silicon and x86_64 under +Rosetta: five bridge integrations, six editor/language/recovery checks and two +pure core token/validation tests, exercising the final normal-RUN-handler path. +The complete 63-check standalone core suite also passed. There were no failures or +skips. Each real-ROM bridge case exercised both the 6809 and 6309. The original interpreter's typed +program and the directly installed program matched byte for byte; canonical +read-back reloaded to the same representation. Paused Load preserved cycle count, +and immediate Read followed by Run executed successfully. Execution printed the +expected result with no queued paste; disk/tape assignments and machine generation +were unchanged. Invalid/oversized source, active loops, INPUT waits and unsupported +machines were rejected without replacing the previous program. + +These original checks use authored isolated machine instances and predate the +line-breakpoint feature. They do not qualify other ROM revisions. + +### BASIC line-debugging validation — November 4, 2026 + +All 40 targeted tests passed on Apple Silicon and x86_64 under Rosetta: ten +BASIC bridge integrations, 19 workspace tests and 11 existing core/native debugger +checks. The BASIC breakpoint cases run on both emulated processors. They verify +stopping before execution, repeated loop stops, Continue without a reset, +subroutine return state and variables, colon statements, coexistence with manual +CPU breakpoints, rejection of mismatched source and invalid line numbers, and +detachment after program-memory edits, PC changes and reset. + +The isolated native UI check verifies both gutter clicks and the accessible +insertion-point toggle, Run to a selected line, Continue, unchanged source and +machine generation, disabling Continue after editing, and clearing breakpoints. +The captured window was visually reviewed for gutter alignment and stopped-line +highlighting. That checkpoint covered line-entry debugging; the later sections record +statement stepping and variable inspection. No default breakpoint is installed. + +### Statement stepping validation — November 5, 2026 + +All 50 targeted tests passed on Apple Silicon and x86_64/Rosetta (Apple Silicon +in a 46-test pass plus four final guard/mapping checks): 17 BASIC bridge tests, +20 workspace tests, two tokenization/export core checks and 11 existing debugger +regressions. The new bridge cases exercise both emulated processors. Coverage +includes same-line statements, source order/CRLF and keyword case, FOR/NEXT, +IF/ELSE, nested and recursive GOSUB, ON GOSUB, explicit breakpoint precedence, +return to the OK prompt after END and a runtime error, an INPUT wait canceled +without clearing its program, and the 600-frame bound on a nonreturning call. +Self-modifying BASIC detaches and stops rather than highlighting stale source. +The editor test verifies that moving the token highlight within one line leaves +source text and insertion point unchanged. + +The isolated native check passed Step Into, Step Over, same-line token rendering, +Continue after the OK-prompt stop, and pausing an INPUT wait. The existing gutter, +Continue and stale-source UI regression also passed. The final window capture was +visually reviewed; only the app window is retained here. Xcode emitted internal +QoS diagnostics during automated editor lookup; those did not fail the tests, +and this validation does not establish their underlying cause. + +## Variables and watches validation — November 5, 2026 + +All 53 targeted tests passed on Apple Silicon and Intel under Rosetta: 19 BASIC +bridge integrations, 21 workspace checks, two pure core checks and 11 debugger +regressions. Each BASIC bridge test exercises both emulated CPUs. Real-ROM +fixtures independently create numbers (including negative, fractional, large +and small values), mixed-case/empty/binary strings, numeric and string arrays, +and DEF FN entries. The inspector recovers their values and source-order array +indices without changing RAM, cycle counts, program revision or media. Tests +also reject stale source, running/mid-statement inspection and damaged tables. +Synthetic RAM checks cover malformed array ranks, lengths, offsets, variable +pointers and string descriptors pointing at device addresses. Watch checks cover +canonical names, bounds, unknown variables, rejected expressions and recovery. + +The final native checks passed array expansion, adding scalar/string/array +watches, value refresh after stepping, clearing values on Continue, and the +existing Step Into/Step Over/INPUT-cancellation workflow. The final asynchronous +stop guard and layout built for both architectures; all 21 workspace tests were +rerun successfully on Apple Silicon. A small disclosure control was replaced by +a full-row accessible array button. The breakpoint ruler now draws and clips its +own separator within the editor, fixing the vertical line previously extending +through the toolbar and footer. Window-only screenshots were visually reviewed. +Xcode still reports its internal QoS warning during UI automation; this pass does +not identify or claim to resolve that separate warning. + +## Step Out, runtime-error and preset validation — November 5, 2026 + +The added real-ROM bridge tests exercise both emulated processors and cover +nested/recursive returns, FOR frames, explicit-breakpoint precedence, stale +source and top-level refusal, division-by-zero, syntax, DATA, type and disk-file +errors, normal ROM error output, and preserved `ON ERR GOTO` behavior. + +An isolated test creates the actual Disk BASIC, Hard Drive BASIC and CoCo SDC +preset definitions from private ROMs and authored starter media. Each preset runs +`DIR` against its own mounted storage, transfers and reads back source, stops at +a breakpoint, inspects a scalar and array, steps into/out of a subroutine, and +reports an unhandled error. Optional private `rgbdos.rom` and `sdcdos.rom` are +required for that case. No personal working media are opened or modified. + +The native UI test checks Step Out availability, caller return, exact source-row +selection, unchanged source, correcting/re-running after an error, and compact +window controls. The resize regression verifies a real size change and checks +that both the header and full preset guidance stay within the window. The +inspector reduces its visible rows in shorter windows while retaining its own +scrolling. Representative window captures: + +- Returned to caller + +- Runtime error source navigation + +Validation for this stage: 57 selected BASIC/core/debugger tests passed on Apple +Silicon and the same 57 passed on Intel through Rosetta, with no skips. The native +Step Out/error-navigation workflow passed in the isolated app. Both build +architectures compiled. Xcode's App Intents metadata notice and internal test +service/QoS diagnostics are not claimed resolved by this change. diff --git a/docs/development/CMOC_BENCHMARKS.md b/docs/development/CMOC_BENCHMARKS.md new file mode 100644 index 0000000..4643595 --- /dev/null +++ b/docs/development/CMOC_BENCHMARKS.md @@ -0,0 +1,66 @@ +# Shipped CMOC benchmark decision + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Results + +All **864 executions passed**: eight CPU workloads, three input seeds, two repeats, +three build profiles, two compiler host slices and three guest processor modes. +Every serialized result byte matched an independent host reference. Repeats had +identical cycle counts; both compiler slices emitted identical guest binaries. + +| Comparison | Measured result | +| --- | --- | +| Existing Release versus Debug, MC6809 | 14.17% fewer cycles, equal-workload geometric mean | +| Frame-pointer omission versus Release, MC6809 | 0.69% fewer cycles | +| Frame-pointer omission versus Release, HD6309 emulation | 0.69% fewer cycles | +| Frame-pointer omission versus Release, HD6309 native | 0.84% fewer cycles | +| Omission size savings | About 3% of summed initialized payload bytes; 17–32 bytes per test program | +| Largest MC6809 omission speed gain | About 2.9%, input handling | + +These modest additional gains do not justify making CMOC's explicitly experimental +frame-pointer omission option the default. Projects with measured size or speed +pressure can opt in and qualify their own behavior. Debug's frame is intentional +and supports verified locals and caller reconstruction. + +## Compiler and method + +The exact CMOC 0.1.100 compiler and target runtime came from the retained +notarized **3.6.2 build 55** app. Its compiler bytes matched the installed +app. SHA-256 of universal `libexec/cmoc`: +`c46271d42037420d3f9d294c670f2d6130c469cf6fd2c41ec2338d990e313512`. +The manifest records all three optimizer fixes and debug metadata at version 1. +The different mutable local staging compiler was not used. + +No compiler was rebuilt or patched during benchmarking. A stock compiler +comparison was not needed to choose defaults for the shipped compiler; previous +target regressions already establish the correctness need for our fixes. + +Profiles were Debug `-O0 -fno-omit-frame-pointer`, existing Release `-O2`, and +Release `-O2 -fomit-frame-pointer`, using generated-project relocation and switch +defaults. Exact breakpoint cycle deltas include the workload call/return and +exclude setup and result collection. Guest IRQ/FIRQ are masked. Three-NOP +calibration passed at 6/6/3 cycles for MC6809, HD6309 emulation/native respectively. +Initialized size includes startup, linked helpers, setup and collection. BSS and +static RAM spans are separate receipt fields; stack/heap reservations are not +included. No host elapsed-time or baseline-subtraction estimate is used. + +The fresh arm64 Release core was built through the existing VCCCoreChecks scheme. +The measured core/device inputs matched the reviewed implementation. All 67 shared Release core checks +and four benchmark evidence-accounting checks passed, with no skips. Structured receipts hash the compiler/tools, runtime archives, linked core and +frozen benchmark inputs. Raw logs, binaries and private ROMs stay outside Git. + +## Limits + +The eight cases cover arithmetic, sprite/collision logic, memory/CRC, sorting/state +dispatch, framebuffer work, sample mixing, indexed input and sector/directory +processing. Device-themed cases use synthetic application buffers; they do not +measure real graphics/audio/input/disk I/O or device-library compatibility. Full +linked test-program size includes harness overhead and is not a game-size forecast. + +The x86_64 compiler ran under Rosetta on Apple Silicon. Both guest CPUs were +emulated, and the harness explicitly selected 6309 native mode while retaining +6809 machine code. This is not physical Intel, macOS 14, physical CoCo, whole-game +frame-rate, audible-output, UI or accessibility qualification. No normal app +session or personal media was operated. Complex projects, interrupts and inline +assembly need separate qualification before considering a global omission default. diff --git a/docs/development/CMOC_INDEXED_ARGUMENT_LOAD.md b/docs/development/CMOC_INDEXED_ARGUMENT_LOAD.md new file mode 100644 index 0000000..a1ae49b --- /dev/null +++ b/docs/development/CMOC_INDEXED_ARGUMENT_LOAD.md @@ -0,0 +1,107 @@ +# CMOC indexed argument-load qualification + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Failure and general correction + +A joystick-driven program passed adjacent axis and calibration bytes to one +function. After loading `centers[index + 1]`, CMOC's `removeUselessLdaOrLdb` +peephole rule deleted the reload of `index` before `centers[index]`: + +```asm +LDB index +LDX #centers +LDB D,X +``` + +The last instruction overwrites B only after computing its effective address. +B is the low byte of D, so the first load is required. Without it, the previous +argument's value becomes the subscript. Correct emulator joystick values can +therefore reach incorrect compiled game logic. + +The rule also checked the instruction mnemonic instead of its operand for +predecrement/postincrement effects, and recognized only an explicit `B,` prefix +on the intervening X load. The new +[`cmoc-indexed-argument-load.patch`](../../tools/toolchain/patches/cmoc-indexed-argument-load.patch) +uses the compiler's existing `InsEffects.read` analysis on both following +instructions. It preserves B dependencies, including D-indexed and indirect +operands, and uses the existing side-effect predicate on the removed load. +Independent overwritten loads can still be optimized. This is a compiler rule +correction; it does not recognize a game, input API, variable name or source +pattern. + +`build.py` applies the patch only to its ignored source copy after the existing +compiler patches. `build-runtime.py` records `vccIndexedArgumentLoadFix: 1`. +The pinned CMOC source and third-party manifests remain unchanged. + +## Target-executed regression + +The authored [fixture](../../tests/toolchain/indexed-arguments/qualification.c) +passes four actual bytes to a capture function from two arrays, at runtime +indices 0 and 2. It covers byte indices, word indices and pointer bases. Distinct +surrounding sentinels distinguish the stale-index error from legitimate values. +The guest prints raw result bytes; expected values and comparison belong to the +host runner, rather than the optimizer under test. + +For each pair of indices, the expected bytes are: + +```text +04 0C 08 10 14 1C 18 20 +``` + +The baseline staged compiler passed `-O0` on MC6809 and HD6309 but failed `-O2` +on both. Its byte-index case printed `04 0C 3A 10 14 1C 3A 20`: the sentinel +`3A` replaced the third argument. Retained generated assembly confirmed the +removed reload immediately before `LDB D,X`. + +The fixed universal staged compiler passed `-O0` and `-O2` on both emulated +processors through both its arm64 and x86_64 compiler slices: eight executions, +each checking all six calls. All use `--coco --no-relocate --switch=jump`. +The CoCo 3 ROM is an explicitly supplied local input. The x86_64 host compiler +ran under Rosetta on Apple Silicon; no physical Intel or physical CoCo result +is claimed. + +Reproduce with a staged runtime and a separately built shared-core library: + +```sh +python3 tests/toolchain/indexed-arguments/check.py \ + platforms/macos/LocalResources/ToolchainBundle \ + /path/to/libVCCCore.a platforms/macos/LocalResources/ROMs/coco3.rom \ + --host-arch arm64 +python3 tests/toolchain/indexed-arguments/check.py \ + platforms/macos/LocalResources/ToolchainBundle \ + /path/to/libVCCCore.a platforms/macos/LocalResources/ROMs/coco3.rom \ + --host-arch x86_64 +``` + +The regression also runs within `tools/toolchain/check.py --rom`. Its runner +uses temporary output and leaves the app, guest sessions and disk images alone. + +## Additional checks and runtime staging + +- The focused native [rule check](../../tests/toolchain/indexed-arguments/check-rule.py) + links the actual compiler build objects and checks 13 dependency/side-effect + guards and two safe removals. It covers direct/indirect B and D indexing, + intervening LDX/LEAX dependencies, and direct/indirect index/stack updates. + +- Existing indexed-subtraction and logical-negation target regressions pass at + `-O0` and `-O2` on both guest processors with the new compiler. + +- The public source-only toolchain build passes; all nine library archive + targets, greeting compile/link, DECB format and known assembler bytes pass. + +- Both compiler slices were rebuilt through `tools/toolchain/build.py` with + explicit `--host-arch arm64` and `--host-arch x86_64` and minimum macOS 14. + +- `tools/toolchain/verify-runtime.py` passes for that bundle: both complete + architecture build chains, system-only dynamic dependencies, relocated bundle + paths, preprocessor errors, dependency regeneration with spaces/quotes/`#`/`$`, + bundled Perl modules, disk allocation and ROM-backed/standalone disk linking, + with developer tools deliberately unavailable to the bundled workflow. + +To run the native rule check after a native `build.py` source build: + +```sh +python3 tests/toolchain/indexed-arguments/check-rule.py \ + .build/cmoc-indexed-arguments/fixed/work/cmoc +``` diff --git a/docs/development/CMOC_RELEASE_QUALIFICATION.md b/docs/development/CMOC_RELEASE_QUALIFICATION.md new file mode 100644 index 0000000..a20de9f --- /dev/null +++ b/docs/development/CMOC_RELEASE_QUALIFICATION.md @@ -0,0 +1,38 @@ +# C development release qualification + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Findings during qualification + +- Build 6 exposed an outdated locally staged CMOC binary: dependency paths with + quotation marks failed the existing relocation regression, although the current + reviewed compiler source already has the correction. Both host slices were rebuilt + from that source; the relocation regression now passes. Packaging now requires the runtime relocation check before + signing or uploading a candidate. + +## Completed November 3, 2026 + +| Check | Result | +| --- | --- | +| Full XCTest, corrected compiler | 414 passed on arm64 and 414 on x86_64/Rosetta; zero failures or skips. The optional local BASIC printer test was enabled. | +| Release core and private starter checks | All 61 core checks; disk/cassette regeneration, hard-disk BASIC, NitrOS-9 boot/shared HD1, Orchestra-90 and Speech/Sound passed. | +| Hello Disk from bundled template | Fresh source copy; native source edit, Save All, incremental rebuild, disk replacement confirmation, verified breakpoint, C step, Continue, normal quit and saved-source reopening. | +| Exact DMG-installed app | Copied from the read-only mounted DMG to a separate location. Signature and Gatekeeper passed. Reopened saved source, rebuilt with its bundled tools, stopped at `main.c:9`, and ran to disk result `0`, generated count `5`, and all five expected words. | +| CoCo Letters | Fresh recursive Make project built in the installed app; generated dictionary and bootable disk; source locations verified in nine C files. Native DOS boot and RGB/Easy/User selection reached the playable board. Separate core execution checked cursor response, nonzero audio, and unchanged disk bytes on 6809 and 6309 with 128 KB. | +| Installed toolchain relocation | The exact installed payload passed the existing runtime verifier, including both complete host-architecture build chains, unusual paths, dependency regeneration, Perl/modules, disk API linking and unavailable developer tools. Thin test copies are re-signed ad hoc; the original installed app retains Developer ID signatures. | +| Media and workspace protection | Full regression coverage passed for failed/cancelled/clean builds, immutable results, live-media cleanup guards, changed/missing files, interrupted builds, draft recovery and saved tab restoration. | +| Distribution | Universal app and DMG accepted by Apple, stapled, and accepted by Gatekeeper; embedded app, resources, DMG checksum, Applications link and Finder layout verified. | + +The native checks used isolated startup storage and separate projects; the normal +emulator and media were not changed. The saved-source reopening was explicit: +the isolated launch intentionally creates fresh preferences each time. Persistent +tab/history/recovery restoration was exercised by the automated model tests. +Native text editing used accessibility text entry because direct synthetic keyboard +events were not delivered reliably to the signed app; keyboard editing/Undo have +separate native regression coverage from the editing milestone. + +CoCo Letters is a build/run qualification fixture, not a bundled game. Its default +selected breakpoint was `waitTicks` at line 85, which this short play sequence did +not reach; its pending source attachment is not counted as a debugger pass. +Hello Disk and the two-CPU source/debugger tests provide that qualification. +Optimized game locals remain subject to the documented debugger limits. diff --git a/docs/development/CMOC_RUNTIME.md b/docs/development/CMOC_RUNTIME.md new file mode 100644 index 0000000..3d64e93 --- /dev/null +++ b/docs/development/CMOC_RUNTIME.md @@ -0,0 +1,79 @@ +# Self-contained CMOC runtime + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Runtime contract + +| Tool or directory | Purpose | +| --- | --- | +| `bin/make` | GNU Make 4.4.1: ordinary, recursive, incremental and parallel Makefile builds. | +| `bin/cmoc`, `libexec/cmoc` | Relocatable wrapper/native CMOC 0.1.100 compiler. | +| `bin/cpp`, `bin/mcpp` | Native CMOC adapter and mcpp 2.7.2 preprocessor. | +| `bin/lwasm`, `bin/lwlink`, `bin/lwar` | LWTools 4.25 assembler, linker and archive tool. | +| `bin/writecocofile` | CMOC's native disk-image insertion utility. | +| `bin/perl` | Universal launcher for bundled Perl 5.44.0 and its matching core modules. | +| `bin/install-coco-boot-loader` | Relocatable wrapper running the unchanged upstream loader script with bundled Perl. | +| `share/cmoc` | Target headers/runtime and optional library archives. | +| `libexec/perl/` | Independent relocatable interpreter/core-module installation; architecture-specific `Config.pm` and XS modules stay paired. | +| `LICENSES`, `manifest.json` | Retained upstream notices, tool versions, library hashes and native-helper architecture inventory. | + +The app selects bundled tools first on PATH and removes inherited Make/Perl overrides. Project recipes may intentionally set their own variables. Makefiles still run ordinary commands: a recipe requiring an additional host compiler, third-party command, GNU-specific tar option or non-core Perl package must supply that dependency. “Full Makeâ€� does not imply every possible program a Make recipe can call is bundled. We do not download CPAN packages or provide a host C/XS development SDK. + +The compiler wrapper creates a temporary space-free alias for target headers/libraries because upstream CMOC builds some assembler/linker commands through a shell. Application and project-directory names containing spaces work. Keep individual source and product filenames simple relative names; arbitrary shell metacharacters/spaces inside those individual names remain an upstream limitation. + +The maintained `cmoc-make-dependencies.patch` escapes generated Make dependency targets/prerequisites and decodes quoted preprocessor paths in both CMOC readers. The adapter quotes raw path characters emitted by mcpp. This covers real SDK header paths inside a relocated `VCC Plus.app`, including parent directories containing spaces, quotes, `#` and `$`. `verify-runtime.py` exercises both `--deps-only` and `--deps`, automatic inclusion/regeneration, changed-header rebuilding and no-op builds on both architectures. + +The bundled CMOC 0.1.100 optimizer preserves accumulator-indexed addresses when simplifying byte subtraction and comparisons. The runtime manifest records `vccIndexedByteSubtractionFix: 1`. The change takes effect when a project is recompiled. [Compiler patch and regression](../../tools/toolchain/patches/README.md) + +The runtime manifest records `vccAddZeroFlagsFix: 1` for correct logical negation of integer results at `-O2`. Recompile existing guest programs to pick up the fix. [Logical negation regression](../../tools/toolchain/patches/README.md) + +App staging adds a deterministic payload hash to the installed manifest. Workspace caches therefore invalidate when the compiler, helpers or headers change, even with the same upstream version. + +Native project builds pass `MAKE=make` with the bundled tools first on PATH. This keeps recursive `$(MAKE)` recipes working when the actual application path contains spaces. The runtime regression includes a recursive child Makefile. + +### Scoped inline-assembly preprocessing + +Ordinary C uses mcpp's standard conforming preprocessing. If explicit `asm { ... }` blocks occur, the adapter obtains a second expansion in mcpp's documented assembler mode and substitutes only those balanced assembly bodies. This preserves immediate/indexed operands such as `#COUNT` and `-COUNT,x` without changing ordinary C token boundaries, string literals, macro stringizing or preprocessing errors. Both passes must identify matching block counts; an incomplete or inconsistent block fails rather than compiling a truncated transformation. Source line markers are retained and translated to CMOC's expected syntax. + +The adapter does not globally enable assembler mode or LWASM `newsource`. Five regressions cover assembly macro operands, multiple blocks/include markers, unchanged C/string behavior, invalid C token-paste rejection, error line numbers and actual generated 6809 immediate bytes. + +## Included target libraries + +The standalone compiler now builds all nine reviewed library archive targets. The installed public runtime includes the following headers/archives; add the relevant `-l` option to the project's Makefile rather than automatically linking everything. + +| Library | Link option | Upstream terms | +| --- | --- | --- | +| BGraph | `-lbgraph` | Public domain, original acknowledgments retained. | +| BSound | `-lbsound` | Public domain. | +| BControl | `-lbcontrol` | Public domain. | +| CardGame | `-lcardgame` | Public domain. | +| HiresTxt | `-lhirestxt` | Public domain. | +| AStar | `-lastar` | Public domain. | +| WydeAlloc | `-lwydealloc` | GPL-3.0-or-later. | +| Ebitor | `-lebitor` | GPL-3.0-or-later. | +| VCC Plus Speech/Sound | `-lssc` | GPL-3.0-or-later. Requires Speech/Sound for audible output. | +| VCC Plus Orchestra-90 | `-lorch90` | GPL-3.0-or-later. Stereo DAC access works with the optional composer ROM omitted. | +| VCC Plus GIME graphics | `-lgime` | GPL-3.0-or-later. Two 320 × 192, 16-color pages on a CoCo 3. | +| VCC Plus joystick input | `-linput -lbcontrol` | GPL-3.0-or-later wrapper over public-domain BControl. Samples one CoCo port per call. | +| VCC Plus C compatibility subset | `-lvcccompat` | GPL-3.0-or-later. In a custom Makefile, also set `export VCC_CMOC_COMPAT = 1` to activate its headers. | +| decbfile ROM-backed core | `-ldecbfile` | Public domain; subset described below. | + +`tools/toolchain/stage-libraries.py` builds eight optional libraries from unchanged source copies with the bundled compiler and unusable Apple SDK settings. Header names, archive bytes and upstream notices are recorded in the runtime. GPL library linking carries its own obligations; compiler licensing does not automatically determine the license of an otherwise independent user program. + +## Validation + +```sh +python3 tools/toolchain/verify-sources.py +python3 tests/toolchain/test_cpp_adapter.py +python3 tools/toolchain/verify-runtime.py platforms/macos/LocalResources/ToolchainBundle +``` + +Runtime verification audits all native helpers for architecture slices and system-only dependencies, relocates the whole payload into a path with spaces, and compiles through bundled Make with invalid Apple developer-directory/SDK settings. It repeats with separately thinned Apple Silicon/Intel helper tools, exercises bundled Perl's Getopt::Long and Digest::SHA XS module, and checks the boot-loader wrapper. Deliberate preprocessing failure must stop Make with the correct line number. Intel execution on Apple Silicon uses Rosetta. + +November 3, 2026: all nine library archive builds passed without the SDK preprocessor. The original CoCo Letters project built its 161,280-byte disk using the bundled compiler, interpreter and asset/boot helpers. Full Apple Silicon and separately thinned Intel builds produced identical disk bytes (SHA-256 `da81baceb20967be2822a353ae64369eda7e830102b21a0127052d04fead1470`); a no-op Make and clean parallel rebuild also passed. Its disk booted on both emulated CPUs with 128 KB; title, RGB/Easy/User selection, cursor response, 90,624 read events, zero writes and 2,040 nonzero audio samples passed. This is a smoke test, not exhaustive gameplay qualification. + +Perl is dual-licensed GPL-1.0-or-later / Artistic-1.0-Perl; retained component notices include the bzip2 BSD-style license. mcpp is BSD-2-Clause. GNU Make's executable is GPL-3.0-or-later; its separate manual retains GFDL terms. Exact source snapshots, upstream notices and hashes are in `third_party/`. No private input is needed to reproduce the public toolchain. + +## C debug metadata + +The local [CMOC debug extension](../../tools/toolchain/patches/README.md) is applied to compiler build copies, leaving the pinned upstream snapshot unchanged. Compiling with `-fno-omit-frame-pointer` emits versioned type/scope/storage metadata; unoptimized preserved frames enable locals. The IDE verifies it against the same linked artifacts used for C source mapping. See [C source debugging](CMOC_SOURCE_DEBUGGING.md) for capabilities and limits. diff --git a/docs/development/CMOC_SOURCE_DEBUGGING.md b/docs/development/CMOC_SOURCE_DEBUGGING.md new file mode 100644 index 0000000..d1972f1 --- /dev/null +++ b/docs/development/CMOC_SOURCE_DEBUGGING.md @@ -0,0 +1,135 @@ +# C source debugging + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +VCC Plus extends the existing CMOC workspace with source-line stepping, verified C call stacks and read-only variable inspection. The source editor, debugger and live CoCo use the same machine; changing inspector tabs never reloads or resets it. + +## Stepping + +Build a project, then run to a verified source breakpoint. **C Step Into** advances to the next mapped source line, entering functions whose source is available. **Over** completes the current line without stopping inside called functions, except at an existing breakpoint. **Out** finishes the current function and stops at its actual return address; the caller may still be completing the original call expression. **Instruction** remains available for assembly-level work. + +Mapping is by file and line, not individual statements or columns. Several statements on one line cannot be stepped separately. A one-line loop stops on a new iteration. Unmapped library code is executed normally; returning into unmapped code shows the assembly fallback. Existing user breakpoints take precedence. Pause cancels a pending step. Instruction, frame and call-depth limits prevent an unbounded step; the stop reason explains why execution paused. Interrupts and 6309 TFM block transfers retain their normal guest behavior. + +Every step checks the paused machine generation, program revision, MMU mapping, PC and verified instruction bytes on the emulation queue. Flat programs retain their original effective-MMU fingerprint throughout a step. A reset, debugger memory edit, changed source, different build or incompatible mapping requires reconnecting the build. Changed executable bytes are not silently treated as the original C program. + +## Banked programs + +Custom Make projects can supply a verified banked debug manifest alongside their build outputs. This associates the delivered program with its original linker output, source/object/listing identities, complete relocated code sections and explicit logical-to-physical RAM page assignments. See [the MCP banked-development contract](MCP_BANKED_PLAYTEST.md) for the manifest and installed-app workflow. A packed or overlapping binary alone is insufficient to reconstruct those associations. + +Different modules may occupy the same CoCo address at different times. The debugger identifies a module by its actual installed RAM pages and complete expected executable bytes, including assembly code outside mapped C lines. Identical opcodes in a loader or another physical page do not establish source identity. ROM overlays do not count as mapped RAM. Overlapping modules must have mutually exclusive page assignments; ambiguous simultaneous claims are rejected. + +Arming disk-source stops pauses only to configure the debugger; it does not copy code into RAM, change PC or reset the machine. Normal DOS/LOADM execution installs the program. A source stop becomes eligible when its own module is mapped and matches its verified code. Other overlays need not be mapped simultaneously. Manual debugger breakpoints remain independent and can still stop in unmatched code. + +The attachment survives expected bank switches. Each paused source location, call stack and variable view uses the currently mapped modules from the same immutable machine snapshot. A bank-aware source step checks the initial paused fingerprint to reject stale commands, then follows declared page switches and selects the matching module at each mapped instruction. A wrong bank or changed module code stops the step with an explanation. The ordinary flat-program fingerprint rules remain unchanged. + +Bank awareness does not recover optimized locals or create a frame convention. Compiler-described globals can be inspected where their storage is currently mapped and verified; unavailable overlay storage remains unavailable. Caller reconstruction still requires the supported, verified U-frame convention and stops at unsupported assembly, optimized or unmapped boundaries. An address by itself does not identify a module, and the debugger does not switch guest banks merely to inspect a value. + +### Verified function-entry stops over MCP + +For an owned playtest, a banked project can expose executable function symbols +in addition to mapped C statements. `get_build.source_debugging.functions` +contains unique names with a mapped C body instruction; `function_entries` +contains unique compiler symbols whose full entry-to-end range is covered by +verified executable guards and physical page assignments. Data/BSS symbols, +ambiguous names and incomplete executable ranges do not become entry stops. + +Select `stop_kind: "function_entry"` with the advertised name when starting an +owned run or arming `playtest_debug`'s `stop_at` action. This can stop in an +assembly input sampler or a verified prologue before its first C statement. +At a pure assembly stop, `source_stop` remains null and `function_stop` identifies +the actual symbol, entry/current address, module, physical RAM and declaration +location. The declaration line is not an executing C statement. Subsequent +instruction steps report `assembly_instruction` where no mapped C line exists. +A C source stop can also include the enclosing verified function identity. + +The runtime uses the same immutable snapshot and complete module-code checks +for these observations. It does not guess locals, unwind an unsupported frame, +execute an expression or switch guest banks. Owned MCP snapshots expose +registers, verified shared globals, locally configured named watches and bounded +readable ranges. Native C source stepping and the native assembly debugger retain +their existing controls. See [the owned-playtest contract](MCP_BANKED_PLAYTEST.md) +for selection, input and retained-disk behavior. + +## Call stacks and caller inspection + +Choose **Call Stack** in the lower inspector while paused in a verified C build. The innermost function is first; recursive invocations appear as separate frames. Selecting a supported caller opens its source at the call site and makes **Variables** and **Watches** use that invocation's parameters and locals. Return to the first frame to inspect the paused function again. + +Frame selection is inspection only: it does not change PC, registers, guest memory or execution. **Into**, **Over**, **Out** and **Instruction** always operate on the actual paused execution point, even while viewing a caller. The editor distinguishes the selected caller from the execution location. Values come from the current paused memory snapshot, not a historical copy taken when the call occurred; globals and objects reached through pointers can reflect changes made by the callee. + +The unwinder supports the ordinary, unoptimized CMOC calling convention with a preserved U frame. It verifies compiled code, frame layout, readable stack links and the direct call instruction associated with each saved return address. Source scope is the caller's call site, not an arbitrary instruction near its return address. Unavailable or ambiguous links stop the stack with an explanation rather than searching memory for plausible return addresses. Interrupt handlers, assembly/optimized frames, indirect calls, nonstandard prologues and unmapped runtime/library callers can therefore leave a partial stack. A partial stack is not a claim that execution started at the oldest displayed function. + +## Variables and watches + +Choose **Variables** in the lower inspector to see compiler-described globals, parameters and locals in the selected frame's scope. Choose **Watches**, enter an expression and press Return or **Add Watch**. Watch expressions are remembered per project; removing one does not alter guest memory. Values are refreshed from a single paused PC/register/memory snapshot and disappear when the program runs or its source identity becomes invalid. + +Supported values include signed/unsigned integers, pointers, arrays and structures/unions. Expand an array or aggregate in **Variables** or **Watches** to browse its elements and members. Pointers show their address first; expanding one explicitly inspects its pointed-to value. Nested values use the selected call-stack frame and the same paused memory snapshot as their parent. Scope and shadowing come from compiler metadata rather than parsing editor text. + +Expansion is read-only. Variables and container children are shown in pages of up to 32 entries; the visible tree is capped at 255 rows and traversal at 12 levels. Pointer cycles stop with an explanation instead of expanding repeatedly. Unsupported children remain individually unavailable so other members can still be inspected. Null pointers, unavailable memory and unsupported pointed-to types produce explanations; a pointer does not imply an array length or an allocation guarantee. A pointer may refer to readable memory that is no longer a live C object. + +Expressions such as `values[2]`, `player.x`, `pointer->field`, `*pointer` or `&score` remain available when a focused watch is more useful than browsing. Expansion never executes a getter or guest function, writes memory, or reads hardware I/O. Open branches stay stable while the same paused snapshot refreshes. Changing frames, advancing execution or invalidating the build clears expansion state so a previous frame’s tree cannot be mistaken for the new context. + +Expressions support integer literals, arithmetic, comparison, bitwise and logical operators. Calculated results use **checked 64-bit watch integers**, not CMOC's target integer-promotion or overflow rules; stored variables retain their declared target types. Function calls, assignments, increment/decrement, casts, floating-point literals and floating-point watch arithmetic/comparisons are not supported. Stored floating-point values are supported as described below. Hardware I/O and unavailable memory are never read through live device ports. Unsupported values produce an explanation, not a guessed number. + +### Floating-point values + +Variables, array elements, structure/union fields, pointer targets and direct watches now display compiler-described floating-point values, including parameters and locals from a verified caller frame. Rebuild existing projects with the updated bundled compiler: older debug metadata does not identify the format and reports that a rebuild is needed. The app never guesses the format from the current ROM, type name or storage size alone. + +The supported encodings are CoCo BASIC's packed five-byte format (also used by CMOC's native float option) and big-endian IEEE binary32 selected by `--mc6839`. The compiler records the encoding in each floating type, including nested types. Unknown formats and genuine unsupported double-precision layouts remain unavailable. CMOC 0.1.100 treats the C spelling `double` as an alias for `float`; that spelling does not add precision. + +BASIC values retain their 32-bit significand and display up to 11 significant decimal digits; IEEE binary32 displays up to 9. Scientific notation handles very small/large values, and IEEE signed zero, subnormals, infinities and NaNs are recognized. The decimal display reflects the stored approximation: for example, CMOC's BASIC-format `0.1f` displays as `0.099999999977`. This is not evidence of a failed calculation. Inspection uses only the existing paused memory snapshot and never calls guest floating-point routines. Arithmetic in watches remains integer-only. + +This decoder does not install additional float runtimes or bundle Motorola's ROM. The BASIC-backed runtime was qualified by running actual arithmetic on both guest CPUs. The native and MC6839 encodings were qualified from real compiler output and synthetic format-boundary tests; executing those optional math runtimes is outside this change. + +Generated Debug Makefiles and the Hello World/Hello Disk templates preserve the frame pointer. Existing custom Makefiles can opt in with `-O0 -fno-omit-frame-pointer --intermediate` on C compilation. Rebuild with the bundled VCC Plus compiler. Locals require both unoptimized code and the preserved U frame; optimized locals are unavailable. Existing projects are never rewritten automatically. Use Project Settings to preview and explicitly regenerate a generated Makefile when desired. + +The compiler extension is a maintained GPL patch applied to a build copy. Pinned upstream sources remain pristine. Versioned type/storage/scope comments and zero-byte labels are associated with the exact object, listing, linker map, source snapshots and executable. See [the patch contract](../../tools/toolchain/patches/README.md). Ordinary builds without the debug-frame option retain their prior compiler output. + +## Remaining limits + +- No editable C variables or semantic refactoring yet. Identifier completion and parameter hints are available as separate source-based editor assistance. + +- Inline assembly and optimized-away or ambiguous C locations retain the native assembly fallback. Verified executable function entries are separately available for owned MCP playtests; they do not create C statement locations. + +- Caller inspection is limited to verified frame chains. Unsupported links stop reconstruction; there is no speculative stack scanning. + +- Source-line stepping does not imply statement-level precision. + +- API-level documentation and online help remain a separate project. + +## Validation + +Verified November 3, 2026: + +- Full `VCCCoreChecks` suite on Apple Silicon and Intel: **348 tests per architecture, 347 passed, one optional local BASIC-printer ROM test skipped, zero failures**. + +- Universal Debug and Release application builds passed. No source warnings; Xcode emits its existing non-actionable AppIntents metadata notice because this app does not use AppIntents. + +- Core regression coverage includes both guest processors, nested calls/returns, interrupts, one-line loops, permanent breakpoints, cancellation, stale program identity, bounded execution and 6309 TFM transfers. + +- Actual compiled two-file programs verify Into/Over/Out, recursive frames, lexical shadowing, integer/array/pointer/structure values, mutation and I/O rejection, and invalidated executable bytes. Metadata coverage also keeps the incremental build workspace alive to exercise macOS temporary-path aliases. + +- The native app built and ran a two-file C project to a source breakpoint, stepped into its helper, displayed `value = 2`, `local = 7`, `score = 5` and `values = [11, 22, 33]`, evaluated `values[1] + local` to **29**, and returned to the caller. The watch correctly reported `local` unavailable after leaving its scope. Keyboard entry remained in the watch field. + +- Call-stack tests recover six real frames across two source files on both guest processors, including recursive arguments/locals and odd-byte frame alignment. They reject corrupt, unavailable, stale-code, unverified-prologue, optimized and interrupt boundaries and enforce a depth limit. + +- The development-model regression verifies that selecting a caller changes its source navigation and values without changing PC, registers, cycles or memory. Polling preserves the selection; changed source hides stale frames and stepping returns inspection to frame zero. + +- Native Call Stack review showed `recurse` × 4, `wrapper`, and `main`. Selecting `wrapper` displayed `value = 7`, `local = 12`, and `byteLocal = 42`. The recursive caller watch `n + local` evaluated to **12**; stepping advanced the actual leaf and restored frame zero, where the watch was **10**. The frame picker stayed open across refreshes, and controls remained usable at 900 × 650 points. + +- Seven additional tree tests cover typed child paths, two-page arrays, nested structures/unions, explicit pointer traversal, unavailable siblings, null/I/O/cycle/depth errors, stale code, and owned snapshot buffers. The compiled two-file fixture checks current/caller values on both guest processors and proves registers, cycles and memory remain unchanged. The model regression also checks root paging, the visible-row limit and expansion identity across refresh/frame/step changes. + +- Native tree review displayed `local.point = {x: -17, y: 21}` and the same object through `local.pointer`, then caller `bag.point = {x: -7, y: 11}`. Array paging advanced to `bag.samples[32] = 132`; stepping restored frame zero and made caller-only watches unavailable. The compact Watches pane now reserves space for its frame picker, entry field and scrollable values at 900 × 650 points. + +- Eight new floating-point tests cover compiler encoding tags and constant bytes for BASIC/native/MC6839, missing/unknown/inconsistent metadata, precision boundaries, IEEE subnormals/special values, memory/I/O/stale-code rejection and explicit arithmetic rejection. The real two-file program performs BASIC-backed addition and multiplication on both guest processors, then verifies globals, parameters, locals, arrays, members, pointers and caller values without changing guest state. + +- Native floating-point review displayed `input = -6.25`, `local = -5.75`, `globalResult = 3.75`, and caller `measurements.x = 1.25`. Expanded array values and direct pointer watches worked; stepping restored frame zero. The revised compiler is staged for both host architectures, and ordinary optimized object bytes remain unchanged. + +- Pinned upstream source hashes remain unchanged; the compiler extension is reproducible from the committed patch. The normal emulator session and user media were not used for these checks. + +These are captures of the running native application, not mockups: + +Caller watch capture · Compact window capture + +Compact variable-inspector layout + +Expanded floating-point caller watch diff --git a/docs/development/MCP_AUDIO_CAPTURE.md b/docs/development/MCP_AUDIO_CAPTURE.md new file mode 100644 index 0000000..234c7c9 --- /dev/null +++ b/docs/development/MCP_AUDIO_CAPTURE.md @@ -0,0 +1,60 @@ +# Disposable guest audio capture + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +A newly exported C connection +uses toolset 7. `capture_playtest_audio` requires both the native **Allow +Disposable Playtests** permission and the exported `playtestAudio: true` flag. +Older grants retain their advertised tools. No microphone permission is used. + +```json +{ + "name": "capture_playtest_audio", + "arguments": {"run_id": "", "request_id": "tone-01", "fields": 60} +} +``` + +The operation releases held keys, drains earlier audio, resumes the owned guest +and advances at most the requested **1–120 emulated fields**, then pauses it. +An armed verified breakpoint can shorten the interval; `completed` reports that +case. It does not record wall-clock playback or the personal emulator session. +For a sound triggered by a key, use ordinary `playtest_input` first and then +capture the following interval. That preceding input's audio is deliberately +outside the clip. Framebuffer capture remains a separate nonadvancing operation. + +The result contains one standard MCP `audio` content block with `mimeType: +"audio/wav"`. Text and structured metadata omit the base64 payload. The WAV is +uncompressed 44,100 Hz stereo, signed 16-bit little-endian PCM from the emulator's +normal audio output, before host volume or playback. No filtering or synthetic +silence is added. A constant DAC level can be silent with a DC offset; analyze +variation or centered RMS rather than requiring all-zero samples. + +The receipt binds the clip to `run_id`, `project_id`, `revision`, `artifact_id` +and `boot`. Its `audio` object reports encoding, sample rate, channels, bit depth, +`sample_frames` (stereo pairs), `sample_count` (interleaved scalar samples), WAV +byte count and SHA-256. `field_start`, `field_end`, `fields_requested`, +`fields_advanced`, `cycles_start` and `cycles_end` describe the actual guest +interval; `advances_execution: true` makes the timing effect explicit. + +Reuse an identical request ID and plan after a transport retry: it returns the +original bytes and interval without advancing again. Changing its plan is a +conflict. A retry after a cold restart still identifies the original clip's boot; +a new clip has the new boot number. Revoked or incompatible runs cannot replay +their clips through a stale grant. + +Each clip is limited to 131,072 stereo sample frames (524,332 WAV bytes). A run +retains at most 16 unique audio requests and 4 MiB of WAV bytes across all its +boots. Before a new request, enough byte allowance must remain for a maximum +clip. Retried receipts consume no additional allowance. Existing emulated-field, +boot and 1,024 mutation-request limits also apply. Receipts expose remaining +audio and mutation budgets. No audio files are automatically written to a project +or published to a server. + +`stop_playtest` is exempt from execution/audio request budgets and retains its +usual ownership, request-conflict, disk-preservation and retry safeguards. Even +after the execution ledger is full, an assistant can stop and retain its owned +worker. This exemption does not authorize another input, step or restart. + +See [verified debugging and diagnostics](MCP_DEBUG_EVIDENCE.md), +[owned playtests](MCP_BANKED_PLAYTEST.md) and +[project refresh](MCP_PROJECT_RELIABILITY.md) for related contracts. diff --git a/docs/development/MCP_BANKED_PLAYTEST.md b/docs/development/MCP_BANKED_PLAYTEST.md new file mode 100644 index 0000000..948f9ae --- /dev/null +++ b/docs/development/MCP_BANKED_PLAYTEST.md @@ -0,0 +1,376 @@ +# Banked C debugging and owned MCP playtests + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Build evidence for packed programs + +Set optional `debugManifest` in `vccplus-project.json` to a generated relative +JSON path, for example `build/debug/manifest.json`. The Make recipe must produce +it alongside the exact configured binary and disk. Changing that setting or its +exporter changes the approved recipe and requires native +[project-refresh review](MCP_PROJECT_RELIABILITY.md) +or a new connection. `get_build` +returns `debug_manifest` with the generated path, SHA-256, byte count and exact +UTF-8 text when it fits the 128 KiB sharing limit. Builds can +succeed without usable debug evidence; their receipts report why source debugging +is unavailable. In `source_debugging`, `status: "verified"` includes verified +source/type information; `"source_only"` distinguishes a verified source map from +unavailable variable metadata, and `"unavailable"` reports a failed map check. +A successful recipe alone does not establish any of these debug claims. +There is no fallback that treats a packed image as an unpacked +source image. + +Manifest version 1 contains: + +```json +{ + "version": 1, + "entryPoint": 3584, + "binary": {"path": "build/game.bin", "sha256": "<64 lowercase hex digits>"}, + "disk": {"path": "build/game.dsk", "sha256": "<64 lowercase hex digits>"}, + "linkMap": {"path": "build/game.map", "sha256": "<64 lowercase hex digits>"}, + "sources": {"main.c": ""}, + "artifacts": { + "build/main.o": "", + "build/main.lst": "", + "build/debug/resident.raw": "" + }, + "modules": [{ + "id": "resident-code", + "sections": ["code"], + "codeSections": ["code"], + "image": {"path": "build/debug/resident.raw", "logicalAddress": 4096}, + "pages": [{"logicalPage": 0, "physicalPage": 56}] + }] +} +``` + +This is a structural example, not a manifest for a runnable program. Include the +complete source set retained by the build service and every project object, +listing and raw slice used as evidence. The source set includes retained UTF-8, +non-NUL `.c`, `.h`, `.s`, `.asm`, `.lwasm` and `.inc` files, including generated +compiler assembly. Paths are canonical project-relative +regular files retained in the immutable result. Symlinks, traversal, inconsistent +hashes, ambiguous ownership and out-of-range sections fail verification. A raw +image can specify `offset` and `length`; logical and physical pages are 8 KiB. +Physical page numbers identify actual RAM backing after hardware mirroring, not +just the value written to an MMU register. Installed RAM capacity is checked by +the emulator. The packed binary's transfer address is `entryPoint`; it can belong +to a loader outside the unpacked C modules. + +Declare each linker section under one module. `codeSections` names executable, +immutable sections; mutable data and BSS belong in `sections` with their real page +assignments but are excluded from code guards. BSS needs no invented raw zeros. +A pure BSS module may omit `image` entirely when `codeSections` is empty; +its explicit page assignments and section ownership still apply. An initialized +section cannot use that omission to skip object byte verification. +Keep mutable bytes out of executable sections. Split modules when unrelated pages +need not remain mapped together. Different overlays may reuse a logical address +only with distinct physical ownership. + +Hashes bind the declaration to one build. VCC Plus independently replays object +relocations against the raw module bytes and verifies live RAM before publishing +source locations or values. Complete executable section guards include code +without C line markers. ROM and I/O mappings cannot masquerade as RAM. A stop in +the wrong bank, changed code or an unmapped overlay has no verified C location. +Expected bank switches preserve the banked attachment. Native banked source runs +use the project's declared disk launch; a binary-only packed project can still run +without a source attachment. Manual address breakpoints +remain separately owned. Optimized locals and unknown frame layouts remain +unavailable; globals are shown only with verified storage placement. + +## Grant a disposable playtest + +In **C Development → Assistant…**, select **Allow Disposable Playtests** and, +for a custom project, **Use Project Makefile**, then save the private connection. +The grant permits repeated launches of current built artifacts without another +launch prompt. It does not grant arbitrary host paths, commands, register writes +or guest-memory edits. Revoking the connection, changing the project revision or +rebuilding invalidates the owned run. + +A playtest uses the installed app's `vcc-playtest` helper in a separate process, +stock Disk BASIC and 512 KB, with MC6809 by default or HD6309 selected in a fresh +build 45 connection, and a private writable copy of the selected +artifact or retained test disk. It does not load another emulator core into the personal session. +It reads no personal settings, tapes, cartridges or mounted drives. The app's +configured launch commands run on that test machine. The worker advances only +when asked, so a capture does not consume game time. + +Use the live tool catalog and `get_capabilities` as the contract: + +| Tool | Purpose | +| --- | --- | +| `list_playtest_disks` | List retained primary boot disks scoped to the current project, with opaque IDs, hashes and artifact provenance. | +| `list_playtest_media` (fresh media grant) | List the current artifact's reviewed disk products and, optionally, an owned run's private copies and compatible retained histories. | +| `exchange_playtest_media` (fresh media grant) | Insert/eject a listed private FD0 copy at a paused, idle guest without reset or time advance; retain the old bytes before replacement. | +| `start_playtest` | Supply current project, revision, artifact and request IDs. Optionally select `processor: "MC6809"` (default) or `"HD6309"`, a retained disk by ID and exact hash, or name `stop_function` with `stop_kind: "c_line"` (default) or `"function_entry"`. | +| `playtest_input` | Send steps of named physical `keys` held for `fields`, with optional complete standard `joysticks` snapshots on fresh joystick grants. Omitted ports center and release. | +| `get_playtest_input` (toolset 9 joystick grant) | Read actual owned input and clock without advancing; input receipts also carry per-step delivery traces. | +| `capture_playtest` | Read the framebuffer PNG, text when available, field clock, CPU and disk identities without advancing. | +| `capture_playtest_graphics` | At a paused owned state, render the current display buffer and optionally one declared buffer by ID, with physical identities and ordered PNG images. | +| `capture_playtest_audio` (development toolset 7) | Advance 1–120 guest fields, then pause and return direct PCM16 stereo WAV with actual timing/boot identity. Requires a fresh audio-enabled owned grant. | +| `playtest_debug` | Pause, continue, instruction-step, or arm a verified named function with `stop_at` and its `stop_kind`. | +| `get_debug_snapshot` | At a verified C or function stop, read its honest stop kind, module/physical identity, registers, permitted memory ranges and named watches. | +| `read_debug_memory` | Read an advertised range from the same immutable stopped snapshot, up to 256 bytes. | +| `get_call_context` (fresh toolset 10) | Read exactly 64 bytes at the paused owned guest’s actual S, with caller/integer-argument interpretation only where compiled evidence proves it. Supply the same run and snapshot IDs. | +| `restart_playtest` | Cold restart the owned machine, retain its writable disk, and repeat the boot commands. | +| `stop_playtest` | End the worker and retain its test disk in the app's development results. | + +[Bounded call context](MCP_CALL_CONTEXT.md) explains raw versus proven values, fresh grants and snapshot invalidation. +Disk exchange covers `playtestDisks` declarations, +private writable sets, correct/wrong/empty media tests and explicit multi-disk +resumption. `restart_playtest` keeps the currently inserted disk; it does not +choose the primary disk automatically. + +Development [debug evidence and diagnostics](MCP_DEBUG_EVIDENCE.md) extend these +receipts to ordinary verified custom-Make artifacts. Flat code uses verified +executable guards and observed runtime mapping; no physical bank is guessed. +See [audio timing, budgets and retry behavior](MCP_AUDIO_CAPTURE.md). Audio capture +is advancing; framebuffer capture is nonadvancing. +[Processor selection](MCP_PLAYTEST_PROCESSORS.md) describes toolset 8, +actual 6309 mode/MD reporting, restart behavior and legacy grants. + +`playtest_input` accepts up to 64 steps, 1–600 fields per step and 3,600 fields per +request. Named keys include lowercase letters, digits, `up`, `down`, `left`, `backspace`, +`right`, `space`, `enter`, `clear`, `break`, `alt`, `control`, `f1`, `f2` and +`shift` and `period`. `period` is the actual unshifted CoCo period key; `backspace` +names the same physical key as `left`. Hold `shift` with a key for its physical +shifted meaning. The ordinary shared-run `send_keys` restrictions are unchanged. +A chord can hold up to eight distinct keys. A run has a bounded total +field budget of 216,000 attempts and 16 boots, including initialization and +restarts. Receipts include `remaining_field_budget` and `remaining_boots`. +`field_clock` counts completed emulated video fields, not game updates or wall +time; a breakpoint can interrupt a field and stop an input plan early. The +worker releases held keys at the end of a plan. Instruction stepping is one CPU instruction, +not a C source step. + +For example, this plan types a period and releases every key. Retrying its exact +request ID and plan returns the prior receipt without another press: + +```json +{"run_id":"","request_id":"period-1","steps":[{"keys":["period"],"fields":6},{"keys":[],"fields":6}]} +``` + +The `get_build.source_debugging` catalogs distinguish `functions` (unique +functions with a mapped C statement) from `function_entries` (unique compiler function symbols whose full +range belongs to verified executable sections). Choose the corresponding +`stop_kind`; assembly-declared input samplers and interrupt/graphics routines can +use the latter without adding fake C statements or changing the compiler. + +```json +{"run_id":"","request_id":"sample-entry-1","action":"stop_at","function":"sample_input","stop_kind":"function_entry"} +``` + +At an assembly entry, `get_debug_snapshot` returns `source_stop: null`, a +`function_stop` with the symbol, entry/current address, physical bank and verified +declaration location, and `stop_kind: "function_entry"`. Instruction steps inside +that function report `"assembly_instruction"` until a mapped C instruction is +reached. A declaration is not a claim that a C statement is executing. Registers, +verified shared globals and bounded memory remain available; C locals and frame +layouts are not guessed. Missing, ambiguous, non-executable or wrong-bank symbols +remain unavailable. The same selector verifies advertised entries and requested +stops. Every module used by that snapshot must still pass its runtime byte +guards; another mapped overlay that has not finished loading acquires no source +claim merely because its page is selected. + +Development build 42 also supports banked `source_only` Release inspection when +typed C metadata is absent. The build advertises `executable_symbols` proven +against its own retained objects, linker placements and initialized executable +bytes. Unique C underscore aliases may select those addresses with +`stop_kind: "function_entry"`. This selects an executable symbol, not a guessed +C function extent. A snapshot reports `symbol_stop`/`symbols_at_pc` and +`executable_stop`; it uses `symbol_entry` or `assembly_instruction` where no C +statement is mapped. `function_stop` remains empty without typed function proof. +Registers and advertised executable-code ranges remain readable, while `watches` +is empty and `source_debugging.variables` explicitly says `unavailable`. No Debug +addresses, guessed C frames or arbitrary memory ranges are substituted. + +Advertised symbol/function catalogs and `symbols_at_pc` have a 32 KiB encoded +JSON budget each, with matching `_total` and `_truncated` fields. Private verified +selectors retain all names even when a public list is truncated. A `symbol_stop` +requires exactly one full verified match, not merely one displayed match. +Executable-code inspection requires known contributing source evidence inside +the shared project scope; an unknown source does not grant code access. + +### Paused graphics-buffer captures + +An optional manifest `framebuffers` array declares up to four buffers: + +```json +"framebuffers": [ + {"id":"page_a","physicalAddress":262144,"mode":"hscreen2"}, + {"id":"page_b","physicalAddress":294912,"mode":"hscreen2"} +] +``` + +These addresses are an example for the bundled GIME library's two pages, not +defaults for another project. IDs contain 1–64 ASCII letters, digits, underscores +or dashes; `displayed` is reserved. Supported layouts are `sg4`, `pmode0` through +`pmode4`, and `hscreen1` through `hscreen4`. The app verifies the manifest's build +identity, and the worker checks the complete buffer against actual installed RAM. +An unsupported format or range is refused. Recipe/exporter changes require the +usual new approval; public calls cannot supply addresses, modes or raw bytes. + +Development build 43 additionally supports **live GIME canvases**. Fixed +`hscreen2` still means BASIC's 320×192, 160-byte-row layout; it is not a label for +every 16-color application. Declare custom canvases explicitly: + +```json +"framebuffers": [ + {"id":"canvas_a","physicalAddress":0,"mode":"current_gime","canvasBytes":65536}, + {"id":"canvas_b","physicalAddress":131072,"mode":"current_gime","canvasBytes":65536} +] +``` + +These example origins are not defaults. `canvasBytes` is required for +`current_gime`, must be a power of two of at least 8 KiB, and must align with the +physical origin. Canvas spans must be disjoint and fit actual installed RAM; +the worker is a 512 KiB machine. Fixed modes do not accept `canvasBytes`. + +At a paused GIME graphics state, the current video origin must identify exactly +one declared active canvas. The selected canvas inherits the live viewport's +width, height, row pitch, horizontal pan, vertical scroll, palette and byte offset +relative to that active canvas. Hardware horizontal row wrapping is preserved. +Every sampled byte must remain in the declared active and selected spans; the +preview refuses an escape instead of inventing vertical canvas-modulo behavior. +Unsupported text/compatibility layouts are refused for this mode. + +Metadata reports `video_origin`, `row_stride_bytes`, `horizontal_offset_bytes` and +`vertical_scroll_lines`; identified canvases also report `canvas_id`, +`canvas_address`, `canvas_bytes` and `viewport_offset`. `physical_address` remains +the first actual sampled byte, including pan, rather than the declared origin. +The two images still share one frozen state. No capture API accepts caller +addresses or changes the live registers/RAM. + +Pause, then call `capture_playtest_graphics` with `run_id` and optional +`buffer_id`. It returns the current displayed-buffer preview first, followed by +the selected declared buffer. Both use the same stopped generation/cycle/field +state and become standard MCP image blocks; metadata carries physical ranges, +layout, dimensions and identity. Rendering uses a copied GPU state, advances no +guest instruction and changes no RAM or registers. Logical preview dimensions +may differ from the bordered 640×480 framebuffer image. + +The normal `capture_playtest` PNG is still the last published video frame. +Its `display_buffer` describes the current video-register selection, which can +already have changed before another frame is published. The paused capture is +labeled `paused_register_preview`; it does not claim to reconstruct a historical +scanout or infer which unregistered page the guest will draw next. + +Only the latest successful artifact in this connection can start an owned run. +Finish one configuration's playtest before building another configuration. + +### Asynchronous startup + +Build 43 advertises `async_playtest_start`. `start_playtest` promptly accepts the +operation with a reserved `run_id`, `status: starting` and a preparation phase. +Poll `get_run` until startup is ready or reports a terminal failure; do not send +movement, capture or debugger calls while it is still preparing. Phase updates +distinguish metadata verification, artifact loading, retention, boot and capture. +Preparation does not hold an open MCP reply for the whole build-map/boot cost. + +Reuse the exact original request ID and arguments to recover the same operation; +a conflicting retry is refused. A failure remains inspectable rather than +silently starting a second machine. `stop_playtest` can cancel the reserved run +while it is starting. Revocation, source/revision changes and cancellation cannot +leave a late-created worker orphaned; cleanup completes before another startup +can replace it. A transport timeout is reported separately from a malformed or +incomplete host envelope, and neither justifies an automatic new start ID. + +Use the connected `project_id` and `revision` with `get_run`, as with ordinary +compiled runs. `status: ready` contains the current worker `receipt`; inspect +its `state` (`paused` or `running`) separately. Startup readiness is not a claim +that the guest reached the requested breakpoint. Initial metadata receipts omit +PNG data; call a capture tool explicitly when ready. Terminal `failed` receipts +retain the phase and bounded error, and a cancelled operation settles only after +any late worker has been retired. + +### Resume a retained test disk + +Stopping or revoking a run retains its writable disk in the app's development +results. `stop_playtest` returns `retained_disk_id` and `retained_disk_sha256`; +`list_playtest_disks` can recover the current project's recorded disks after an +app restart or connection replacement. A listed record supplies `disk_sha256`; +pass that value as `retained_disk_sha256` when starting the run. Listing reads +bounded provenance metadata; resumption rechecks the actual disk bytes against +the supplied hash. Legacy or incomplete records are not added to that listing. +These are opaque selections, not host paths. Rebuild the current project and pass the selected receipt to +`start_playtest`: + +```json +{"project_id":"","revision":0,"artifact_id":"","request_id":"resume-save-1","retained_disk_id":"","retained_disk_sha256":""} +``` + +Both retained-disk fields are required together. The app checks the saved bytes, +project ownership and recorded base-artifact disk hash before launching. A +rebuild may have a new artifact ID while producing the same base disk bytes. +A changed base disk requires a fresh test; the interface does not silently mix +an old saved disk with changed program evidence. Resuming cold-boots a fresh +machine using the project's declared commands. It restores disk contents, not +CPU or RAM state. Use the guest program's normal Load/Continue action afterward. + +The retained original stays unchanged. The resumed run gets a separate writable +copy and, when stopped, its own retained ID with a parent-disk link. Receipts +distinguish the selected disk's hash from the current artifact disk hash, and +runtime source verification still checks the code actually loaded in RAM. + +Receipt identities have separate meanings: + +| Field | Meaning | +| --- | --- | +| `artifact_disk_sha256` | Fresh disk bytes produced by the current build artifact. | +| `disk_original_sha256` | Initial bytes copied into this worker, including a selected retained save. | +| `disk_sha256` | Current writable test-disk bytes after guest activity. | +| `retained_disk_sha256` | Exact bytes successfully persisted when the worker is stopped. | +| `disk_origin` / `disk_provenance.origin` | Recorded origin, including `legacy_receipt` when old provenance is absent. | + +Recorded children preserve `origin_artifact_id` and +`origin_artifact_disk_sha256` separately from the current execution artifact and +`parent_disk_id`. Current build identity does not assert that it generated a +legacy disk's historical bytes. + +Disks retained before this feature have no project/artifact sidecar. They are +never exposed through an unscoped listing. A client that already holds that +run's UUID and exact disk SHA-256 from its previous receipt can explicitly resume +it from the fixed app-managed retention area. Its origin is reported as +`legacy_receipt`; the app does not invent missing old artifact provenance. +Subsequent child records preserve that origin and bind to the current project +and selected execution artifact. No arbitrary file path, memory write or change +to the personal machine is accepted by this interface. + +Successful retention publishes the disk and its metadata together. Replacing a +run waits for persistence. If a write fails after export, the app keeps the +exported bytes for retry and does not claim `disk_retained: true`. Keep the app +open while resolving that failure; repeating the same stop request retries +persistence without executing the guest or exporting a second disk. + +Use a fresh request ID for each distinct action. Retrying an identical accepted +request returns its receipt without executing inputs or restarting twice. Reusing +an ID for a different action is rejected. Broken worker communication retires the +run instead of risking a duplicated action. Save/load tests use real guest input +and the retained disk; debugger writes are not part of this interface. + +A PNG belongs to the guest display, not a capture of the Mac desktop. The public MCP transport returns a standard image content block alongside +dimensions and frame identity; the internal worker uses `png_base64`. Consumers +may save that image within their own project. Source snapshots expose only verified +shared program ranges, never arbitrary live machine memory. Available named +watch rows include their verified address, byte count and bank identity when +the storage belongs to a shared readable range, so clients do not guess where +a structure resides. + +## Qualification + +See the current development validation and remaining checks. +The distribution record identifies the delivered candidate and completed checks. +Authored regressions cover both guest CPUs, wrong-bank stops, complete code +mutation, stale source commands, immutable bridge inputs, manifest tampering, +physical storage ownership and input request retries. Actual game evidence and +remaining limitations are recorded with the candidate rather than asserted by +this protocol description. + +Large compiler type records can exceed the assembler's input-line limit. The +reader recovers complete records only from the retained, source-hashed compiler +assembly and requires matching listing record order, count and exact truncation +prefixes, then verifies all referenced object/linker labels as before. This +supports large application structures without relaxing build identity checks. +The optional `VCC_TEST_BANKED_ARTIFACT` XCTest input qualifies any retained +custom-project artifact without executing its Makefile or starting an emulator. diff --git a/docs/development/MCP_BUILD45_VALIDATION.md b/docs/development/MCP_BUILD45_VALIDATION.md new file mode 100644 index 0000000..727e729 --- /dev/null +++ b/docs/development/MCP_BUILD45_VALIDATION.md @@ -0,0 +1,29 @@ +# MCP processor selection — build 45 + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Contract and focused qualification + +[Processor selection](MCP_PLAYTEST_PROCESSORS.md) documents toolset 8's optional +canonical CPU, MC6809 default, normalized retry identity, actual CPU/mode/MD +reporting and 6309-only debugger registers. CPU selection is fixed for the run; +guest code controls native mode. Existing ownership, executable guards, bank +checks, budgets, keyboard release and retained-media protections remain intact. + +- **107 selected XCTest cases passed per host architecture**, arm64 and x86_64 + under Rosetta, with zero failures or skips. Suites: `CMOCBuildServiceTests`, + `CMOCVariableDebugTests`, `MCPPlaytestTests` through the VCCMac scheme. + +- Real 512 KB guests exercised both CPUs: artifact/global bytes, verified flat + stops, frame/audio metadata, bounded input, retries, cold restart and retention. + A separate authored 6309 guest executed LDW/TFR and LDMD, exposing actual + E/F/W/V/MD values and native mode; a pre-LDMD stop after cold restart proved + MD zero and emulation mode. No host memory/register writes manufactured it. + +- Native and Intel/Rosetta helper protocol regressions passed, including toolsets + 5/7/8, absent or malformed processor permission, canonical selectors and invalid values. + +- The reusable public acceptance fixture/script is checked in. Its new guest + N command compiles with the installed toolchain and executes LDMD only when + deliberately entered in an HD6309 run. Compiler `volatile` support remains + absent and is reported honestly; qualification uses actual observed bytes. diff --git a/docs/development/MCP_CALL_CONTEXT.md b/docs/development/MCP_CALL_CONTEXT.md new file mode 100644 index 0000000..e03449d --- /dev/null +++ b/docs/development/MCP_CALL_CONTEXT.md @@ -0,0 +1,118 @@ +# Owned playtest call context + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Access and timing + +The tool requires toolset 10 or newer and explicit boolean `playtest` and +`playtestCallContext` fields in the private grant. BASIC, assembly, legacy grants +and ordinary shared runs do not gain access. Native export records the current +consent; editing client-side grant fields cannot enlarge the app's permission. +The consent explains the bounded stack inspection. + +First pause at a verified stop in an owned disposable guest, then obtain its +immutable snapshot: + +```json +{"name":"get_debug_snapshot","arguments":{"run_id":""}} +``` + +Use the returned IDs without adding an address, length or expression: + +```json +{"name":"get_call_context","arguments":{"run_id":"","snapshot_id":""}} +``` + +The app checks the connection, project, revision, artifact and owned worker. +It captures the worker without advancing it and requires the same boot, field +clock, frame, cycles, generation, processor/mode/MD, registers, mapping, +program revision, complete memory and availability mask. A step, resume, restart, +new snapshot, disk exchange, rebuild, source change or revocation invalidates old context. +Request-budget bookkeeping is not guest state and does not invalidate a read. +Repeated reads of an unchanged snapshot return the same context. + +## Bounded raw view + +`status: "available"` supplies `stack_window` with exactly 64 bytes starting at +actual register **S**. It includes byte values, big-endian `words_be` with offsets +and addresses, and the physical RAM spans backing the logical window. Every +byte must be available RAM. ROM, unavailable pages, protected high memory, +wrapping ranges and unverified program locations fail closed. + +`interpretation: "uninterpreted"` is deliberate: words can be saved registers, +locals, padding or arguments. Do not call an arbitrary stack word a return +address or a C value. The caller cannot choose another address, increase the +window, dereference a pointer, evaluate a guest expression or modify state. +This tool does not add stack ranges to `read_debug_memory`, whose existing +advertised ranges remain unchanged. + +## Evidence-gated interpretations + +`caller` and `arguments` have their own availability status, independent of the +raw view. A verified source location alone does not prove a call frame. + +Caller interpretation requires compiler function metadata and verified normal +CMOC preserved-U prologue/epilogue bytes. At exact entry it uses the two bytes at +S; in a mapped body it uses U+2 only when the complete saved-frame/return slot is +inside the same 64-byte window. The return value must match one unique verified +direct call instruction targeting this callee, in approved caller source and +verified live code. There is no scan for plausible return addresses, speculative +unwinding, indirect-call guess or interrupt/tail-call assumption. + +Integer argument values require compiler-provided positive frame offsets and +full-function scope, that normal ABI proof and a verified direct caller. Only +nonoverlapping, named integer locations wholly inside the same window are +interpreted. Unsupported types, pointers/aggregates, unknown or optimized frames, +missing metadata, ambiguous callers and locations outside the window stay +unavailable. No pointed-to storage is read. + +`recorded_parameter_count` counts eligible compiler location records; +`all_recorded_parameters_available` states whether all those records were +interpreted. It does not prove that metadata contains the function's complete +prototype or all runtime arguments. Each interpreted item carries its location, +byte count and evidence label. + +For an optimized/source-only entry, the raw view can still help an assistant +compare the stop with the project's own assembly emitted through its approved +Make diagnostic and `get_build_log`. Such analysis must distinguish observations +from inferred ABI meaning; the app does not manufacture typed arguments. + +## Qualification + +Focused authored helper tests cover safe bounds, RAM/bank identity, proven entry +and body cases, unsupported frames, ambiguous calls, stale metadata and types. +The public-helper harness checks fresh/legacy/forged grant discovery and dispatch, +strict two-ID arguments and unavailable results. Real worker and authenticated +host-boundary checks are recorded below. Private ROMs/toolchain and temporary +results remain outside Git; missing inputs are explicit skips. + +### Executed checks — November 12, 2026 + +- Ten authored helper tests passed on arm64 and x86_64: bounds, unavailable RAM, + bank/source identity, entry and body interpretation, signed integer widths, + unsupported frames/types, ambiguous callers, stale metadata and overlaps. + +- Five debugger inspection tests passed on both architectures, including the + semantic fingerprint regression and existing BASIC, assembly and C inspection. + +- The real authenticated native C-grant test passed on both architectures. A + compiled seven-argument fixture exercised build, owned startup, snapshot and + context requests over the actual local transport. Wrong run/snapshot IDs, + extra address arguments, stepping/rebuild staleness, revocation and unapproved + or forged client grants were rejected. A non-owned run ID was rejected; this + test did not launch a separate ordinary shared run. + +- A real 512 KB worker fixture passed on MC6809, HD6309 emulation mode and HD6309 + native mode on both host architectures. Ordinary guest instructions created + the call/arguments. Repeated inspection preserved the complete captured guest + state; inspected and uninspected twins subsequently produced identical, + nonconstant guest PCM. Return, restart and retained-disk bytes also matched. + No host memory/register injection was used to create the call or its values. + +- The public helper's complete protocol harness passed with both arm64 and + x86_64 helpers, including 23 fresh/legacy/malformed/forged grant variants, + strict two-ID schema validation and unavailable-result forwarding. + +The x86_64 test bundle and worker were verified as thin Intel binaries and ran +through Rosetta on Apple Silicon. This is not physical Intel or macOS 14 +qualification. diff --git a/docs/development/MCP_DEBUG_EVIDENCE.md b/docs/development/MCP_DEBUG_EVIDENCE.md new file mode 100644 index 0000000..99d8a2d --- /dev/null +++ b/docs/development/MCP_DEBUG_EVIDENCE.md @@ -0,0 +1,137 @@ +# Verified custom-Make debugging through MCP + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Read the build evidence first + +Every completed executable build now reports `source_debugging` in `get_build`, +including ordinary custom-Make builds without a banked manifest. Successful +compilation and verified debugging are separate results: + +- `verified` means the executable/source map and compiler type metadata passed + verification. `source_only` means executable evidence passed but typed C + metadata is unavailable; `reason` explains why. `unavailable` identifies an + executable, map, object, listing or source verification failure. + +- `c_line_stops` lists actual compiler-mapped statements, with shared source path, + line, logical address and declared bank identity where applicable. `functions` + names only unique functions with a verified C statement inside their body. + +- `function_entries` names verified executable entries, including supported + assembly/prologue entries. An entry stop does not establish a C statement or + stack-frame layout. `function_details` distinguishes a declaration from an + available C stop and explains missing C statements. + +- `globals` lists shared file/global declarations, their verified type/storage + and module identity. These are declarations, not guessed runtime values. + Unsupported storage/type layouts are explicitly unavailable. + +- Binary/link-map hashes, load entry, module page assignments and + `owned_stop_evidence` identify the exact build. Every catalog includes total + and truncation fields and is bounded by its encoded size. + +Ordinary flat custom Makefiles must retain the matching binary, linker `.map`, +linked project `.o`, assembler `.lst` and source snapshots. Keep CMOC +`--intermediate` enabled when compiling and linking. The bundled compiler emits +its `VCCDBG1` type/storage records; retaining compiler-generated `.s` permits +verification of records too long for an assembler listing row. A useful Debug +compile uses `-O0 -fno-omit-frame-pointer`; optimized builds can legitimately +have fewer C statements or unavailable locals. No user Makefile is rewritten +merely to provide debugger metadata. + +For example, a normal recipe can compile and link with: + +```make +obj/main.o: main.c + @mkdir -p obj + "$(CMOC)" --coco -O0 -fno-omit-frame-pointer --intermediate --intdir=obj -c -o $@ $< +program.bin: obj/main.o + "$(CMOC)" --coco --intermediate --org=2800 -o $@ obj/main.o +``` + +This fragment only illustrates retained evidence; disk construction and launch +commands remain the project's declared recipe. Packed, relocated or bank-switched +programs must supply the public version-1 [banked debug manifest](MCP_BANKED_PLAYTEST.md). +Its hashes, unpacked images, section ownership and actual physical page identities +are required. It never falls back to a flat interpretation after verification +fails. + +## Stop and inspect the owned guest + +With an approved disposable-playtest connection, build the current revision and +use an advertised `functions` name as `stop_function` in `start_playtest`, or +`function_entries` with `stop_kind: "function_entry"`. Poll asynchronous startup +with `get_run`. Later `playtest_debug` with `action: "stop_at"` accepts the same +verified name/stop kind. Neither call accepts an arbitrary stop address. + +Ordinary flat builds use the existing native guarded-breakpoint path. Complete +object-relocated executable bytes must match before the first named stop can +attach; the actual worker's mapping fingerprint is retained. No assumed stock +physical pages are substituted. Continuing can remove selected stops while +retaining the exact same code/mapping identity. A changed mapping or executable +byte makes the old attachment unavailable. An empty inspection selection alone +cannot establish an initial attachment. + +At the verified paused state, `get_debug_snapshot` reports registers, honest +stop kind, source/function entry where known, actual physical pages/mapping +fingerprint and bounded `globals` values from the same safe memory capture. +A global outside the readable stopped mapping has an `unavailable` reason. +Unshared declarations are omitted. C frame locals remain unavailable at owned +entry/instruction stops; no frame is inferred from U or a guessed prologue. +Locally configured watches retain their existing rules. + +`read_debug_memory` accepts only ranges advertised by that immutable snapshot, +up to 256 bytes. Resume, input, step, restart, source/artifact changes and +connection revocation invalidate the applicable observation. Inspection performs +no guest expressions, register writes, memory writes or side-effecting I/O reads. +A mismatched binary, object relocation, source identity or bank cannot produce a +verified snapshot merely because a requested function name exists. + +For diagnostics and paged compiler output, use `get_build` and `get_build_log`; +those receipts are independent of whether source debugging is available. + +## Diagnose the selected build + +A newly exported toolset 7 C grant has `projectDiagnostics: true` and advertises +`get_build_log`. Build receipts retain action, configuration, revision and final +status. Both successful and failed builds report structured `diagnostics`, with +severity, source path/line/column when shared and known, stage, message and raw +diagnostic text. `first_error` selects an error even when warnings precede it or +fill the visible diagnostic list. `diagnostics_total` and +`diagnostics_truncated` explain bounded previews. + +`exit_code` is the actual Make process status when one exists; it is null for a +preparation failure. A post-Make validation failure can correctly report exit 0 +and `failure_kind: "validation"`: the command succeeded but its output was +unacceptable. `failure_stage` distinguishes compiler, assembler, linker, Make, +preparation or validation when the evidence identifies it. `invocation` records +the top-level command. `failing_command` is available only when a recognized +echoed command precedes the first retained error; hidden recipe commands remain +unavailable. Raw diagnostics stay in the redacted combined log, including lines +without source locations. Separate stdout/stderr are not fabricated. + +```json +{"name":"get_build_log","arguments":{"build_id":"","offset":0,"limit":16384}} +``` + +Follow `next_offset` until null to retrieve every retained UTF-8 byte. Offsets +refer to the frozen redacted log; they never read a host file or rerun a tool. +Each page accepts 1–32,768 bytes, preserving complete Unicode scalars (a scalar +can exceed an unusually small requested limit). The SHA-256 covers the complete +retained log. Only this connection's build IDs are accepted. + +The process log retains at most 512 KiB, preserving its beginning and end when +clipped; the normal receipt shows a smaller preview. `process_output_bytes`, +`process_output_truncated`, `log_retained_bytes`, `log_truncated` and +`first_error_scope` distinguish complete evidence from a retained subset. +Pagination recovers the complete retained log, not bytes already dropped at the +process-output limit. The interface reports that limitation explicitly. + +## Bounded owned call context + +Fresh toolset-10 C playtest grants add `get_call_context(run_id, snapshot_id)`. +It exposes only a fixed 64-byte RAM window at actual S from the same immutable +verified pause. Proven normal CMOC calls can include caller and integer argument +locations; optimized, indirect or unknown frames retain explicit unavailability. +It does not enlarge ordinary memory-read ranges or shared-run access. See the +[call-context contract and qualification](MCP_CALL_CONTEXT.md). diff --git a/docs/development/MCP_PLAYTEST_MEDIA.md b/docs/development/MCP_PLAYTEST_MEDIA.md new file mode 100644 index 0000000..216d47b --- /dev/null +++ b/docs/development/MCP_PLAYTEST_MEDIA.md @@ -0,0 +1,187 @@ +# Owned-playtest disk exchange + +A fresh C connection with **Allow Disposable Playtests** can advertise +`playtest_media_exchange` and the `list_playtest_media` / +`exchange_playtest_media` tools. Check live discovery and `get_capabilities` +before planning exchanges. Existing connections keep their original schemas; +new tools require a newly reviewed connection and a restarted client helper. +This feature operates only on an owned disposable guest, never the ordinary +shared run or personal mounted media. + +## Declare the disk products + +In **C Development → Project Settings → Build**, list additional playtest disk +outputs, one project-relative path per line. The portable project configuration +uses: + +```json +{ + "diskImage": "build/HOME.dsk", + "playtestDisks": [ + "build/DATA.dsk", + "build/WRONG.dsk", + "build/CORRUPT.dsk" + ] +} +``` + +This is a configuration fragment. Keep the rest of the project's actual build +and launch settings. The primary `diskImage` remains the boot disk. Up to eight +additional `.dsk` or `.os9` products are supported, each no larger than 512 KiB. +They must be ordinary generated files from the same approved Make build. The +app validates relative paths, distinct outputs, source/output separation, +regular-file identity and exact build hashes; symbolic or hard-linked products +are refused. A successful normal/disk build must produce every declared disk. +Changing declarations changes the reviewed recipe and isolated build identity. +Source refresh review preserves drafts and does not run the guest. + +The app retains immutable artifact copies. A playtest creates its own writable +copy of each declared disk, including the primary. It does not edit project +products. Deliberately wrong editions and corrupted game catalogs/payloads may +be separate declared images. The app still rejects malformed disk containers; +validation of a game-specific label, edition or checksum belongs to the guest. + +## List and select without paths + +Call `list_playtest_media` with the current project, revision and artifact: + +```json +{"project_id":"","revision":0,"artifact_id":""} +``` + +The response's `media` rows supply opaque `media_id` values, readable project +product names, `base_sha256`, current `media_sha256`, byte counts and compatible +retained choices. Add `run_id` to inspect this run's private copies, including +inserted/dirty/retained state. Listing never advances emulation. The current +mounted disk is measured in the worker; ejected copies use their frozen bytes. +A writable copy's current hash can differ from its artifact base hash. + +Compatible retained choices are bounded to the latest sixteen per product; +counts and a truncation flag identify omitted history. `list_playtest_disks` +keeps its older primary-boot-disk-only contract. Additional world/data disks +are not advertised as primary boot selections. + +The drive is **FD0**. No tool accepts a host pathname, another drive number, +arbitrary bytes, another project's disks or a personal guest. Product IDs bind +to the current artifact, not just a filename. Listing and insertion recheck the +project/revision/artifact and any retained disk's exact provenance and bytes. + +## Exchange at a guest prompt + +1. Boot the primary disk through the project's declared commands. +2. Use normal guest input to reach its disk-change prompt. +3. Pause the owned run with `playtest_debug` and `action: "pause"`. A guest + waiting for keyboard input is still a running machine until explicitly paused. +4. Insert a listed private copy with its exact current hash: + +```json +{"run_id":"","request_id":"insert-data-1","action":"insert","media_id":"","media_sha256":""} +``` + +To leave FD0 empty, omit both selection fields: + +```json +{"run_id":"","request_id":"eject-data-1","action":"eject"} +``` + +An exchange also requires an idle floppy controller. A paused CPU or stopped +motor alone does not prove an incomplete guest transaction has finished. The +app refuses an exchange while a command is pending; it never cancels the guest's +disk I/O to force a swap. Continue through the guest's normal recovery path and +pause at an appropriate prompt instead. + +The host exports and durably retains the old disk before committing replacement. +The worker validates the complete new image before removing the old one. It +checks the old hash and media generation again at commit. A validation, +provenance, stale-ownership or retention refusal before commit leaves the old +paused disk and its dirty bytes intact. The same private copy is reused when switching back. + +Exchanges do not reset the guest, advance its field clock, type keys or modify +RAM/registers. The response reports `previous_media`, retained snapshot identity, +new selection, `media_generation`, hashes, dirty state and the unchanged clock, +with `guest_advanced: false` and `guest_reset: false`. Normal input resumes the +guest so it can read the newly inserted disk itself. Capture the framebuffer +and inspect the game's response; a successful mount is not proof that the game +accepted the media. + +Reuse a request ID only with the identical selection. The cached receipt prevents +a retry from performing another exchange; different arguments conflict. Exchanges +consume the existing owned mutation-request budget, not emulated fields. The +normal input, audio, startup and ownership limits remain in force. + +An ownership refusal at the final precommit check returns `stale_run` and leaves the +current disk in place. If the worker acknowledges a committed exchange but +run ownership expires before its success reply can be returned, the still-authorized +connection can receive `stale_run_after_commit`: the swap happened, and its +committed receipt is retained. This reason distinguishes that acknowledged +outcome from a precommit refusal; it does not restore authority or include the +withheld receipt. Connection revocation takes precedence and returns +`access_denied` without exposing the run outcome. + +Do not issue a new request ID to repeat an exchange after a lost reply or +`stale_run_after_commit`. An identical-ID/identical-arguments retry can reuse a +retained receipt only if the same run still passes the current connection, +project, revision and artifact ownership checks. Inspection for reconciliation +has the same authorization requirements. A revoked grant cannot retrieve a +receipt or inspect its former run merely because the app retained the outcome. +If the run is no longer accessible, use a newly reviewed connection and the +compatible retained-disk listing described below; old-run access is not renewed. + +Obtain a new debug snapshot after an exchange; earlier inspection/call-context +snapshots are invalidated even though CPU/RAM and the field clock did not change. +The public helper gives exchange the existing bounded 55-second playtest +transport deadline, allowing durable retention before returning its receipt. + +If the worker connection fails after a possible commit and its final selection +cannot be confirmed, the run is retired. The host retains every frozen copy and +reports `media_selection_uncertain` instead of guessing which disk was inserted. +List media without the retired `run_id` to recover compatible retained choices, +then start a fresh run. An interrupted reply is not evidence that no swap took +place; do not create another request to repeat an uncertain operation in that run. + +## Save, restart and retain every disk + +For a one-drive application, insert Home at its save prompt, use its real Save +command, then insert Data to continue. `restart_playtest` cold-boots the currently +inserted private disk through the declared commands; it keeps all the other +private copies and their changes. Insert the boot disk first when the current +data disk cannot boot. Restart does not automatically choose another disk. + +`stop_playtest` retains every disk in the owned set, even when FD0 is empty. +`retained_media` returns an individual immutable disk ID/hash and product +provenance for each. The established top-level `retained_disk_id` and +`retained_disk_sha256` refer to the primary Home copy. Cleanup remains possible +after the execution/request budget is exhausted. Failed persistence is retryable +without sending a second STOP or discarding the frozen exported bytes. + +To start a new run, use the primary retained fields as before. Additional copies +are explicit fresh-grant selections: + +```json +{ + "project_id":"", + "revision":0, + "artifact_id":"", + "request_id":"resume-disk-set-1", + "retained_disk_id":"", + "retained_disk_sha256":"", + "retained_media":[{ + "media_id":"", + "retained_disk_id":"", + "retained_disk_sha256":"" + }] +} +``` + +Omit `retained_media` for fresh additional copies. Each selected retained image +must match this project, primary artifact base and its own declared product/base +hash. A stale product ID, changed data image, wrong project or altered retained +bytes is refused. Retained originals remain immutable; resumed runs receive +separate private copies and retain their parent links. This restores disks, not +running CPU/RAM state. Use the guest's normal Load/Continue action after boot. + +See [owned playtests](MCP_BANKED_PLAYTEST.md), +[project refresh](MCP_PROJECT_RELIABILITY.md) and +[custom Make projects](MCP_CUSTOM_MAKE.md). The +[validation record](MCP_PLAYTEST_MEDIA_VALIDATION.md) distinguishes generic +guest/transport checks from application-specific acceptance. diff --git a/docs/development/MCP_PLAYTEST_PROCESSORS.md b/docs/development/MCP_PLAYTEST_PROCESSORS.md new file mode 100644 index 0000000..d221c8a --- /dev/null +++ b/docs/development/MCP_PLAYTEST_PROCESSORS.md @@ -0,0 +1,82 @@ +# Processor selection for disposable MCP playtests + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Discovery and starting a run + +Export a fresh C Assistant connection with **Allow Disposable Playtests**. +Toolset 8 with `playtestProcessors: true` adds optional `processor` to +`start_playtest`. Earlier grants retain their schemas and MC6809 default. +This adds no tool: a fully enabled fresh C connection still advertises 28. + +`get_capabilities` reports `playtest_processor_selection`, +`playtest_processors: ["MC6809", "HD6309"]` and +`playtest_default_processor: "MC6809"`. Use the live schema when choosing input. + +```json +{ + "name": "start_playtest", + "arguments": { + "project_id": "", + "revision": 0, + "artifact_id": "", + "request_id": "6309-entry-1", + "processor": "HD6309", + "stop_function": "main", + "stop_kind": "function_entry" + } +} +``` + +Omitting `processor` selects `MC6809`. Exact canonical names are required; +numeric values, `6309`, null and aliases are rejected. Explicit MC6809 and the +omitted default identify the same selection. An identical start request returns +its reserved run. Changing processor with that ID returns `request_id_conflict`. + +Startup remains asynchronous: poll `get_run` until ready, failed or cancelled. +Pending receipts report `requested_processor` without claiming an observed +execution mode. Once ready, the worker receipt reports actual CPU state. + +## Actual processor and execution mode + +Worker receipts, captures and owned debugger snapshots report: + +| Field | MC6809 | HD6309 | +| --- | --- | --- | +| `processor` | `MC6809` | `HD6309` | +| `requested_processor` | `MC6809` | `HD6309` | +| `execution_mode` | `not_applicable` | `emulation` or `native` | +| `md_register` | null | Actual MD byte | +| Legacy `cpu` in worker receipts | `6809` | `6309` | + +The 6309 resets into emulation mode. Only guest instructions such as `LDMD` +change mode; the tool never sets MD. Mode is observed at each receipt's actual +stop. A guest that executes LDMD again after restart may therefore already be +native by its next stop. 6309 debugger registers additionally include actual +`E`, `F`, `W`, `V` and `MD`; W combines E/F. MC6809 snapshots omit those registers. + +Existing code, bank, source, global and memory availability checks still apply. +A processor choice does not create C metadata or change a compiler target. +Build an artifact appropriate to the selected CPU. `restart_playtest` retains +the processor and writable disk. To change CPU, stop and start another run with +a new request ID. Retained disks may be resumed under either CPU after the usual +project, artifact and hash checks; compare actual run identities in test reports. + +## Input, audio and limits + +Ownership, revision, executable-byte verification, field, boot, mutation and +audio limits remain in force. Stop/retention remains available after execution +budgets are exhausted. Shared-run `send_keys` restrictions are unchanged. + +`playtest_input` releases physical keys at the end of each bounded plan. +`capture_playtest_audio` also releases keys before and after its recording +interval; it records the following guest interval, not prior input or sound. +Do not use it to claim a continuously held moving-route test. See the +[audio contract](MCP_AUDIO_CAPTURE.md) and +[banked playtest contract](MCP_BANKED_PLAYTEST.md). + +Qualification should run the same compatible disk on both CPUs and retain its +artifact hash, actual CPU/mode, boot/field identity, framebuffer, debugger/global +evidence and stop/retention receipts. Native-mode validation requires guest code +that really executes LDMD. The [build 45 record](MCP_BUILD45_VALIDATION.md) +identifies executed checks and their limits. diff --git a/docs/development/MCP_PROJECT_RELIABILITY.md b/docs/development/MCP_PROJECT_RELIABILITY.md new file mode 100644 index 0000000..3a182da --- /dev/null +++ b/docs/development/MCP_PROJECT_RELIABILITY.md @@ -0,0 +1,100 @@ +# Project inputs, cache safety and scoped MCP refresh + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## One content-based input manifest + +Project navigation entries, build snapshots, input hashes and assistant scope use +`CMOCProjectInputManifest`. Its entries identify relative path, role, inclusion +reason, content hash, relevant control permissions and whether the entry affects +the source revision/build. Excluded directory rows explain the entire subtree +without reading or hashing its generated contents. The public manifest is paged; +it contains metadata, not file bytes or private connection credentials. + +Nested C headers are included recursively. Explicit configured include paths, +sources, generator prerequisites and approved support roots remain inputs. +Retained generated C is still a source input unless declared as an output. +Conventional compiler products, declared binary/disk/debug outputs, logs, +receipts and incidental evidence directories are excluded. There is no blanket +exclusion of every `build` or `generated` directory. + +Projects can add these optional literal, project-relative settings: + +```json +{ + "resourceInputs": ["assets/questions.dat", "out/prebuilt.dat"], + "generatedInputs": [".build/shared/generated.h"], + "outputDirectories": ["out", "test-evidence"] +} +``` + +Explicit resources/generated inputs override soft directory exclusions; they +cannot be the same path as a concrete declared output. The arrays do not accept +shell patterns or outside-root paths. Version-control metadata stays excluded. +Included paths cannot traverse symlinks. Support remains limited to explicitly +declared regular sibling directories; an include or dependency file never grants +access to a new root. + +The same product/evidence exclusions apply inside approved support folders. +Intentional native helper executables in those approved roots are retained. A +settings file inside a support folder is ordinary input data; it cannot declare +additional support roots or expand access. An explicit single-file exception +inside an excluded project folder does not re-include its siblings. + +Content and relevant control permissions determine identity. Modification times +are Make scheduling hints, so touching a file does not itself change a revision. +An actual source/header/resource edit still invalidates the affected artifact +and owned run. Restricted C recipes use only their reviewed C/header set (or the +fixed Hello Disk inputs), not unrelated personal Makefiles or resources. + +## Inspect and refresh a connection + +- `read_project_inputs(project_id, offset?, limit?)` pages the approved manifest + and current refresh summary; `limit` is 1–256. + +- `refresh_project(project_id, revision, request_id)` refreshes authorized inputs + or requests native review for a changed scope/control set. Reuse the identical + request ID for the same operation. + +- `get_project_refresh(project_id, refresh_id)` reports pending, approved, + rejected or unchanged status, current revision and bounded change metadata. + +Existing clean shared files refresh under their grant. The native workbench +updates clean tabs while preserving unsaved drafts. An external edit that +conflicts with a draft's saved base requires local resolution; refresh does not +discard or silently merge that draft. + +New included files, recipe/generator changes, support scope changes and executable +control permissions require native review. The window shows concrete relative +paths, old/new inclusion/roles/permissions/hashes and bounded before/after text. +Approval rechecks the reviewed inputs, session and editor identity before adoption; +it does not execute Make or start a guest. Rejected/pending changes block build, +run and source-edit application, while safe status/help/approved-file inspection +and refresh polling remain available. Private credentials never appear in these +responses. A new support root's members are not read or hashed before native +approval authorizes that root. + +Stale-state errors retain their ordinary error text and add structured +`error_details` with expected/current revision/artifact facts and changed relative +input paths where known. Lists include totals/truncation indicators rather than +exceeding the transport limit. Inspect the current state before retrying with +updated identities; do not silently create another run. + +## Safe cache reuse + +The cache is an isolated working copy. Its index and dependency provenance are +checked before reuse. Removed inputs, corrupt/missing populated-cache receipts, +or dependency files referring to missing/foreign snapshot paths cause that +working copy to be discarded and repopulated from current approved inputs. +Supported relative dependencies and valid workspace/toolchain absolute paths +retain normal incremental behavior. + +The app does not rewrite arbitrary Make dependency syntax or run a project's +`clean` recipe to repair a cache. Original source, personal media and immutable +earlier build artifacts remain intact. Every included input is protected against +recipe mutation; declared outputs are distinct and can be regenerated/cleaned. + +The following development stage adds [audio capture](MCP_AUDIO_CAPTURE.md) and +[verified debugging/build diagnostics](MCP_DEBUG_EVIDENCE.md). Existing +owned-worker bounds, request idempotency, verified debugging and disk provenance +remain in force. diff --git a/docs/development/REPOSITORY_LAYOUT.md b/docs/development/REPOSITORY_LAYOUT.md new file mode 100644 index 0000000..160454d --- /dev/null +++ b/docs/development/REPOSITORY_LAYOUT.md @@ -0,0 +1,15 @@ +# Repository organization + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +| Directory | Responsibility | +| --- | --- | +| `src/core/` | Shared CPU, MMU, I/O, video/timing, debugger and machine-session code. Existing `VCC::Mac` C++ names remain to avoid an unrelated API refactor. Conditional Windows host bridges remain beside shared code where needed. | +| `src/devices/` | Portable cartridge/device models, FD-502 disk images, hard disks/clock, RAM disk, Speech/Sound chip cores. | +| `platforms/macos/` | Native app, Xcode project, bridge, resources, packaging and Mac-specific tools. Open `platforms/macos/VCC.xcodeproj`. | +| `platforms/windows/` | Original Windows UI, plugins, resources, Visual Studio solution and build scripts. Open `Vcc.sln` here or run its build scripts from this directory. This is not yet a VCC Plus Windows product. | +| `third_party/` | Retained legacy graphics dependencies and reviewed, pinned development-tool/library/example sources. See the inventory. | +| `tools/` | Repository/toolchain integration scripts. | +| `tests/` | Shared core, Mac interface/bridge and optional toolchain compatibility checks. | +| `docs/` | Product, development and validation documentation; approved artwork. | +| `.build/`, `dist/` | Ignored local build products and distribution candidates. | diff --git a/docs/macos/AUDIO_CASSETTE.md b/docs/macos/AUDIO_CASSETTE.md new file mode 100644 index 0000000..2b807c8 --- /dev/null +++ b/docs/macos/AUDIO_CASSETTE.md @@ -0,0 +1,49 @@ +# Native audio and cassette milestone + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Boundaries and compatibility + +- A 44.1 kHz scheduled event samples the PIA sound state, selected analog source, independent cartridge outputs and cassette input/output. Samples follow emulated time and stop when the machine pauses. Reset clears the PIA output latches and replaces the sampler event. + +- The packed PIA words are converted explicitly to signed stereo float samples. Native output uses AVAudioEngine/AVAudioSourceNode over the Mac audio system. The render callback only drains a fixed-capacity, single-producer/single-consumer buffer; it allocates no memory, acquires no locks, and never calls the emulator. [Apple source-node guidance](https://developer.apple.com/documentation/avfaudio/avaudiosourcenode/init(renderblock:)) requires avoiding blocking operations in device render callbacks. + +- The machine queue refills roughly 100 ms ahead, with at most four frames per turn. Device consumption paces emulation without changing the CPU/GIME clock ratios. Output starts only after the reserve is filled. The queue has an 8,192-frame hard limit; the extra reserve adds about 50 ms of latency over the preceding implementation. Missing samples become silence; underrun, overrun, consumed/submitted/nonzero sample counts, occupancy and output-start counters are exposed in bridge snapshots. Zero volume still consumes samples. Volume/mute changes now preserve the running engine and queued audio. The producer uses interactive scheduling priority; a one-second loss of consumption falls back to silent pacing. See [timing and reliability](TIMING_RELIABILITY.md) for sustained checks and limits. + +- The Windows sampler's `+25 Hz` host-buffer compensation is not carried over; output consumption supplies pacing. This is an intentional host-side difference that still needs sustained comparison with Windows. + +- CAS retains the upstream least-significant-bit-first 21/40-sample waveforms, amplitude reduction and rising-edge decoder. Fast CAS retains the `$83` BASIC pulse-width convention. Motor gaps use emulated time. No ROM patch is bundled. + +- WAV parsing walks RIFF chunks, including unknown chunks and padding, and checks sizes before reading. Input accepts mono/stereo PCM 8/16/24/32-bit and float32 at 8–192 kHz. Stereo is averaged; sample positions are normalized to 44.1 kHz. Compressed WAV and WAVE_FORMAT_EXTENSIBLE are not accepted in this milestone. + +- Files and normalized/recorded WAV images are bounded to 64 MiB, including export-header space; CAS is bounded to 1 MiB. Recording stops at capacity. Recording resumes only through a new recording; this milestone does not overwrite sections of existing tapes or splice recordings. + +- The active deck lives in memory. File-backed cassette assignment is now remembered and reopens stopped at the beginning on relaunch; unexported recordings are protected by quit/replacement safeguards, not serialized as a saved execution state. See startup behavior and profiles. A separate audio-output picker, analog filtering and broader cassette-library qualification remain outside this baseline. + +## Validation and outstanding checks + +Verified on the local Apple Silicon Mac with Xcode 27.2/macOS 27.2: + +- 51 XCTest tests: 39 shared core checks, seven bridge tests and five native tests. + +- Debug and Release universal app builds; the 39-check Release console suite and both-CPU BASIC integrations passed on arm64 and x86_64 under Rosetta. Rosetta does not validate physical Intel hardware. + +- Focused audio/cassette and both-CPU BASIC integrations passed AddressSanitizer and UndefinedBehaviorSanitizer. The full legacy suite stops under UBSan at the existing signed-left-shift issue in `ssc/sp0256.cpp:125`; at this early checkpoint that chip was not connected to the Mac machine. Speech/Sound was integrated later; this historical sanitizer result is not a claim about the current full suite. LeakSanitizer is unavailable on this platform. + +- Real native audio-device consumption at zero volume, pause stability, restart and shutdown. + +- Concurrent ring-buffer ordering/wraparound, explicit channel/sign conversion, mute, bounded overflow, underrun silence and sample timing from both CPU engines. + +- Tape motor gating, position/end behavior, reset retention, fast-load PIA reads, export/save state, invalid WAV input, all accepted sample representations, rate normalization, unknown chunks and truncated files. + +- File loading with uppercase extensions, spaces and Unicode; oversized inputs are rejected and source bytes remain unchanged. + +- The optional `VCCCoreChecks --rom /path/to/coco3.rom` check boots both CPUs, verifies BASIC SOUND produces samples, records the authored program using CSAVE to CAS and WAV, clears BASIC, reloads through CLOAD, and checks LIST/RUN and `42`. It separately repeats fast CAS loading. No ROM or generated tape is committed. + +## Analog routing correction — November 11, 2026 + +The native sampler now honors sound enable and the DAC/cassette/cartridge/ground +selector. This fixes the reproduced Quadrapassel splash-screen buzz with both +Speech/Sound and Orchestra-90 connected, while retaining normal effects and +independent external stereo. The game and installed app were not changed. +See [cause, reproduction and qualification](AUDIO_ROUTING.md). diff --git a/docs/macos/AUDIO_ROUTING.md b/docs/macos/AUDIO_ROUTING.md new file mode 100644 index 0000000..dcc66f6 --- /dev/null +++ b/docs/macos/AUDIO_ROUTING.md @@ -0,0 +1,125 @@ +# Analog sound routing and Quadrapassel regression + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Cause and correction + +The native sampler mixed cartridge output into the speaker regardless of the +PIA sound-enable control and selected analog input. An idle Speech/Sound output +has unsigned midpoint 128. The old path emitted that as a large DC signal; +joystick polling switched the mux to the cassette branch and back, chopping it +into an audible waveform even though the game had disabled analog sound. + +The sampler now follows the hardware routing: + +| Analog selector | Source while sound is enabled | +| --- | --- | +| 0 | Six-bit CoCo DAC | +| 1 | Cassette input | +| 2 | Cartridge SND | +| 3 | Ground / silence | + +The sound-enable control gates that analog path. Single-bit sound and the +modeled Orchestra-90 external RCA outputs remain independent. Cartridge PCM is +centered on 128; a zero sample remains a valid negative peak, distinct from an +absent/inactive sound device. The current DAC register is read even if the guest +last wrote it during a muted joystick measurement. Final float mixing saturates +rather than wrapping a signed packed word. Cartridge clocks and cassette +advancement continue while muted or unselected. + +The native sampler uses the new read-only PIA sound snapshot and separate +cartridge speaker/external outputs. The original Windows packed mixer remains +unchanged. Existing DAC, single-bit and Orchestra-90 gain conventions are retained. + +Hardware cross-checks: MAME's [CoCo implementation](https://github.com/mamedev/mame/blob/master/src/mame/trs/coco.cpp) +describes the selector map with its Tandy service-manual citation; its +[CoCo machine wiring](https://github.com/mamedev/mame/blob/master/src/mame/trs/coco12.cpp) +connects PIA selection, sound-enable inhibit and the separate single-bit path. +No MAME implementation was imported. + +## Unchanged real game reproduction + +The optional `tests/macos/audio-game-validation.cpp` boots a supplied DOS disk +through ordinary keyboard input, with local CoCo 3/Disk BASIC, Speech/Sound and +Orchestra-90 ROMs. The source disk is read-only host input; guest writes affect +only an owned memory copy. No text, registers or guest RAM are injected to create +the observed results. The matrix uses 512 KiB, 1x overclock and both emulated CPUs, +with a mounted stopped cassette and FD-502 in startup slot 4. + +The real-game matrix ran on arm64. The test used Quadrapassel `QUADPSL01.DSK`, SHA-256 +`4ac171e87c51dfd99b302b9e035a91a59c030144e5ae0661a6d2dfc84ba3a63f`. +Its repository remained clean and its source disk hash stayed unchanged. +After 1,800 settling fields, each idle capture spans 120 fields: + +| Configuration | Before | Corrected | +| --- | --- | --- | +| FD-502 only, either CPU | Exact digital silence | Exact digital silence | +| FD-502 + Orchestra-90, either CPU | Exact digital silence | Exact digital silence | +| FD-502 + Speech/Sound, 6809 | 84,827 / 88,651 nonzero frames; 1,409 transitions; AC RMS 0.101581 | Every sample zero | +| FD-502 + both cartridges, 6809 | Same repeating erroneous signal | Every sample zero | +| FD-502 + Speech/Sound, 6309 | 84,818 / 88,651 nonzero frames; 1,421 transitions; AC RMS 0.101695 | Every sample zero | +| FD-502 + both cartridges, 6309 | Same repeating erroneous signal | Every sample zero | + +With both cartridges present, normal Enter and D/right keyboard input started +the game and produced movement effects on both CPUs. Peak was 0.242188 and the +final half-second was exactly silent. Thus the correction does not globally mute +the game. Raw PCM, framebuffer captures and logs remain private and outside Git. + +Example reproduction after building the current core through Xcode: + +```sh +DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer \ + xcrun clang++ -std=c++17 -O2 -mmacosx-version-min=14.0 \ + tests/macos/audio-game-validation.cpp /path/to/libVCCCore.a \ + -o /tmp/audio-game-validation +/tmp/audio-game-validation /path/to/ROMs /path/to/game.DSK \ + /tmp/audio-game-captures --expect-quiet +``` + +The quiet-title and movement assertions apply to a DOS-boot game with the same +Enter-to-start and D-to-move controls. It is an explicit optional compatibility +check, not a general assertion that every game's title screen should be silent. + +## Regression qualification + +- All 67 portable core checks passed, including the new authored routing + regression on both guest CPUs. It covers all mux states, the sound gate, + joystick-style selector changes, current DAC latch, unsigned midpoint and zero + cartridge samples, independent one-bit/Orchestra stereo, and saturation. + +- Seventeen focused XCTest checks passed on arm64 and again on x86_64 under + Rosetta: audio buffer/scheduling/routing, cassette images and monitor, cartridge + behavior, real output-device pause/restart, and volume changes retaining clocks. + +- Real-ROM speech and AY tone checks passed on both CPUs: 22 phonemes, + 443,259 PCM frames, speech range 0.504 and tone range 0.332. Authored speech + fixtures now explicitly select and enable cartridge audio. Test WAV writers + retain actual signed PCM rather than subtracting another midpoint. Both speech + WAV hashes remain identical to the previously qualified greeting capture + recorded in the Speech/Sound guide. + +- The guest Speech/Sound SDK checks passed on both CPUs with missing/absent and + real firmware, phrases, joystick polling, tones and noise. Orchestra-90 SDK + checks retained exact channel plateaus and approximately 3,996 frames/s at + normal speed and 3,986–3,988 at fast speed on both CPUs. + +- The isolated native playback test passed with both real cartridges, the + unchanged game, and 25% volume. Across three seconds, emulated fields advanced + from 2,336 to 2,515 and the real output device consumed another 132,182 sample + frames. Nonzero-signal count remained zero and audio-engine start count stayed + one. No mute or engine restart manufactured silence. + +The native test is opt-in through `VCC_AUDIO_GAME_DISK`; ordinary UI runs skip it +without that supplied disk or private ROMs. `--audio-game-listening ROM_DIRECTORY +DOS_BOOT_DISK` also selects the same temporary fixture and automatically pauses. +This is native output-consumption and digital-signal evidence, not a new human +listening confirmation, physical Intel test or macOS 14 runtime qualification. +The user's physical-machine observation remains the independent comparison. + +The native case also passed independently after reopening its single main +window through **Window → VCC UI Tests** (45.061 seconds). The test now uses that +public reopening path and raises its window before capturing, avoiding saved +closed-window state and unrelated foreground-window captures. The final window +capture was visually checked against the game's splash screen and both sound +cartridges. The universal normal Debug app built successfully; no DMG or +installation was performed. diff --git a/docs/macos/CARTRIDGES.md b/docs/macos/CARTRIDGES.md new file mode 100644 index 0000000..09b7219 --- /dev/null +++ b/docs/macos/CARTRIDGES.md @@ -0,0 +1,41 @@ +# Native ROM cartridges and Multi-Pak Interface + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Routing and retained behavior + +`devices/CartridgeDevice.h` implements the single-slot/MPI bus without host UI or dynamic libraries. `devices/RomCartridge.h` retains the memory mapping and bank-switch behavior from `platforms/windows/libcommon/vcc/bus/rom_cartridge.cpp`: + +- ROM addressing uses `((address & 32767) + bankOffset) % imageSize`. + +- Writes to `$FF40` select one of sixteen 16 KiB bank offsets. Reset selects bank zero. Bank switching remains enabled as in the Windows ROM loader. + +- Raw ROMs assert the cartridge-present line for the retained PIA auto-start mechanism; FD-502 does not assert it. + +MPI routing follows `pakrouter.cpp`: `$FF7F` bits 4–5 select the ROM (CTS) slot, and bits 0–1 select the disk-port (SCS) slot. The register reads back those selected fields, with unused bits zero. `$FF40–$FF5F` accesses go only to SCS; ROM reads go only to CTS. Other port writes broadcast to active MPI slots, and reads return the first nonzero response in slot order. All active devices receive horizontal-sync callbacks; NMI is not gated by the ROM selection. Packed stereo samples mix each channel independently with saturation. Empty ROM slots read `$FF`; empty ports read zero. + +Reset restores CTS and SCS to the physical startup selector. Software routing is runtime state, not a remembered preference. The native window shows current ROM and disk-port slots. Cartridge-line state follows CTS, including software changes: the Windows router updates it on physical selection but omits the update in its `$FF7F` write path. This port deliberately updates it on both paths so a deselected ROM does not leave a stale auto-start signal. Runtime reference comparison of that difference remains open. + +The bridge owns one virtual hard-disk controller and one FD-502 instance that can be referenced in both retained configurations, but at most once in the active MPI. Layout changes validate before replacement, keep disk snapshots/save tokens valid, and run on the serialized emulation queue. Inactive configurations receive no ticks, port traffic or audio. All five device assignments reset when the machine resets, without clearing mounted disk bytes. + +## Persistence and missing files + +An additive `cartridges` section in the existing version-1 `DiskAssignments.json` stores mode, first-MPI-use state, startup selector, slot device kinds and ROM file URLs. It contains no ROM bytes, disk contents or machine state. Existing disk-only settings migrate to a single FD-502 assignment when a disk ROM is remembered. Both configurations restore before emulation starts, including inactive ROMs. Corrupt layouts, invalid slots/URLs and duplicate MPI floppy or hard-disk assignments are rejected. + +An unavailable ROM remains assigned, appears as **Unavailable**, and contributes no device to the bus. Other slots and disks can still restore. **Retry Unavailable ROMs** reloads only missing ROMs; it retains the owned bytes of working cartridges. Choose a replacement or Remove to change a remembered assignment. File locations are absolute URLs, with the same move/rename limitations as disk assignments. Settings-write failures remain visible with **Retry Saving Settings**. + +## Validation + +Automated coverage adds four C++ cartridge checks and six bridge/model/persistence tests: + +- Raw ROM mirroring, bank wrap/reset, size rejection, independent CTS/SCS routing, empty slots, other-port broadcast/priority, ticks, ungated NMI, stereo mixing, physical selection and mode changes. + +- Authored guest programs on both 6809 and 6309 select separate ROM and disk slots and read the expected cartridge bytes/register values. A PIA check verifies cartridge-present status follows the selected ROM. + +- Old-settings migration, first MPI activation, independent configurations, slot movement/removal, all assignments and startup choice across model recreation, missing-file recovery without reloading working slots (including an unavailable ROM copied on first MPI activation), invalid selections, retained dirty disks and explicit saving while disconnected. + +- Bridge rejection of duplicate floppy controllers and layout changes during an incomplete disk command, preserving the previous layout and mounted disk. + +- The existing automatic-saving test now runs guest sector writes in both single-slot and MPI mode on both CPUs, verifying exact file bytes, continued execution and clean reopen. + +All 82 XCTest tests passed on Apple Silicon and on the Intel build under Rosetta with the local Xcode 27.2 toolchain on November 1, 2026. Debug and universal Release builds succeeded. The universal Release app was checked with an authored 8 KiB cartridge and a locally supplied CoCo 3 system ROM: native selection in MPI slot 1 auto-started the program and displayed `CART OK` on both 6809 and 6309. Slot 4 retained FD-502. Actual quit/relaunch restored MPI mode, the ROM file, FD-502 and startup slot 1. The temporary ROM was then removed, startup slot returned to 4, and single-cartridge mode restored the user's original FD-502/drive assignment, clean with automatic saving enabled. The verification app was closed. Native missing-file/busy-operation failures are covered by automated tests rather than separately forced in this UI pass. Physical Intel/macOS 14, Windows runtime comparisons and a broader commercial cartridge library remain separate compatibility work. No supplied ROMs or generated media are committed. diff --git a/docs/macos/CPU_CORE.md b/docs/macos/CPU_CORE.md new file mode 100644 index 0000000..dada03f --- /dev/null +++ b/docs/macos/CPU_CORE.md @@ -0,0 +1,89 @@ +# CPU extraction — Phase 1 + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Boundaries and ownership + +- `CpuMemory.h` declares the existing byte/word memory and map-selection operations. `CpuMemory.cpp` routes them to the real MMU by default. Isolated CPU checks explicitly install a flat 64 KiB `CpuMemoryBus` from `tests/core/CpuChecks.cpp` and detach it afterward. The separate machine checks use the real MMU; see [memory and hardware extraction](MACHINE_CORE.md). The flat test bus is excluded from the library and application targets. + +- `CpuHost.h` exposes synchronous debugger hooks for halt, step, breakpoints, trace triggers, interrupt tracing, and patched haltpoints. `CpuHost.cpp` forwards these to the existing Windows debugger by default. The non-Windows default supports a halt latch without tracing; the Mac controller installs its own hooks before running a machine. Tests install a recording implementation and detach it after each check. + +- Hosts retain ownership of installed hooks. Install/detach on the emulation thread, outside execution, and keep the object alive while installed. The engines, scheduler, and joystick clock still have global state. Run one engine at a time; these are not yet independent machine instances or thread-safe UI entry points. + +- CPU initialization, reset, execution, register snapshots, breakpoints, and trace-trigger functions remain the original public interfaces. Call initialization before reset, especially for the 6309 register-pointer tables. `Exec(budget)` returns unused cycles, which can be negative when the final instruction exceeds the budget. + +- The retained register unions require little-endian hosts and 8/16/32-bit byte/short/int layouts. Compile-time checks document those assumptions. Both supported Mac architectures meet them. This is an initial layout check, not a completed audit of every instruction, aliasing assumption, or arithmetic edge case. + +## Reproducible checks + +Seven new XCTest cases share their C++ implementation with the console runner: + +| Check | Coverage | +| --- | --- | +| 6809 execution | Reset vector/registers/masks, authored guest loop, indexed writes, arithmetic flags, word-store byte order/address wrap | +| 6309 execution | The same checks in 6809-compatible mode | +| 6809 interrupts | IRQ/FIRQ/NMI vectors and stack frames, RTI, shared interrupt sources, reset masks and cleared sources | +| 6309 interrupts | The same checks in emulation mode | +| 6309 native mode | LDMD, LDQ/STQ byte order, native NOP timing, restoration of emulation timing on reset | +| CPU debugger | Triggered trace boundaries, breakpoint halt, no execution while halted, single-step for both engines | +| Event scheduler | Initial clock rate, exact-boundary deferral, ordering, callback-created events, reschedule/erase, rebase, overclock, reset | + +The authored guest fixture executes 69 instructions and stores bytes 1–16 at `$4100`. Both engines end at `$4012`, A=`$10`, B=`$00`, X=`$4110`, S=`$7000`. Its expected 222 cycles comprise 14 setup cycles and 16 iterations of 13 cycles. These are synthetic architectural expectations; a matching Windows CPU trace has **not** yet been captured. Existing Windows evidence remains described in the reference review. + +The scheduler's embedded legacy static-initialization test block is disabled in the Mac library with `USE_DEBUG_TESTS=false`; the explicit XCTest/console checks above run in both configurations. Existing SSC smoke assertions remain enabled in Release. + +## Defects found during extraction + +1. `Event` used `mResolution` before that member was initialized, because C++ initializes members in declaration order. It now initializes clock scaling with a defined constant. A full reset also clears requested clock/overclock settings, so a later rebase cannot restore stale settings. + +2. `HD6309Reset` cleared native-mode bits but retained cached native instruction timings. It now resets that timing table through the existing mode-setting function. The native-mode reset check failed before this fix. + +These are shared source fixes and are included in the Windows build definition. Windows recompilation and reference comparison of this increment are still pending. + +## Scripsit II timing correction — November 4, 2026 + +Color Scripsit II booted its menu but hung after **E** on the Mac. Its editor +polls the PIA VSYNC flag with `TST` while its IRQ handler acknowledges that same +flag. Advancing all instruction cycles after the operand read allowed every +edge to be acknowledged before the polling loop observed it. + +The 6809 and 6309 emulation-mode `TST` direct, indexed and extended paths now +advance the addressing/data cycles before reading the operand, followed by the +two remaining internal cycles. Total instruction timing and indexed addressing +penalties are unchanged. This follows Figure 18, sheets 3–5 of the +[Motorola MC6809 datasheet](https://colorcomputerarchive.com/repo/Documents/Datasheets/MC6809%20HMOS%208%20Bit%20Microprocessor%20(Motorola).pdf). +The 6309 native-mode path retains its previous timing. This is a targeted timing +correction, not a claim of complete bus-cycle or 6847T1 conformance. + +Validation: + +- ROM-free checks exercise every edge position for direct, indexed, extended + and indexed-offset forms on both CPUs: sampling time, total cycles, one read, + flags, and a polling loop whose IRQ handler acknowledges the flag. These + checks fail with the original CPU implementations. + +- All 61 console checks pass. Both Apple Silicon and Intel/Rosetta XCTest runs + execute 491 tests, with two skips and no failures. + +- The optional real-cartridge probe passes on both CPUs: boot, polling-loop + exit, inserted text retained in memory, Ctrl–Break menu return, and reentry. + The tested cartridge SHA-256 is + `2dfac5ecb1d7c5853e5dbf1059730bd134e891751429e1643149b669056c43db`. + +- Native isolated-app inspection verifies editor entry, typing and the `VU` + lowercase display option. Native automated Ctrl–Break delivery was + inconclusive; menu return is verified through the emulated keyboard matrix + by the probe, not claimed as a completed native shortcut check. + +The [Scripsit manual](https://colorcomputerarchive.com/repo/Documents/Manuals/Applications/Color%20Scripsit%20II%20(Tandy).pdf) +explains that **E** enters editor command mode, then **I** starts insertion. +**Break** returns to command mode; **Ctrl–Break** returns to the main menu. +The default display represents lowercase letters as inverse uppercase glyphs. + +To run the optional probe after building `VCCCore`, compile +`tests/macos/scripsit-compatibility-probe.cpp` with C++17 and link the built +`libVCCCore.a`. Pass a private CoCo 3 system ROM, the Scripsit II cartridge, +and an output prefix. It writes one PPM capture per processor; it neither +changes supplied media nor includes ROM payloads in the repository. The +native UITesting app also accepts `--cartridge-validation SYSTEM_ROM CARTRIDGE` +and optional `--cartridge-6309`, using isolated preferences. diff --git a/docs/macos/DEBUGGER.md b/docs/macos/DEBUGGER.md new file mode 100644 index 0000000..ea544c0 --- /dev/null +++ b/docs/macos/DEBUGGER.md @@ -0,0 +1,85 @@ +# Native debugger + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Execution semantics + +Explicit instruction stepping retains the Windows CPU engines' behavior: execute the opcode before servicing pending interrupts. Continue uses normal interrupt dispatch and temporarily bypasses a breakpoint just reached, so an interrupt-handler breakpoint can still stop execution. + +HD6309 **Step** completes an entire TFM block-transfer instruction. Event timing continues during the transfer and completed video frames are counted/published at their actual raster boundaries. Continue from a breakpoint on TFM can stop again at the same address after one transfer byte, following the retained core's breakpoint checks. This differs from the whole-instruction Step action. + +The 6309 stepping loop now clears stale TFM continuation after PC changes, reset and invalid-instruction traps, preventing it from following arbitrary code indefinitely. Regression programs cover both native and emulation modes, interrupted transfers, invalid operands and transfers spanning multiple frames. + +The last completed video frame remains visible while paused; a few instruction steps need not complete a new raster frame. Single-step audio is discarded so resuming does not play a delayed burst. + +## Implementation boundaries + +`MachineSession` owns debug execution and breakpoints. The Objective-C++ controller captures CPU state, memory and machine/media status on its existing serial queue. No live core pointers cross into Swift. A window-owned `DebuggerModel` requests snapshots at most five times per second while visible; only one inspection is pending at a time. Closing cancels polling. Edits retain focus and text drafts and wait for a fresh authoritative capture before allowing another mutation. + +Disassembly reuses upstream VCC opcode tables with portable formatting over captured bytes. It supports both CPU instruction sets, signed offsets, indexed forms, address wrapping and HD6309 register/bit/TFM forms. Invalid encodings produce bounded `FCB` rows. VCC's optional HALT/BREAK pseudo-opcodes are not enabled in this baseline and are not presented as active instructions. A capture is bounded to 64 KiB of logical memory, 48 decoded rows and an additional 256 physical RAM bytes only when physical inspection is selected. MMU data and both memory spaces belong to the same execution boundary. No work is added to normal frame polling when the debugger is closed. + +## Validation + +Authored programs and private, isolated app preferences are used throughout. No ROM or personal media is required by the debugger tests. Verified on November 3, 2026 with Xcode 27.2 on Apple Silicon: + +- All **202 background XCTest checks passed on arm64 and x86_64 under Rosetta**, with zero failures. The full suite contains 203 tests; the unrelated foreground Metal presentation case was excluded from the background runs. + +- Nineteen added debugger tests cover both CPU engines, snapshots and async commands, exact stepping, pending interrupts, repeat breakpoint stops, reset preservation, mapped-memory protection, strict input, focus/drafts, decoder forms and long/interrupted/invalid TFM transfers. + +- The targeted native XCUITest passed: live opening, Pause/Set PC/Step, memory edit, breakpoint hit/removal, Continue, resizing, typing across refresh and close/reopen. Session generation and authored mounted media were retained. The native window was visually inspected. + +- Universal Release app built and its executable verified to contain both arm64 and x86_64. This is a build check, not a newly signed/notarized distribution release. + +- No new test requires private ROMs. Existing unsigned/local development products and test results stay outside Git. The previously published local signed app/DMG were not replaced. + +The captured workspace uses the authored diagnostic loop and a test RAM edit. Tests under Rosetta are not physical Intel validation. The native UI check ran on the current Mac, not macOS 14, and does not certify comprehensive VoiceOver usability or Windows debugger parity. + +## MMU and physical RAM increment — November 3, 2026 + +Eight new core/bridge/model tests cover both processors and all four RAM capacities; task switching and disabled mappings; ROM overlays and all-RAM mode; FE00 overrides and fixed ROM vectors; high 8 MB banks, latched prefixes and mirrored RAM; immutable snapshots, end bounds and recovery after a smaller RAM configuration. Physical capture has no device-read side effects and does not advance guest clocks or mutate the machine. + +All **210 background tests passed on arm64 and x86_64 under Rosetta**. The full suite now contains 211 tests; the unrelated foreground Metal presentation case was excluded from these background runs. The existing debugger stepping/breakpoint/edit/focus UI case and the new live MMU/physical-memory UI case passed. Native inspection caught an accessibility-label recursion crash in selectable physical bytes; replacing them with plain labeled text fixed the crash, and the same test passed again. Final screenshot review corrected the segmented-picker label layout. The final universal Release app built successfully with both architectures. The signed distribution app and DMG were not replaced. + +Both captures use the authored diagnostic in the isolated test app. The memory and MMU areas scroll independently; the divider can be dragged to give either more space. The normal emulator and personal media were untouched. Rosetta is not a substitute for physical Intel testing, and these UI checks do not certify macOS 14 or comprehensive VoiceOver behavior. + +At the time of the MMU increment, physical export/disassembly, source/listing association and execution tracing were outside its scope; the following increment implements them. Physical editing remains excluded. Inspecting MMU controls does not change them; guest software remains responsible for programming the MMU. + +### Source listings + +Use **Source → Open Listing…** to select a LWASM `.lst` or text listing. Generate an absolute listing with the [LWTOOLS assembler](https://www.lwtools.ca/manual/manual.html), for example: + +```sh +lwasm --6809 --format=decb --list=program.lst --output=program.bin program.asm +``` + +The listing does not load its program. Load the corresponding binary separately, then use exact logical CPU addresses for source following and breakpoints. The importer does not assert that listing bytes match current memory, and it does not read filenames embedded in the listing. Source locations retain LWASM's sometimes-truncated filename and original line number; the left-hand row number identifies the listing itself. + +- Click a circle to add/remove a shared address breakpoint. Dashed circles identify disabled breakpoints. Their context menus offer Enable/Disable, Show Disassembly, Show in Memory, Set PC Here while paused, and Copy Source Line. + +- **Follow PC** selects an exact addressed line, never a guessed nearby line. If several source lines share an address, a selected matching line is preferred; all share the same logical breakpoint. An unmatched PC is reported explicitly. + +- **Find Next** searches source text and source locations, ignores case and wraps at the end. Searching or selecting a line turns off source PC following, allowing inspection without losing the selected location to live polling. + +- **Close** unloads debugging information and retains all shared breakpoints. Failed imports preserve the previously loaded listing. Neither action changes guest execution. + +- Imports are bounded to 8 MB, 50,000 lines and 4,096 characters per line. UTF-8 and BOM-marked UTF-16, standard filename/line metadata, `--list-nofiles`, cycle annotations, duplicate addresses and address zero are supported. Comments, directives, continuation bytes and non-code offsets remain visible without invented instruction associations. + +CMOC uses LWASM to produce relocatable object files and LWLINK to assign final addresses. Its intermediate `.lst` is not a final logical-address listing. This standalone listing importer still rejects `SECTION`/`ENDSECTION` with a linker-map explanation. The separate **Develop → C Development** workspace now builds CMOC projects, resolves object sections through the matching linker map, verifies the linked executable bytes and supports C-source breakpoints across translation units. It retains exact build/source identity and does not treat a raw relocatable listing as an executable address map. See the workspace implementation and validation. The workspace now also provides [C source-line Into/Over/Out, variables and read-only watches](../development/CMOC_SOURCE_DEBUGGING.md). These use verified compiler metadata and the same machine; they are separate from importing an arbitrary assembler listing. Multiple statements on one source line are not separately mapped. See the C development roadmap for remaining work. + +### Memory tools and tracing + +See [Memory Tools](DEBUGGER_MEMORY_TOOLS.md) for bounded physical disassembly, explicit logical origin, raw range export and optional OS-9 interpretation. See [Trace](DEBUGGER_TRACING.md) for start/stop addresses, historical before/after registers, real interrupt/video events, native scheduler events, timing marks and ranged CSV export. CSV formatting runs off the emulator queue after capturing an immutable bounded range. + +The original authored assembly and actual LWASM-generated listing are safe to retain in Git and correspond to the test diagnostic's two-instruction loop. Personal ROMs, games, compiler builds and generated test exports remain outside the repository. + +### Completion validation + +The checks below record completion of the original Windows-parity debugger milestone. Later CMOC workspace qualification is recorded separately in the workspace guide. + +The final background suite passed **233 tests with zero failures on arm64 and x86_64 under Rosetta**, run separately on November 3, 2026. The full scheme contains 234 tests (61 shared and 173 Mac); the unrelated foreground Metal presentation case was excluded from these background runs. Twenty-three new tests cover listing parsing and failure recovery, disabled breakpoints, memory bounds/export, OS-9 interpretation, trace triggers and immutable samples, both CPU register sets, range export and asynchronous file-save success/failure. + +Four targeted native UI cases passed during this increment: the existing execution/edit/focus case, MMU/physical inspection, source listings/disabled breakpoints, and memory/trace export. The final two-case run verified the corrected compact Source layout and background saves through actual native file panels. It read back the exact five-byte raw export and trace CSV, checked field focus and retained drafts, and checked continued execution, audio and mounted media where no explicit execution command was issued. The full unrelated UI suite was not rerun. + +Native screenshot review exposed a Source minimum-height conflict in a restored compact window. The source and memory panes now share a stable combined minimum height, keeping execution controls below the title bar. A regression assertion guards that layout. An earlier overlapping test run contended for the audio device; the final architecture suites ran separately and both passed. All three final window captures were visually inspected. The final universal Release build succeeded, and its executable was verified to contain both arm64 and x86_64. This is a local build check; the signed distribution app and DMG were not replaced. + +These captures use only the isolated authored diagnostic. Source lines and memory panes scroll independently; the splitter can give either more room. See the Windows source-level parity review for remaining differences. Fresh side-by-side Windows runtime comparison, physical Intel hardware, macOS 14 and comprehensive VoiceOver certification remain validation gaps. The CMOC workspace and SDC baseline are now implemented and qualified within their documented scope. diff --git a/docs/macos/DEBUGGER_MEMORY_TOOLS.md b/docs/macos/DEBUGGER_MEMORY_TOOLS.md new file mode 100644 index 0000000..b884f79 --- /dev/null +++ b/docs/macos/DEBUGGER_MEMORY_TOOLS.md @@ -0,0 +1,41 @@ +# Debugger memory tools + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Disassembly + +Choose **Mapped CPU** or **Physical RAM**, then enter hexadecimal **Start** and **End (inclusive)** addresses. Physical RAM uses the installed capacity, up to `$7FFFFF` for 8 MB. Mapped CPU uses `$0000–$FFFF`. Reversed, overflowing and wrapping ranges are rejected. + +For physical RAM, **Assumed CPU origin** specifies the 16-bit logical address at which those bytes would execute. This controls relative branch destinations. The **Location** column always shows the actual RAM location; **CPU** shows the assumed logical address. Physical RAM is not implicitly mapped into the running processor merely by viewing it. + +**Disassemble** captures up to the first 4,096 bytes and displays at most 128 rows. It takes a new capture only when requested; the caption identifies the processor and capture's cycle count. Changing address fields does not silently replace an existing capture. An incomplete instruction at the end becomes an explicitly marked `FCB`, with no invented trailing bytes. Unavailable mapped I/O is marked as unavailable and advances one address. Rows provide a native **Copy Row** context-menu action. + +Both MC6809 and HD6309 use the retained VCC opcode tables. HD6309 decoding is available in native and emulation mode. The normal live disassembly view continues to follow the actual CPU PC; this separate area deliberately does not follow PC. + +## OS-9 interpretation + +**Interpret OS-9 calls and module headers** is opt-in because ordinary software may use SWI2 differently. It consumes the service byte after SWI2, names known OS-9/NitrOS-9 requests, and leaves unknown/private requests numeric. Names follow the [NitrOS-9 service definitions](https://github.com/nitros9project/nitros9/blob/master/defs/os9.d). This annotation does not imply that a particular guest OS implements every named service. + +A module header is recognized only with `$87CD` sync and valid nine-byte header parity. Its row reports size, name offset, type/language, and attributes/revision. Program, system and file-manager headers also show execution and storage offsets. Header interpretation is an aid to inspection; it does not validate a module's CRC or load, relocate or execute it. + +## Raw binary export + +**Export Binary…** captures the entire selected range and opens a native save panel. The immutable captured bytes are saved atomically. The default extension is `.raw`; this is not a Disk BASIC `LOADM` file and has no DECB header. Export while running captures one execution boundary and does not stop the session. Export a paused machine when repeatable guest state is important. + +A mapped range containing unavailable I/O is rejected before opening the save panel. The app does not substitute zeroes into an exported image. Choose a range excluding that I/O, or export physical RAM instead. This safeguard also applies to a whole-CPU-space export. + +File errors remain visible in Memory Tools. Canceling the save panel writes nothing and changes no emulated state. Export does not alter mounted disks or acknowledge their dirty state. + +## Graphics Preview + +Open **Debug → Show Debugger → Graphics Preview**. **Current Video Page** follows the active video registers and palette, including the physical page that the video chip sees. While running, the preview samples up to four times per second. Pausing lets you inspect a stable page. A capture reads memory without advancing the emulated beam or changing the program. + +**At Address** interprets a hexadecimal start address as text/SG4, PMODE 0–4, or HSCREEN 1–4. Select **Mapped CPU** for addresses used by BASIC or assembly instructions. Select **Physical RAM** for a page elsewhere in installed memory. A manual PMODE preview has its own color-set selector. A range extending beyond its address space produces an error. Unavailable mapped I/O appears as a gray pattern. + +Click a pixel or enter **X** and **Y** in Pixel Inspector. It shows the stored byte, its address and the bit mask for that pixel. Attributed GIME text also shows the attribute byte. Composite artifact colors can depend on neighboring bits. **Show Byte in Memory** selects the byte in the matching address space. **Preview as Graphics** opens a preview from the memory inspector. Fit and 1×–4× zoom use nearest-neighbor scaling. **Highlight step changes** marks pixels whose displayed color changed across a single debugger instruction on the same page and mapping. + +## Scope and validation + +Regression coverage exercises both CPUs, logical versus physical backing, the final byte of 8 MB RAM, full physical export, invalid and overflowing ranges, immutable captures, unchanged guest cycles/PC/generation, incomplete instructions, unavailable I/O, optional OS-9 calls, unknown services and valid/invalid module headers. Model coverage checks native export data and file bytes, read-error refusal, address parsing and physical decoding at the final byte. + +Separate Windows raw ROM/PAK views and adjustable memory-grid widths remain outside these tools. Mapped ROM remains inspectable through the CPU address space. Physical editing, assembly-level Step Over/Out, arbitrary register editing and conditional/watchpoint debugging are not provided by these tools. The separate [C workspace](../development/CMOC_SOURCE_DEBUGGING.md) implements C source-level Into/Over/Out. diff --git a/docs/macos/DEBUGGER_TRACING.md b/docs/macos/DEBUGGER_TRACING.md new file mode 100644 index 0000000..cb7194a --- /dev/null +++ b/docs/macos/DEBUGGER_TRACING.md @@ -0,0 +1,43 @@ +# Native execution tracing + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Capture + +- Capture options and trigger edits apply on **Start New**, not to a capture already in progress. + +- Choose **1–100,000 samples**. **Start New** replaces the previous capture and arms the trace. The bound counts instruction and optional event rows together. At the limit, capture stops and the machine continues in its existing state. + +- **Start at** accepts up to 32 logical hexadecimal addresses separated by spaces or commas; `$` and `0x` prefixes are accepted. Blank means the next executed instruction. Matching any start address begins capture immediately before that instruction. + +- **Stop before** accepts the same syntax. Matching any stop address stops capture before that instruction, while the instruction still executes normally. This is a trace trigger, not a breakpoint. Identical start/stop addresses produce an empty capture. With no stop addresses, use the limit or **Stop**. + +- **Clear** stops capture and removes its samples. Soft/cold reset and processor/RAM changes stop capture and retain already collected samples. Loading a different machine/profile or quitting clears it. + +- Instructions store their own pre-execution bytes and before/after register states. Self-modifying code, subsequent edits, and MMU changes do not rewrite historical samples. Inspection does not re-read device ports; an instruction whose encoding crosses unavailable I/O is explicitly unavailable rather than decoded from invented bytes. + +Instruction tracing uses the retained CPU engines' before/after hooks. Ordinary HD6309 TFM tracing follows their per-transfer-byte execution loop; an explicit debugger Step captures the whole TFM instruction, consistent with the existing Step operation. A partially filled capture remains armed when a breakpoint pauses execution, and continues when the user continues or steps. + +## Events and timing + +IRQ request, servicing and vector-entry rows come directly from the CPU hooks. IRQ/FIRQ/NMI names identify the line. A request does not imply that the CPU serviced it; separate rows establish that. The retained CPU engines do not emit a separate masked-interrupt callback, so the Mac does not invent masked events from the CC register. + +**Screen events** records real HSYNC/VSYNC transitions and guest video-register changes from the existing GPU/register hooks. **Scheduler events** records entry and return of the native bounded frame-execution call. The Mac uses the event-driven timing engine; it does not fabricate the old Windows scheduler's state-switch variables, drift or nanosecond budgets. Screen events are timing/register events, not screenshots. + +Rows expose the frame number and absolute emulated **master clock** within the current machine timeline. The native raster period is 263 × 912 master clocks; the frame-relative event clock supplies the remainder. Master clocks remain comparable across normal guest CPU speed/overclock changes. Instruction-cycle counts are measured by the CPU engines and are distinct from master clocks. + +Select two rows and choose **Mark A** and **Mark B** to compare their master-clock difference and nominal emulated milliseconds (14.31818 MHz master crystal). This is guest time, not wall-clock capture duration or playback timing. A new capture or Clear resets marks. + +## Inspection and export + +The viewer fetches immutable pages of at most 256 rows at 2.5 Hz only while visible. Previous/Next and a decimal sample-number field navigate the capture. Select a row for its complete CPU before/after registers, event detail and instruction-cycle count. Both CPU register sets are supported. + +**Export CSV** uses a decimal inclusive first/last sample range; a blank end means the current last sample. The range is copied on the machine's serial queue, then CSV formatting runs on a background queue before opening a native save panel. The emulator can continue during formatting. Cancellation or write failure leaves the trace and emulator unchanged. Export uses the retained historical samples, including instruction bytes. Numeric CSV addresses, clocks, cycles and register values are decimal; instruction operands remain assembler-style hexadecimal. Event numbers correspond to `TraceEvent` in `MachineDefs.h`. + +The maximum capture is deliberately finite. It is not an unbounded profiler or a host-performance measurement. Trace capture and export consume extra CPU/memory while enabled; normal disabled execution uses the already-existing false debug-hook checks. + +## Regression coverage + +`DebuggerTraceTests` checks both processors, bounded capture without pausing or resetting, multiple start/stop addresses, stepping, immutable snapshots, ranged export, real screen/scheduler events and monotonic clocks across frame boundaries. It checks actual CPU IRQ request/service/vector callbacks, plus capture retention across reset. It also covers authoritative enabled/disabled breakpoint state and atomic rejection of conflicting states. + +`DebuggerTraceBridgeTests` checks immutable decoded samples, before/after register text for both CPUs, range export, rejected triggers without losing a previous capture, strict trigger parsing and enabled/disabled breakpoint bridge state. Native UI validation and final build results are recorded in the main [debugger guide](DEBUGGER.md). diff --git a/docs/macos/FLOPPY_CORE.md b/docs/macos/FLOPPY_CORE.md new file mode 100644 index 0000000..f2a579d --- /dev/null +++ b/docs/macos/FLOPPY_CORE.md @@ -0,0 +1,85 @@ +# Built-in FD-502 and DSK core milestone + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Reused source and host boundary + +`src/devices/FD502/Fd502Device.cpp` adapts the command model from Joseph Forgione's `platforms/windows/FD502/wd1793.cpp`: drive/side selection, register addresses, command families, step/settle delays, transfer timeouts, delayed byte-transfer completion and completion NMI. `src/devices/FD502/DiskImage.cpp` retains the sector-image geometry and layout. Copyright/provenance notices remain in the source. The original Windows DLL, settings/UI and physical-drive implementation are unchanged. + +The portable implementation owns its registers, transfer buffer, four drives and head positions. It has no Windows handles, physical-floppy driver, native UI, global controller state or filesystem access. Separate instances are isolated. `src/devices/CartridgeDevice.h` supplies a small built-in registry and single-slot bus. The initial registry contains FD-502; it does not load a DLL. That initial callback contract carried NMI only. The subsequent native bus adds the selected devices’ cartridge signaling, DMA and MPI routing; see [cartridge integration](CARTRIDGES.md) and [hard disks](HARD_DISKS.md). + +The session calls the device once on each falling horizontal-sync edge, after the PIA sync callback, matching the Windows `USE_NEWTIMING` connection. Pause freezes device time. Soft/cold reset cancel commands and stop the motor while retaining the device, mechanical head positions, mounted images and modified bytes. Shutdown disconnects callbacks before destroying the machine host. CPU changes and ROM reloads retain device ownership and reset controller state. + +An FD-502 requires a user-supplied 8 or 16 KiB disk ROM, separate from the 32 KiB system ROM. The ROM occupies a 16 KiB cartridge window; an 8 KiB image is padded with `0xff`. Public source builds contain neither ROM. Explicit private inputs are now supported by Debug staging and local signed packaging. + +## Image and transfer support + +- Headerless JVC/DSK defaults to 18 sectors per track, 256 bytes per sector and one side, as upstream does. Double-sided geometry must be described by a JVC header or a recognized OS-9 descriptor; image length alone does not disambiguate it. + +- JVC headers of one through four bytes specify sectors, sides, sector-size code and first-sector number. Supported limits are 1–256 tracks, one/two sides, 1–64 sectors, and 128/256/512/1,024-byte sectors. The payload must be a multiple of 256 bytes and contain complete tracks. Images are bounded to 16 MiB. + +- Headerless OS-9 sector images with the upstream 18-sector geometry are recognized only when their descriptor's total sector count matches the image length. This is image-layout support, not evidence that NitrOS-9 boots yet. + +- Restore, seek, step, single/multiple sector read/write, synthetic read-address, force interrupt and sector-image write-track formatting are connected. A standard blank 35-track DSK is 161,280 bytes. `DSKINI` supplies the filesystem through guest controller commands. + +- The control register selects all four single-sided drives, or either side of a selected double-sided drive. Unowned ports return zero and ignore writes. NMI completion uses the retained density/control-bit gate; forced interrupts retain upstream's simplified low-nibble behavior. + +- Writes change owned image bytes. Complete sectors commit together; interrupted partial sectors are discarded. Whole write-track streams are validated before any sector changes. Write protection is enforced before data acceptance and again by the image backend. + +- Busy controllers reject media replacement. Dirty images require explicit export acknowledgement or discard before drive eject/replacement. Serialization preserves the image header and untouched sectors. The application bridge now enforces these protections when disabling the whole device and when quitting; bus installation is an owner-level operation, not a user-facing eject command. + +Some safety and determinism changes are intentional: malformed geometry is rejected before indexing or shifting; invalid sectors cannot alias another track; short images are rejected rather than padded on read; switching drive/side aborts an active transfer; write-track parsing is bounded and transactional; random index wobble is replaced by a fixed 3,144-scanline revolution. Multi-sector commands now advance until the next sector is unavailable, whereas the retained Windows implementation records the multi-sector flag without using it. An end-of-transfer timeout no longer reports lost data when all payload bytes were serviced. + +This retains the upstream controller's simplified timing model. HALT-line behavior, detailed density/side-compare/verify options, address CRC fidelity, copy-protected media and rotational timing accuracy are not established by this milestone. Read-track returns record-not-found for sector containers, consistent with upstream's JVC/OS-9 path. This initial checkpoint rejected DMK, VDK and attribute-byte JVC containers. See the November 5 update below for DMK and VDK. Becker networking, the Disto clock, alternate DOS configurations, MPI and physical drives are outside this checkpoint. + +## Validation + +Validated November 1, 2026 using the local Xcode 27.2 toolchain: + +- **57 XCTest tests passed:** 45 shared C++ checks, seven application-bridge tests and five native tests. + +- Debug and Release apps built as arm64/x86_64 universal binaries. + +- The 45-check Release console suite and both-CPU disk-ROM integrations passed as arm64 and as x86_64 under Rosetta. Rosetta is not physical Intel validation. + +- Focused floppy checks and both-CPU disk-ROM integrations passed AddressSanitizer and UndefinedBehaviorSanitizer. The pre-existing full-suite speech-chip sanitizer limitation remains documented in [audio/cassette validation](AUDIO_CASSETTE.md). + +- The earlier optional system-ROM checks still pass BASIC sound, CAS/WAV save/load, fast CAS and soft/cold resets on both CPUs with no disk device installed. + +- Six new shared checks cover image geometry/round trips, invalid input and bounds, command timing, transfers/formatting, protection/cancellation, bus routing/lifetime and complete machine integration. + +- The machine integration uses an authored ROM to verify mapped cartridge ROM/data reads, one controller tick per scanline, and an actual FD-502 completion NMI serviced by both 6809 and 6309 engines. Pause/reset/shutdown lifetime checks do not require external ROMs. + +- The optional disk-ROM check boots Disk Extended Color BASIC on both CPUs, runs `DSKINI0`, saves `10 PRINT 6*7`, verifies its directory entry, serializes/ejects/reloads the DSK bytes, cold-boots, and verifies `LOAD`, `LIST`, and `RUN` printing `42`. A protected save must report `?WP ERROR` and leave all image bytes unchanged. + +Run the ROM-free tests through Product → Test in Xcode or the shared `VCCCoreChecks` scheme. To run the optional integration after building the Release console target: + +```sh +build/macos/Build/Products/Release/VCCCoreChecks --disk-rom /path/to/coco3.rom /path/to/disk11.rom +``` + +The optional check currently expects the standard 8 KiB disk ROM. It opens both supplied ROM files read-only and creates every disk byte in memory. No ROMs, generated disks, logs or binaries are checked in. + +Native drive/file controls, errors and filesystem export/reopen are covered by the follow-on milestone. NitrOS-9 boot/file operations, MPI and native configuration persistence were added in [hard disks](HARD_DISKS.md), [cartridges](CARTRIDGES.md) and profiles. The initial milestone left Windows interchange, broader disk-library qualification and physical Intel/macOS 14 testing open. + +## DMK and VDK — November 5, 2026 + +All four FD-502 drives now mount and save DMK track images and uncompressed VDK sector images. The Mac file picker, Finder/drop routing, profile restoration and Software Library share this support. Standard DSK remains the first New Disk choice. A file named `.dsk` may contain any supported representation. Save As preserves the bytes in that representation, including extended headers and untouched tracks. + +- **DMK.** The WD1793 reads the track's address table, actual sector sizes, deleted-data marks, and recorded CRCs. READ ADDRESS exposes the stored ID field. READ TRACK returns the captured track bytes after its pointer table. FM sectors stored twice and mixed FM/MFM disks are supported. A sector write updates its data mark, payload and CRC in place. WRITE TRACK replaces only a completed, validated track. Image-level write protection takes precedence over the drive switch. + +- **VDK.** Signature, declared header length, tracks and sides locate the sector payload, including the 256-byte headers on both library VDKs. The reader also accepts the minimal 12-byte header produced by Windows VCC. This work applies to the FD-502. The separate CoCo SDC backend retains its own format limits. + +- **Compatibility limits.** The controller uses deterministic timing and a simplified density model. Software relying on precise rotation, flux transitions or unusual protection routines needs title-specific testing. A readable Dragon-format disk still requires guest software compatible with the emulated CoCo. + +### Validation and reproduction + +The local Software Library contained **54 distinct DMK images and two VDK images** across 44 packages. Of the 55 DMK occurrences, 49 had a `.dsk` suffix. Disk BASIC read an independently located sector from each of the 56 images on **both the 6809 and 6309**. For the 55 writable images the test wrote a pattern, checked the surrounding bytes, ejected, remounted, reread and tried a protected write. White Fire's header protection rejected the initial write. Tests used in-memory copies. + +*Shamus* exposed a false address marker in a protected directory track. A regression case reproduces it with authored bytes. The original disk passed `DIR` and reached its title screen with `RUN"SHAMUS"`. *Color FLEX 5.0:4* booted to its date prompt. *Kidwriter* listed its directory and reached its loading screen. Both extended-header VDKs passed sector checks. These observations describe the part of each title actually exercised. + +- Run `VCCCoreChecks --disk-rom /path/to/coco3.rom /path/to/disk11.rom` for the six DSK/DMK/VDK × CPU round trips. Each creates a new disk, runs `DSKINI0`, saves a BASIC program, lists the directory, reopens the disk, cold-boots, loads and runs the program, and checks write protection. + +- For retained software, [the optional real-media probe](../../tests/macos/fd502-media-probe.cpp) takes the ROMs, disk file, physical track, sector and independently determined payload offset. For the protected *Shamus* edition use `17 1 109019 --dir SHAMUS`. For Tiburon's `Dragon/S37H.VDK` use `17 3 157440`. Each invocation tests both processors and opens all host inputs read-only. + +- The Xcode regressions cover failure without replacing mounted media, header protection, format-preserving export, Finder/drop choices and library routing. `testCreateDMKAndVDKFromFloppyWindow` exercises both menu choices in the isolated running app. diff --git a/docs/macos/GRAPHICS_CORE.md b/docs/macos/GRAPHICS_CORE.md new file mode 100644 index 0000000..5f8ae91 --- /dev/null +++ b/docs/macos/GRAPHICS_CORE.md @@ -0,0 +1,43 @@ +# Graphics and frame timing — Phase 1 + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Portable interfaces + +- `VideoState` holds borrowed emulated memory and a host-owned render surface. It contains no window handles. The Windows `SystemState` inherits these fields, preserving source access for existing callers; `VideoHost.cpp` forwards surface and clearing requests to the Windows implementation. + +- The Mac checks use a packed **640 × 480** surface of 32-bit **`0x00RRGGBB`** pixels. Pitch is measured in pixels, not bytes. On the supported little-endian hosts the bytes are B, G, R, zero. The native display bridge treats these as opaque pixels rather than interpreting the zero byte as transparency. The renderer still retains upstream 8/16/24-bit entry points for Windows, but the Mac path and new pixel tests use 32-bit output only. + +- `ApplyVideoRegister` and `ApplyTimerRegister` connect machine-register writes directly to a selected `GimeGpu`. Tests now use the real graphics/timer implementation instead of recording those calls. External input, cartridge devices, audio delivery, cassette files, and printer output remain explicit test replacements. + +- `RunFrame` is a synchronous execution operation. It returns when a frame completes, the debugger halts, a cycle budget is reached, or the CPU makes no progress. The final instruction can exceed the requested budget. Budget-limited frames can resume; the function does not restart the raster, pace wall-clock time, lock a window, or flush audio. The Windows event-based frame loop uses it too, replacing a loop that could wait indefinitely after a breakpoint. + +Only one scheduled GPU/machine may own the global scheduler and host bindings at a time. Install the machine, video and debugger hosts, initialize memory/CPU, reset the scheduler, and then reset/configure the GPU before execution. Keep the surface and borrowed memory alive during rendering. Call `StopEvents` before changing hosts, memory, or the scheduled GPU. GPU callbacks carry weak lifetime guards, so abandoned callbacks cannot dereference a destroyed renderer. `StopEvents` cancels all owned raster and timer tags, while leaving unrelated scheduler events alone. Immediate debugger preview GPUs do not own scheduled raster tags. + +## Seven added checks + +| Check | Coverage | +| --- | --- | +| Pixel output | Known red/green/blue/white values, nibble order, horizontal/vertical doubling, alternating black scanlines, and unsupported-width regression | +| Mode sweep | 2,304 CoCo 3 / compatibility register combinations across every active row, framebuffer guards, and a separate composite PMODE4 artifact-path check | +| Raster timing | Both CPUs complete 263-line frames; 912 clocks per line; four-line VSYNC pulse; subsequent frame period of 239,856 clocks | +| Full-frame pixels | CPU-driven eight-bar RGB image, every active pixel checked independently, and top/bottom border placement | +| GIME timers | Fast-clock restart delay, interrupt issue delay, overlapping delayed IRQs for short periods, zero-count stop, and scanline-clock countdown | +| Video lifecycle | Reset replaces existing callbacks, stop cancels owned events, and destroyed renderer callbacks expire safely | +| Frame stops | Breakpoint halt returns immediately, bounded work, partial-frame resume, and stalled-CPU detection | + +The synthetic `BRA` loop takes three CPU cycles per instruction. At 16 clocks per cycle, the first completed frame consumes 14,994 cycles because event boundaries are exclusive and execution finishes whole instructions; the following frame consumes 14,991 cycles. These checks preserve the retained source's timing model. They do not establish exact agreement with every GIME revision or a new Windows trace. + +The mode sweep includes combinations whose derived width exceeds the supported framebuffer. Those layouts are deliberately skipped, rather than allowed to write into unrelated rows. The sweep establishes memory safety for the tested inputs; it is not visual parity evidence for every mode, palette, scroll, or mid-line register transition. + +## Corrections and validation + +Graphics operations now use their own GPU instance rather than accidentally calling the global Windows renderer. Raster update bookkeeping is initialized and cleared on reset; display geometry is established before the first sync event. Timer clock selection lives in the GPU, reset/stop cancels its scheduled work, and switching away from the fast timer cancels its remaining retrigger event. Multiple delayed IRQs are preserved when the timer period is shorter than the issue delay. + +AddressSanitizer found an existing framebuffer overflow: a 1-bpp/128-byte row derived 1,024 pixels, causing the unsigned stretch factor to underflow and a border write to land past the framebuffer. Unsupported oversized layouts now leave the surface untouched, and duplicated border-row writes are bounded. A targeted regression check accompanies the broader sweep. + +The full RGB color-bar frame was also exported outside the repository and visually inspected. It is generated entirely from authored RAM contents and the retained renderer; no ROM file, screenshot, binary, or user media was added to Git. See the build guide for current validation results. + +## Subsequent integration and open qualification + +The [Mac controller](MAC_CONTROLLER.md), [native boot](NATIVE_BOOT.md), [audio/cassette](AUDIO_CASSETTE.md), input and selected cartridge/storage devices now use this renderer. The native Metal display presents the active picture at 4:3 with the selected scaling/filtering; the core framebuffer contract above remains unchanged. Physical Intel/macOS 14, broader guest video modes, Windows recompilation/reference comparison and the wider representation audit remain open in the [porting plan](PORTING_PLAN.md). diff --git a/docs/macos/HARD_DISKS.md b/docs/macos/HARD_DISKS.md new file mode 100644 index 0000000..cacc801 --- /dev/null +++ b/docs/macos/HARD_DISKS.md @@ -0,0 +1,47 @@ +# Native virtual hard disks + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Saving and recovery + +Writable backed images save automatically, coalesced at roughly one-second intervals. Only changed sectors cross the bridge. Per-sector revisions prevent a completed save from clearing guest writes made while that save was pending. Normal saves keep emulation running. Quit pauses and drains pending automatic saves, then warns if temporary, unbacked, protected or failed-save changes remain. + +Host saves run off the emulation queue: copy the source to a sibling temporary file, verify its SHA-256 against the last known contents, apply sector changes and any zero-filled growth, synchronize the file, and atomically replace the source. File coordination and identity/size/modification checks detect ordinary external changes. Symbolic links are resolved so automatic saving preserves the link. A failed save retains in-memory changes, pauses execution, and offers Retry Save or Save As. Missing files are not silently recreated. Concurrent writes by noncooperating applications are not supported; do not share a writable backing file between emulators or drives. + +Copying can use filesystem copy-on-write support, but hashing still scans the whole image. Long-running workloads and repeated writes to maximum-size images need performance profiling. Images are held in memory; explicit full-image export also needs temporary memory. This is not a crash-recovery journal, and a crash can lose changes not yet saved. + +The guest flush command requests an immediate background-save pass. Its success status means the request was accepted, **not** that bytes are already durable on the Mac filesystem. Temporary/protected modes still apply. This differs from the Windows implementation’s synchronous `FlushFileBuffers` and remains a documented durability limitation. + +Drive URLs, protection, temporary mode and clock options live in the additive `hardDisks` section of the existing version-1 `DiskAssignments.json` under Application Support. Older settings remain readable. Missing images retain their assignments and expose **Retry Unavailable Hard Disks**. Moving or renaming a file requires selecting it again; these are file URLs, not persistent bookmarks. Preferences contain no image or ROM bytes. + +## Device contract + +`HardDisk/HardDiskDevice.h` adapts `HardDisk/cc3vhd.cpp` into an owned portable device. It retains two drives, 24-bit sector addressing, 256-byte transfers, current-MMU DMA and the baseline register map: + +| Address | Operation | +| --- | --- | +| `$FF80–$FF82` | Sector number, high byte first | +| `$FF83` | Command write / status read | +| `$FF84–$FF85` | 16-bit DMA address, high byte first | +| `$FF86` | Drive 0 or 1 | + +Commands are 0 read, 1 write and 2 flush. Status is 0 success, 4 missing/out-of-range, 5 write protected, `$FE` invalid command and `$FF` after reset. DMA wraps at 16 bits and follows current mapped memory, including an 8 KiB boundary. Recursive commands caused by DMA into I/O are suppressed. Reads past current EOF return zeroes within the 512 MiB limit; writes grow the image with zero-filled gaps. The Windows EOF loop’s stale-last-byte behavior and inclusive upper-bound bug are deliberately corrected. + +The clock uses the retained serial cookie and ports `$FF78/$FF79/$FF7C`. It starts from Mac local time and keeps VCC/NitrOS-9’s years-since-1900 encoding. Guest clock writes are disabled by default. When enabled, they change only a session-local virtual offset, never the Mac clock. Reset clears serial transaction state; relaunch discards the offset. Clock-enable and write-permission preferences persist. + +## Validation + +Ten new hostless tests cover image bounds/growth, dirty-sector revisions, protocol/status/drive selection, DMA wrap and MMU boundaries, both CPU engines through MPI alongside FD-502, clock packets and write protection, atomic file saving, read-only/missing/external-change recovery, symlinks, invalid files, temporary mode, settings restoration, blank creation/export, disconnection, pending-save quit draining, and stale acknowledgements. All 92 XCTest tests passed on arm64 and x86_64 under Rosetta. Debug and universal Release builds succeeded with the local Xcode 27.2 toolchain. + +An optional ROM-dependent console check booted the supplied NitrOS-9 image through RGBDOS on both emulated CPUs, created `vccmactest` with the expected contents, and independently parsed its OS-9 file descriptor/data from a reopened image. It passed on arm64 and x86_64 under Rosetta. Supplied files are opened read-only; all guest writes stay in an owned memory copy: + +```sh +build/macos/Build/Products/Release/VCCCoreChecks --hard-disk \ + /path/to/coco3.rom /path/to/rgbdos.rom /path/to/VCCEmuDisk.vhd +``` + +This check expects the tested RGBDOS/NitrOS-9 `DOS255` boot layout, not an arbitrary VHD. The tested image is 135,659,520 bytes with SHA-256 `2ccd07cdfd6aa4d8a1d3ceff04f0a6c3490bde23e40e7c136830334f2264f462`. The supplied Empty and Sierra VHDs were inventoried as sector-aligned images; their applications/boot paths have not been exercised. + +The native Release-app pass opened a disposable NitrOS-9 copy, verified its sector count, toggled protection/temporary mode, created and saved a 64 KiB blank second image, assigned the controller in MPI, and verified both images/options and the controller assignment after actual quit/relaunch. The device-specific Hard Drives menu was checked to appear on assignment, open the controls, and disappear on removal; menu observation was corrected during that check. Test media were then ejected and the user’s original cartridge and floppy settings restored. Native NitrOS-9 typing and file saves were not separately exercised in this UI pass; those paths are covered by the headless boot check and automated host-file tests. Original supplied images remain unchanged. No ROMs, images, screenshots or raw logs are committed. + +Physical Intel/macOS 14 runtime, Windows reopening of Mac-written images, broader NitrOS-9/software libraries, sustained I/O and power-loss recovery remain outside this validation. SuperIDE remains deferred. SDC is a separate implemented device with its own supported formats and qualification limits. diff --git a/docs/macos/MACHINE_CORE.md b/docs/macos/MACHINE_CORE.md new file mode 100644 index 0000000..94bc52b --- /dev/null +++ b/docs/macos/MACHINE_CORE.md @@ -0,0 +1,45 @@ +# Memory and hardware registers — Phase 1 + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Connections and ownership + +`MachineHost.h` makes the remaining connections explicit: ROM provisioning, cartridge memory/ports/audio, graphics register writes, timer controls, CPU selection and interrupt lines, keyboard scans, joystick strobes, tape signals, and printer bits. Every connection is required in the interface. The Mac tests install a recording host with synthetic ROM/cartridge bytes and controlled input. It records video/timer requests; it does not render video, advance a GIME timer, decode tape files, or emulate a cartridge device. + +`MachineHost.cpp` supplies the Windows adapter, forwarding to the original implementations. Windows printer file/console handling has moved out of the PIA source into `PrinterWin.cpp`. That file is included in the Windows project and excluded from the Mac project. The native Mac host and Printer Output are now implemented separately; this extraction fixture uses a recording host. + +The normal CPU memory functions now dispatch to the real MMU. Isolated instruction tests explicitly install a `CpuMemoryBus` containing flat memory, then detach it. The machine checks leave that override unset. No synthetic ROM or test bus is linked into the application target. + +Install the machine/debugger hosts before initialization and keep them alive until execution and teardown finish. Select and initialize a CPU before routing interrupts to it. Clear the isolated CPU bus override when using the real MMU. Initialization, reset, execution, inspection, host replacement, and teardown must all be serialized by the machine controller: the legacy global state and initialization flag do **not** provide thread-safe ownership. Accessing a missing machine host on macOS fails explicitly rather than silently discarding a hardware operation. + +`MmuInit` validates the RAM configuration and prepares RAM/ROM before replacing the active allocation. Allocation or ROM-provider failure returns null and retains the previous memory. The provider receives a 32 KiB buffer prefilled with `$FF`; file selection and ROM validation belong to the host. `LoadRom` similarly preserves the current ROM on failure. `MmuShutdown` releases both allocations and can be called repeatedly. Borrowed RAM/ROM pointers are invalidated by successful reinitialization or shutdown. The Windows host still reads the configured ROM path; its existing hard-reset caller treats a null initialization result as fatal. + +## Added shared checks + +| Check | Coverage | +| --- | --- | +| MMU mapping | 128 KiB, 512 KiB, 2 MiB, and 8 MiB configurations; reset/disabled maps; both tasks; physical write isolation; bank masks and 8 MiB prefix; debugger snapshots | +| ROM and vectors | All four internal/cartridge ROM selections, write protection, SAM RAM/ROM toggles, internal interrupt vectors, and the fixed `$FE00` RAM-vector window | +| Memory lifecycle | Power-on pattern, invalid configuration, failed ROM loading/reloading, replacement ROM, bounded page inspection, repeated teardown | +| GIME/SAM registers | Selected-CPU floating-bus reads, palette masks, combined video offset, timer command forwarding, speed controls, bit-addressed video settings, cartridge port routing, IRQ/FIRQ masks and acknowledgement | +| PIA registers | Data direction, keyboard column mask, joystick strobes, DAC/stereo sample, cassette output/input/motor, serial bit forwarding, mux selection | +| PIA interrupts | Sync-edge polarity, independently asserted sources, control/data acknowledgement, cartridge FIRQ, side-effect-free debugger reads, reset | +| Mapped CPU execution | Both CPUs execute guest writes to MMU/task registers, isolate `$A5` and `$5A` in physical pages 5 and 6, receive a GIME IRQ through the SAM vector, stack into mapped RAM, acknowledge the interrupt, and return with RTI | + +These are authored source-level expectations, not a newly captured Windows reference trace. The existing Windows evidence remains separate. No ROM downloads, user media, raw logs, or binaries are added to the repository. + +## Corrections covered by the checks + +- GIME floating-bus reads now consult the selected CPU; previously they always consulted the 6809, including when the 6309 was running. + +- GIME and PIA resets release their asserted CPU interrupt lines as well as clearing register latches. + +- MMU initialization rejects out-of-range RAM configurations and preserves active allocations on failure. Debugger page reads are bounded, and reads after teardown cannot dereference freed memory. + +- SAM vector reads use the current internal ROM allocation, avoiding a stale cached pointer after memory reinitialization. + +## Validation and remaining work + +The Debug console suite passes 21 checks on arm64. The Release suite passes on arm64 and as x86_64 under Rosetta. AddressSanitizer and UndefinedBehaviorSanitizer pass the combined CPU, scheduler, and machine checks. See the build guide for the current XCTest result and IDE instructions. + +Graphics generation and frame/timer scheduling are now [extracted](GRAPHICS_CORE.md). The [Mac machine host and application bridge](MAC_CONTROLLER.md) now own serialized lifecycle and frame delivery. The [native boot milestone](NATIVE_BOOT.md) now adds ROM selection, Metal display and keyboard input. These checks validate register behavior and callback routing, not complete video/audio/tape/device timing. Windows recompilation, physical Intel testing, macOS 14 runtime testing, and full Windows/Mac trace parity remain outstanding. Phase 1 is still in progress. diff --git a/docs/macos/MAC_CONTROLLER.md b/docs/macos/MAC_CONTROLLER.md new file mode 100644 index 0000000..450c0b1 --- /dev/null +++ b/docs/macos/MAC_CONTROLLER.md @@ -0,0 +1,47 @@ +# Mac machine controller and application bridge — Phase 1 + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Ownership and execution + +`src/core/MachineSession` is the synchronous C++ owner. It accepts an exact 32 KiB ROM image and either the 6809 or 6309, currently with 512 KiB RAM and RGB output. ROM bytes are copied before initialization. Invalid size/processor input leaves the current machine intact. Initialization failure after ownership transfer leaves an empty session with hosts, memory, and scheduled events released. + +The retained engines still contain process-wide globals. An atomic ownership claim permits only one loaded session. A rejected second session cannot replace the first session's hosts. This claim does not make low-level emulator APIs thread-safe: initialization, execution, snapshots, and destruction must all be serialized, and direct core tests cannot run alongside a loaded session. + +The session installs the real machine, video, and CPU-debugger hosts and connects video/timer writes and interrupts to the selected CPU. SAM double-speed and turbo requests update the retained scheduler. The joystick ramp clock now has non-Windows storage in the core rather than in the test executable; native joystick input is now connected. + +- Loading creates a paused machine at its ROM reset vector. + +- Resume starts execution; Pause stops future frame execution without resetting state. + +- Advance executes at most one frame, with a 100,000-cycle safety budget. A halt pauses the machine; a stalled or over-budget frame pauses and reports an error. + +- Reset constructs a fresh machine, including a new GPU, from the retained ROM and processor selection. RAM, registers, callbacks, frame counters and graphics state restart. This is a **cold reset**. + +- Soft Reset follows the retained Windows warm-reset sequence for the connected hardware, preserving the RAM allocation and its contents at the reset boundary. It resets CPU/PIA/SAM/MMU and scheduled raster/timer work, reloads the owned ROM bytes, releases keys, advances the generation and clears published frames/counters. It preserves the running/paused choice. Guest warm-start code can subsequently modify RAM; program recovery depends on the guest. The retained GIME register image/palette are not cold-initialized. Attached devices receive the corresponding native bus reset. + +- Shutdown is idempotent and cancels events, frees RAM/ROM, detaches hosts and releases ownership. The synchronous session can subsequently load again. + +At the initial controller checkpoint, cartridges/MPI, disks and printer were disconnected. Those selected devices are now connected; see [cartridges](CARTRIDGES.md), native disks, [hard disks](HARD_DISKS.md), SDC and Printer Output. [Audio and cassette](AUDIO_CASSETTE.md) now connect the retained PIA sound/input/output through scheduled samples and a persistent in-memory deck. The native audio callback consumes a bounded buffer without accessing the core. Deferred Windows peripherals are not emulated by the native host. The app exposes ROM/media selection and native input for its implemented devices. + +## Native bridge and frame delivery + +`platforms/macos/Bridge/VCCMachineController` wraps the session in Objective-C++ for Swift. Every command and timer callback runs on one private serial dispatch queue. Completion callbacks carry immutable snapshots to the main queue; no UI code reads the live core. Snapshots contain state, generation, frame/cycle counts, program counter, an optional error, and an owned pixel copy. + +Completed frames contain 640 × 480 packed `0x00RRGGBB` pixels. Both C++ frame ownership and the bridge's `NSData` copy allow a display consumer to retain a frame safely across later execution, reset, or shutdown. Generation changes distinguish frames across resets. Reset clears the current frame; a new frame appears after execution resumes. The preview explicitly ignores the zero high byte as alpha and disables image interpolation. + +With native audio enabled, the machine queue fills a bounded sample buffer in response to device consumption, at most four frames per turn. With audio disabled, it uses the nominal NTSC frame interval (239,856 / 14,318,180 seconds), without unbounded catch-up. The UI requests snapshots at 30 Hz with at most one poll outstanding. This controller checkpoint alone did not establish sustained accuracy; subsequent [timing and sleep/wake checks](TIMING_RELIABILITY.md) record the implemented baseline and remaining coverage. + +Bridge shutdown is terminal. Commands submitted afterward report an error; queued frame delivery cannot restart the machine. Deallocation also drains the worker and releases ownership. The application delegate waits for asynchronous shutdown before approving Quit; closing the sole window pauses execution. + +## Validation + +Five new shared C++ suites cover both CPUs, empty/paused/running transitions, cold reset determinism, retained frame ownership, singleton exclusion/destruction, ROM validation and copied ROM lifetime. Three additional hostless XCTest suites exercise asynchronous command order, main-queue completion, paced execution, pause stability, reset/shutdown, invalid input, post-shutdown rejection and deallocation/reacquisition. + +Soft-reset checks additionally verify all 512 KiB remain byte-for-byte unchanged before guest execution, interrupt masking/reset vectors, default MMU mapping, held-key release, event replacement, immutable previous frames, repeated reset and paused behavior on both CPUs. Two bridge tests exercise soft reset with each CPU. + +The test inventory is **39 shared core checks** plus **7 Mac bridge tests** and **5 native tests** (51 in XCTest). See the build guide for verified configurations. Authored diagnostics and tests are source code; no third-party ROM, raw Windows evidence, screenshots or binaries are included. + +## Subsequent integration and open qualification + +Native ROM boot, Metal/input, audio/cassette, device routing, disks, profiles and debugger/C-workspace commands now share this serialized machine owner. [Sustained timing and sleep/wake](TIMING_RELIABILITY.md) have baseline evidence. Physical Intel/macOS 14, broader workloads and Windows comparisons remain required; Rosetta and deployment-target builds do not establish those results. See the [current porting plan](PORTING_PLAN.md). diff --git a/docs/macos/NATIVE_BOOT.md b/docs/macos/NATIVE_BOOT.md new file mode 100644 index 0000000..f3af2d8 --- /dev/null +++ b/docs/macos/NATIVE_BOOT.md @@ -0,0 +1,31 @@ +# Native ROM boot, Metal display and keyboard — Phase 2 + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Display and input boundaries + +- `EmulatorDisplay` embeds a native `MTKView` in SwiftUI. The CPU renderer still produces a 640 × 480 packed `0x00RRGGBB` image. Metal uploads it as BGRA bytes, forces opaque output, samples with nearest filtering, and letterboxes to 4:3 using drawable pixel dimensions. Retina backing size and window size do not alter the emulation timer. + +- Every GPU submission owns its upload texture. Up to three submissions can be in flight; if the GPU is busy, presentation skips rather than waiting on the main thread or overwriting a texture still in use. Discrete-memory devices use managed uploads; unified-memory devices use shared uploads. Physical Intel GPU validation remains outstanding. + +- `DisplayShader.txt` contains the small Metal shader source. It is copied into the app/test bundle and compiled through the Metal runtime at startup. The local Xcode installation lacks the optional offline Metal toolchain; this keeps the checked-in project self-contained without downloading that component. Initialization errors are shown in the native window. + +- `CocoKeyboard` tracks held host-key identities and translated chords. Key-up removes the original chord even if modifiers changed. Host key-repeat is ignored; the emulated machine handles repeat. Shift transitions update held letters/special keys. Natural punctuation retains its selected chord until release. + +- `MachineSession::setKeyboard` accepts a complete held-key matrix on the emulation queue. The PIA reads the actual active-low CoCo matrix, and new presses issue the retained GIME keyboard interrupt. Pause ignores further input until resumed. Focus loss, window deactivation, app deactivation, ROM replacement and reset release held keys. + +- The retained renderer's blink state toggles at the Windows frame-loop interval. [Audio and cassette](AUDIO_CASSETTE.md) now connect to scheduled PIA samples. Joystick input, disks and [cartridge/MPI](CARTRIDGES.md) were connected in subsequent milestones; no Windows DLL loader is used. + +## Repeatable checks + +The default suite needs no ROM: **39 shared C++ checks + 7 bridge tests + 5 native display/file/keyboard tests = 51 XCTest tests**. The Metal tests read actual GPU output at five drawable sizes and verify resize preserves the source frame. They verify red/green/blue order, top/bottom orientation, opaque alpha and black letterboxing. Keyboard tests cover all 56 matrix positions, real PIA reads, modifiers, natural punctuation, repeat and release. File checks cover valid, missing, directory, wrong-size, oversized and invalid-vector input. + +An optional integration check uses a ROM supplied at run time: + +```sh +build/macos/Build/Products/Release/VCCCoreChecks --rom /path/to/coco3.rom +``` + +It boots each CPU for 300 frames, enters `10 PRINT 6*7` and `RUN` through matrix presses/releases, checks for `42` in guest text RAM, verifies pause, soft-resets while running and paused, lists/reruns the retained program, and cold-boots back to a clean BASIC prompt. The ROM and resulting screenshots are never written into Git. + +The supplied ROM has SHA-256 `ad358430568250eb8330a37f85361d9ce67e5ae6d5a28c17b31802cd3953a5d2`, already recorded in Phase 0. Both CPU modes passed this check on arm64 and under x86_64 Rosetta. The native BASIC display, program execution and both reset controls were exercised on the local Apple Silicon Mac. Both CPU modes passed running/paused soft reset and keyboard focus recovery; window zoom/restore and clean Quit were also checked. See the interactive check record. This is not evidence of physical Intel, macOS 14 runtime, exhaustive graphics-mode parity, or sustained timing accuracy. See the build guide for build/test results. diff --git a/docs/macos/PORTING_PLAN.md b/docs/macos/PORTING_PLAN.md new file mode 100644 index 0000000..d20be8d --- /dev/null +++ b/docs/macos/PORTING_PLAN.md @@ -0,0 +1,37 @@ +# VCC Plus for Mac: native macOS porting plan + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## 3. Recommended architecture + +| Area | Implementation | Boundary to preserve | +| --- | --- | --- | +| Application lifecycle, menus, emulator window | AppKit; use SwiftUI for suitable settings and forms | UI commands reach the core through explicit operations | +| CPU, memory, GIME, PIA, bus, device behavior | Existing C/C++ | Emulated hardware behavior remains independent of UI frameworks | +| Swift-to-C++ access | A small Objective-C++ bridge with an explicit interface | Keep C++ ownership and implementation details out of UI code | +| Display | Metal/MetalKit presenting the generated framebuffer | Preserve pixel generation, palette, artifact colors, and scanline behavior | +| Audio | Core Audio output consuming buffered samples | Preserve emulated sound timing; accommodate host sample rates separately | +| Input | AppKit keyboard/mouse events and Game Controller support | Translate host events into CoCo key and joystick state | +| Files and preferences | Native file panels, Foundation, and appropriate C++ file operations | Attach DSK images to emulated floppy drives; separate media access from hardware logic; no physical floppy backend | +| Networking and serial | Native sockets/serial facilities behind device-specific interfaces | Preserve the emulated protocol and register behavior | +| Expansion devices | Built-in C/C++ modules with native device selection and configuration UI | Preserve slot selection, device operations, callbacks, and user controls; DLL loading is not required | +| Build | Xcode project with app, C++ library, and test targets | Build and test the core independently from the application | + +Use one emulation worker initially and keep application UI on the main thread. Send commands to the worker and publish consistent state snapshots back to the UI. Transfer video and audio through bounded buffers with defined ownership. Audio callbacks must avoid disk access, allocation, and waiting on the UI. + +The core remains the authority for emulated time. Display refresh rates and audio hardware rates must not redefine CPU speed or device timing. + +Do not create a general replacement for Win32 APIs. Replace each actual dependency with an appropriate core interface or native Mac implementation. Start with one emulated machine per application; multiple independent machines would require additional work on the existing global state. + +## Device scope decision — November 3, 2026 + +| Device | Decision | User value and reason | +| --- | --- | --- | +| Speech/Sound Cartridge | Implemented | Speech and synthesized sound used by CoCo software; native media management cannot replace those hardware capabilities. | +| SDC | Implemented baseline; broaden compatibility | Native SDC-DOS ROM/folder selection, protected/writable cards, directory commands, DSK/JVC/VDK, multidisk switching and 512-byte streaming. All four Multi-Pak positions have SDC artwork, shared native controls and actual-transfer indication. Double Dragon loads all nine disks and reaches gameplay on both CPUs at 2 MB. SDC Explorer 1.35 passes configuration, browsing and BASIC launch; broader collection and OS-9 coverage remains open; flash programming, RTC and SDF/special formats are deferred. See scope and validation. | +| Game Master Cartridge | Evaluate later with representative games | Banked ROM and its sound chip may be required by desired games. Require concrete test software before committing scope. | +| SuperIDE | Deferred | Virtual hard disks already cover ordinary storage needs; revisit for software requiring the IDE interface. | +| Becker/DriveWire | Outbound TCP implemented, November 5 | Optional FD-502 Becker networking for NitrOS-9 clients and a guest-only local Mac shell with 80×24 terminal handling. The Software Library and existing disks handle file delivery. See the NitrOS-9 guide. | +| ACIA/RS-232 | Deferred | Revisit for terminal, BBS or serial-device workflows. | +| Bit-banger printer output | Implemented | Native live text capture, text/raw export and printing; see Printer Output. Broader serial communications remain deferred. | +| X-SID | Deferred | Revisit for specific music/software that benefits from this sound device. | diff --git a/docs/macos/TIMING_RELIABILITY.md b/docs/macos/TIMING_RELIABILITY.md new file mode 100644 index 0000000..347128c --- /dev/null +++ b/docs/macos/TIMING_RELIABILITY.md @@ -0,0 +1,95 @@ +# Phase 3 timing and sustained-use checks + +> Technical evidence extract for the VCC Plus white paper. Only reviewed contracts, mechanisms, methods, results and limitations are retained. Original validation dates and configuration limits remain historical; this export is not a new test run. + +## Timing contract + +The retained Windows timing implementation enables `USE_NEWTIMING`. Its event clock is 14,318,180 Hz; a frame has 263 scanlines of 912 clocks each. That is 239,856 clocks per frame, approximately 59.695 frames/second. Sound-disabled Mac execution uses this interval, retaining deadlines across small host scheduling delays. A delay longer than four frame intervals abandons the old deadline instead of replaying a large backlog. Pause, reset, and sound enable/disable establish a new deadline. + +With sound enabled, output consumption paces a queue approximately 100 ms ahead of the device. This adds about 50 ms of queue latency compared with the previous target; guest clocks are unchanged. Output starts only after the reserve is filled, in bounded batches of at most four guest frames per queue turn. CPU instructions, video, cassette samples, and device events still use guest time. Muting changes gain only; it does not flush the queue, restart the output engine, or execute extra guest frames to refill it. The render callback remains allocation-free and lock-free. A running engine that consumes no samples for a second falls back to silent, nominal-speed execution and reports an error; toggling Sound retries output. + +The retained `$FFD8`/`$FFD9` speed switches and `$FF96` turbo bit provide normal, double, and quadruple CPU throughput. They leave raster duration and audio sample production unchanged. `TimingChecks.cpp` exercises those mapped registers on both CPUs using an authored three-cycle branch loop and verifies the independent cycle totals and sample counts. + +This is source-contract validation, not a new timed Windows/Mac comparison. Windows also has host-specific throttle/audio feedback and a 60 FPS target. The Mac does not copy the Windows sampler's `+25 Hz` compensation. Windows frame skipping advances all guest frames while omitting presentations; the Mac likewise publishes fewer display updates than guest frames. Native Machine Settings now provide presentation intervals of 1–6 frames, fast-forward, and CPU overclock factors of 1–16. Their cycle/sample, transition, persistence and media-safety tests extend this source-contract validation; timed Windows comparisons and sustained high-overclock tests remain open. + +## Repeatable checks + +The normal Xcode test action includes: + +- Thirty simulated minutes of irregular host callbacks without accumulating frame drift; short-delay catch-up, long-delay recovery, and resume deadline reset. + +- Audio-progress timeout, progress recovery, and timeout reset after pause/device restart. + +- Normal/double/turbo/back-to-normal register sequences on both CPU engines, with unchanged video/audio timing. + +- A modeled 80 ms producer stall while the audio consumer keeps reading; the new reserve retains every sample and refills without overflow. The previous 50 ms reserve fails this case. + +- Native volume/mute changes without output-engine restarts; switching to silent pacing and back; existing pause, reset, shutdown, buffer ordering and overflow/underrun checks. + +The opt-in real-time runner uses the actual native controller and audio output, loads a separately supplied CoCo 3 ROM read-only, and types this authored BASIC workload: + +```basic +10 SOUND100,255 +20 PRINT 42 +30 GOTO10 +RUN +``` + +It never loads remembered settings, mounts media, writes the ROM, or changes system volume. Its own output gain is zero; nonzero samples are counted before gain to verify that the tone loop continues. Logs report wall time, emulated frame time, consumed audio time, buffer occupancy, output starts, maximum callback request, maximum refill interval, sample shortages, and resident memory. Refill intervals exclude graph-creation time, before consumption begins. Counts are lifetime totals; the measured interval subtracts the warm-up baseline. Missing audio is measured in stereo sample frames (44,100 per second), not individual incidents. Memory includes retained frame snapshots. + +From the repository root: + +```sh +export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer +# Native output remains active, with zero gain. +tests/macos/run-sustained-check.sh /path/to/coco3.rom 1800 6809 +# Test the other CPU with sound disabled and nominal host pacing. +VCC_CHECK_ARCH=x86_64 tests/macos/run-sustained-check.sh /path/to/coco3.rom 1800 6309 silent +``` + +`VCC_CHECK_ARCH` accepts `arm64` or `x86_64`; the default is the host architecture. `VCC_CHECK_BUILD_DIR` optionally selects a build directory outside the checkout. The script builds both architecture slices. Rosetta execution is useful coverage but does not substitute for physical Intel hardware. + +The script temporarily prevents idle system sleep for the runner's lifetime without changing saved power settings. Leave the Mac awake (do not manually sleep it) and its output route unchanged for a baseline run. The requested duration begins after boot, typing, and warm-up. Acceptance requires maximum sampled frame/audio deviation from wall time below 250 ms, resident-memory growth below 64 MiB, no additional sample shortages or overflow, continued execution without reset/error, and stable frame/audio counters after Pause. Each maximum is sampled approximately once per second, so this does not measure every short transient or end-to-end display latency. Output-device and sleep tests are separate interruption checks; their results must not be combined with uninterrupted baselines. + +## Local evidence + +Verified November 1–2, 2026, locally on Apple M5 Pro with Xcode 27.2/macOS 27.2: + +- All 110 XCTest tests passed on arm64 and x86_64 under Rosetta. The Release console runner passed all 55 shared checks in both architecture slices, and the app built as a universal binary. + +- The native app ran a NitrOS-9 shell on the main display at both 120 Hz (4,818 frames / 80.638 seconds, approximately 59.75 FPS) and 60 Hz (3,997 frames / 66.955 seconds, approximately 59.697 FPS). These are short accessibility-counter measurements, not precision visual synchronization measurements. The first attempted interval was discarded because a ROM load reset the counter. The display was restored to 120 Hz. + +- Moving the running app to a second physical 60 Hz monitor retained the shell and rendering: 4,265 frames / 71.389 seconds, approximately 59.74 FPS. The app was returned to the original 120 Hz display. + +- Two native-app RSS observations about eight minutes apart, spanning monitor changes, were 407,968 KiB and 341,520 KiB. This includes loaded media and display resources; it is a bounded-memory spot check, not a peak-memory trace. + +- Native Pause held NitrOS-9 at frame 32,380 for more than 50 seconds; Run resumed the same shell, and Return produced a fresh prompt without reset or stuck input. + +- The default USB headphone device runs at 48 kHz, exercising AVAudioEngine's conversion from the guest's 44.1 kHz stream. A second connected display runs at 60 Hz. Neither test changes guest clock constants. + +Development runs with the earlier 50 ms reserve exposed intermittent shortages. The first pair used default queue priority; another audio run tested interactive priority. Desktop use and Xcode builds/tests continued during these runs: + +| 30-minute workload | Maximum frame/audio deviation | Peak RSS growth | Missing / overflow samples | Result | +| --- | --- | --- | --- | --- | +| arm64, 6809, native audio, default queue priority | 66.770 / 49.140 ms | 1,343,488 bytes | 1,888 / 0 | **Failed** the strict no-gap criterion. One early shortage totaled about 42.8 ms of missing samples; no additional shortages followed. Execution, bounded drift, memory and Pause checks otherwise held. | +| arm64, 6309, native audio, interactive queue priority and 50 ms reserve | 68.915 / 36.070 ms | 1,359,872 bytes | 1,029 / 0 | **Failed** the no-gap criterion after a shortage at about 25 minutes. Priority alone was insufficient. | +| x86_64 under Rosetta, 6309, sound disabled, default queue priority | 87.698 ms / not applicable | 2,490,368 bytes | 0 / 0 | **Passed** nominal pacing, memory and Pause criteria. | + +After those shortfalls, the reserve was increased to 100 ms with full prefill before engine startup. A diagnostic run observed requests of at most 471 samples, so there was no oversized callback requirement in that run. The final implementation passed separate thirty-minute native-audio runs on arm64/6809 and x86_64/6309, concurrently with the native diagnostic app. This is not a guarantee against arbitrary OS stalls; the callback fills any future shortage with silence and counts it. Hardware interruption checks remain separate. + +The final 100 ms reserve results were: + +| 30-minute workload | Maximum frame/audio deviation | Peak RSS growth | Missing / overflow samples | Result | +| --- | --- | --- | --- | --- | +| arm64, 6809, native audio | 38.235 / 7.738 ms | 1,327,104 bytes | 0 / 0 | **Passed**, including continued tone production, no reset/error, and stable frame/audio counters after Pause. | +| x86_64 under Rosetta, 6309, native audio | 37.072 / 10.018 ms | 11,231,232 bytes | 0 / 0 | **Passed** the same criteria. Most memory growth occurred early, then remained bounded. | + +Both engines stayed at one successful start throughout their measured interval. The largest observed callback request was 471 sample frames; maximum refill intervals were 23.344 ms (arm64) and 23.435 ms (x86_64). These runs did not reproduce the earlier longer interruption, so the separate modeled 80 ms stall remains the direct regression for the added reserve. Passing a thirty-minute window does not guarantee glitch-free output under every host workload. + +The 100 ms implementation passed a separate 120-second native 6809 run while the default output was changed from USB headphones to built-in speakers: zero missing/overflow samples, maximum frame/audio deviations 45.132/43.363 ms, peak RSS growth 1,458,176 bytes. Audio continued without a graph restart (the engine start count remained one). Observed callbacks requested at most 471 sample frames, and the maximum measured refill interval was 10.992 ms. This establishes continued output consumption across the system route change; it was performed at zero gain and is not a listening comparison. USB output and its existing volume were restored, and the native app remained running. The user then put the Mac to sleep and woke/unlocked it. The updated native app was paused at frame 9,423 with Sound enabled and no error, remained at that count after wake, and resumed to frame 13,562 without reset or error. This uses the authored diagnostic session; the earlier NitrOS-9 session had already passed pause/resume and keyboard checks. + +## Remaining acceptance work + +This milestone does not by itself close M3. Physical Intel hardware, macOS 14, exact-revision Windows timed comparisons, a broader game/OS-9 workload matrix, additional audio devices/sample rates, and sustained visual synchronization remain separate coverage. The one-second stalled-consumer detector is covered with a fake clock; a forced live-driver hang has not been exercised. Controller reconnection and keyboard/mouse input were verified in native input. Audio listening and cassette round trips are recorded in [audio/cassette](AUDIO_CASSETTE.md). + +For this timing checkpoint, ROMs, raw logs, generated media and raw screenshots remain outside Git. The repository retains authored checks and summaries; later milestones also include curated native screenshots with their provenance. diff --git a/docs/media/ATTRIBUTION.md b/docs/media/ATTRIBUTION.md new file mode 100644 index 0000000..67692aa --- /dev/null +++ b/docs/media/ATTRIBUTION.md @@ -0,0 +1,73 @@ +# Artwork attribution + +This record applies to the hardware masters, their native PDF derivatives, +and the About assets retained with VCC Plus. The illustrations use historical +hardware references and simplified scene geometry; they are not dimensioned +hardware drawings. Reference photographs and authoring font files are not +included. SVG IDs, state groups and drawing geometry are independent of the +descriptive provenance text. + +## Original artwork notice + +The shared [Original Artwork notice](../../platforms/macos/Resources/About/ArtworkNotice.txt) +states: + +> Except where otherwise identified, original artwork owned by Brian K. Holman is © 2026 Brian K. Holman. All rights reserved. +> +> Permission is granted to use and redistribute this artwork unchanged with VCC Plus, including modified versions of its GPL-licensed software. Other reproduction, modification or redistribution requires prior written permission, except as permitted by applicable law. Third-party materials remain subject to their respective licenses and rights. +> +> The CoCo 3 and CM-8 monitor presentation in VCC Plus’s skeuomorphic System view was inspired by SockMaster’s “pic of CoCo 3 and CM-8 monitor,â€� published on CoCopedia. VCC Plus’s artwork was designed and rendered independently. The remaining hardware illustrations were independently designed using historical photographs and renderings as references. + +This notice is distinct from the application’s [GPL text](../../COPYING). +Original component notices still apply. The shared +[copyright notice](../../platforms/macos/Resources/About/CopyrightNotice.txt) +identifies Dezota and its logo as trademarks of Dezota LLC. Tandy, Motorola, +Hitachi, Intel and other referenced names and marks remain with their respective +owners. They identify represented hardware or visual references; their inclusion +does not imply affiliation, sponsorship or endorsement. + +## Public sources and typography + +- **CoCo 3 and CM-8 inspiration:** [SockMaster’s CoCopedia illustration](https://www.cocopedia.com/wiki/File:COCO-CM8.GIF). +- **TANDY wordmark:** [Tandy computer logo.svg on Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg), attributed there to Tandy Corporation and identified as PD-textlogo and trademarked. Its contours are adapted in proportion and color in the illustrated nameplates. +- **Motorola and Hitachi symbols:** the [Motorola](https://1000logos.net/motorola-logo/) and [Hitachi](https://1000logos.net/hitachi-logo/) reference pages. The processor badges retain symbol contours and recolor them silver. The company wordmarks are omitted. +- **Processor-frame inspiration:** the 2015–2020 panel on the [Intel Inside reference page](https://1000logos.net/intel-inside-logo/) informed the framed-chip arrangement. The frame, circuit decoration and companion-badge composition are original artwork; the reference image is not embedded. +- **CoCo screen character shapes:** copyright 2015 Joseph Forgione, derived from [cc2font.h](../../src/core/cc2font.h), under GPL-3.0-or-later. These vector character shapes are separate from the host interface fonts. +- **Hardware lettering:** outlined Arial and Eurostile lettering, including Eurostile Bold where recorded in the individual masters. Font files are not included. Re-authoring the outlines requires an appropriate local font installation; ordinary app builds use committed artwork. +- **Apple interface sources:** [SF Pro](https://developer.apple.com/fonts/) supplies outlined caption typography in the static macOS concept collection; that collection also credits [SF Symbols](https://developer.apple.com/sf-symbols/) for interface-icon outlines. Native SwiftUI/AppKit controls request SF Symbols by name. A static SVG path and a native `systemName` reference are different representations; this attribution does not identify every static path as an SF Symbol. + +Public reference URLs and source identifications document provenance; they do +not grant additional rights to third-party marks, fonts or other material. + +## Retained asset groups + +| Files or group | Provenance and representation | +| --- | --- | +| `tandy-color-computer-3.svg`, `tandy-color-computer-3-computer.svg`, `tandy-color-computer-3-system.svg`, `tandy-color-computer-3-with-drive.svg`, `tandy-color-computer-3-full-system.svg`, `tandy-color-computer-3-virtual-system.svg`, `tandy-cm-8-monitor.svg`, `tandy-128k-color-computer-3-badge.svg`, `tandy-rgb-color-monitor-cm-8-badge.svg` | CoCo 3, CM-8 and case/nameplate illustrations with shared component geometry. The TANDY, typography, screen-glyph and SockMaster credits above apply to the elements each file contains. | +| `tandy-multi-pak-interface.svg`, `tandy-multi-pak-interface-badge.svg` | Later beige Multi-Pak form and illustrative connector geometry. Relative scale and arrangement also reference Tandy’s *Multi-Pak Interface for Color Computer 2*, Figure 2, PDF page 6 (printed page 4). Historical manuals are curated by the [Color Computer Archive](https://colorcomputerarchive.com/). | +| `tandy-fd-502-controller.svg`, `tandy-fd-502-disk-drive.svg`, `tandy-fd-502-disk-drive-badge.svg`, `tandy-fd-502-ribbon-cable.svg` | FD-502-labelled artwork adapted from historical FD-series enclosure, cartridge and drive-mechanism references. Cable routes and proportions are illustrative. TANDY contours and outlined hardware lettering retain the credits above. | +| `tandy-virtual-drive-system.svg`, `tandy-virtual-drive-system-badge.svg`, `tandy-virtual-drive-system-controller.svg`, `tandy-virtual-drive-system-ribbon-cable.svg` | Original fictional four-floppy/two-hard-drive equipment derived from the drive/controller illustration family; not a historical Tandy product. | +| `tandy-deluxe-joystick.svg`, `tandy-deluxe-joystick-badge.svg` | Deluxe Joystick case and nameplate illustrations based on historical hardware and packaging references. | +| `tandy-computer-cassette-recorder.svg`, `tandy-computer-cassette-recorder-badge.svg` | CCR-81-inspired case and transport illustrations. The custom TANDY caption adapts historical Radio Shack/TRS-80 and TANDY badge variants. | +| `tandy-color-computer-rom-cartridge.svg`, `tandy-color-computer-rom-cartridge-green.svg`, `tandy-color-computer-rom-cartridge-red.svg`, `tandy-color-computer-rom-cartridge-yellow.svg`, `tandy-color-computer-rom-cartridge-colors.svg` | Shared generic cartridge form with color treatments and original placeholder labels; referenced game-label artwork is not reproduced. | +| `motorola-inside-badge.svg`, `hitachi-inside-badge.svg` | Processor symbols, recoloring and original companion-frame composition, with the public symbol and frame references above. | +| `orchestra-90-label.svg` | Label adaptation referencing the [Tandy Orchestra-90 cartridge label](https://colorcomputerarchive.com/repo/Documents/Manuals/Hardware/Orchestra-90%20Cart%20Label%20%28Tandy%29.gif). The runtime shell and RCA sockets also reference the [CoCopedia hardware entry](https://www.cocopedia.com/wiki/Orchestra-90_CC_%2826-3143%29). | +| `speech-sound-label.svg` | Label/shell adaptation referencing Tandy’s [Speech/Sound Cartridge Service Manual](https://colorcomputerarchive.com/repo/Documents/Manuals/Hardware/Speech-Sound%20Cartridge%20Service%20Manual%20%28Tandy%29.pdf), model 26-3144A. | +| `coco-sdc-label.svg` | Original simplified label arrangement referencing the [Retro Rewind CoCo SDC cartridge photograph](https://retrorewind.ca/image/cachewebp/catalog/Framed%20Products/cocosdc-500x500.webp). The photograph and retailer logo are not embedded. | +| `tandy-thermal-printer-tp-10-badge.svg`, `tandy-tp-10-printer.svg`, `tandy-tp-10-shell.png` | Original TP-10 illustration/nameplate adaptations with a custom TANDY caption. The printer SVG embeds a raster shell illustration losslessly and adds editable vector state overlays. The source PNG is included for regeneration. | +| `manual-help.svg` | Original vector Help-button illustration with outlined lettering. | +| `runtime-system.svg` | Hardware scene composition and runtime state layers derived from the component masters. Component, symbol, typography and screen-glyph notices remain applicable to included elements. | +| `proposal/stacked-system.svg` | Static macOS concept sheet retaining hardware geometry and outlined concept captions. `prepare-hardware.py --author-master` selects its hardware group and removes the authored BASIC screen; it does not copy the outer concept captions into the runtime scene. Ordinary Xcode builds use committed native PDFs. | +| `about/dezota.svg`, `about/dezota-dark.svg`, `about/founder.svg` | About-window brand treatments and founder illustration. Dezota’s marks retain their ownership above. The founder SVG includes embedded raster components. | + +The compiled hardware PDFs, app icon and installer artwork retain the credits +of their source components. The static Software Library shelf illustration in +`platforms/macos/Resources/Hardware/software-library-shelf.png` includes Color +File II, Mega-Bug and Bedlam cover references; those original cover designs +remain with their respective creators, with reference publications curated by +the Color Computer Archive. The shelf is one authored composite illustration, +not a collection of bundled catalog thumbnails. + +The printer shell, founder illustration and shelf demonstrate why the presence +of an SVG or PDF does not imply that every retained artwork asset is purely +vector. No reference photograph is embedded in the hardware reconstructions. diff --git a/docs/media/about/dezota-dark.svg b/docs/media/about/dezota-dark.svg new file mode 100644 index 0000000..de26669 --- /dev/null +++ b/docs/media/about/dezota-dark.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/docs/media/about/dezota.svg b/docs/media/about/dezota.svg new file mode 100644 index 0000000..4d762d0 --- /dev/null +++ b/docs/media/about/dezota.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/docs/media/about/founder.svg b/docs/media/about/founder.svg new file mode 100644 index 0000000..ddd8486 --- /dev/null +++ b/docs/media/about/founder.svg @@ -0,0 +1,403 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/media/coco-sdc-label.svg b/docs/media/coco-sdc-label.svg new file mode 100644 index 0000000..e92e1c4 --- /dev/null +++ b/docs/media/coco-sdc-label.svg @@ -0,0 +1,15 @@ + +CoCo SDC cartridge label +Original outlined label based on the Retro Rewind CoCo SDC cartridge reference. No reference-photograph pixels or font files are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + diff --git a/docs/media/hitachi-inside-badge.svg b/docs/media/hitachi-inside-badge.svg new file mode 100644 index 0000000..41b62b7 --- /dev/null +++ b/docs/media/hitachi-inside-badge.svg @@ -0,0 +1,216 @@ + + + Hitachi inside badge + Compact square Hitachi inside companion badge. The Hitachi symbol appears above lowercase inside lettering on a charcoal panel, with a warm silver chip frame and a subtle circuit border matching the CoCo case badges. + Hitachi symbol reference: https://1000logos.net/hitachi-logo/. Symbol contours and proportions are retained and recolored silver. The frame and layout take inspiration from the 2015–2020 Intel Inside panel illustrated at https://1000logos.net/intel-inside-logo/; the frame and circuit details are original companion-badge artwork. Lowercase inside lettering is outlined from Eurostile. No reference-image pixels or font files are embedded. Third-party marks remain with their respective owners. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Hitachi inside + + + + + Subtle etched circuit border + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Warm silver chip frame + + + + + + + + + + + Hitachi symbol + + + + + inside + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/manual-help.svg b/docs/media/manual-help.svg new file mode 100644 index 0000000..075c0ef --- /dev/null +++ b/docs/media/manual-help.svg @@ -0,0 +1,45 @@ + + VCC Plus domed Help button with raised ivory lettering + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/media/motorola-inside-badge.svg b/docs/media/motorola-inside-badge.svg new file mode 100644 index 0000000..832f6d8 --- /dev/null +++ b/docs/media/motorola-inside-badge.svg @@ -0,0 +1,215 @@ + + + Motorola inside badge + Compact square Motorola inside companion badge. The Motorola symbol appears above lowercase inside lettering on a charcoal panel, with a warm silver chip frame and a subtle circuit border matching the CoCo case badges. + Motorola symbol reference: https://1000logos.net/motorola-logo/. Symbol contours and proportions are retained and recolored silver. The frame and layout take inspiration from the 2015–2020 Intel Inside panel illustrated at https://1000logos.net/intel-inside-logo/; the frame and circuit details are original companion-badge artwork. Lowercase inside lettering is outlined from Eurostile. No reference-image pixels or font files are embedded. Third-party marks remain with their respective owners. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Motorola inside + + + + + Subtle etched circuit border + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Warm silver chip frame + + + + + + + + + + + Motorola symbol + + + + inside + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/orchestra-90-label.svg b/docs/media/orchestra-90-label.svg new file mode 100644 index 0000000..e017ad7 --- /dev/null +++ b/docs/media/orchestra-90-label.svg @@ -0,0 +1,14 @@ + +Orchestra-90 cartridge label +Vector label adapted from historical Tandy cartridge-label references. Eurostile Bold lettering is outlined; no scanned pixels or font files are embedded. See ATTRIBUTION.md. + + + + + + + + + + + diff --git a/docs/media/proposal/stacked-system.svg b/docs/media/proposal/stacked-system.svg new file mode 100644 index 0000000..b249bf8 --- /dev/null +++ b/docs/media/proposal/stacked-system.svg @@ -0,0 +1,5719 @@ + + + Stacked storage, shared connections + Four floppy drives and two hard drives occupy the original storage footprint. + Static macOS interface concept, not an application screenshot. Hardware artwork is adapted from the hardware SVG masters. The proposal collection's recorded interface sources include outlined Apple SF Pro caption lettering and SF Symbols icon outlines; hardware lettering retains its Arial and Eurostile provenance. CoCo screen character shapes derive from src/core/cc2font.h, copyright 2015 Joseph Forgione, GPL-3.0-or-later. The runtime authoring path selects the hardware scene, not the surrounding concept captions. See ../ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Virtual Drive System: four floppy drives and two hard drives + + Low rubber feet + + + + + + + Cream enclosure, three times the FD 502 case height + + + + + + + + + + + Two banks of top ventilation slots + + Front ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Rear ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY VIRTUAL DRIVE SYSTEM + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Four populated floppy drives above two blank hard-drive faces + + + Floppy drive FD3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + FD3 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + FD2 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + FD1 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + FD0 lower-left drive identifier + + + + + + + + + + + + + + + + + Hard drive HD1: black face with one activity LED + + + + + + Single activity LED + + + + + + HD1 lower-left drive identifier + + + + + + + + + + + + + + + + + Hard drive HD0: black face with one activity LED + + + + + + Single activity LED + + + + + + HD0 lower-left drive identifier + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Computer Cassette Recorder, based on the CCR-81 + + Low rubber feet on the same implied tabletop + + + + + Folded light-metal carrying handle beneath the front edge + + + + + + + + + + Rounded cream enclosure + + + + + + + + + + + + + Perforated rear speaker grille + + + + + + Tape counter, recorder badge, indicator and transport labels + + + + + + + + + + + + + + + + + + + + + TANDY COMPUTER CASSETTE RECORDER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Cassette activity LED + + + + + Loaded — green + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Six transport keys, with a red Record key + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Smoked cassette lid with selectable empty and loaded tape bay + + + + + + + + + Loaded labeled cassette beneath the smoked lid + + TANDY data cassette with paper label, two visible reels and a tape window + + Black cassette shell + + + + + + + Replaceable TANDY data cassette label + + + + + TANDY + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tape spools, sprocket hubs and center tape window + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Cassette screws and lower tape-head opening + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Deluxe Joystick + + Low rubber feet resting on the implied tabletop + + + + + Sloped cream plastic housing + + + + + + + + + + + + + + TANDY DELUXE JOYSTICK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Deep recessed joystick well + + + + + + + + + + + + + + + + + + + Red fire button + + + + + + + + + Upright tapered black joystick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Hard drive HD1: black face with one activity LED + + + + + + Single activity LED + + HD1 activity LED + + + Empty — dark grey + + + + + + + + + + HD1 lower-left drive identifier + + + + + + + + + + + + + + + + + + + Hard drive HD0: black face with one activity LED + + + + + + Single activity LED + + HD0 activity LED + + + + Loaded — green + + + + + + + + + HD0 lower-left drive identifier + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Floppy drive FD1 + + + + + + FD1 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD1: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + FD1 lower-left drive identifier + + + + + + + + + + + + + + + + + + + Floppy drive FD0 + + + + + + FD0 activity LED + + + + Loaded — green + + + + + + + + + + + + + + + + + + FD0: empty and unlocked, or loaded and locked + + + Loaded — colored disk edge and vertical locked latch + + Fully seated 5.25-inch disk: only the jacket edge and a small label portion are visible + + + + + Replaceable FD0 label fragment + + + + + + + + + + + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + FD0 lower-left drive identifier + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Floppy drive FD3 + + + + + + FD3 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD3: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + FD3 lower-left drive identifier + + + + + + + + + + + + + + + + + + + Floppy drive FD2 + + + + + + FD2 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD2: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + FD2 lower-left drive identifier + + + + + + + + + + + + + + + + + + Two banks of top ventilation slots + + Front ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Rear ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY DISK DRIVE FD 502 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Multi-Pak Interface, four-slot cartridge expansion interface + + Raised left-side cartridge connector housing + + + + + + + + + + + + + + + + + + + Rubber feet + + + + + + + Inset lower base + + + + + Molded beige Multi-Pak housing + + + + + + + + + + + + + + + + + + + + Four cartridge bays, slot 1 at the front and slot 4 at the rear + + + + + Cartridge slot 1 + + + + + + + + + + + + + + + + + + Cartridge slot 2 + + + + + + + + + + + + + + + + + + Cartridge slot 3 + + + + + + + + + + + + + + + + + + Cartridge slot 4 + + + + + + + + + + + + + + + + + + + Six ventilation slots + + + + + + + + + + + + + + + + + + + + + TANDY / / / MULTI-PAK INTERFACE + + + + + + + + + + + Red green and blue diagonal stripes + + + + + + + + + + + + + + + + + + + + + + + + + + + Four-position program pak selector + + + + Multi-Pak selector — choose one + + + + + Slot 4 + + Selector set to position 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Four independently populated slots, painted rear to front; one drive controller at most + + Slot 4 — choose Empty, ROM or controller + + + + Tandy FD 502 disk controller cartridge + + Male cartridge edge connector, hidden inside the Multi-Pak when installed + + + + + + + + + + + + + + + + + + + + + + + + + + Straight black molded cartridge body seated directly in the slot + + + + + + + + Three rows of ventilation slots + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY COLOR COMPUTER / DISK DRIVE / FD 502 label + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Slot 3 — choose Empty, ROM or controller + + + + Tandy FD 502 disk controller cartridge + + Male cartridge edge connector, hidden inside the Multi-Pak when installed + + + + + + + + + + + + + + + + + + + + + + + + + + Straight black molded cartridge body seated directly in the slot + + + + + + + + Three rows of ventilation slots + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY COLOR COMPUTER / DISK DRIVE / FD 502 label + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Slot 2 — choose Empty, ROM or controller + + + Standard ROM cartridge + + Standard Tandy ROM cartridge with two upper finger-grip notches + + Black molded shell with two finger grips + + + + + + + + + + + + + + + + + + + + + + + Replaceable TANDY ROM cartridge label + + Label wrapped across the upper edge + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY wordmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Recessed insertion arrow pointing toward the connector + + + + + + + + Slot 1 — choose Empty, ROM or controller + + + Standard ROM cartridge + + Standard Tandy ROM cartridge with two upper finger-grip notches + + Black molded shell with two finger grips + + + + + + + + + + + + + + + + + + + + + + + Replaceable TANDY ROM cartridge label + + Label wrapped across the upper edge + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY wordmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Recessed insertion arrow pointing toward the connector + + + + + + + + + Tandy RGB Color Monitor CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + DISK EXTENDED COLOR BASIC 2.1 startup screen + + + + + + + + + + + + + + + + + + + + + + + + + TANDY RGB COLOR MONITOR CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY Color Computer 3 + + + + + + + + + + + + + + + + + + + + + + + + + Five horizontal rows of cooling vents + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY / / / COLOR COMPUTER 3 — selectable RAM + + + + + + + + + + + + + + + + + + + + + + Computer RAM — choose one + + + 512 KB + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Color Computer 3 keyboard — perspective-correct sculpted keycaps + + + + + ! / 1 + + + + + + + + + + + + + + + + + + " / 2 + + + + + + + + + + + + + + + + + + # / 3 + + + + + + + + + + + + + + + + + + $ / 4 + + + + + + + + + + + + + + + + + + % / 5 + + + + + + + + + + + + + + + + + + & / 6 + + + + + + + + + + + + + + + + + + ' / 7 + + + + + + + + + + + + + + + + + + ( / 8 + + + + + + + + + + + + + + + + + + ) / 9 + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + * / : + + + + + + + + + + + + + + + + + + = / - + + + + + + + + + + + + + + + + + + ESC / BREAK + + + + + + + + + + + + + + + + + + + + + + + + ALT + + + + + + + + + + + + + + + + + Q + + + + + + + + + + + + + + + W + + + + + + + + + + + + + + + E + + + + + + + + + + + + + + + R + + + + + + + + + + + + + + + T + + + + + + + + + + + + + + + Y + + + + + + + + + + + + + + + U + + + + + + + + + + + + + + + I + + + + + + + + + + + + + + + O + + + + + + + + + + + + + + + P + + + + + + + + + + + + + + + @ + + + + + + + + + + + + + + + CLEAR + + + + + + + + + + + + + + + + + + + UP + + + + + + + + + + + + + CTRL + + + + + + + + + + + + + + + + + + A + + + + + + + + + + + + + + + S + + + + + + + + + + + + + + + D + + + + + + + + + + + + + + + F + + + + + + + + + + + + + + + G + + + + + + + + + + + + + + + H + + + + + + + + + + + + + + + J + + + + + + + + + + + + + + + K + + + + + + + + + + + + + + + L + + + + + + + + + + + + + + + + / ; + + + + + + + + + + + + + + + + + + ENTER + + + + + + + + + + + + + + + + + + + LEFT + + + + + + + + + + + + + RIGHT + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + Z + + + + + + + + + + + + + + + X + + + + + + + + + + + + + + + C + + + + + + + + + + + + + + + V + + + + + + + + + + + + + + + B + + + + + + + + + + + + + + + N + + + + + + + + + + + + + + + M + + + + + + + + + + + + + + + < / , + + + + + + + + + + + + + + + + + + > / . + + + + + + + + + + + + + + + + + + ? / / + + + + + + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + DOWN + + + + + + + + + + + + + SPACE + + + + + + + + + + + + F1 + + + + + + + + + + + + + + + + F2 + + + + + + + + + + + + + + + + + + Alternative processor badges on the computer case + Both badge layers are enabled for editor import. Motorola is stacked above and covers Hitachi by default. Hide Motorola to reveal Hitachi, or hide the parent layer to remove both. Both use the computer nameplate plane at the far right of the case badge area. + + + Hitachi inside + + + + + Subtle etched circuit border + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Warm silver chip frame + + + + + + + + + + + Hitachi symbol + + + + + inside + + + + + + + + + + + + + + Motorola inside + + + + + Subtle etched circuit border + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Warm silver chip frame + + + + + + + + + + + Motorola symbol + + + + inside + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/runtime-system.svg b/docs/media/runtime-system.svg new file mode 100644 index 0000000..d52297f --- /dev/null +++ b/docs/media/runtime-system.svg @@ -0,0 +1,8502 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Virtual Drive System: four floppy drives and two hard drives + + Low rubber feet + + + + + + + Cream enclosure, three times the FD 502 case height + + + + + + + + + + + Two banks of top ventilation slots + + Front ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Rear ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY VIRTUAL DRIVE SYSTEM + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Four populated floppy drives above two blank hard-drive faces + + + Floppy drive FD3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + FD3 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + FD2 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + FD1 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + FD0 lower-left drive identifier + + + + + + + + + + + + + + + + + Hard drive HD1: black face with one activity LED + + + + + + Single activity LED + + + + + + HD1 lower-left drive identifier + + + + + + + + + + + + + + + + + Hard drive HD0: black face with one activity LED + + + + + + Single activity LED + + + + + + HD0 lower-left drive identifier + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy FD 502 enclosure with two floppy drives + + Low rubber feet + + + + + + + Cream metal drive enclosure + + + + + + + + + + + Two banks of top ventilation slots + + Front ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Rear ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY DISK DRIVE FD 502 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Two populated floppy drive bays + + + Upper floppy disk drive + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Lower floppy disk drive + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Computer Cassette Recorder, based on the CCR-81 + + Low rubber feet on the same implied tabletop + + + + + Folded light-metal carrying handle beneath the front edge + + + + + + + + + + Rounded cream enclosure + + + + + + + + + + + + + Perforated rear speaker grille + + + + + + Tape counter, recorder badge, indicator and transport labels + + + + + + + + + + + + + + + + + + + + + TANDY COMPUTER CASSETTE RECORDER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Cassette activity LED + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Six transport keys, with a red Record key + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Smoked cassette lid with selectable empty and loaded tape bay + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Deluxe Joystick + + Low rubber feet resting on the implied tabletop + + + + + Sloped cream plastic housing + + + + + + + + + + + + + + TANDY DELUXE JOYSTICK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Deep recessed joystick well + + + + + + + + + + + + + + + + + + + Red fire button + + + + + + + + + Upright tapered black joystick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Hard drive HD1: black face with one activity LED + + + + + + Single activity LED + + HD1 activity LED + + + + + + + + + HD1 lower-left drive identifier + + + + + + + + + + + + + + + + + + + Hard drive HD0: black face with one activity LED + + + + + + Single activity LED + + HD0 activity LED + + + + + + + + + HD0 lower-left drive identifier + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Floppy drive FD1 + + + + + + FD1 activity LED + + + + + + + + + + + + + + + + + + FD1: empty and unlocked, or loaded and locked + + + + + + + + + + FD1 lower-left drive identifier + + + + + + + + + + + + + + + + + + + Floppy drive FD0 + + + + + + FD0 activity LED + + + + + + + + + + + + + + + + + + FD0: empty and unlocked, or loaded and locked + + + + + + + + + + FD0 lower-left drive identifier + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Floppy drive FD3 + + + + + + FD3 activity LED + + + + + + + + + + + + + + + + + + FD3: empty and unlocked, or loaded and locked + + + + + + + + + + FD3 lower-left drive identifier + + + + + + + + + + + + + + + + + + + Floppy drive FD2 + + + + + + FD2 activity LED + + + + + + + + + + + + + + + + + + FD2: empty and unlocked, or loaded and locked + + + + + + + + + + FD2 lower-left drive identifier + + + + + + + + + + + + + + + + + + Two banks of top ventilation slots + + Front ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Rear ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY DISK DRIVE FD 502 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Multi-Pak Interface, four-slot cartridge expansion interface + + Raised left-side cartridge connector housing + + + + + + + + + + + + + + + + + + + Rubber feet + + + + + + + Inset lower base + + + + + Molded beige Multi-Pak housing + + + + + + + + + + + + + + + + + + + + Four cartridge bays, slot 1 at the front and slot 4 at the rear + + + + + Cartridge slot 1 + + + + + + + + + + + + + + + + + + Cartridge slot 2 + + + + + + + + + + + + + + + + + + Cartridge slot 3 + + + + + + + + + + + + + + + + + + Cartridge slot 4 + + + + + + + + + + + + + + + + + + + Six ventilation slots + + + + + + + + + + + + + + + + + + + + + TANDY / / / MULTI-PAK INTERFACE + + + + + + + + + + + Red green and blue diagonal stripes + + + + + + + + + + + + + + + + + + + + + + + + + + + Four-position program pak selector + + + + Multi-Pak selector — choose one + + + + + + + + + + + Four independently populated slots, painted rear to front; one drive controller at most + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy RGB Color Monitor CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY RGB COLOR MONITOR CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY Color Computer 3 + + + + + + + + + + + + + + + + + + + + + + + + + Five horizontal rows of cooling vents + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY / / / COLOR COMPUTER 3 — selectable RAM + + + + + + + + + + + + + + + + + + + + + + Computer RAM — choose one + + + + + + + + + + + + + + + + + + + + + + + + + Color Computer 3 keyboard — perspective-correct sculpted keycaps + + + + + ! / 1 + + + + + + + + + + + + + + + + + + " / 2 + + + + + + + + + + + + + + + + + + # / 3 + + + + + + + + + + + + + + + + + + $ / 4 + + + + + + + + + + + + + + + + + + % / 5 + + + + + + + + + + + + + + + + + + & / 6 + + + + + + + + + + + + + + + + + + ' / 7 + + + + + + + + + + + + + + + + + + ( / 8 + + + + + + + + + + + + + + + + + + ) / 9 + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + * / : + + + + + + + + + + + + + + + + + + = / - + + + + + + + + + + + + + + + + + + ESC / BREAK + + + + + + + + + + + + + + + + + + + + + + + + ALT + + + + + + + + + + + + + + + + + Q + + + + + + + + + + + + + + + W + + + + + + + + + + + + + + + E + + + + + + + + + + + + + + + R + + + + + + + + + + + + + + + T + + + + + + + + + + + + + + + Y + + + + + + + + + + + + + + + U + + + + + + + + + + + + + + + I + + + + + + + + + + + + + + + O + + + + + + + + + + + + + + + P + + + + + + + + + + + + + + + @ + + + + + + + + + + + + + + + CLEAR + + + + + + + + + + + + + + + + + + + UP + + + + + + + + + + + + + CTRL + + + + + + + + + + + + + + + + + + A + + + + + + + + + + + + + + + S + + + + + + + + + + + + + + + D + + + + + + + + + + + + + + + F + + + + + + + + + + + + + + + G + + + + + + + + + + + + + + + H + + + + + + + + + + + + + + + J + + + + + + + + + + + + + + + K + + + + + + + + + + + + + + + L + + + + + + + + + + + + + + + + / ; + + + + + + + + + + + + + + + + + + ENTER + + + + + + + + + + + + + + + + + + + LEFT + + + + + + + + + + + + + RIGHT + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + Z + + + + + + + + + + + + + + + X + + + + + + + + + + + + + + + C + + + + + + + + + + + + + + + V + + + + + + + + + + + + + + + B + + + + + + + + + + + + + + + N + + + + + + + + + + + + + + + M + + + + + + + + + + + + + + + < / , + + + + + + + + + + + + + + + + + + > / . + + + + + + + + + + + + + + + + + + ? / / + + + + + + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + DOWN + + + + + + + + + + + + + SPACE + + + + + + + + + + + + F1 + + + + + + + + + + + + + + + + F2 + + + + + + + + + + + + + + + + + + Alternative processor badges on the computer case + Both badge layers are enabled for editor import. Motorola is stacked above and covers Hitachi by default. Hide Motorola to reveal Hitachi, or hide the parent layer to remove both. Both use the computer nameplate plane at the far right of the case badge area. + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/speech-sound-label.svg b/docs/media/speech-sound-label.svg new file mode 100644 index 0000000..7fd07ca --- /dev/null +++ b/docs/media/speech-sound-label.svg @@ -0,0 +1,14 @@ + +Speech/Sound cartridge label +Vector label adapted from historical Tandy cartridge-label references. Eurostile Bold lettering is outlined; no scanned pixels or font files are embedded. See ATTRIBUTION.md. + + + + + + + + + + + diff --git a/docs/media/tandy-128k-color-computer-3-badge.svg b/docs/media/tandy-128k-color-computer-3-badge.svg new file mode 100644 index 0000000..3052c74 --- /dev/null +++ b/docs/media/tandy-128k-color-computer-3-badge.svg @@ -0,0 +1,118 @@ + + + TANDY / / / COLOR COMPUTER 3 badge — selectable RAM + Shared standalone Color Computer 3 case badge with four switchable outlined RAM labels: 128 KB, 512 KB, 2 MB and 8 MB. 128 KB is shown by default. Frame, TANDY wordmark, RGB stripes and model lettering are shared. + Color Computer 3 and CM-8 hardware artwork based on historical hardware references. Component geometry and shared badge artwork are retained across standalone and composite versions. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Computer RAM — choose one + + 128 KB + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-cm-8-monitor.svg b/docs/media/tandy-cm-8-monitor.svg new file mode 100644 index 0000000..5db94b0 --- /dev/null +++ b/docs/media/tandy-cm-8-monitor.svg @@ -0,0 +1,157 @@ + + + Tandy RGB Color Monitor CM-8 + Standalone CM-8 monitor, green BASIC startup screen, pedestal, and matching monitor badge. + Color Computer 3 and CM-8 hardware artwork based on historical hardware references. Component geometry and shared badge artwork are retained across standalone and composite versions. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Arial and Eurostile Bold; no font files are embedded. CoCo screen character shapes derive from ../../src/core/cc2font.h, copyright 2015 Joseph Forgione, GPL-3.0-or-later; see ../../COPYING. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy RGB Color Monitor CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + DISK EXTENDED COLOR BASIC 2.1 startup screen + + + + + + + + + + + + + + + + + + + + + + + + + TANDY RGB COLOR MONITOR CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-color-computer-3-computer.svg b/docs/media/tandy-color-computer-3-computer.svg new file mode 100644 index 0000000..5bfe657 --- /dev/null +++ b/docs/media/tandy-color-computer-3-computer.svg @@ -0,0 +1,1248 @@ + + + Tandy Color Computer 3 + Standalone Color Computer 3, with the existing perspective keyboard and matching 128 K case badge. + Color Computer 3 and CM-8 hardware artwork based on historical hardware references. Component geometry and shared badge artwork are retained across standalone and composite versions. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Arial and Eurostile Bold; no font files are embedded. CoCo screen character shapes derive from ../../src/core/cc2font.h, copyright 2015 Joseph Forgione, GPL-3.0-or-later; see ../../COPYING. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY Color Computer 3 + + + + + + + + + + + + + + + + + + + + + + + + + Five horizontal rows of cooling vents + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY / / / COLOR COMPUTER 3 — selectable RAM + + + + + + + + + + + + + + + + + + + + + + Computer RAM — choose one + + 128 KB + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Color Computer 3 keyboard — perspective-correct sculpted keycaps + + + + + ! / 1 + + + + + + + + + + + + + + + + + + " / 2 + + + + + + + + + + + + + + + + + + # / 3 + + + + + + + + + + + + + + + + + + $ / 4 + + + + + + + + + + + + + + + + + + % / 5 + + + + + + + + + + + + + + + + + + & / 6 + + + + + + + + + + + + + + + + + + ' / 7 + + + + + + + + + + + + + + + + + + ( / 8 + + + + + + + + + + + + + + + + + + ) / 9 + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + * / : + + + + + + + + + + + + + + + + + + = / - + + + + + + + + + + + + + + + + + + ESC / BREAK + + + + + + + + + + + + + + + + + + + + + + + + ALT + + + + + + + + + + + + + + + + + Q + + + + + + + + + + + + + + + W + + + + + + + + + + + + + + + E + + + + + + + + + + + + + + + R + + + + + + + + + + + + + + + T + + + + + + + + + + + + + + + Y + + + + + + + + + + + + + + + U + + + + + + + + + + + + + + + I + + + + + + + + + + + + + + + O + + + + + + + + + + + + + + + P + + + + + + + + + + + + + + + @ + + + + + + + + + + + + + + + CLEAR + + + + + + + + + + + + + + + + + + + UP + + + + + + + + + + + + + CTRL + + + + + + + + + + + + + + + + + + A + + + + + + + + + + + + + + + S + + + + + + + + + + + + + + + D + + + + + + + + + + + + + + + F + + + + + + + + + + + + + + + G + + + + + + + + + + + + + + + H + + + + + + + + + + + + + + + J + + + + + + + + + + + + + + + K + + + + + + + + + + + + + + + L + + + + + + + + + + + + + + + + / ; + + + + + + + + + + + + + + + + + + ENTER + + + + + + + + + + + + + + + + + + + LEFT + + + + + + + + + + + + + RIGHT + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + Z + + + + + + + + + + + + + + + X + + + + + + + + + + + + + + + C + + + + + + + + + + + + + + + V + + + + + + + + + + + + + + + B + + + + + + + + + + + + + + + N + + + + + + + + + + + + + + + M + + + + + + + + + + + + + + + < / , + + + + + + + + + + + + + + + + + + > / . + + + + + + + + + + + + + + + + + + ? / / + + + + + + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + DOWN + + + + + + + + + + + + + SPACE + + + + + + + + + + + + F1 + + + + + + + + + + + + + + + + F2 + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-color-computer-3-full-system.svg b/docs/media/tandy-color-computer-3-full-system.svg new file mode 100644 index 0000000..fb1e1fb --- /dev/null +++ b/docs/media/tandy-color-computer-3-full-system.svg @@ -0,0 +1,5902 @@ + + + Tandy Color Computer 3 complete system with cassette recorder, Deluxe Joystick, CM-8 monitor, Multi-Pak Interface and FD 502 + Full Tandy Color Computer system with independently selectable Empty, standard ROM cartridge, or FD 502 controller in each Multi-Pak slot. Controller and its slot-specific ribbon route toggle together. Rear slot 4 contains the controller by default, with slots 1–3 empty. ROM cartridges have a recessed wraparound label, notched upper finger grips on both sides, and an insertion arrow. The existing equipment, RAM, processor, activity-light and selector alternatives are preserved. + Color Computer 3 and CM-8 hardware artwork based on historical hardware references. Component geometry and shared badge artwork are retained across standalone and composite versions. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Arial and Eurostile Bold; no font files are embedded. CoCo screen character shapes derive from ../../src/core/cc2font.h, copyright 2015 Joseph Forgione, GPL-3.0-or-later; see ../../COPYING. Additional public symbol references: https://1000logos.net/hitachi-logo/; https://1000logos.net/motorola-logo/. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy FD 502 enclosure with two floppy drives + + Low rubber feet + + + + + + + Cream metal drive enclosure + + + + + + + + + + + Two banks of top ventilation slots + + Front ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Rear ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY DISK DRIVE FD 502 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Two populated floppy drive bays + + + Upper floppy disk drive + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Lower floppy disk drive + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Computer Cassette Recorder, based on the CCR-81 + + Low rubber feet on the same implied tabletop + + + + + Folded light-metal carrying handle beneath the front edge + + + + + + + + + + Rounded cream enclosure + + + + + + + + + + + + + Perforated rear speaker grille + + + + + + Tape counter, recorder badge, indicator and transport labels + + + + + + + + + + + + + + + + + + + + + TANDY COMPUTER CASSETTE RECORDER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Cassette activity LED + + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Six transport keys, with a red Record key + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Smoked cassette lid with selectable empty and loaded tape bay + + + + + + + + Empty cassette bay + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Deluxe Joystick + + Low rubber feet resting on the implied tabletop + + + + + Sloped cream plastic housing + + + + + + + + + + + + + + TANDY DELUXE JOYSTICK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Deep recessed joystick well + + + + + + + + + + + + + + + + + + + Red fire button + + + + + + + + + Upright tapered black joystick + + + + + + + + + + + + + + + + + Tandy FD 502 enclosure with two floppy drives + + Low rubber feet + + + + + + + Cream metal drive enclosure + + + + + + + + + + + Two banks of top ventilation slots + + Front ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Rear ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY DISK DRIVE FD 502 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Two populated floppy drive bays + + + Upper floppy disk drive + + + + + + FD1 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD1: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + + Lower floppy disk drive + + + + + + FD0 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD0: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + + + + + + Tandy Multi-Pak Interface, four-slot cartridge expansion interface + + Raised left-side cartridge connector housing + + + + + + + + + + + + + + + + + + + Rubber feet + + + + + + + Inset lower base + + + + + Molded beige Multi-Pak housing + + + + + + + + + + + + + + + + + + + + Four cartridge bays, slot 1 at the front and slot 4 at the rear + + + + + Cartridge slot 1 + + + + + + + + + + + + + + + + + + Cartridge slot 2 + + + + + + + + + + + + + + + + + + Cartridge slot 3 + + + + + + + + + + + + + + + + + + Cartridge slot 4 + + + + + + + + + + + + + + + + + + + Six ventilation slots + + + + + + + + + + + + + + + + + + + + + TANDY / / / MULTI-PAK INTERFACE + + + + + + + + + + + Red green and blue diagonal stripes + + + + + + + + + + + + + + + + + + + + + + + + + + + Four-position program pak selector + + + + Multi-Pak selector — choose one + + + Slot 2 + + Selector set to position 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Four independently populated slots, painted rear to front; one drive controller at most + + Slot 4 — choose Empty, ROM or controller + + + + FD 502 controller + matching ribbon + + Ribbon route for slot 4 + + Gray ribbon cable with a red edge stripe, leading to the rear of the FD 502 enclosure + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Drive-end ribbon connector + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy FD 502 disk controller cartridge + + Male cartridge edge connector, hidden inside the Multi-Pak when installed + + + + + + + + + + + + + + + + + + + + + + + + + + Straight black molded cartridge body seated directly in the slot + + + + + + + + Three rows of ventilation slots + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY COLOR COMPUTER / DISK DRIVE / FD 502 label + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Slot 3 — choose Empty, ROM or controller + + Empty + + + + + + Slot 2 — choose Empty, ROM or controller + + Empty + + + + + + Slot 1 — choose Empty, ROM or controller + + Empty + + + + + + + Tandy RGB Color Monitor CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + DISK EXTENDED COLOR BASIC 2.1 startup screen + + + + + + + + + + + + + + + + + + + + + + + + + TANDY RGB COLOR MONITOR CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY Color Computer 3 + + + + + + + + + + + + + + + + + + + + + + + + + Five horizontal rows of cooling vents + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY / / / COLOR COMPUTER 3 — selectable RAM + + + + + + + + + + + + + + + + + + + + + + Computer RAM — choose one + + 128 KB + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Color Computer 3 keyboard — perspective-correct sculpted keycaps + + + + + ! / 1 + + + + + + + + + + + + + + + + + + " / 2 + + + + + + + + + + + + + + + + + + # / 3 + + + + + + + + + + + + + + + + + + $ / 4 + + + + + + + + + + + + + + + + + + % / 5 + + + + + + + + + + + + + + + + + + & / 6 + + + + + + + + + + + + + + + + + + ' / 7 + + + + + + + + + + + + + + + + + + ( / 8 + + + + + + + + + + + + + + + + + + ) / 9 + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + * / : + + + + + + + + + + + + + + + + + + = / - + + + + + + + + + + + + + + + + + + ESC / BREAK + + + + + + + + + + + + + + + + + + + + + + + + ALT + + + + + + + + + + + + + + + + + Q + + + + + + + + + + + + + + + W + + + + + + + + + + + + + + + E + + + + + + + + + + + + + + + R + + + + + + + + + + + + + + + T + + + + + + + + + + + + + + + Y + + + + + + + + + + + + + + + U + + + + + + + + + + + + + + + I + + + + + + + + + + + + + + + O + + + + + + + + + + + + + + + P + + + + + + + + + + + + + + + @ + + + + + + + + + + + + + + + CLEAR + + + + + + + + + + + + + + + + + + + UP + + + + + + + + + + + + + CTRL + + + + + + + + + + + + + + + + + + A + + + + + + + + + + + + + + + S + + + + + + + + + + + + + + + D + + + + + + + + + + + + + + + F + + + + + + + + + + + + + + + G + + + + + + + + + + + + + + + H + + + + + + + + + + + + + + + J + + + + + + + + + + + + + + + K + + + + + + + + + + + + + + + L + + + + + + + + + + + + + + + + / ; + + + + + + + + + + + + + + + + + + ENTER + + + + + + + + + + + + + + + + + + + LEFT + + + + + + + + + + + + + RIGHT + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + Z + + + + + + + + + + + + + + + X + + + + + + + + + + + + + + + C + + + + + + + + + + + + + + + V + + + + + + + + + + + + + + + B + + + + + + + + + + + + + + + N + + + + + + + + + + + + + + + M + + + + + + + + + + + + + + + < / , + + + + + + + + + + + + + + + + + + > / . + + + + + + + + + + + + + + + + + + ? / / + + + + + + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + DOWN + + + + + + + + + + + + + SPACE + + + + + + + + + + + + F1 + + + + + + + + + + + + + + + + F2 + + + + + + + + + + + + + + + + + + Alternative processor badges on the computer case + Both badge layers are enabled for editor import. Motorola is stacked above and covers Hitachi by default. Hide Motorola to reveal Hitachi, or hide the parent layer to remove both. Both use the computer nameplate plane at the far right of the case badge area. + + + Hitachi inside + + + + + Subtle etched circuit border + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Warm silver chip frame + + + + + + + + + + + Hitachi symbol + + + + + inside + + + + + + + + + + + + + + Motorola inside + + + + + Subtle etched circuit border + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Warm silver chip frame + + + + + + + + + + + Motorola symbol + + + + inside + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-color-computer-3-system.svg b/docs/media/tandy-color-computer-3-system.svg new file mode 100644 index 0000000..03b31d2 --- /dev/null +++ b/docs/media/tandy-color-computer-3-system.svg @@ -0,0 +1,1851 @@ + + + Tandy Color Computer 3, CM-8 monitor and Multi-Pak Interface + Complete system with the original computer and monitor and the Multi-Pak connected closely on the right, with the rear edges aligned and approximate relative scale based on the manual. + Color Computer 3 and CM-8 hardware artwork based on historical hardware references. Component geometry and shared badge artwork are retained across standalone and composite versions. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Arial and Eurostile Bold; no font files are embedded. CoCo screen character shapes derive from ../../src/core/cc2font.h, copyright 2015 Joseph Forgione, GPL-3.0-or-later; see ../../COPYING. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Multi-Pak Interface, four-slot cartridge expansion interface + + Raised left-side cartridge connector housing + + + + + + + + + + + + + + + + + + + Rubber feet + + + + + + + Inset lower base + + + + + Molded beige Multi-Pak housing + + + + + + + + + + + + + + + + + + + + Four cartridge bays, slot 1 at the front and slot 4 at the rear + + + + + Cartridge slot 1 + + + + + + + + + + + + + + + + + + Cartridge slot 2 + + + + + + + + + + + + + + + + + + Cartridge slot 3 + + + + + + + + + + + + + + + + + + Cartridge slot 4 + + + + + + + + + + + + + + + + + + + Six ventilation slots + + + + + + + + + + + + + + + + + + + + + TANDY / / / MULTI-PAK INTERFACE + + + + + + + + + + + Red green and blue diagonal stripes + + + + + + + + + + + + + + + + + + + + + + + + + + + Four-position program pak selector + + + + Multi-Pak selector — choose one + + + Slot 2 + + Selector set to position 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy RGB Color Monitor CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + DISK EXTENDED COLOR BASIC 2.1 startup screen + + + + + + + + + + + + + + + + + + + + + + + + + TANDY RGB COLOR MONITOR CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY Color Computer 3 + + + + + + + + + + + + + + + + + + + + + + + + + Five horizontal rows of cooling vents + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY / / / COLOR COMPUTER 3 — selectable RAM + + + + + + + + + + + + + + + + + + + + + + Computer RAM — choose one + + 128 KB + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Color Computer 3 keyboard — perspective-correct sculpted keycaps + + + + + ! / 1 + + + + + + + + + + + + + + + + + + " / 2 + + + + + + + + + + + + + + + + + + # / 3 + + + + + + + + + + + + + + + + + + $ / 4 + + + + + + + + + + + + + + + + + + % / 5 + + + + + + + + + + + + + + + + + + & / 6 + + + + + + + + + + + + + + + + + + ' / 7 + + + + + + + + + + + + + + + + + + ( / 8 + + + + + + + + + + + + + + + + + + ) / 9 + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + * / : + + + + + + + + + + + + + + + + + + = / - + + + + + + + + + + + + + + + + + + ESC / BREAK + + + + + + + + + + + + + + + + + + + + + + + + ALT + + + + + + + + + + + + + + + + + Q + + + + + + + + + + + + + + + W + + + + + + + + + + + + + + + E + + + + + + + + + + + + + + + R + + + + + + + + + + + + + + + T + + + + + + + + + + + + + + + Y + + + + + + + + + + + + + + + U + + + + + + + + + + + + + + + I + + + + + + + + + + + + + + + O + + + + + + + + + + + + + + + P + + + + + + + + + + + + + + + @ + + + + + + + + + + + + + + + CLEAR + + + + + + + + + + + + + + + + + + + UP + + + + + + + + + + + + + CTRL + + + + + + + + + + + + + + + + + + A + + + + + + + + + + + + + + + S + + + + + + + + + + + + + + + D + + + + + + + + + + + + + + + F + + + + + + + + + + + + + + + G + + + + + + + + + + + + + + + H + + + + + + + + + + + + + + + J + + + + + + + + + + + + + + + K + + + + + + + + + + + + + + + L + + + + + + + + + + + + + + + + / ; + + + + + + + + + + + + + + + + + + ENTER + + + + + + + + + + + + + + + + + + + LEFT + + + + + + + + + + + + + RIGHT + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + Z + + + + + + + + + + + + + + + X + + + + + + + + + + + + + + + C + + + + + + + + + + + + + + + V + + + + + + + + + + + + + + + B + + + + + + + + + + + + + + + N + + + + + + + + + + + + + + + M + + + + + + + + + + + + + + + < / , + + + + + + + + + + + + + + + + + + > / . + + + + + + + + + + + + + + + + + + ? / / + + + + + + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + DOWN + + + + + + + + + + + + + SPACE + + + + + + + + + + + + F1 + + + + + + + + + + + + + + + + F2 + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-color-computer-3-virtual-system.svg b/docs/media/tandy-color-computer-3-virtual-system.svg new file mode 100644 index 0000000..6cccc77 --- /dev/null +++ b/docs/media/tandy-color-computer-3-virtual-system.svg @@ -0,0 +1,6390 @@ + + + Tandy Color Computer 3 virtual system with four floppy drives and two hard drives + Full Tandy Color Computer system with independently selectable Empty, standard ROM cartridge, or Virtual Drive System controller in each Multi-Pak slot. Controller and its slot-specific ribbon route toggle together. Slots 1–3 show blue, green and red ROM cartridges by default; rear slot 4 contains the Virtual Drive System controller and its ribbon cable. ROM cartridges have a recessed wraparound label, notched upper finger grips on both sides, and an insertion arrow. The existing equipment, RAM, processor, activity-light and selector alternatives are preserved. The cassette and FD0 are loaded by default, with green indicators and FD0 locked by its vertical latch. The other floppy bays remain empty. + Fictional Virtual Drive System artwork, not a historical Tandy product. The enclosure, controller and ribbon derive from the FD-series hardware illustrations; four floppy bays sit above two hard-disk bays. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. CoCo screen character shapes derive from ../../src/core/cc2font.h, copyright 2015 Joseph Forgione, GPL-3.0-or-later; see ../../COPYING. Additional public symbol references: https://1000logos.net/hitachi-logo/; https://1000logos.net/motorola-logo/. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Virtual Drive System: four floppy drives and two hard drives + + Low rubber feet + + + + + + + Cream enclosure, three times the FD 502 case height + + + + + + + + + + + Two banks of top ventilation slots + + Front ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Rear ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY VIRTUAL DRIVE SYSTEM + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Four populated floppy drives above two blank hard-drive faces + + + Floppy drive FD3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + FD3 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + FD2 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + FD1 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + FD0 lower-left drive identifier + + + + + + + + + + + + + + + + + Hard drive HD1: black face with one activity LED + + + + + + Single activity LED + + + + + + HD1 lower-left drive identifier + + + + + + + + + + + + + + + + + Hard drive HD0: black face with one activity LED + + + + + + Single activity LED + + + + + + HD0 lower-left drive identifier + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Computer Cassette Recorder, based on the CCR-81 + + Low rubber feet on the same implied tabletop + + + + + Folded light-metal carrying handle beneath the front edge + + + + + + + + + + Rounded cream enclosure + + + + + + + + + + + + + Perforated rear speaker grille + + + + + + Tape counter, recorder badge, indicator and transport labels + + + + + + + + + + + + + + + + + + + + + TANDY COMPUTER CASSETTE RECORDER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Cassette activity LED + + + + + Loaded — green + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Six transport keys, with a red Record key + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Smoked cassette lid with selectable empty and loaded tape bay + + + + + + + + + Loaded labeled cassette beneath the smoked lid + + TANDY data cassette with paper label, two visible reels and a tape window + + Black cassette shell + + + + + + + Replaceable TANDY data cassette label + + + + + TANDY + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tape spools, sprocket hubs and center tape window + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Cassette screws and lower tape-head opening + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Deluxe Joystick + + Low rubber feet resting on the implied tabletop + + + + + Sloped cream plastic housing + + + + + + + + + + + + + + TANDY DELUXE JOYSTICK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Deep recessed joystick well + + + + + + + + + + + + + + + + + + + Red fire button + + + + + + + + + Upright tapered black joystick + + + + + + + + + + + + + + + + + Tandy Virtual Drive System: four floppy drives and two hard drives + + Low rubber feet + + + + + + + Cream enclosure, three times the FD 502 case height + + + + + + + + + + + Two banks of top ventilation slots + + Front ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Rear ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY VIRTUAL DRIVE SYSTEM + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Four populated floppy drives above two blank hard-drive faces + + + Floppy drive FD3 + + + + + + FD3 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD3: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + FD3 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD2 + + + + + + FD2 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD2: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + FD2 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD1 + + + + + + FD1 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD1: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + FD1 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD0 + + + + + + FD0 activity LED + + + + Loaded — green + + + + + + + + + + + + + + + + + + FD0: empty and unlocked, or loaded and locked + + + Loaded — colored disk edge and vertical locked latch + + Fully seated 5.25-inch disk: only the jacket edge and a small label portion are visible + + + + + Replaceable FD0 label fragment + + + + + + + + + + + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + FD0 lower-left drive identifier + + + + + + + + + + + + + + + + + Hard drive HD1: black face with one activity LED + + + + + + Single activity LED + + HD1 activity LED + + + Empty — dark grey + + + + + + + + + + HD1 lower-left drive identifier + + + + + + + + + + + + + + + + + Hard drive HD0: black face with one activity LED + + + + + + Single activity LED + + HD0 activity LED + + + Empty — dark grey + + + + + + + + + + HD0 lower-left drive identifier + + + + + + + + + + + + + + + + + + + + + Tandy Multi-Pak Interface, four-slot cartridge expansion interface + + Raised left-side cartridge connector housing + + + + + + + + + + + + + + + + + + + Rubber feet + + + + + + + Inset lower base + + + + + Molded beige Multi-Pak housing + + + + + + + + + + + + + + + + + + + + Four cartridge bays, slot 1 at the front and slot 4 at the rear + + + + + Cartridge slot 1 + + + + + + + + + + + + + + + + + + Cartridge slot 2 + + + + + + + + + + + + + + + + + + Cartridge slot 3 + + + + + + + + + + + + + + + + + + Cartridge slot 4 + + + + + + + + + + + + + + + + + + + Six ventilation slots + + + + + + + + + + + + + + + + + + + + + TANDY / / / MULTI-PAK INTERFACE + + + + + + + + + + + Red green and blue diagonal stripes + + + + + + + + + + + + + + + + + + + + + + + + + + + Four-position program pak selector + + + + Multi-Pak selector — choose one + + + Slot 2 + + Selector set to position 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Four independently populated slots, painted rear to front; one drive controller at most + + Slot 4 — choose Empty, ROM or controller + + + + Virtual Drive System controller + matching ribbon + + Ribbon route for slot 4 + + Virtual Drive System ribbon cable, routed to the rear of the tall enclosure + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Drive-end ribbon connector + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Virtual Drive System controller cartridge + + Male cartridge edge connector, hidden inside the Multi-Pak when installed + + + + + + + + + + + + + + + + + + + + + + + + + + Straight black molded cartridge body seated directly in the slot + + + + + + + + Three rows of ventilation slots + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY VIRTUAL DRIVE SYSTEM + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Slot 3 — choose Empty, ROM or controller + + + Standard ROM cartridge + + Standard Tandy ROM cartridge with two upper finger-grip notches + + Black molded shell with two finger grips + + + + + + + + + + + + + + + + + + + + + + + Replaceable TANDY ROM cartridge label + + Label wrapped across the upper edge + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY wordmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Recessed insertion arrow pointing toward the connector + + + + + + + + + Slot 2 — choose Empty, ROM or controller + + + Standard ROM cartridge + + Standard Tandy ROM cartridge with two upper finger-grip notches + + Black molded shell with two finger grips + + + + + + + + + + + + + + + + + + + + + + + Replaceable TANDY ROM cartridge label + + Label wrapped across the upper edge + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY wordmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Recessed insertion arrow pointing toward the connector + + + + + + + + + Slot 1 — choose Empty, ROM or controller + + + Standard ROM cartridge + + Standard Tandy ROM cartridge with two upper finger-grip notches + + Black molded shell with two finger grips + + + + + + + + + + + + + + + + + + + + + + + Replaceable TANDY ROM cartridge label + + Label wrapped across the upper edge + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY wordmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Recessed insertion arrow pointing toward the connector + + + + + + + + + + Tandy RGB Color Monitor CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + DISK EXTENDED COLOR BASIC 2.1 startup screen + + + + + + + + + + + + + + + + + + + + + + + + + TANDY RGB COLOR MONITOR CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY Color Computer 3 + + + + + + + + + + + + + + + + + + + + + + + + + Five horizontal rows of cooling vents + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY / / / COLOR COMPUTER 3 — selectable RAM + + + + + + + + + + + + + + + + + + + + + + Computer RAM — choose one + + 128 KB + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Color Computer 3 keyboard — perspective-correct sculpted keycaps + + + + + ! / 1 + + + + + + + + + + + + + + + + + + " / 2 + + + + + + + + + + + + + + + + + + # / 3 + + + + + + + + + + + + + + + + + + $ / 4 + + + + + + + + + + + + + + + + + + % / 5 + + + + + + + + + + + + + + + + + + & / 6 + + + + + + + + + + + + + + + + + + ' / 7 + + + + + + + + + + + + + + + + + + ( / 8 + + + + + + + + + + + + + + + + + + ) / 9 + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + * / : + + + + + + + + + + + + + + + + + + = / - + + + + + + + + + + + + + + + + + + ESC / BREAK + + + + + + + + + + + + + + + + + + + + + + + + ALT + + + + + + + + + + + + + + + + + Q + + + + + + + + + + + + + + + W + + + + + + + + + + + + + + + E + + + + + + + + + + + + + + + R + + + + + + + + + + + + + + + T + + + + + + + + + + + + + + + Y + + + + + + + + + + + + + + + U + + + + + + + + + + + + + + + I + + + + + + + + + + + + + + + O + + + + + + + + + + + + + + + P + + + + + + + + + + + + + + + @ + + + + + + + + + + + + + + + CLEAR + + + + + + + + + + + + + + + + + + + UP + + + + + + + + + + + + + CTRL + + + + + + + + + + + + + + + + + + A + + + + + + + + + + + + + + + S + + + + + + + + + + + + + + + D + + + + + + + + + + + + + + + F + + + + + + + + + + + + + + + G + + + + + + + + + + + + + + + H + + + + + + + + + + + + + + + J + + + + + + + + + + + + + + + K + + + + + + + + + + + + + + + L + + + + + + + + + + + + + + + + / ; + + + + + + + + + + + + + + + + + + ENTER + + + + + + + + + + + + + + + + + + + LEFT + + + + + + + + + + + + + RIGHT + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + Z + + + + + + + + + + + + + + + X + + + + + + + + + + + + + + + C + + + + + + + + + + + + + + + V + + + + + + + + + + + + + + + B + + + + + + + + + + + + + + + N + + + + + + + + + + + + + + + M + + + + + + + + + + + + + + + < / , + + + + + + + + + + + + + + + + + + > / . + + + + + + + + + + + + + + + + + + ? / / + + + + + + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + DOWN + + + + + + + + + + + + + SPACE + + + + + + + + + + + + F1 + + + + + + + + + + + + + + + + F2 + + + + + + + + + + + + + + + + + + Alternative processor badges on the computer case + Both badge layers are enabled for editor import. Motorola is stacked above and covers Hitachi by default. Hide Motorola to reveal Hitachi, or hide the parent layer to remove both. Both use the computer nameplate plane at the far right of the case badge area. + + + Hitachi inside + + + + + Subtle etched circuit border + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Warm silver chip frame + + + + + + + + + + + Hitachi symbol + + + + + inside + + + + + + + + + + + + + + Motorola inside + + + + + Subtle etched circuit border + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Warm silver chip frame + + + + + + + + + + + Motorola symbol + + + + inside + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-color-computer-3-with-drive.svg b/docs/media/tandy-color-computer-3-with-drive.svg new file mode 100644 index 0000000..1c12852 --- /dev/null +++ b/docs/media/tandy-color-computer-3-with-drive.svg @@ -0,0 +1,1940 @@ + + + Tandy Color Computer 3, CM-8 monitor and FD 502 disk drive + Computer and monitor, with the vented dual-drive FD 502 enclosure spaced on the right. The FD 502 shares the equipment perspective, with its front aligned to the CoCo front and its support pads resting on the same implied tabletop. It has two continuous disk insertion slots. Transparent background. + Color Computer 3 and CM-8 hardware artwork based on historical hardware references. Component geometry and shared badge artwork are retained across standalone and composite versions. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Arial and Eurostile Bold; no font files are embedded. CoCo screen character shapes derive from ../../src/core/cc2font.h, copyright 2015 Joseph Forgione, GPL-3.0-or-later; see ../../COPYING. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy FD 502 enclosure with two floppy drives + + Low rubber feet + + + + + + + Cream metal drive enclosure + + + + + + + + + + + Two banks of top ventilation slots + + Front ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Rear ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY DISK DRIVE FD 502 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Two populated floppy drive bays + + + Upper floppy disk drive + + + + + + FD1 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD1: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + + Lower floppy disk drive + + + + + + FD0 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD0: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + + + + + Tandy RGB Color Monitor CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + DISK EXTENDED COLOR BASIC 2.1 startup screen + + + + + + + + + + + + + + + + + + + + + + + + + TANDY RGB COLOR MONITOR CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY Color Computer 3 + + + + + + + + + + + + + + + + + + + + + + + + + Five horizontal rows of cooling vents + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY / / / COLOR COMPUTER 3 — selectable RAM + + + + + + + + + + + + + + + + + + + + + + Computer RAM — choose one + + 128 KB + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Color Computer 3 keyboard — perspective-correct sculpted keycaps + + + + + ! / 1 + + + + + + + + + + + + + + + + + + " / 2 + + + + + + + + + + + + + + + + + + # / 3 + + + + + + + + + + + + + + + + + + $ / 4 + + + + + + + + + + + + + + + + + + % / 5 + + + + + + + + + + + + + + + + + + & / 6 + + + + + + + + + + + + + + + + + + ' / 7 + + + + + + + + + + + + + + + + + + ( / 8 + + + + + + + + + + + + + + + + + + ) / 9 + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + * / : + + + + + + + + + + + + + + + + + + = / - + + + + + + + + + + + + + + + + + + ESC / BREAK + + + + + + + + + + + + + + + + + + + + + + + + ALT + + + + + + + + + + + + + + + + + Q + + + + + + + + + + + + + + + W + + + + + + + + + + + + + + + E + + + + + + + + + + + + + + + R + + + + + + + + + + + + + + + T + + + + + + + + + + + + + + + Y + + + + + + + + + + + + + + + U + + + + + + + + + + + + + + + I + + + + + + + + + + + + + + + O + + + + + + + + + + + + + + + P + + + + + + + + + + + + + + + @ + + + + + + + + + + + + + + + CLEAR + + + + + + + + + + + + + + + + + + + UP + + + + + + + + + + + + + CTRL + + + + + + + + + + + + + + + + + + A + + + + + + + + + + + + + + + S + + + + + + + + + + + + + + + D + + + + + + + + + + + + + + + F + + + + + + + + + + + + + + + G + + + + + + + + + + + + + + + H + + + + + + + + + + + + + + + J + + + + + + + + + + + + + + + K + + + + + + + + + + + + + + + L + + + + + + + + + + + + + + + + / ; + + + + + + + + + + + + + + + + + + ENTER + + + + + + + + + + + + + + + + + + + LEFT + + + + + + + + + + + + + RIGHT + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + Z + + + + + + + + + + + + + + + X + + + + + + + + + + + + + + + C + + + + + + + + + + + + + + + V + + + + + + + + + + + + + + + B + + + + + + + + + + + + + + + N + + + + + + + + + + + + + + + M + + + + + + + + + + + + + + + < / , + + + + + + + + + + + + + + + + + + > / . + + + + + + + + + + + + + + + + + + ? / / + + + + + + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + DOWN + + + + + + + + + + + + + SPACE + + + + + + + + + + + + F1 + + + + + + + + + + + + + + + + F2 + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-color-computer-3.svg b/docs/media/tandy-color-computer-3.svg new file mode 100644 index 0000000..bb8c6d4 --- /dev/null +++ b/docs/media/tandy-color-computer-3.svg @@ -0,0 +1,1397 @@ + + + Tandy Color Computer 3 with Tandy RGB Color Monitor CM-8 + Color Computer 3 and CM-8 monitor illustration based on historical hardware references. Beige Color Computer 3, individually sculpted keys, RGB-striped TANDY / / / COLOR COMPUTER 3 badge, CM-8 monitor with TANDY RGB COLOR MONITOR CM-8 badge, green BASIC startup screen. Transparent background. All visible artwork and lettering are vector paths and shapes; no raster images or external fonts. + Color Computer 3 and CM-8 hardware artwork based on historical hardware references. Component geometry and shared badge artwork are retained across standalone and composite versions. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Arial and Eurostile Bold; no font files are embedded. CoCo screen character shapes derive from ../../src/core/cc2font.h, copyright 2015 Joseph Forgione, GPL-3.0-or-later; see ../../COPYING. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy RGB Color Monitor CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + DISK EXTENDED COLOR BASIC 2.1 startup screen + + + + + + + + + + + + + + + + + + + + + + + + + TANDY RGB COLOR MONITOR CM-8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY Color Computer 3 + + + + + + + + + + + + + + + + + + + + + + + + + Five horizontal rows of cooling vents + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY / / / COLOR COMPUTER 3 — selectable RAM + + + + + + + + + + + + + + + + + + + + + + Computer RAM — choose one + + 128 KB + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Color Computer 3 keyboard — perspective-correct sculpted keycaps + + + + + ! / 1 + + + + + + + + + + + + + + + + + + " / 2 + + + + + + + + + + + + + + + + + + # / 3 + + + + + + + + + + + + + + + + + + $ / 4 + + + + + + + + + + + + + + + + + + % / 5 + + + + + + + + + + + + + + + + + + & / 6 + + + + + + + + + + + + + + + + + + ' / 7 + + + + + + + + + + + + + + + + + + ( / 8 + + + + + + + + + + + + + + + + + + ) / 9 + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + * / : + + + + + + + + + + + + + + + + + + = / - + + + + + + + + + + + + + + + + + + ESC / BREAK + + + + + + + + + + + + + + + + + + + + + + + + ALT + + + + + + + + + + + + + + + + + Q + + + + + + + + + + + + + + + W + + + + + + + + + + + + + + + E + + + + + + + + + + + + + + + R + + + + + + + + + + + + + + + T + + + + + + + + + + + + + + + Y + + + + + + + + + + + + + + + U + + + + + + + + + + + + + + + I + + + + + + + + + + + + + + + O + + + + + + + + + + + + + + + P + + + + + + + + + + + + + + + @ + + + + + + + + + + + + + + + CLEAR + + + + + + + + + + + + + + + + + + + UP + + + + + + + + + + + + + CTRL + + + + + + + + + + + + + + + + + + A + + + + + + + + + + + + + + + S + + + + + + + + + + + + + + + D + + + + + + + + + + + + + + + F + + + + + + + + + + + + + + + G + + + + + + + + + + + + + + + H + + + + + + + + + + + + + + + J + + + + + + + + + + + + + + + K + + + + + + + + + + + + + + + L + + + + + + + + + + + + + + + + / ; + + + + + + + + + + + + + + + + + + ENTER + + + + + + + + + + + + + + + + + + + LEFT + + + + + + + + + + + + + RIGHT + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + Z + + + + + + + + + + + + + + + X + + + + + + + + + + + + + + + C + + + + + + + + + + + + + + + V + + + + + + + + + + + + + + + B + + + + + + + + + + + + + + + N + + + + + + + + + + + + + + + M + + + + + + + + + + + + + + + < / , + + + + + + + + + + + + + + + + + + > / . + + + + + + + + + + + + + + + + + + ? / / + + + + + + + + + + + + + + + + + + SHIFT + + + + + + + + + + + + + + + + + + + DOWN + + + + + + + + + + + + + SPACE + + + + + + + + + + + + F1 + + + + + + + + + + + + + + + + F2 + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-color-computer-rom-cartridge-colors.svg b/docs/media/tandy-color-computer-rom-cartridge-colors.svg new file mode 100644 index 0000000..b3e7a9c --- /dev/null +++ b/docs/media/tandy-color-computer-rom-cartridge-colors.svg @@ -0,0 +1,694 @@ + + + Tandy Color Computer ROM cartridges — four slot colors + Four front-facing cartridge views in a two-by-two arrangement: slot 1 muted blue, slot 2 sage green, slot 3 brick red and slot 4 ochre yellow. All labels and captions are outlined vectors. The neutral background can be hidden independently. + Simplified Color Computer ROM-cartridge artwork based on historical cartridge forms. The generic label does not reproduce a game cover or cartridge label. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Arial and Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Neutral background — hide for transparency + + + + Slot 1 — Muted blue + + Standard Tandy ROM cartridge with two upper finger-grip notches + + Connector visibility — choose one + + Exposed recessed card edge + + + + + + + + + + + + + + + + + + + + + + + + + + + + Black molded shell with two finger grips + + + + + + + + + + + + + + + + + + + + + + + Replaceable TANDY ROM cartridge label + + Label wrapped across the upper edge + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY wordmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Recessed insertion arrow pointing toward the connector + + + + + + + + + + + + + + + + + + + + + + + + Slot 2 — Sage green + + Standard Tandy ROM cartridge with two upper finger-grip notches + + Connector visibility — choose one + + Exposed recessed card edge + + + + + + + + + + + + + + + + + + + + + + + + + + + + Black molded shell with two finger grips + + + + + + + + + + + + + + + + + + + + + + + Replaceable TANDY ROM cartridge label + + Label wrapped across the upper edge + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY wordmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Recessed insertion arrow pointing toward the connector + + + + + + + + + + + + + + + + + + + + + + + + Slot 3 — Brick red + + Standard Tandy ROM cartridge with two upper finger-grip notches + + Connector visibility — choose one + + Exposed recessed card edge + + + + + + + + + + + + + + + + + + + + + + + + + + + + Black molded shell with two finger grips + + + + + + + + + + + + + + + + + + + + + + + Replaceable TANDY ROM cartridge label + + Label wrapped across the upper edge + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY wordmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Recessed insertion arrow pointing toward the connector + + + + + + + + + + + + + + + + + + + + + + + Slot 4 — Ochre yellow + + Standard Tandy ROM cartridge with two upper finger-grip notches + + Connector visibility — choose one + + Exposed recessed card edge + + + + + + + + + + + + + + + + + + + + + + + + + + + + Black molded shell with two finger grips + + + + + + + + + + + + + + + + + + + + + + + Replaceable TANDY ROM cartridge label + + Label wrapped across the upper edge + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY wordmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Recessed insertion arrow pointing toward the connector + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-color-computer-rom-cartridge-green.svg b/docs/media/tandy-color-computer-rom-cartridge-green.svg new file mode 100644 index 0000000..28151f7 --- /dev/null +++ b/docs/media/tandy-color-computer-rom-cartridge-green.svg @@ -0,0 +1,183 @@ + + + Tandy Color Computer ROM cartridge — sage green + Upright standard black ROM cartridge, with notched finger grips on both sides, a recessed wraparound TANDY label, molded insertion arrow and switchable protected or exposed connector detail. Sage green label palette matches Multi-Pak slot 2. + Simplified Color Computer ROM-cartridge artwork based on historical cartridge forms. The generic label does not reproduce a game cover or cartridge label. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Standard Tandy ROM cartridge with two upper finger-grip notches + + Connector visibility — choose one + + Exposed recessed card edge + + + + + + + + + + + + + + + + + + + + + + + + + + + + Black molded shell with two finger grips + + + + + + + + + + + + + + + + + + + + + + + Replaceable TANDY ROM cartridge label + + Label wrapped across the upper edge + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY wordmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Recessed insertion arrow pointing toward the connector + + + + + \ No newline at end of file diff --git a/docs/media/tandy-color-computer-rom-cartridge-red.svg b/docs/media/tandy-color-computer-rom-cartridge-red.svg new file mode 100644 index 0000000..c062fec --- /dev/null +++ b/docs/media/tandy-color-computer-rom-cartridge-red.svg @@ -0,0 +1,183 @@ + + + Tandy Color Computer ROM cartridge — brick red + Upright standard black ROM cartridge, with notched finger grips on both sides, a recessed wraparound TANDY label, molded insertion arrow and switchable protected or exposed connector detail. Brick red label palette matches Multi-Pak slot 3. + Simplified Color Computer ROM-cartridge artwork based on historical cartridge forms. The generic label does not reproduce a game cover or cartridge label. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Standard Tandy ROM cartridge with two upper finger-grip notches + + Connector visibility — choose one + + Exposed recessed card edge + + + + + + + + + + + + + + + + + + + + + + + + + + + + Black molded shell with two finger grips + + + + + + + + + + + + + + + + + + + + + + + Replaceable TANDY ROM cartridge label + + Label wrapped across the upper edge + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY wordmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Recessed insertion arrow pointing toward the connector + + + + + \ No newline at end of file diff --git a/docs/media/tandy-color-computer-rom-cartridge-yellow.svg b/docs/media/tandy-color-computer-rom-cartridge-yellow.svg new file mode 100644 index 0000000..43fb821 --- /dev/null +++ b/docs/media/tandy-color-computer-rom-cartridge-yellow.svg @@ -0,0 +1,183 @@ + + + Tandy Color Computer ROM cartridge — ochre yellow + Upright standard black ROM cartridge, with notched finger grips on both sides, a recessed wraparound TANDY label, molded insertion arrow and switchable protected or exposed connector detail. Ochre yellow label palette matches Multi-Pak slot 4. + Simplified Color Computer ROM-cartridge artwork based on historical cartridge forms. The generic label does not reproduce a game cover or cartridge label. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Standard Tandy ROM cartridge with two upper finger-grip notches + + Connector visibility — choose one + + Exposed recessed card edge + + + + + + + + + + + + + + + + + + + + + + + + + + + + Black molded shell with two finger grips + + + + + + + + + + + + + + + + + + + + + + + Replaceable TANDY ROM cartridge label + + Label wrapped across the upper edge + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY wordmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Recessed insertion arrow pointing toward the connector + + + + + \ No newline at end of file diff --git a/docs/media/tandy-color-computer-rom-cartridge.svg b/docs/media/tandy-color-computer-rom-cartridge.svg new file mode 100644 index 0000000..cde612b --- /dev/null +++ b/docs/media/tandy-color-computer-rom-cartridge.svg @@ -0,0 +1,183 @@ + + + Tandy Color Computer ROM cartridge + Upright standard black ROM cartridge, with notched finger grips on both sides, a recessed wraparound TANDY label, molded insertion arrow and switchable protected or exposed connector detail. + Simplified Color Computer ROM-cartridge artwork based on historical cartridge forms. The generic label does not reproduce a game cover or cartridge label. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Standard Tandy ROM cartridge with two upper finger-grip notches + + Connector visibility — choose one + + Exposed recessed card edge + + + + + + + + + + + + + + + + + + + + + + + + + + + + Black molded shell with two finger grips + + + + + + + + + + + + + + + + + + + + + + + Replaceable TANDY ROM cartridge label + + Label wrapped across the upper edge + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY wordmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Recessed insertion arrow pointing toward the connector + + + + + \ No newline at end of file diff --git a/docs/media/tandy-computer-cassette-recorder-badge.svg b/docs/media/tandy-computer-cassette-recorder-badge.svg new file mode 100644 index 0000000..8f695a9 --- /dev/null +++ b/docs/media/tandy-computer-cassette-recorder-badge.svg @@ -0,0 +1,64 @@ + + + Tandy Computer Cassette Recorder badge + Custom silver-bordered black nameplate. Large TANDY wordmark at left; COMPUTER centered above CASSETTE RECORDER at right. + CCR-81-inspired recorder artwork based on historical hardware references. The custom two-line TANDY caption adapts the Radio Shack/TRS-80 and TANDY badge variants. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Arial and Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + TANDY COMPUTER CASSETTE RECORDER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-computer-cassette-recorder.svg b/docs/media/tandy-computer-cassette-recorder.svg new file mode 100644 index 0000000..65a56ca --- /dev/null +++ b/docs/media/tandy-computer-cassette-recorder.svg @@ -0,0 +1,651 @@ + + + Tandy Computer Cassette Recorder + Cream CCR-81-inspired recorder with perforated speaker grille, smoked cassette lid, Empty and Loaded tape layers, counter, six transport keys and custom TANDY badge. The loaded tape has a replaceable TANDY DATA CASSETTE label, two reels and a tape window. + CCR-81-inspired recorder artwork based on historical hardware references. The custom two-line TANDY caption adapts the Radio Shack/TRS-80 and TANDY badge variants. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Arial and Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Computer Cassette Recorder, based on the CCR-81 + + Low rubber feet on the same implied tabletop + + + + + Folded light-metal carrying handle beneath the front edge + + + + + + + + + + Rounded cream enclosure + + + + + + + + + + + + + Perforated rear speaker grille + + + + + + Tape counter, recorder badge, indicator and transport labels + + + + + + + + + + + + + + + + + + + + + TANDY COMPUTER CASSETTE RECORDER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Cassette activity LED + + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Six transport keys, with a red Record key + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Smoked cassette lid with selectable empty and loaded tape bay + + + + + + + + Empty cassette bay + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-deluxe-joystick-badge.svg b/docs/media/tandy-deluxe-joystick-badge.svg new file mode 100644 index 0000000..479d95a --- /dev/null +++ b/docs/media/tandy-deluxe-joystick-badge.svg @@ -0,0 +1,52 @@ + + + Tandy Deluxe Joystick badge + Standalone silver-bordered black nameplate reading TANDY DELUXE JOYSTICK. The same vector master appears on the joystick front. + Tandy Deluxe Joystick artwork based on historical case, product and packaging references. Housing, fire button, well and stick are independently drawn in the shared scene perspective. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + TANDY DELUXE JOYSTICK + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-deluxe-joystick.svg b/docs/media/tandy-deluxe-joystick.svg new file mode 100644 index 0000000..3da62eb --- /dev/null +++ b/docs/media/tandy-deluxe-joystick.svg @@ -0,0 +1,182 @@ + + + Tandy Deluxe Joystick + Standalone cream Tandy Deluxe Joystick with a red fire button, deep black well, tapered upright stick, and TANDY DELUXE JOYSTICK front badge. + Tandy Deluxe Joystick artwork based on historical case, product and packaging references. Housing, fire button, well and stick are independently drawn in the shared scene perspective. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Deluxe Joystick + + Low rubber feet resting on the implied tabletop + + + + + Sloped cream plastic housing + + + + + + + + + + + + + + TANDY DELUXE JOYSTICK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Deep recessed joystick well + + + + + + + + + + + + + + + + + + + Red fire button + + + + + + + + + Upright tapered black joystick + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-fd-502-controller.svg b/docs/media/tandy-fd-502-controller.svg new file mode 100644 index 0000000..9cf0ef2 --- /dev/null +++ b/docs/media/tandy-fd-502-controller.svg @@ -0,0 +1,174 @@ + + + Tandy FD 502 controller cartridge + Straight upright black FD 502 controller cartridge with a silver TANDY COLOR COMPUTER / DISK DRIVE / FD 502 label, ventilation and male card edge, sized to seat directly in the Multi-Pak slot. + FD-502-labelled drive, controller and ribbon artwork adapted from historical FD-series hardware references. Geometry and cable routing are illustrative rather than dimensioned technical drawings. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy FD 502 disk controller cartridge + + Male cartridge edge connector, hidden inside the Multi-Pak when installed + + + + + + + + + + + + + + + + + + + + + + + + + + Straight black molded cartridge body seated directly in the slot + + + + + + + + Three rows of ventilation slots + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY COLOR COMPUTER / DISK DRIVE / FD 502 label + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-fd-502-disk-drive-badge.svg b/docs/media/tandy-fd-502-disk-drive-badge.svg new file mode 100644 index 0000000..c041f0d --- /dev/null +++ b/docs/media/tandy-fd-502-disk-drive-badge.svg @@ -0,0 +1,52 @@ + + + Tandy Disk Drive FD 502 badge + Standalone black and silver top enclosure nameplate reading TANDY DISK DRIVE FD 502. All lettering consists of vector outlines. + FD-502-labelled drive, controller and ribbon artwork adapted from historical FD-series hardware references. Geometry and cable routing are illustrative rather than dimensioned technical drawings. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + TANDY DISK DRIVE FD 502 + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-fd-502-disk-drive.svg b/docs/media/tandy-fd-502-disk-drive.svg new file mode 100644 index 0000000..8913f06 --- /dev/null +++ b/docs/media/tandy-fd-502-disk-drive.svg @@ -0,0 +1,547 @@ + + + Tandy Disk Drive FD 502 — dual-drive enclosure + Standalone cream FD 502 enclosure with two black floppy drives, two banks of top ventilation, and a TANDY DISK DRIVE FD 502 nameplate. Transparent surrounding background. + FD-502-labelled drive, controller and ribbon artwork adapted from historical FD-series hardware references. Geometry and cable routing are illustrative rather than dimensioned technical drawings. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy FD 502 enclosure with two floppy drives + + Low rubber feet + + + + + Cream metal drive enclosure + + + + + + + + + + + Two banks of top ventilation slots + + Front ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Rear ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY DISK DRIVE FD 502 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Two populated floppy drive bays + + + Upper floppy disk drive + + + + + + FD1 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD1: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + + Lower floppy disk drive + + + + + + FD0 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD0: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-fd-502-ribbon-cable.svg b/docs/media/tandy-fd-502-ribbon-cable.svg new file mode 100644 index 0000000..3687174 --- /dev/null +++ b/docs/media/tandy-fd-502-ribbon-cable.svg @@ -0,0 +1,222 @@ + + + FD 502 ribbon cable + Gray ribbon cable with individual conductor ridges, a red edge stripe and a drive-end connector, in the full-system routing and perspective. + FD-502-labelled drive, controller and ribbon artwork adapted from historical FD-series hardware references. Geometry and cable routing are illustrative rather than dimensioned technical drawings. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + Gray ribbon cable with a red edge stripe, leading to the rear of the FD 502 enclosure + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Drive-end ribbon connector + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-multi-pak-interface-badge.svg b/docs/media/tandy-multi-pak-interface-badge.svg new file mode 100644 index 0000000..7177f6c --- /dev/null +++ b/docs/media/tandy-multi-pak-interface-badge.svg @@ -0,0 +1,56 @@ + + + Tandy Multi-Pak Interface case badge + Standalone TANDY wordmark, red green and blue diagonal stripes, and MULTI-PAK INTERFACE lettering on a black nameplate with a silver rim. + Multi-Pak Interface artwork based on historical hardware references and Tandy's Multi-Pak Interface for Color Computer 2 manual, Figure 2 (PDF page 6; printed page 4). Scale and connector geometry are illustrative. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + TANDY / / / MULTI-PAK INTERFACE + + + + + + + + + + + Red green and blue diagonal stripes + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-multi-pak-interface.svg b/docs/media/tandy-multi-pak-interface.svg new file mode 100644 index 0000000..406c03b --- /dev/null +++ b/docs/media/tandy-multi-pak-interface.svg @@ -0,0 +1,456 @@ + + + Tandy Multi-Pak Interface + Standalone Multi-Pak Interface in the same perspective and beige vector style as the Color Computer 3 illustration. Four recessed cartridge slots, six vents, original TANDY badge, front selector, rounded molded housing, and a raised left-side connector. + Multi-Pak Interface artwork based on historical hardware references and Tandy's Multi-Pak Interface for Color Computer 2 manual, Figure 2 (PDF page 6; printed page 4). Scale and connector geometry are illustrative. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Arial and Eurostile; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Multi-Pak Interface, four-slot cartridge expansion interface + + Raised left-side cartridge connector housing + + + + + + + + + + + + + + + + + + + Rubber feet + + + + + + + Inset lower base + + + + + Molded beige Multi-Pak housing + + + + + + + + + + + + + + + + + + + + Four cartridge bays, slot 1 at the front and slot 4 at the rear + + + + + Cartridge slot 1 + + + + + + + + + + + + + + + + + + Cartridge slot 2 + + + + + + + + + + + + + + + + + + Cartridge slot 3 + + + + + + + + + + + + + + + + + + Cartridge slot 4 + + + + + + + + + + + + + + + + + + + Six ventilation slots + + + + + + + + + + + + + + + + + + + + + TANDY / / / MULTI-PAK INTERFACE + + + + + + + + + + + Red green and blue diagonal stripes + + + + + + + + + + + + + + + + + + + + + + + + + + + Four-position program pak selector + + + + Multi-Pak selector — choose one + + + Slot 2 + + Selector set to position 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-rgb-color-monitor-cm-8-badge.svg b/docs/media/tandy-rgb-color-monitor-cm-8-badge.svg new file mode 100644 index 0000000..8b14deb --- /dev/null +++ b/docs/media/tandy-rgb-color-monitor-cm-8-badge.svg @@ -0,0 +1,54 @@ + + + TANDY RGB COLOR MONITOR CM-8 + Standalone CM-8 monitor nameplate: straight original TANDY wordmark, silver rectangular border, black inset, RGB COLOR MONITOR CM-8 lettering, and three long horizontal red, green, and blue rectangles across the top of the model lettering. No angled stripes. All visible artwork is vector geometry. + CM-8 monitor nameplate with upright TANDY contours and horizontal RGB accents, based on historical monitor-badge references. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-thermal-printer-tp-10-badge.svg b/docs/media/tandy-thermal-printer-tp-10-badge.svg new file mode 100644 index 0000000..73a0619 --- /dev/null +++ b/docs/media/tandy-thermal-printer-tp-10-badge.svg @@ -0,0 +1,40 @@ + + + Tandy Thermal Printer TP-10 badge + Silver-bordered black nameplate for the native Printer Output window. A custom TANDY THERMAL PRINTER TP-10 nameplate using the joystick badge style; it does not imply printer graphics or control-code emulation. + Original TP-10 window nameplate with a custom TANDY caption adapting the hardware's Radio Shack/TRS-80 identity. No reference-photograph pixels are embedded. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Frame and wordmark reuse the Deluxe Joystick badge master. Model lettering is outlined from Eurostile Bold. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + TANDY THERMAL PRINTER TP-10 + + + + + + + + + + + + + + + + diff --git a/docs/media/tandy-tp-10-printer.svg b/docs/media/tandy-tp-10-printer.svg new file mode 100644 index 0000000..0e2751a --- /dev/null +++ b/docs/media/tandy-tp-10-printer.svg @@ -0,0 +1,159 @@ + + + Tandy TP-10 thermal printer + Cream thermal printer with substantial rear housing, sloping top, rounded front wall, domed smoked cover and cylindrical paper roll. Capture light and retained-output marks are separate runtime states. + Original shaded TP-10 illustration with a custom TANDY caption adapting the Radio Shack/TRS-80 hardware identity. The embedded transparent shell PNG is authored illustration, not a reference photograph; editable vector overlays represent paper and lamp states. Printed marks indicate retained output, not thermal-printer emulation. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-tp-10-shell.png b/docs/media/tandy-tp-10-shell.png new file mode 100644 index 0000000..42412f0 Binary files /dev/null and b/docs/media/tandy-tp-10-shell.png differ diff --git a/docs/media/tandy-virtual-drive-system-badge.svg b/docs/media/tandy-virtual-drive-system-badge.svg new file mode 100644 index 0000000..9f2429d --- /dev/null +++ b/docs/media/tandy-virtual-drive-system-badge.svg @@ -0,0 +1,56 @@ + + + Tandy Virtual Drive System badge + Silver-bordered black TANDY VIRTUAL DRIVE SYSTEM nameplate. + Fictional Virtual Drive System artwork, not a historical Tandy product. The enclosure, controller and ribbon derive from the FD-series hardware illustrations; four floppy bays sit above two hard-disk bays. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + TANDY VIRTUAL DRIVE SYSTEM + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-virtual-drive-system-controller.svg b/docs/media/tandy-virtual-drive-system-controller.svg new file mode 100644 index 0000000..ae5be24 --- /dev/null +++ b/docs/media/tandy-virtual-drive-system-controller.svg @@ -0,0 +1,163 @@ + + + Tandy Virtual Drive System controller + Direct-fit black controller cartridge with TANDY VIRTUAL DRIVE SYSTEM label and exposed card edge. + Fictional Virtual Drive System artwork, not a historical Tandy product. The enclosure, controller and ribbon derive from the FD-series hardware illustrations; four floppy bays sit above two hard-disk bays. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Virtual Drive System controller cartridge + + Male cartridge edge connector, hidden inside the Multi-Pak when installed + + + + + + + + + + + + + + + + + + + + + + + + + + Straight black molded cartridge body seated directly in the slot + + + + + + + + Three rows of ventilation slots + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY VIRTUAL DRIVE SYSTEM + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-virtual-drive-system-ribbon-cable.svg b/docs/media/tandy-virtual-drive-system-ribbon-cable.svg new file mode 100644 index 0000000..11ba9ef --- /dev/null +++ b/docs/media/tandy-virtual-drive-system-ribbon-cable.svg @@ -0,0 +1,222 @@ + + + Virtual Drive System ribbon cable + Gray ribbon with a red edge stripe and connector, routed from the Multi-Pak cartridge to the taller Virtual Drive System. + Fictional Virtual Drive System artwork, not a historical Tandy product. The enclosure, controller and ribbon derive from the FD-series hardware illustrations; four floppy bays sit above two hard-disk bays. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + Virtual Drive System ribbon cable, routed to the rear of the tall enclosure + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Drive-end ribbon connector + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/media/tandy-virtual-drive-system.svg b/docs/media/tandy-virtual-drive-system.svg new file mode 100644 index 0000000..8fd8d42 --- /dev/null +++ b/docs/media/tandy-virtual-drive-system.svg @@ -0,0 +1,899 @@ + + + Tandy Virtual Drive System + Tall cream enclosure with four floppy drives above two blank hard-drive faces, six equally sized bays, top vents and TANDY VIRTUAL DRIVE SYSTEM badge. + Fictional Virtual Drive System artwork, not a historical Tandy product. The enclosure, controller and ribbon derive from the FD-series hardware illustrations; four floppy bays sit above two hard-disk bays. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Lettering is outlined from Eurostile Bold; no font files are embedded. No reference-photograph pixels are embedded. See ATTRIBUTION.md. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tandy Virtual Drive System: four floppy drives and two hard drives + + Low rubber feet + + + + + + + Cream enclosure, three times the FD 502 case height + + + + + + + + + + + Two banks of top ventilation slots + + Front ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Rear ventilation bank + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TANDY VIRTUAL DRIVE SYSTEM + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Four populated floppy drives above two blank hard-drive faces + + + Floppy drive FD3 + + + + + + FD3 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD3: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + FD3 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD2 + + + + + + FD2 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD2: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + FD2 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD1 + + + + + + FD1 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD1: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + FD1 lower-left drive identifier + + + + + + + + + + + + + + + + + Floppy drive FD0 + + + + + + FD0 activity LED + + + Empty — dark grey + + + + + + + + + + + + + + + + + + + FD0: empty and unlocked, or loaded and locked + + Empty — horizontal unlocked latch + + Short latch handle, rotated around its existing hub + + + + + + + + + + + + + + + FD0 lower-left drive identifier + + + + + + + + + + + + + + + + + Hard drive HD1: black face with one activity LED + + + + + + Single activity LED + + HD1 activity LED + + + Empty — dark grey + + + + + + + + + + HD1 lower-left drive identifier + + + + + + + + + + + + + + + + + Hard drive HD0: black face with one activity LED + + + + + + Single activity LED + + HD0 activity LED + + + Empty — dark grey + + + + + + + + + + HD0 lower-left drive identifier + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/white-paper-evidence.json b/docs/white-paper-evidence.json new file mode 100644 index 0000000..b26832b --- /dev/null +++ b/docs/white-paper-evidence.json @@ -0,0 +1,757 @@ +{ + "schema_version": 2, + "documents": [ + { + "path": "docs/development/ASSEMBLY_WORKSPACE.md", + "export_sha256": "f1f4500dca0170bccf999b4f30a215315f4bd0221e5f56336c05ec379cf4a6a9", + "selected_headings": [ + { + "heading": "__intro__", + "level": 1 + }, + { + "heading": "Working with several files", + "level": 2 + }, + { + "heading": "Share an assembly project with a local assistant", + "level": 2 + }, + { + "heading": "Verification on November 5, 2026", + "level": 2 + } + ], + "paper_reference_keys": [ + "D13" + ] + }, + { + "path": "docs/development/BASIC_WORKSPACE.md", + "export_sha256": "d73ec36d94f37bf064700c8c1d19b30fca23fd2c4c7b45a443759d4e16947cf5", + "selected_headings": [ + { + "heading": "Direct machine operations", + "level": 2 + }, + { + "heading": "BASIC line breakpoints", + "level": 2 + }, + { + "heading": "Statement stepping and Step Over", + "level": 2 + }, + { + "heading": "Step Out and runtime errors", + "level": 2 + }, + { + "heading": "Variables and watches", + "level": 2 + }, + { + "heading": "Validation approach", + "level": 2 + }, + { + "heading": "Initial validation — November 4, 2026", + "level": 3 + }, + { + "heading": "BASIC line-debugging validation — November 4, 2026", + "level": 3 + }, + { + "heading": "Statement stepping validation — November 5, 2026", + "level": 3 + }, + { + "heading": "Variables and watches validation — November 5, 2026", + "level": 2 + }, + { + "heading": "Step Out, runtime-error and preset validation — November 5, 2026", + "level": 2 + } + ], + "paper_reference_keys": [ + "D12" + ] + }, + { + "path": "docs/development/CMOC_BENCHMARKS.md", + "export_sha256": "d17929f26a5bca3f31fef22018eec7969b5d3ae9306c089c63487ec173ef6f95", + "selected_headings": [ + { + "heading": "Results", + "level": 2 + }, + { + "heading": "Compiler and method", + "level": 2 + }, + { + "heading": "Limits", + "level": 2 + } + ], + "paper_reference_keys": [ + "D26" + ] + }, + { + "path": "docs/development/CMOC_INDEXED_ARGUMENT_LOAD.md", + "export_sha256": "f15d646071a02075c91f790420833b735c8537e6e114a02d495df906ca579c16", + "selected_headings": [ + { + "heading": "Failure and general correction", + "level": 2 + }, + { + "heading": "Target-executed regression", + "level": 2 + }, + { + "heading": "Additional checks and runtime staging", + "level": 2 + } + ], + "paper_reference_keys": [ + "D20" + ] + }, + { + "path": "docs/development/CMOC_RELEASE_QUALIFICATION.md", + "export_sha256": "80a4c553da8ff3eb4df7464ca0663c221b39604345c2c5f3ba3e0f06e8bd9aab", + "selected_headings": [ + { + "heading": "Findings during qualification", + "level": 2 + }, + { + "heading": "Completed November 3, 2026", + "level": 2 + } + ], + "paper_reference_keys": [ + "D24" + ] + }, + { + "path": "docs/development/CMOC_RUNTIME.md", + "export_sha256": "c76871a76088b08e8c47110f596631f0cc426a73adb75f956c0abe508a6de9f7", + "selected_headings": [ + { + "heading": "Runtime contract", + "level": 2 + }, + { + "heading": "Scoped inline-assembly preprocessing", + "level": 3 + }, + { + "heading": "Included target libraries", + "level": 2 + }, + { + "heading": "Validation", + "level": 2 + }, + { + "heading": "C debug metadata", + "level": 2 + } + ], + "paper_reference_keys": [ + "D14", + "D21", + "D24" + ] + }, + { + "path": "docs/development/CMOC_SOURCE_DEBUGGING.md", + "export_sha256": "4c68e24b09ff3c6d3f0d72ad1fb7573c212fb35f81010c983da034fdbf65f454", + "selected_headings": [ + { + "heading": "__intro__", + "level": 1 + }, + { + "heading": "Stepping", + "level": 2 + }, + { + "heading": "Banked programs", + "level": 2 + }, + { + "heading": "Verified function-entry stops over MCP", + "level": 3 + }, + { + "heading": "Call stacks and caller inspection", + "level": 2 + }, + { + "heading": "Variables and watches", + "level": 2 + }, + { + "heading": "Floating-point values", + "level": 3 + }, + { + "heading": "Remaining limits", + "level": 2 + }, + { + "heading": "Validation", + "level": 2 + } + ], + "paper_reference_keys": [ + "D02", + "D09" + ] + }, + { + "path": "docs/development/MCP_AUDIO_CAPTURE.md", + "export_sha256": "5b4746bc68ea2e93c5bb1f5d54aa063fb409557b6ba2b085118225a304ed841b", + "selected_headings": [ + { + "heading": "__intro__", + "level": 1 + } + ], + "paper_reference_keys": [ + "D18" + ] + }, + { + "path": "docs/development/MCP_BANKED_PLAYTEST.md", + "export_sha256": "fad90fcb7e5ca3670d803f02578e44e637b0b126f7716dc4198f253ea7eae3a6", + "selected_headings": [ + { + "heading": "Build evidence for packed programs", + "level": 2 + }, + { + "heading": "Grant a disposable playtest", + "level": 2 + }, + { + "heading": "Paused graphics-buffer captures", + "level": 3 + }, + { + "heading": "Asynchronous startup", + "level": 3 + }, + { + "heading": "Resume a retained test disk", + "level": 3 + }, + { + "heading": "Qualification", + "level": 2 + } + ], + "paper_reference_keys": [ + "D07", + "D11" + ] + }, + { + "path": "docs/development/MCP_BUILD45_VALIDATION.md", + "export_sha256": "d9fb9382d0e908cd8060d50c0a473a479ce8e9f1ea184a29ac1a174feecfc621", + "selected_headings": [ + { + "heading": "Contract and focused qualification", + "level": 2 + } + ], + "paper_reference_keys": [ + "D17" + ] + }, + { + "path": "docs/development/MCP_CALL_CONTEXT.md", + "export_sha256": "1bd9f44f14ab8eabd289571834307ebc6ceb1fe3f81109fc5a2d8bf3857438c9", + "selected_headings": [ + { + "heading": "Access and timing", + "level": 2 + }, + { + "heading": "Bounded raw view", + "level": 2 + }, + { + "heading": "Evidence-gated interpretations", + "level": 2 + }, + { + "heading": "Qualification", + "level": 2 + }, + { + "heading": "Executed checks — November 12, 2026", + "level": 3 + } + ], + "paper_reference_keys": [ + "D15" + ] + }, + { + "path": "docs/development/MCP_DEBUG_EVIDENCE.md", + "export_sha256": "79fe80ae2c40808e6da821bae1d2de1aa4c18b5f7e24b3a40707fdd473cf086e", + "selected_headings": [ + { + "heading": "Read the build evidence first", + "level": 2 + }, + { + "heading": "Stop and inspect the owned guest", + "level": 2 + }, + { + "heading": "Diagnose the selected build", + "level": 2 + }, + { + "heading": "Bounded owned call context", + "level": 2 + } + ], + "paper_reference_keys": [ + "D05" + ] + }, + { + "path": "docs/development/MCP_PLAYTEST_PROCESSORS.md", + "export_sha256": "14ad39d6b95f8efca3d95f622587806514066cfde98358d1808d7c5cd039aae1", + "selected_headings": [ + { + "heading": "Discovery and starting a run", + "level": 2 + }, + { + "heading": "Actual processor and execution mode", + "level": 2 + }, + { + "heading": "Input, audio and limits", + "level": 2 + } + ], + "paper_reference_keys": [ + "D17" + ] + }, + { + "path": "docs/development/MCP_PROJECT_RELIABILITY.md", + "export_sha256": "109fd4c39ac16c8b2b497fadf50f283772e2f9b39bca394e271e9d79d597ae83", + "selected_headings": [ + { + "heading": "One content-based input manifest", + "level": 2 + }, + { + "heading": "Inspect and refresh a connection", + "level": 2 + }, + { + "heading": "Safe cache reuse", + "level": 2 + } + ], + "paper_reference_keys": [ + "D16" + ] + }, + { + "path": "docs/development/REPOSITORY_LAYOUT.md", + "export_sha256": "238f26baba46e8e1419595bc32c9c92f74b90c4efe43539e4f154c5901568fe1", + "selected_headings": [ + { + "heading": "__intro__", + "level": 1 + } + ], + "paper_reference_keys": [ + "A06" + ] + }, + { + "path": "docs/macos/AUDIO_CASSETTE.md", + "export_sha256": "e250421aef2f4c9fa88480acffd773a66edcdfd7783d25bbc226a3d2cce0c9da", + "selected_headings": [ + { + "heading": "Boundaries and compatibility", + "level": 2 + }, + { + "heading": "Validation and outstanding checks", + "level": 2 + }, + { + "heading": "Analog routing correction — November 11, 2026", + "level": 2 + } + ], + "paper_reference_keys": [ + "A14" + ] + }, + { + "path": "docs/macos/AUDIO_ROUTING.md", + "export_sha256": "eacd467a5dd6d736a3492a81a3d4390152b63fa63353af0327e2087d8cec8057", + "selected_headings": [ + { + "heading": "Cause and correction", + "level": 2 + }, + { + "heading": "Unchanged real game reproduction", + "level": 2 + }, + { + "heading": "Regression qualification", + "level": 2 + } + ], + "paper_reference_keys": [ + "E15" + ] + }, + { + "path": "docs/macos/CARTRIDGES.md", + "export_sha256": "a12aa417fbef14bc8c5aae804803d50879649df0b4cd30fcb493c49a236b0697", + "selected_headings": [ + { + "heading": "Routing and retained behavior", + "level": 2 + }, + { + "heading": "Persistence and missing files", + "level": 2 + }, + { + "heading": "Validation", + "level": 2 + } + ], + "paper_reference_keys": [ + "A10", + "E14" + ] + }, + { + "path": "docs/macos/CPU_CORE.md", + "export_sha256": "6180aca7c7a9a6d4f793ca76b45633c2e083f84e095adfaa8ea21512162ed4fc", + "selected_headings": [ + { + "heading": "Boundaries and ownership", + "level": 2 + }, + { + "heading": "Reproducible checks", + "level": 2 + }, + { + "heading": "Defects found during extraction", + "level": 2 + }, + { + "heading": "Scripsit II timing correction — November 4, 2026", + "level": 2 + } + ], + "paper_reference_keys": [ + "A02", + "E01" + ] + }, + { + "path": "docs/macos/DEBUGGER.md", + "export_sha256": "43f57e99efcd15b90da092f938aaccb07c35882f0dc6bb03a0b983b810838224", + "selected_headings": [ + { + "heading": "Execution semantics", + "level": 2 + }, + { + "heading": "Implementation boundaries", + "level": 2 + }, + { + "heading": "Validation", + "level": 2 + }, + { + "heading": "MMU and physical RAM increment — November 3, 2026", + "level": 2 + }, + { + "heading": "Source listings", + "level": 3 + }, + { + "heading": "Memory tools and tracing", + "level": 3 + }, + { + "heading": "Completion validation", + "level": 3 + } + ], + "paper_reference_keys": [ + "D03", + "E13" + ] + }, + { + "path": "docs/macos/DEBUGGER_MEMORY_TOOLS.md", + "export_sha256": "030ff6d680359c1656c091f6e0176ebacd0b685b79cd1c0996b49906b483dbb7", + "selected_headings": [ + { + "heading": "Disassembly", + "level": 2 + }, + { + "heading": "OS-9 interpretation", + "level": 2 + }, + { + "heading": "Raw binary export", + "level": 2 + }, + { + "heading": "Graphics Preview", + "level": 2 + }, + { + "heading": "Scope and validation", + "level": 2 + } + ], + "paper_reference_keys": [ + "D04" + ] + }, + { + "path": "docs/macos/DEBUGGER_TRACING.md", + "export_sha256": "9da93fdaeb87f7868b1adeecb99e9ee3c20b3e3bfb61278a2d74ad048b1d2b65", + "selected_headings": [ + { + "heading": "Capture", + "level": 2 + }, + { + "heading": "Events and timing", + "level": 2 + }, + { + "heading": "Inspection and export", + "level": 2 + }, + { + "heading": "Regression coverage", + "level": 2 + } + ], + "paper_reference_keys": [ + "D06" + ] + }, + { + "path": "docs/macos/FLOPPY_CORE.md", + "export_sha256": "eeb5d4a7cbc9a41473a69ce44823a4e6c717854693b4770046c290ed746c3091", + "selected_headings": [ + { + "heading": "Reused source and host boundary", + "level": 2 + }, + { + "heading": "Image and transfer support", + "level": 2 + }, + { + "heading": "Validation", + "level": 2 + }, + { + "heading": "DMK and VDK — November 5, 2026", + "level": 2 + }, + { + "heading": "Validation and reproduction", + "level": 3 + } + ], + "paper_reference_keys": [ + "E09" + ] + }, + { + "path": "docs/macos/GRAPHICS_CORE.md", + "export_sha256": "89fe9dcdbf12294b61de961ded09d64146394a552be932d4b61520db4fd15879", + "selected_headings": [ + { + "heading": "Portable interfaces", + "level": 2 + }, + { + "heading": "Seven added checks", + "level": 2 + }, + { + "heading": "Corrections and validation", + "level": 2 + }, + { + "heading": "Subsequent integration and open qualification", + "level": 2 + } + ], + "paper_reference_keys": [ + "A04", + "E06" + ] + }, + { + "path": "docs/macos/HARD_DISKS.md", + "export_sha256": "2adb2ad908404c3b274d9cc4e4460ae4d4f7bba26ddabcf66f96e1d13fa87945", + "selected_headings": [ + { + "heading": "Saving and recovery", + "level": 2 + }, + { + "heading": "Device contract", + "level": 2 + }, + { + "heading": "Validation", + "level": 2 + } + ], + "paper_reference_keys": [ + "E11" + ] + }, + { + "path": "docs/macos/MACHINE_CORE.md", + "export_sha256": "f23234c546286bf03ff162dd1595f99192ea7f395688e5873aa6a010e74193a0", + "selected_headings": [ + { + "heading": "Connections and ownership", + "level": 2 + }, + { + "heading": "Added shared checks", + "level": 2 + }, + { + "heading": "Corrections covered by the checks", + "level": 2 + }, + { + "heading": "Validation and remaining work", + "level": 2 + } + ], + "paper_reference_keys": [ + "A03", + "E04" + ] + }, + { + "path": "docs/macos/MAC_CONTROLLER.md", + "export_sha256": "f0d89e49a3467085bf1cffaeadfcabd883c324fc3567eeb85c9140a3e2e4d104", + "selected_headings": [ + { + "heading": "Ownership and execution", + "level": 2 + }, + { + "heading": "Native bridge and frame delivery", + "level": 2 + }, + { + "heading": "Validation", + "level": 2 + }, + { + "heading": "Subsequent integration and open qualification", + "level": 2 + } + ], + "paper_reference_keys": [ + "A05", + "D01" + ] + }, + { + "path": "docs/macos/NATIVE_BOOT.md", + "export_sha256": "c668a13507b0a3c1508c2f606b592cca0631ac9d2f963402eb2f1458e0e4144d", + "selected_headings": [ + { + "heading": "Display and input boundaries", + "level": 2 + }, + { + "heading": "Repeatable checks", + "level": 2 + } + ], + "paper_reference_keys": [ + "A11" + ] + }, + { + "path": "docs/macos/PORTING_PLAN.md", + "export_sha256": "b9d7dcf3a2e8d223f7049ca7810e5758e13253c6c80913b628dc3b6d451faa47", + "selected_headings": [ + { + "heading": "3. Recommended architecture", + "level": 2 + }, + { + "heading": "Device scope decision — November 3, 2026", + "level": 2 + } + ], + "paper_reference_keys": [ + "A01" + ] + }, + { + "path": "docs/macos/TIMING_RELIABILITY.md", + "export_sha256": "aee9a63a900c9fcf64849886001ee66bd52b18dc7bed690afb3a90d9c95f3ba3", + "selected_headings": [ + { + "heading": "Timing contract", + "level": 2 + }, + { + "heading": "Repeatable checks", + "level": 2 + }, + { + "heading": "Local evidence", + "level": 2 + }, + { + "heading": "Remaining acceptance work", + "level": 2 + } + ], + "paper_reference_keys": [ + "E17" + ] + } + ] +} diff --git a/examples/assembly/Dispatch/layout.link b/examples/assembly/Dispatch/layout.link new file mode 100644 index 0000000..cc8d601 --- /dev/null +++ b/examples/assembly/Dispatch/layout.link @@ -0,0 +1,2 @@ +section code load 3f00 +entry start diff --git a/examples/assembly/Dispatch/main.asm b/examples/assembly/Dispatch/main.asm new file mode 100644 index 0000000..462dc6d --- /dev/null +++ b/examples/assembly/Dispatch/main.asm @@ -0,0 +1,32 @@ +; Dispatch: entry, display and data. The copy routine lives in receive.asm. +CHROUT equ $a002 ; ROM's indirect character-output vector + + section code + export start + import receive +start leax packet,pcr + leay received,pcr + ldb #expected-packet ; number of bytes before the checksum + jsr receive ; LWLINK supplies the other module's address +inspect cmpa expected,pcr + bne damaged + leax received,pcr + bra print +damaged leax badmsg,pcr +print lda ,x+ + beq finish + bsr emit + bra print +finish lda #13 + bsr emit + rts ; hand control back to BASIC +emit pshs x ; the print loop needs X after the ROM call + jsr [CHROUT] + puls x,pc + +packet fcc "ORB" +expected fcb $e3 +received fcb 0,0,0,0 ; the fourth byte terminates the printed string +badmsg fcc "CHECK" + fcb 0 + endsection diff --git a/examples/assembly/Dispatch/receive.asm b/examples/assembly/Dispatch/receive.asm new file mode 100644 index 0000000..9f0e9e5 --- /dev/null +++ b/examples/assembly/Dispatch/receive.asm @@ -0,0 +1,14 @@ +; Contract: X = input, Y = output, B = positive number of bytes. +; Returns A = sum modulo 256. Both pointers advance and B reaches zero. + section code + export receive +receive clra +next adda ,x + pshs a + lda ,x+ + sta ,y+ + puls a + decb + bne next + rts + endsection diff --git a/examples/assembly/Dispatch/vccplus-assembly.json b/examples/assembly/Dispatch/vccplus-assembly.json new file mode 100644 index 0000000..4ce2a12 --- /dev/null +++ b/examples/assembly/Dispatch/vccplus-assembly.json @@ -0,0 +1,5 @@ +{ + "main": "main.asm", + "modules": ["receive.asm"], + "linkScript": "layout.link" +} diff --git a/examples/assembly/hardware-debugging/pixel-mask.asm b/examples/assembly/hardware-debugging/pixel-mask.asm new file mode 100644 index 0000000..d0726d7 --- /dev/null +++ b/examples/assembly/hardware-debugging/pixel-mask.asm @@ -0,0 +1,11 @@ +; PIXEL-MASK.ASM -- follow one byte from a register into ordinary RAM. +; This scratch byte belongs to the program. You can examine it without +; changing the live display. Later you will look for a byte on a video page. + org $3f00 +start leax sample,pcr ; X points to our one-byte sample. + lda #$81 ; Two end bits are set: %10000001. +shift lsra ; Shift right. Which bit goes into carry? +store sta ,x ; Set a breakpoint here, before the write. +done rts ; Return to the caller with the byte stored. +sample fcb $00 ; Assembling and running reloads this zero. + end start diff --git a/examples/assembly/manual/bankwalk.asm b/examples/assembly/manual/bankwalk.asm new file mode 100644 index 0000000..29b62b0 --- /dev/null +++ b/examples/assembly/manual/bankwalk.asm @@ -0,0 +1,26 @@ +; BANKWALK.ASM -- a reversible mapping experiment for a fresh 512 KB Disk BASIC. +; Before running, verify MMU enabled, task 0, block 2 = $3A in the debugger. +; Begin at the BASIC prompt with no unsaved program or active devices. +bank2 equ $ffa2 ; task 0, logical $4000-$5fff +window equ $4123 ; offset $0123 into block 2 + org $3f00 ; code and scratch live in block 1 +start pshs cc,a ; preserve incoming flags and A + orcc #$50 ; hold IRQ and FIRQ until restored + lda bank2 + anda #$3f ; 512 KB supplies six bank bits + sta oldbank,pcr + lda #1 + sta bank2 ; window now sees physical $02123 + lda window + sta oldbyte,pcr ; keep the byte even on a fresh machine + lda #$a5 + sta window +inspect lda oldbyte,pcr ; pause BEFORE this instruction + sta window ; put the borrowed byte back + lda oldbank,pcr + sta bank2 ; restore the original translation +restored puls cc,a,pc ; flags restored, return to BASIC + +oldbank fcb 0 +oldbyte fcb 0 + end start diff --git a/examples/assembly/manual/byte.asm b/examples/assembly/manual/byte.asm new file mode 100644 index 0000000..e59049c --- /dev/null +++ b/examples/assembly/manual/byte.asm @@ -0,0 +1,6 @@ +; BYTE.ASM -- Watch register A while the processor counts up one step. + org $3f00 +start lda #$29 ; Load the number $29 (decimal 41) into A. + inca ; Add one. What will A hold after this step? +done rts ; Return to BASIC with the result still in A. + end start diff --git a/examples/assembly/manual/choice.asm b/examples/assembly/manual/choice.asm new file mode 100644 index 0000000..bf92ac7 --- /dev/null +++ b/examples/assembly/manual/choice.asm @@ -0,0 +1,21 @@ +; CHOICE.ASM -- Press 1 for E (Earth) or 2 for M (Mars). +POLCAT equ $a000 ; Keyboard polling vector. Returns a key in A. +CHROUT equ $a002 ; Character-output vector. +CR equ 13 + + org $3f00 +start lda #'? ; Show that the program is waiting for a key. + jsr [CHROUT] +choose jsr [POLCAT] ; Check the keyboard without waiting for Enter. + cmpa #'1 + beq earth ; A matching comparison sets the Z flag. + cmpa #'2 + bne choose ; No key or an unexpected key: try again. +mars lda #'M + bra printit ; Skip the Earth path. +earth lda #'E +printit jsr [CHROUT] ; Both paths meet here with one letter in A. + lda #CR + jsr [CHROUT] + rts + end start diff --git a/examples/assembly/manual/dispatch.asm b/examples/assembly/manual/dispatch.asm new file mode 100644 index 0000000..5ec61de --- /dev/null +++ b/examples/assembly/manual/dispatch.asm @@ -0,0 +1,44 @@ +; DISPATCH.ASM -- receive a three-byte station code and check its sum. +; Disk BASIC, MC6809 or HD6309. Run a personal copy from the assembly editor. +CHROUT equ $a002 ; indirect ROM character-output vector + org $3f00 +start leax packet,pcr ; X walks the incoming bytes + leay received,pcr ; Y walks a separate writable buffer + ldb #size + bsr receive +inspect cmpa expected,pcr ; stop here to inspect A and the copy + bne damaged + leax received,pcr + bra print +damaged leax badmsg,pcr +print lda ,x+ + beq finish ; both text paths end with a zero byte + bsr emit + bra print +finish lda #13 ; put the BASIC prompt on its own line + bsr emit + rts + +; Input: X source, Y destination, B positive byte count. +; Output: A = sum modulo 256. X and Y advance; B ends at zero. +receive clra +next adda ,x ; add this byte, leave X at it for the copy + pshs a ; keep the running sum while moving the byte + lda ,x+ + sta ,y+ + puls a + decb + bne next + rts + +emit pshs x ; caller still needs its position after ROM I/O + jsr [CHROUT] + puls x,pc + +packet fcc "ORB" +size equ *-packet +expected fcb $e3 ; $4F + $52 + $42 = $E3 +received fcb 0,0,0,0 ; fourth byte stays zero for printing +badmsg fcc "CHECK" + fcb 0 + end start diff --git a/examples/assembly/manual/dispatch6309.asm b/examples/assembly/manual/dispatch6309.asm new file mode 100644 index 0000000..d9bd0ff --- /dev/null +++ b/examples/assembly/manual/dispatch6309.asm @@ -0,0 +1,22 @@ +; DISPATCH6309.ASM -- copy a station code with the HD6309 block move. +; Choose the HD6309 guest and assembly target. Start in Disk BASIC. +CHROUT equ $a002 + org $3f00 +start leax packet,pcr + leay received,pcr + ldw #size ; W counts the bytes left to transfer +copy tfm x+,y+ ; move from X to Y and increment both +inspect leax received,pcr ; stop here to inspect W, X, Y and RAM +next lda ,x+ + beq finish + pshs x + jsr [CHROUT] + puls x + bra next +finish lda #13 + jsr [CHROUT] + rts ; no change to the guest's processor mode +packet fcc "ORB" +size equ *-packet +received fcb 0,0,0,0 + end start diff --git a/examples/assembly/manual/letter.asm b/examples/assembly/manual/letter.asm new file mode 100644 index 0000000..ba42434 --- /dev/null +++ b/examples/assembly/manual/letter.asm @@ -0,0 +1,11 @@ +; LETTER.ASM -- Give one byte to BASIC's character output routine. +CHROUT equ $a002 ; Address of the ROM character-output vector. +CR equ 13 ; Carriage return starts a fresh line. + + org $3f00 +start lda #'A ; Load this character's ASCII code into A. + jsr [CHROUT] ; Call the routine whose address is at CHROUT. + lda #CR + jsr [CHROUT] ; Leave the next BASIC prompt on its own line. + rts ; Return to the caller in BASIC. + end start diff --git a/examples/assembly/manual/mode.asm b/examples/assembly/manual/mode.asm new file mode 100644 index 0000000..2117280 --- /dev/null +++ b/examples/assembly/manual/mode.asm @@ -0,0 +1,11 @@ +; MODE.ASM -- a bounded HD6309 experiment for Disk BASIC at reset mode. +; Run on a fresh HD6309 guest, with MD=0. Both stops are before instructions. + org $3f00 +start pshs cc ; remember BASIC's interrupt masks + orcc #$50 ; mask IRQ and FIRQ for the short experiment + ldmd #1 ; select 6309 native mode +native ldw #$1234 ; inspect MD, then step and read E and F + ldmd #0 ; restore reset mode before calling BASIC +restored puls cc ; restore the caller's condition codes + rts + end start diff --git a/examples/assembly/manual/return.asm b/examples/assembly/manual/return.asm new file mode 100644 index 0000000..94c542d --- /dev/null +++ b/examples/assembly/manual/return.asm @@ -0,0 +1,15 @@ +; RETURN.ASM -- A subroutine advances one letter, then returns to its caller. +CHROUT equ $a002 ; Address of the ROM character-output vector. +CR equ 13 + + org $3f00 +start lda #'A ; Begin with the letter A ($41). +call jsr nextletter ; Save the address of 'display' on the S stack. +display jsr [CHROUT] ; The subroutine has left the new letter in A. + lda #CR + jsr [CHROUT] + rts ; Finish the main program and return to BASIC. + +nextletter inca ; ASCII B follows ASCII A. +back rts ; Retrieve the saved address and resume at display. + end start diff --git a/examples/assembly/manual/softirq.asm b/examples/assembly/manual/softirq.asm new file mode 100644 index 0000000..a787c9d --- /dev/null +++ b/examples/assembly/manual/softirq.asm @@ -0,0 +1,31 @@ +; SOFTIRQ.ASM -- install, call and remove a BASIC RAM SWI trampoline. +; Fresh CoCo 3 Disk BASIC, MC6809 or HD6309 in emulation mode only. +; From a debugger stop, Continue through cleanup before returning to BASIC. +hook equ $0106 ; three-byte RAM stub reached via $FFFA + org $3f00 +start pshs cc,d,x ; preserve the caller's flags, D and X + orcc #$50 ; keep IRQ & FIRQ out during this experiment + lda hook + ldx hook+1 + sta oldop,pcr + stx oldaddr,pcr + lda #$7e ; extended JMP opcode + leax handler,pcr + stx hook+1 + sta hook ; JMP handler now complete + clr visits,pcr + lda #$4f ; known bytes to locate in the stack frame + ldb #$52 +trigger swi ; CPU stacks state and follows the SWI vector +returned lda oldop,pcr ; breakpoint to compare S after RTI + sta hook + ldx oldaddr,pcr + stx hook+1 +restored puls cc,d,x,pc ; restore flags, D and X, return to BASIC + +handler inc visits,pcr ; memory survives the return + rti ; reload the stacked context, including PC +oldop fcb 0 +oldaddr fdb 0 +visits fcb 0 + end start diff --git a/examples/assembly/planet.asm b/examples/assembly/planet.asm new file mode 100644 index 0000000..b018162 --- /dev/null +++ b/examples/assembly/planet.asm @@ -0,0 +1,57 @@ +; PLANET.ASM -- A 40-column CoCo 3 program for Disk Extended Color BASIC. +; Start at the BASIC prompt. In VCC Plus, open this file and choose Run. + +POLCAT equ $a000 ; ROM vector: poll keyboard, ASCII key in A +CHROUT equ $a002 ; ROM vector: print the character in A +WIDTH equ $f643 ; CoCo 3 ROM: set text width to B columns +ATTR equ $fe08 ; Attribute BASIC uses for the next character +BG6 equ $ffb6 ; GIME background palette slot 6 +CR equ 13 ; ASCII carriage return starts a new line + + org $3f00 +start ldb #40 + jsr WIDTH ; Use the CoCo 3 lowercase-capable text display. + ldx #menu + bsr puts + +choose jsr [POLCAT] ; Poll until we get ASCII '1' or '2'. + cmpa #'1 + beq earth + cmpa #'2 + bne choose ; No key (or a different key)? Try again. + +mars ldb #$25 ; Warm red background, visible on RGB and CMP. + ldx #redmsg + bra greet +earth ldb #$0a ; Cool blue background. + ldx #bluemsg + +greet stb BG6 ; Choose the tint for the greeting only. + lda #%00011110 ; White foreground (3), background slot 6. + sta ATTR + bsr puts ; X points to the selected greeting. + clr ATTR ; Back to BASIC's usual text colors. + lda #CR + jsr [CHROUT] + rts ; Return to BASIC, just as puts returns to us. + +; Print the zero-terminated string at X. X+ advances to the next byte. +puts lda ,x+ + beq done + pshs x ; Keep our place across the ROM call. + jsr [CHROUT] + puls x + bra puts +done rts ; Return to the caller of puts. + +menu fcc "What planet do you live on?" + fcb CR + fcc "1) Earth" + fcb CR + fcc "2) Mars" + fcb CR,0 +bluemsg fcc "Hello Nice Blue Dot World!" + fcb 0 +redmsg fcc "Hello Cold Red Dot World!" + fcb 0 + end start ; DECB execution address for Run or EXEC. diff --git a/examples/basic/back-at-the-coco/PORT.bas b/examples/basic/back-at-the-coco/PORT.bas new file mode 100644 index 0000000..578624e --- /dev/null +++ b/examples/basic/back-at-the-coco/PORT.bas @@ -0,0 +1,5 @@ +10 WIDTH 40 +20 PRINT "WELCOME BACK TO PORT ZERO." +30 INPUT "CALL SIGN";N$ +40 PRINT "GOOD TO HAVE YOU ABOARD, ";N$;"!" +50 END diff --git a/examples/basic/back-at-the-coco/STRIPES.bas b/examples/basic/back-at-the-coco/STRIPES.bas new file mode 100644 index 0000000..fc32a47 --- /dev/null +++ b/examples/basic/back-at-the-coco/STRIPES.bas @@ -0,0 +1,7 @@ +10 PMODE 4,1:PCLS 0:SCREEN 1,1 +20 FOR X=24 TO 118 STEP 2 +30 LINE (X,48)-(X,144),PSET +40 LINE (X+113,48)-(X+113,144),PSET +50 NEXT X +60 IF INKEY$="" THEN 60 +70 SCREEN 0,0:END diff --git a/examples/basic/hardware-debugging/BEACON.bas b/examples/basic/hardware-debugging/BEACON.bas new file mode 100644 index 0000000..fde83fb --- /dev/null +++ b/examples/basic/hardware-debugging/BEACON.bas @@ -0,0 +1,15 @@ +10 WIDTH 32:PCLEAR 4:CLS +20 PMODE 1,1:PCLS 0:SCREEN 1,0 +30 COLOR 1,0:LINE(32,80)-(96,112),PSET,B +40 LINE(32,80)-(64,48),PSET:LINE(64,48)-(96,80),PSET +50 PMODE 1,3:PCLS 0:COLOR 3,0 +60 LINE(144,48)-(184,80),PSET,B +70 PSET(162,64,3) +80 A$=INKEY$:IF A$="" THEN 80 +90 SCREEN 1,0 +100 A$=INKEY$:IF A$="" THEN 100 +110 PMODE 1,1:SCREEN 1,0 +120 A$=INKEY$:IF A$="" THEN 120 +130 SCREEN 0,0:WIDTH 40:CLS +140 PRINT "BEACON CHECK COMPLETE" +150 END diff --git a/examples/basic/meet-your-color-computer/BEACON.bas b/examples/basic/meet-your-color-computer/BEACON.bas new file mode 100644 index 0000000..907a7de --- /dev/null +++ b/examples/basic/meet-your-color-computer/BEACON.bas @@ -0,0 +1,2 @@ +10 PRINT "THIS IS MOON BASE." +20 PRINT "CAN YOU HEAR ME?" diff --git a/examples/basic/meet-your-color-computer/QUIZ.bas b/examples/basic/meet-your-color-computer/QUIZ.bas new file mode 100644 index 0000000..00ad052 --- /dev/null +++ b/examples/basic/meet-your-color-computer/QUIZ.bas @@ -0,0 +1,17 @@ +10 CLS +20 S=0 +30 PRINT "MOON BASE CREW QUIZ" +40 PRINT "WHICH PART SHOWS A MESSAGE?" +50 PRINT "1 SCREEN 2 KEYBOARD" +60 INPUT A +70 IF A=1 THEN S=S+1 +80 PRINT "WHICH KEEPS A SAVED PROGRAM?" +90 PRINT "1 RAM 2 DISK" +100 INPUT A +110 IF A=2 THEN S=S+1 +120 PRINT "WHAT DOES PRINT 2+3 SHOW?" +130 PRINT "1 FIVE 2 THE TEXT 2+3" +140 INPUT A +150 IF A=1 THEN S=S+1 +160 PRINT "YOUR SCORE";S;"OUT OF 3" +170 END diff --git a/examples/basic/meet-your-color-computer/SIGNAL.bas b/examples/basic/meet-your-color-computer/SIGNAL.bas new file mode 100644 index 0000000..c2bb8b0 --- /dev/null +++ b/examples/basic/meet-your-color-computer/SIGNAL.bas @@ -0,0 +1,5 @@ +10 CLS +20 FOR I=1 TO 3 +30 PRINT "BLINK";I +40 NEXT I +50 PRINT "SIGNAL SENT!" diff --git a/examples/basic/planet-explorer/ADDRESS.bas b/examples/basic/planet-explorer/ADDRESS.bas new file mode 100644 index 0000000..82eaf00 --- /dev/null +++ b/examples/basic/planet-explorer/ADDRESS.bas @@ -0,0 +1,6 @@ +10 WIDTH 40:CLS +20 A=42 +30 PRINT "VALUE";A +40 PRINT "ADDRESS ";HEX$(VARPTR(A)) +50 PRINT "FIRST BYTE";PEEK(VARPTR(A)) +60 END diff --git a/examples/basic/planet-explorer/CHART.bas b/examples/basic/planet-explorer/CHART.bas new file mode 100644 index 0000000..cbaa33b --- /dev/null +++ b/examples/basic/planet-explorer/CHART.bas @@ -0,0 +1,18 @@ +10 WIDTH 40:CLS +20 DIM P$(2),X(2),Y(2) +30 FOR I=1 TO 2:READ P$(I),X(I),Y(I):NEXT I +40 HSCREEN 2:HCLS 0 +42 PALETTE 0,0:PALETTE 1,9:PALETTE 2,36:PALETTE 3,63 +45 HCOLOR 3:HPRINT(1,1),"STAR CHART - PRESS A KEY TO LAND" +50 FOR I=1 TO 2 +60 HCIRCLE(X(I),Y(I)),12,I +70 HSET(X(I),Y(I),I) +75 HPRINT(INT(X(I)/8)-2,INT(Y(I)/8)+2),P$(I) +80 NEXT I +90 A=HPOINT(X(1),Y(1)):B=HPOINT(X(2),Y(2)) +100 IF INKEY$="" THEN 100 +110 HSCREEN 0:PALETTE RGB:WIDTH 40:CLS +120 PRINT P$(1);" MARKER";A +130 PRINT P$(2);" MARKER";B +140 END +150 DATA EARTH,64,80,MARS,176,100 diff --git a/examples/basic/planet-explorer/CONSOLE.bas b/examples/basic/planet-explorer/CONSOLE.bas new file mode 100644 index 0000000..826cd5d --- /dev/null +++ b/examples/basic/planet-explorer/CONSOLE.bas @@ -0,0 +1,13 @@ +10 WIDTH 32:CLS:PRINT "32 COLUMNS - PRESS A KEY" +20 IF INKEY$="" THEN 20 +30 WIDTH 40:CLS:ATTR 3,0 +40 LOCATE 0,1:PRINT "40 COLUMNS - PRESS A KEY"; +50 LOCATE 38,2:PRINT "*"; +60 IF INKEY$="" THEN 60 +70 WIDTH 80:CLS +80 LOCATE 0,1:PRINT "80 COLUMNS"; +90 LOCATE 48,1:PRINT "SUPPLIES LEFT"; +100 LOCATE 0,2:PRINT "PRESS A KEY"; +110 LOCATE 48,2:PRINT USING "##";6 +120 IF INKEY$="" THEN 120 +130 ATTR 0,1:WIDTH 40:CLS:PRINT "BACK AT THE HELM" diff --git a/examples/basic/planet-explorer/HELM.bas b/examples/basic/planet-explorer/HELM.bas new file mode 100644 index 0000000..a5f62e5 --- /dev/null +++ b/examples/basic/planet-explorer/HELM.bas @@ -0,0 +1,10 @@ +10 WIDTH 40:CLS +20 PRINT "PLANET EXPLORER" +30 PRINT "1 EARTH 2 MARS" +40 INPUT "SET COURSE";C$ +50 IF C$="1" THEN P$="EARTH":GOTO 90 +60 IF C$="2" THEN P$="MARS":GOTO 90 +70 PRINT "TRY 1 OR 2" +80 GOTO 40 +90 PRINT "BOUND FOR ";P$ +100 END diff --git a/examples/basic/planet-explorer/LEAK.bas b/examples/basic/planet-explorer/LEAK.bas new file mode 100644 index 0000000..a182f22 --- /dev/null +++ b/examples/basic/planet-explorer/LEAK.bas @@ -0,0 +1,8 @@ +10 WIDTH 40:CLS +20 S=6 +30 FOR T=1 TO 3 +40 S=S-1 +50 S=S-1 +60 PRINT "TURN";T;" SUPPLIES";S +70 NEXT T +80 END diff --git a/examples/basic/planet-explorer/LOCKERS.bas b/examples/basic/planet-explorer/LOCKERS.bas new file mode 100644 index 0000000..224aeff --- /dev/null +++ b/examples/basic/planet-explorer/LOCKERS.bas @@ -0,0 +1,8 @@ +10 WIDTH 40:CLS +20 OPEN "D",#1,"LOCKERS.DAT:0",8 +30 FIELD #1,8 AS N$ +40 LSET N$="EARTH":PUT #1,1 +50 LSET N$="MARS":PUT #1,2 +60 GET #1,2:PRINT "LOCKER TWO: ";N$ +70 GET #1,1:PRINT "LOCKER ONE: ";N$ +80 CLOSE #1 diff --git a/examples/basic/planet-explorer/LOGBOOK.bas b/examples/basic/planet-explorer/LOGBOOK.bas new file mode 100644 index 0000000..65a9b6d --- /dev/null +++ b/examples/basic/planet-explorer/LOGBOOK.bas @@ -0,0 +1,9 @@ +10 WIDTH 80:CLS +20 OPEN "I",#1,"VOYAGE.DAT:0" +30 INPUT #1,P$,S +40 CLOSE #1 +50 LOCATE 0,1:PRINT "FLIGHT LOG"; +60 LOCATE 48,1:PRINT "SUPPLIES LEFT"; +70 LOCATE 0,2:PRINT P$; +80 LOCATE 48,2:PRINT S +90 END diff --git a/examples/basic/planet-explorer/ORDER.bas b/examples/basic/planet-explorer/ORDER.bas new file mode 100644 index 0000000..574912e --- /dev/null +++ b/examples/basic/planet-explorer/ORDER.bas @@ -0,0 +1,10 @@ +10 WIDTH 40:CLS +20 PRINT 2+3*4 +30 PRINT (2+3)*4 +40 PRINT 2^3 +50 PRINT 6/2-1 +60 PRINT 4>3;4=3;4<>3 +70 PRINT "RED"+" DUST" +80 PRINT (4>3) AND (2=2) +90 PRINT NOT (4>3) +100 END diff --git a/examples/basic/planet-explorer/PAGES.bas b/examples/basic/planet-explorer/PAGES.bas new file mode 100644 index 0000000..85b9681 --- /dev/null +++ b/examples/basic/planet-explorer/PAGES.bas @@ -0,0 +1,13 @@ +5 WIDTH 32:CLS +10 PMODE 1,1:PCLS 0:SCREEN 1,0 +20 COLOR 1,0:LINE(16,16)-(95,95),PSET,BF +30 PMODE 1,3:PCLS 0:COLOR 3,0 +40 LINE(160,64)-(223,127),PSET,BF +50 IF INKEY$="" THEN 50 +60 SCREEN 1,0 +70 IF INKEY$="" THEN 70 +80 PMODE 1,1:SCREEN 1,0 +90 IF INKEY$="" THEN 90 +100 SCREEN 0,0:WIDTH 40:CLS +110 PRINT "BOTH PAGES ARE HOME" +120 END diff --git a/examples/basic/planet-explorer/RADAR.bas b/examples/basic/planet-explorer/RADAR.bas new file mode 100644 index 0000000..802683c --- /dev/null +++ b/examples/basic/planet-explorer/RADAR.bas @@ -0,0 +1,8 @@ +10 WIDTH 40:CLS +20 PRINT "RIGHT STICK SCANNER" +30 PRINT "MOVE THE STICK. PRESS A KEY TO SCAN." +40 IF INKEY$="" THEN 40 +50 X=JOYSTK(0) +60 IF X<24 THEN PRINT "WEST SIGNAL":END +70 IF X>39 THEN PRINT "EAST SIGNAL":END +80 PRINT "CENTER SIGNAL" diff --git a/examples/basic/planet-explorer/RATIONS.bas b/examples/basic/planet-explorer/RATIONS.bas new file mode 100644 index 0000000..e07de45 --- /dev/null +++ b/examples/basic/planet-explorer/RATIONS.bas @@ -0,0 +1,7 @@ +10 WIDTH 40:CLS +20 S=6 +30 FOR T=1 TO 3 +40 S=S-1 +60 PRINT "TURN";T;" SUPPLIES";S +70 NEXT T +80 END diff --git a/examples/basic/planet-explorer/VOYAGE.bas b/examples/basic/planet-explorer/VOYAGE.bas new file mode 100644 index 0000000..3e97f1b --- /dev/null +++ b/examples/basic/planet-explorer/VOYAGE.bas @@ -0,0 +1,33 @@ +5 DIM P$(2),X(2),Y(2) +6 FOR I=1 TO 2:READ P$(I),X(I),Y(I):NEXT I +10 WIDTH 40:CLS +20 PRINT "FLIGHT DECK" +30 PRINT "1 EARTH 2 MARS" +40 INPUT "SET COURSE";C$ +50 IF C$="1" THEN D=1:GOTO 90 +60 IF C$="2" THEN D=2:GOTO 90 +70 PRINT "TRY 1 OR 2" +80 GOTO 40 +90 S=6 +100 FOR T=1 TO D+1 +110 S=S-1 +120 PRINT "TURN";T;" SUPPLIES";S +130 NEXT T +135 GOSUB 300 +140 PLAY "T180O3L8CEG" +150 GOSUB 200 +160 PRINT "LOG SAVED FOR ";P$(D) +170 END +200 OPEN "O",#1,"VOYAGE.DAT:0" +210 WRITE #1,P$(D),S +220 CLOSE #1 +230 RETURN +300 HSCREEN 2:HCLS 0:HCOLOR 3 +305 PALETTE 0,0:PALETTE 1,9:PALETTE 2,36:PALETTE 3,63 +310 HPRINT(1,1),"LANDING AT "+P$(D) +320 HCIRCLE(X(D),Y(D)),12,D +330 HSET(X(D),Y(D),D) +340 HPRINT(1,20),"PRESS A KEY TO LAND" +350 IF INKEY$="" THEN 350 +360 HSCREEN 0:PALETTE RGB:WIDTH 40:CLS:RETURN +400 DATA EARTH,64,80,MARS,176,100 diff --git a/examples/basic/planet.bas b/examples/basic/planet.bas new file mode 100644 index 0000000..5ea69b7 --- /dev/null +++ b/examples/basic/planet.bas @@ -0,0 +1,14 @@ +10 REM EARTH OR MARS - COCO 3 +20 WIDTH 40:CLS +30 PRINT "What planet do you live on?" +40 PRINT "1) Earth" +50 PRINT "2) Mars" +60 K$=INKEY$ +70 IF K$="1" THEN 110 +80 IF K$<>"2" THEN 60 +90 PALETTE 6,37:M$="Hello Cold Red Dot World!" +100 GOTO 120 +110 PALETTE 6,10:M$="Hello Nice Blue Dot World!" +120 ATTR 3,6 +130 PRINT M$ +140 ATTR 0,0:END diff --git a/examples/basic/software-storage-and-peripherals/CARGO.bas b/examples/basic/software-storage-and-peripherals/CARGO.bas new file mode 100644 index 0000000..12aa058 --- /dev/null +++ b/examples/basic/software-storage-and-peripherals/CARGO.bas @@ -0,0 +1 @@ +10 PRINT "CARGO ORIGINAL" diff --git a/examples/basic/software-storage-and-peripherals/VOICE.bas b/examples/basic/software-storage-and-peripherals/VOICE.bas new file mode 100644 index 0000000..cd2bc20 --- /dev/null +++ b/examples/basic/software-storage-and-peripherals/VOICE.bas @@ -0,0 +1,12 @@ +10 REM A GREETING FOR THE SPEECH/SOUND CARTRIDGE +20 A=&HFF7E +30 M$="HELLO FROM YOUR COLOR COMPUTER. "+CHR$(13) +40 PRINT "SENDING GREETING" +50 FOR I=1 TO LEN(M$) +60 T=0 +70 IF PEEK(A)>=128 THEN 100 +80 T=T+1:IF T<500 THEN 70 +90 PRINT "CHECK SPEECH CARTRIDGE":END +100 POKE A,ASC(MID$(M$,I,1)) +110 NEXT I +120 PRINT "GREETING SENT" diff --git a/examples/basic/users-handbook/KEYS.bas b/examples/basic/users-handbook/KEYS.bas new file mode 100644 index 0000000..c5d7c43 --- /dev/null +++ b/examples/basic/users-handbook/KEYS.bas @@ -0,0 +1,4 @@ +10 CLS +20 INPUT "FLIGHT NUMBER";N +30 PRINT "FLIGHT";N +40 END diff --git a/examples/basic/users-handbook/LANDPAD.bas b/examples/basic/users-handbook/LANDPAD.bas new file mode 100644 index 0000000..9abff5c --- /dev/null +++ b/examples/basic/users-handbook/LANDPAD.bas @@ -0,0 +1,17 @@ +10 WIDTH 32:CLS +20 PRINT "BEACON LANDING" +30 PRINT "FIND THE PAD WITH THE BEACON." +40 PRINT "PRESS L OR R TO LAND." +50 PRINT "PRESS SPACE TO SEE THE PADS." +60 IF INKEY$<>" " THEN 60 +70 PMODE 4,1:PCLS 0:SCREEN 1,1 +80 FOR X=26 TO 96 STEP 2 +90 LINE (X,86)-(X,140),PSET +100 LINE (X+131,86)-(X+131,140),PSET +110 NEXT X +120 LINE (192,38)-(192,66),PSET +130 LINE (178,52)-(206,52),PSET +140 K$=INKEY$:IF K$<>"L" AND K$<>"R" THEN 140 +150 SCREEN 0,0:CLS +160 IF K$="R" THEN PRINT "BEACON FOUND!":END +170 PRINT "DARK PAD. TRY THE OTHER ONE!":END diff --git a/examples/cmoc/HelloDisk/.gitignore b/examples/cmoc/HelloDisk/.gitignore new file mode 100644 index 0000000..ceb23d3 --- /dev/null +++ b/examples/cmoc/HelloDisk/.gitignore @@ -0,0 +1,7 @@ +obj/ +generated/ +HELLO.bin +HELLO.dsk +HELLO.map +HELLO.link +.vccplus-build/ diff --git a/examples/cmoc/HelloDisk/Makefile b/examples/cmoc/HelloDisk/Makefile new file mode 100644 index 0000000..8132fd9 --- /dev/null +++ b/examples/cmoc/HelloDisk/Makefile @@ -0,0 +1,74 @@ +# Generated by VCC Plus — edit Project Settings to regenerate. +# Ordinary GNU Make; no VCC Plus project parser is required to build it. +CMOC ?= cmoc +PERL ?= perl +WRITECOCOFILE ?= writecocofile +INSTALL_LOADER ?= install-coco-boot-loader +VCC_CONFIGURATION ?= Debug +ifeq ($(VCC_CONFIGURATION),Release) +OPTIM ?= -O2 +else +OPTIM ?= -O0 +DEBUG_FRAME ?= -fno-omit-frame-pointer +endif +define VCC_DEFINES + +endef +define VCC_COMPILER_OPTIONS + +endef +define VCC_LINKER_OPTIONS + +endef +CPPFLAGS += -Iinclude $(VCC_DEFINES) +CFLAGS += --coco --intermediate --deps --stack-space=2048 $(OPTIM) $(DEBUG_FRAME) $(VCC_COMPILER_OPTIONS) +LDFLAGS += --coco --intermediate --org=2800 $(VCC_LINKER_OPTIONS) +LDLIBS += -ldecbfile +OBJECTS := obj/main.o obj/src/display.o obj/src/disk.o obj/generated/word-count.o +.PHONY: all build clean disk libraries +all: build +build: HELLO.bin +HELLO.bin: $(OBJECTS) Makefile + @mkdir -p $(dir $@) + "$(CMOC)" $(LDFLAGS) -o $@ $(OBJECTS) $(LDLIBS) +obj/main.o: main.c Makefile generated/word-count.c generated/WORDS.DAT + @mkdir -p $(dir $@) + "$(CMOC)" $(CPPFLAGS) $(CFLAGS) --intdir=$(dir $@) -c -o $@ $< + +obj/src/display.o: src/display.c Makefile generated/word-count.c generated/WORDS.DAT + @mkdir -p $(dir $@) + "$(CMOC)" $(CPPFLAGS) $(CFLAGS) --intdir=$(dir $@) -c -o $@ $< + +obj/src/disk.o: src/disk.c Makefile generated/word-count.c generated/WORDS.DAT + @mkdir -p $(dir $@) + "$(CMOC)" $(CPPFLAGS) $(CFLAGS) --intdir=$(dir $@) -c -o $@ $< + +obj/generated/word-count.o: generated/word-count.c Makefile generated/word-count.c generated/WORDS.DAT + @mkdir -p $(dir $@) + "$(CMOC)" $(CPPFLAGS) $(CFLAGS) --intdir=$(dir $@) -c -o $@ $< + +generated/word-count.c generated/WORDS.DAT &: tools/build-data.pl assets/words.txt Makefile + @mkdir -p generated + $(PERL) tools/build-data.pl assets/words.txt generated/word-count.c generated/WORDS.DAT + test -f generated/word-count.c + test -f generated/WORDS.DAT + +# DOS helper: Pierre Sarrazin, autostart.c 0.1.2, public domain. +obj/vcc-dos-boot/loader.bin: Makefile + @mkdir -p $(dir $@) + @printf '%s\n' '// autostart.c - Program to be run by the Disk Basic DOS command.' '// By Pierre Sarrazin ' '// This file is in the public domain.' '//' '// Reference: Roger Schrag, "A Special Use For The DOS Command",' '// The Rainbow, November 1984, p.140.' '//' '// To compile: cmoc --dos autostart.c' '// To install on CoCo disk image: install-coco-boot-loader some-image.dsk autostart.bin' '// To run on CoCo: type DOS and to automatically run *.BAS.' '//' '// Version history:' '// 0.1.0 2016-01-16 Use of legacy.h discontinued.' '// 0.1.1 2018-04-03 Adapted to CMOC 0.1.51 (const).' '// 0.1.2 2018-08-04 Basic line now forced to be uppercase.' '' '#include ' '' '#define ENDFLG 0x00 // STOP/END FLAG: POSITIVE=STOP, NEG=END' '#define CINBFL 0x70 // CONSOLE IN BUFFER FLAG: 00=NOT EMPTY, $$FF=EMPTY' '#define RVEC4 0x016a // RAM hook: CONSOLE IN' '' '' 'byte oldHookInstr;' 'word oldHookAddr;' 'const char *basicLineReader;' '' '' 'void feedKeyboard()' '{' ' word preservedX;' ' asm("stx", preservedX);' '' ' * (byte *) CINBFL = 0; // console in buffer now not empty' '' ' char nextBasicByte = (char) toupper(*basicLineReader);' ' ++basicLineReader;' ' if (nextBasicByte == 0) // if finished returning Basic line' ' {' ' * (byte *) RVEC4 = oldHookInstr;' ' * (word *) (RVEC4 + 1) = oldHookAddr;' ' nextBasicByte = '"'"'\r'"'"'; // return "Enter" to cause execution of Basic line' ' }' '' ' asm {' ' lda nextBasicByte' ' ldx preservedX' ' tfr u,s // discard stack frame' ' leas 4,s // discard previous stack frame ptr and return addr' ' rts // return to caller of CONSOLE IN' ' }' '}' '' '' 'int main()' '{' ' * (byte *) ENDFLG = - * (byte *) ENDFLG; // why?' '' ' basicLineReader =' ' #ifndef COMMAND' ' "RUN\"*.BAS\""' ' #else' ' COMMAND' ' #endif' ' ;' '' ' // Install function feedKeyboard() as CONSOLE IN routine.' ' //' ' oldHookInstr = * (byte *) RVEC4;' ' oldHookAddr = * (word *) (RVEC4 + 1);' '' ' * (byte *) RVEC4 = 0x7e; // JMP instruction' ' * (void **) (RVEC4 + 1) = (void *) feedKeyboard;' '' ' * (word *) 0x2600 = 0; // overwrite "OS" marker with two null bytes' '' ' asm("jmp", "$$ac7c"); // go interpret a Basic line (which is read from console)' '' ' return 0; // avoids compiler error' '}' > obj/vcc-dos-boot/loader.c + "$(CMOC)" --dos -O0 --limit=2800 -o $@ '-DCOMMAND="LOADM\"HELLO.BIN\":EXEC"' obj/vcc-dos-boot/loader.c + +disk: HELLO.dsk +HELLO.dsk: HELLO.bin generated/WORDS.DAT obj/vcc-dos-boot/loader.bin Makefile + @mkdir -p $(dir $@) + $(PERL) -e 'print chr(255) x (35*18*256)' > $@ + $(INSTALL_LOADER) $@ obj/vcc-dos-boot/loader.bin + $(WRITECOCOFILE) $@ HELLO.bin + $(WRITECOCOFILE) $@ generated/WORDS.DAT + +clean: + rm -rf obj + rm -f HELLO.bin HELLO.map HELLO.link HELLO.dsk generated/word-count.c generated/WORDS.DAT + +-include $(OBJECTS:.o=.d) diff --git a/examples/cmoc/HelloDisk/README.md b/examples/cmoc/HelloDisk/README.md new file mode 100644 index 0000000..dc754dd --- /dev/null +++ b/examples/cmoc/HelloDisk/README.md @@ -0,0 +1,45 @@ +# Hello Disk — CMOC project example + +An authored VCC Plus example under GPL-3.0-or-later, using the public-domain, +ROM-backed decbfile library included in the development runtime. No game source, +ROM, third-party standalone disk driver, generated executable, or disk image is +included in this example. + +1. In VCC Plus choose **Develop → C Development → New** and select **Hello Disk — multi-file disk example** (the default). Choose a new writable folder. +2. Alternatively, copy this repository folder and **Open** it. Both approaches create your own editable source; the installed template stays unchanged. +3. **Project Settings** shows the source files, include directory, disk library, + generated resource recipe and disk launch command. Its Makefile is generated + using the same settings available in that window. +4. Boot the **Disk BASIC** machine profile. **Build** creates `HELLO.bin` and a + `HELLO.dsk` containing the executable and `WORDS.DAT`, entirely in the isolated + build workspace. It does not alter your source folder or mounted disks. +5. Use the disk launch control to mount the development disk in FD0 and run the + configured `DOS` command. You can also type `LOADM"HELLO":EXEC` at BASIC. + Confirm the media replacement when + prompted; retain any existing unsaved disk changes first. +6. The program reads its words from the emulated floppy through the Disk BASIC + ROM, prints them, then reports disk result `0` and generated word count `5`. + +`main.c` calls functions in `src/display.c` and `src/disk.c`. Their shared header +is `include/hello.h`. A short Perl build recipe turns `assets/words.txt` into a C +translation unit and disk data together. Change the word list, build again and +observe the regenerated outputs. Add a breakpoint on an executable C line to +inspect the program using the existing debugger. Generated C can be inspected +from the frozen build snapshot; the editable input is the word list and recipe. + +**Project Settings → Disk & Run → DOS boot** defaults to **Run this program** +for new Hello Disk copies. The build creates a small public-domain loader from +Pierre Sarrazin’s `autostart.c` under `obj/vcc-dos-boot` and reserves track 34 +before adding files. It does not add a C source file to your editable project. +Choose **None** to build a disk without DOS boot. Existing project copies are +not changed automatically. Building or mounting alone does not run the program. + +For command-line builds, put VCC Plus's `Contents/Resources/Toolchain/bin` on +`PATH` and run its bundled `make disk`. `make VCC_CONFIGURATION=Release disk` +uses the optimized configuration. Source changes are tracked through CMOC `.d` +header dependencies. `make clean` removes generated objects, data and disks. +Unlike the native app's isolated build, command-line Make writes these outputs +in this folder. + +This example needs a functioning CoCo/Disk BASIC ROM configuration and keeps +those ROM services mapped. It is not a standalone-ROM-free disk implementation. diff --git a/examples/cmoc/HelloDisk/assets/words.txt b/examples/cmoc/HelloDisk/assets/words.txt new file mode 100644 index 0000000..b88f98d --- /dev/null +++ b/examples/cmoc/HelloDisk/assets/words.txt @@ -0,0 +1,5 @@ +HELLO +WORLD +CMOC +VCC +PLUS diff --git a/examples/cmoc/HelloDisk/include/hello.h b/examples/cmoc/HelloDisk/include/hello.h new file mode 100644 index 0000000..2ba7d41 --- /dev/null +++ b/examples/cmoc/HelloDisk/include/hello.h @@ -0,0 +1,8 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#ifndef HELLO_DISK_H +#define HELLO_DISK_H +#include +extern const unsigned char generatedWordCount; +void showHeading(void); +unsigned char showDiskWords(void); +#endif diff --git a/examples/cmoc/HelloDisk/main.c b/examples/cmoc/HelloDisk/main.c new file mode 100644 index 0000000..c469f82 --- /dev/null +++ b/examples/cmoc/HelloDisk/main.c @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#include +#include +#include "hello.h" + +int main(void) +{ + unsigned char status; + initCoCoSupport(); + setHighSpeed(FALSE); + showHeading(); + status = showDiskWords(); + printf("DISK RESULT: %u\n", status); + printf("GENERATED WORD COUNT: %u\n", generatedWordCount); + return status; +} diff --git a/examples/cmoc/HelloDisk/src/disk.c b/examples/cmoc/HelloDisk/src/disk.c new file mode 100644 index 0000000..e945a1c --- /dev/null +++ b/examples/cmoc/HelloDisk/src/disk.c @@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#include +#include +#include "hello.h" + +static DECBDrive drives[1]; +static DECBFile file; +static byte words[256]; + +byte showDiskWords(void) +{ + byte status = decb_init(drives, 1); + if (status != DECB_OK) + return status; + status = decb_registerDrive(0); + if (status == DECB_OK) + status = decb_openSectorFile(&file, 0, "WORDS.DAT"); + if (status == DECB_OK) + { + status = decb_readSector(&file, words, 0); + words[255] = 0; + if (status == DECB_OK) + printf("%s\n", words); + decb_closeSectorFile(&file); + } + decb_shutdown(); + return status; +} diff --git a/examples/cmoc/HelloDisk/src/display.c b/examples/cmoc/HelloDisk/src/display.c new file mode 100644 index 0000000..f4f277d --- /dev/null +++ b/examples/cmoc/HelloDisk/src/display.c @@ -0,0 +1,8 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#include +#include "hello.h" +void showHeading(void) +{ + printf("HELLO FROM A MULTI-FILE PROJECT\n"); + printf("WORDS READ FROM THE FLOPPY:\n"); +} diff --git a/examples/cmoc/HelloDisk/tools/build-data.pl b/examples/cmoc/HelloDisk/tools/build-data.pl new file mode 100644 index 0000000..5dca810 --- /dev/null +++ b/examples/cmoc/HelloDisk/tools/build-data.pl @@ -0,0 +1,24 @@ +#!/usr/bin/env perl +# SPDX-License-Identifier: GPL-3.0-or-later +use strict; +use warnings; +@ARGV == 3 or die "Usage: build-data.pl words.txt generated.c WORDS.DAT\n"; +my ($input, $source, $disk_data) = @ARGV; +open my $in, '<', $input or die "$input: $!\n"; +my @words; +while (<$in>) { + s/\r?\n\z//; + next if $_ eq ''; + /\A[A-Z]+\z/ or die "Words must contain uppercase A-Z only\n"; + push @words, $_; +} +close $in; +@words <= 255 or die "Too many words\n"; +my $bytes = join("\r", @words) . "\r\0"; +length($bytes) <= 256 or die "Example data must fit one disk sector\n"; +open my $c, '>', $source or die "$source: $!\n"; +print {$c} "/* Generated from assets/words.txt. */\n#include \nconst unsigned char generatedWordCount = " . scalar(@words) . ";\n"; +close $c or die "$source: $!\n"; +open my $data, '>:raw', $disk_data or die "$disk_data: $!\n"; +print {$data} $bytes . ("\0" x (256 - length($bytes))); +close $data or die "$disk_data: $!\n"; diff --git a/examples/cmoc/HelloDisk/vccplus-project.json b/examples/cmoc/HelloDisk/vccplus-project.json new file mode 100644 index 0000000..3892924 --- /dev/null +++ b/examples/cmoc/HelloDisk/vccplus-project.json @@ -0,0 +1,79 @@ +{ + "binary" : "HELLO.bin", + "buildTarget" : "disk", + "cleanTarget" : "clean", + "configurations" : [ + { + "makeArguments" : [ + + ], + "name" : "Debug" + }, + { + "makeArguments" : [ + "VCC_CONFIGURATION=Release" + ], + "name" : "Release" + } + ], + "diskImage" : "HELLO.dsk", + "diskTarget" : "disk", + "entrySource" : "main.c", + "jobs" : 4, + "launchCommands" : [ + "DOS" + ], + "launchMode" : "disk", + "makefile" : "Makefile", + "makefileSettings" : { + "compilerOptions" : [ + + ], + "defines" : [ + + ], + "diskBootMode" : "program", + "diskFiles" : [ + "generated/WORDS.DAT" + ], + "diskImage" : "HELLO.dsk", + "executable" : "HELLO.bin", + "generatedResources" : [ + { + "command" : "$(PERL) tools/build-data.pl assets/words.txt generated/word-count.c generated/WORDS.DAT", + "inputs" : [ + "tools/build-data.pl", + "assets/words.txt" + ], + "outputs" : [ + "generated/word-count.c", + "generated/WORDS.DAT" + ] + } + ], + "includePaths" : [ + "include" + ], + "libraries" : [ + "decbfile" + ], + "libraryPaths" : [ + + ], + "libraryProjects" : [ + + ], + "linkerOptions" : [ + + ], + "origin" : "2800", + "releaseOptimization" : "-O2", + "sources" : [ + "main.c", + "src/display.c", + "src/disk.c", + "generated/word-count.c" + ], + "stackSpace" : 2048 + } +} \ No newline at end of file diff --git a/examples/cmoc/MissionRecorder/Makefile b/examples/cmoc/MissionRecorder/Makefile new file mode 100644 index 0000000..22ececb --- /dev/null +++ b/examples/cmoc/MissionRecorder/Makefile @@ -0,0 +1,57 @@ +# Generated by VCC Plus — edit Project Settings to regenerate. +# Ordinary GNU Make; no VCC Plus project parser is required to build it. +CMOC ?= cmoc +PERL ?= perl +WRITECOCOFILE ?= writecocofile +INSTALL_LOADER ?= install-coco-boot-loader +VCC_CONFIGURATION ?= Debug +ifeq ($(VCC_CONFIGURATION),Release) +OPTIM ?= -O2 +else +OPTIM ?= -O0 +DEBUG_FRAME ?= -fno-omit-frame-pointer +endif +define VCC_DEFINES + +endef +define VCC_COMPILER_OPTIONS + +endef +define VCC_LINKER_OPTIONS + +endef +export VCC_CMOC_COMPAT = 1 +CPPFLAGS += $(VCC_DEFINES) +CFLAGS += --coco --intermediate --deps --stack-space=2048 $(OPTIM) $(DEBUG_FRAME) $(VCC_COMPILER_OPTIONS) +LDFLAGS += --coco --intermediate --org=2000 --limit=7800 $(VCC_LINKER_OPTIONS) +LDLIBS += -lbank -lgime -linput -lbcontrol -lssc -lorch90 -lhirestxt -lvcccompat -ldecbfile +OBJECTS := obj/main.o obj/flight.o obj/report.o +.PHONY: all build clean disk libraries +all: build +build: RECORDER.bin +RECORDER.bin: $(OBJECTS) Makefile + @mkdir -p $(dir $@) + "$(CMOC)" $(LDFLAGS) -o $@ $(OBJECTS) $(LDLIBS) +obj/main.o: main.c Makefile + @mkdir -p $(dir $@) + "$(CMOC)" $(CPPFLAGS) $(CFLAGS) --intdir=$(dir $@) -c -o $@ $< + +obj/flight.o: flight.c Makefile + @mkdir -p $(dir $@) + "$(CMOC)" $(CPPFLAGS) $(CFLAGS) --intdir=$(dir $@) -c -o $@ $< + +obj/report.o: report.c Makefile + @mkdir -p $(dir $@) + "$(CMOC)" $(CPPFLAGS) $(CFLAGS) --intdir=$(dir $@) -c -o $@ $< + +disk: RECORDER.dsk +RECORDER.dsk: RECORDER.bin Makefile + @mkdir -p $(dir $@) + $(PERL) -e 'print chr(255) x (35*18*256)' > $@ + $(WRITECOCOFILE) $@ RECORDER.bin + +clean: + rm -rf obj + rm -f RECORDER.bin RECORDER.map RECORDER.link RECORDER.dsk + +-include $(OBJECTS:.o=.d) diff --git a/examples/cmoc/MissionRecorder/flight.c b/examples/cmoc/MissionRecorder/flight.c new file mode 100644 index 0000000..8699a9a --- /dev/null +++ b/examples/cmoc/MissionRecorder/flight.c @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include +#include +#include +#include +#include +#include +#include "mission.h" + +enum { SKY, WHITE, ICE, GOLD, BASALT, RIDGE, TEAL }; +#define NO_MARK 255 +/* The steady beacon plays from resident, read-only data during the flight. */ +static const struct orch90_frame beacon[] = { + {128,128}, {142,128}, {148,128}, {142,128}, {128,128}, {114,128}, {108,128}, {114,128}, + {128,128}, {142,128}, {148,128}, {142,128}, {128,128}, {128,128}, {128,128}, {128,128}, + {128,128}, {128,128}, {128,142}, {128,142}, {128,148}, {128,148}, {128,142}, {128,142}, + {128,128}, {128,128}, {128,114}, {128,114}, {128,128}, {128,128}, {128,128}, {128,128} +}; +static byte previousShip[2], previousMark[2], hidden; + +static void label(unsigned x, byte y, const char *text, byte color) +{ + while (*text) { + const byte *glyph = font5x8 + ((unsigned)*text++ - ' ') * 8; + byte row, col; + for (row = 0; row < 8; ++row) + for (col = 0; col < 5; ++col) + if (!(glyph[row] & (0x80 >> col))) + gime_plot(x + col, y + row, color); + x += 6; + } +} + +/* Paint the permanent landscape once on each page before switching on sound. */ +static void landscape(void) +{ + unsigned i; + gime_clear(SKY); + label(8, 7, "MISSION RECORDER", ICE); + label(240, 7, "SURVEY / 01", WHITE); + gime_fill_rect(8, 20, 304, 1, TEAL); + for (i = 0; i < 16; ++i) { + unsigned x = i * 20, y = 106 + ((i * 7) % 19); + gime_plot(x + 4, 28 + ((i * 11) % 17), WHITE); + gime_fill_rect(x, y, 20, 141 - y, BASALT); + gime_fill_rect(x, y, 20, 2, RIDGE); + gime_fill_rect(x + 9, 139, 2, 4, ICE); + } + label(8, 149, "SECTOR 07 MARK --", WHITE); + label(8, 164, "A/D OR RIGHT STICK: STEER SPACE/FIRE: MARK", WHITE); + label(8, 178, "S: SAVE AND PRINT Q: DISCARD", ICE); +} + +static void digits(unsigned x, byte value) +{ + char pair[3]; + pair[0] = '0' + value / 10; + pair[1] = '0' + value % 10; + pair[2] = 0; + gime_fill_rect(x, 149, 11, 8, SKY); + label(x, 149, pair, WHITE); +} + +/* Each hidden page remembers where its own ship was painted. Erase just + that footprint. A mark stays put for the rest of this flight. */ +static byte draw(byte sector, byte mark) +{ + byte old = previousShip[hidden]; + unsigned x = (unsigned)sector * 20; + if (old != sector) { + if (old != NO_MARK) + gime_fill_rect((unsigned)old * 20 + 2, 53, 16, 12, SKY); + gime_fill_rect(x + 7, 53, 6, 3, ICE); + gime_fill_rect(x + 4, 56, 12, 3, WHITE); + gime_fill_rect(x + 2, 59, 16, 3, TEAL); + gime_fill_rect(x + 5, 62, 2, 3, GOLD); + gime_fill_rect(x + 13, 62, 2, 3, GOLD); + digits(50, sector); + previousShip[hidden] = sector; + } + if (mark != NO_MARK && previousMark[hidden] != mark) { + gime_fill_rect((unsigned)mark * 20 + 8, 68, 4, 4, GOLD); + digits(110, mark); + previousMark[hidden] = mark; + } + hidden ^= 1; + return gime_present(); +} + +static byte flightLoop(byte speech, byte *mark, byte *speechError) +{ + VccInput stick; + byte sector = 7, recorded = NO_MARK; + ssc_phrase words; + byte exit = 0; + unsigned started = 0, lastSample = getTimer(); + words.remaining = 0; + input_init(&stick, INPUT_RIGHT); + for (;;) { + byte key = inkey(), fire = 0, previous = sector; + unsigned now = getTimer(); + if (key >= 'a' && key <= 'z') key -= 'a' - 'A'; + if (key == 'Q') exit = DISCARDED; + if (key == 'S' && recorded != NO_MARK) exit = RECORDED; + /* Service one cartridge byte per turn. Remember Save or Quit even + when there is no ready signal. Two seconds bounds the whole phrase. */ + if (words.remaining) { + if ((unsigned)(now - started) < 120) ssc_service(&words); + else { words.remaining = 0; *speechError = SSC_TIMEOUT; } + } + if (exit) { + if (words.remaining) continue; + if (exit == RECORDED && !bank_read(0, mark, 1)) return FLIGHT_ERROR; + return exit; + } + if ((unsigned)(now - lastSample) >= 5) { + lastSample = now; + input_sample(&stick); + fire = stick.pressed & INPUT_PRIMARY; + if (stick.dx < 0 && sector > 0) --sector; + if (stick.dx > 0 && sector < 15) ++sector; + } + if (key == 'A' && sector > 0) --sector; + if (key == 'D' && sector < 15) ++sector; + if ((key == ' ' || fire) && recorded == NO_MARK) { + if (!bank_write(0, §or, 1)) return FLIGHT_ERROR; + recorded = sector; + if (speech) { + started = now; + ssc_begin_phrase(&words, "MARK RECORDED"); + } + } else if (previous == sector) { + continue; + } + if (!draw(sector, recorded)) { + if (words.remaining) *speechError = SSC_TIMEOUT; + return FLIGHT_ERROR; + } + } +} + +unsigned char fly(unsigned char audio, unsigned char *mark) +{ + static const byte colors[] = {0x01, 0x3f, 0x1f, 0x36, 0x20, 0x34, 0x0f}; + byte i, result = FLIGHT_ERROR, stereo = 0, speechError = SSC_OK; + unsigned route = 0; + if (!bank_open()) { + printf("USE STANDARD COCO 3 BASIC WITH\n512K OR MORE\n"); + return FLIGHT_ERROR; + } + if (!gime_open()) { + bank_close(); + printf("GRAPHICS UNAVAILABLE\n"); + return FLIGHT_ERROR; + } + for (i = 0; i < sizeof(colors); ++i) gime_set_palette(i, colors[i]); + previousShip[0] = previousShip[1] = NO_MARK; + previousMark[0] = previousMark[1] = NO_MARK; + hidden = 0; + landscape(); + if (gime_present()) { + /* Show the ship only when the second page and controls are ready. */ + landscape(); + if (audio & AUDIO_SPEECH) route = ssc_route_audio(); + if (audio & AUDIO_STEREO) + stereo = orch90_start(beacon, sizeof(beacon) / sizeof(beacon[0]), 1, ORCH90_CLOCK_NORMAL); + if (draw(7, NO_MARK)) + result = flightLoop(audio & AUDIO_SPEECH, mark, &speechError); + if (stereo) orch90_stop(); + if (audio & AUDIO_SPEECH) { + if (speechError == SSC_TIMEOUT) ssc_reset(); + ssc_restore_audio(route); + } + } + gime_close(); + bank_close(); + if (speechError != SSC_OK) printf("SPEECH UNAVAILABLE\n"); + if ((audio & AUDIO_STEREO) && !stereo) printf("STEREO PLAYER UNAVAILABLE\n"); + if (result == FLIGHT_ERROR) printf("FLIGHT TRANSFER OR DISPLAY ERROR\n"); + return result; +} diff --git a/examples/cmoc/MissionRecorder/main.c b/examples/cmoc/MissionRecorder/main.c new file mode 100644 index 0000000..a04ce41 --- /dev/null +++ b/examples/cmoc/MissionRecorder/main.c @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include "mission.h" + +int main(void) +{ + byte key, sector, result; + cls(1); + printf("MISSION RECORDER\n\n1 SILENT 2 SPEECH\n3 STEREO 4 BOTH\nQ QUIT\nSELECT AUDIO\n"); + do { + key = waitkey(0); + if (key == 'Q' || key == 'q') return 0; + } while (key < '1' || key > '4'); + + result = fly(key - '1', §or); + if (result == DISCARDED) printf("FLIGHT DISCARDED\n"); + if (result == FLIGHT_ERROR) return 1; + if (result == RECORDED) return saveReport(sector); + return 0; +} diff --git a/examples/cmoc/MissionRecorder/mission.h b/examples/cmoc/MissionRecorder/mission.h new file mode 100644 index 0000000..df8bdc5 --- /dev/null +++ b/examples/cmoc/MissionRecorder/mission.h @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#ifndef MISSION_H +#define MISSION_H + +#define AUDIO_SPEECH 1 +#define AUDIO_STEREO 2 + +enum FlightResult { FLIGHT_ERROR, DISCARDED, RECORDED }; + +unsigned char fly(unsigned char audio, unsigned char *mark); +int saveReport(unsigned char sector); + +#endif diff --git a/examples/cmoc/MissionRecorder/report.c b/examples/cmoc/MissionRecorder/report.c new file mode 100644 index 0000000..2eeaa96 --- /dev/null +++ b/examples/cmoc/MissionRecorder/report.c @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include +#include +#include +#include "mission.h" + +enum { IO_ERROR, MISSING, OCCUPIED }; + +static int inspect(const char *name) +{ + FILE *f = fopen(name, "rb"); + if (!f) return vcc_file_error() == DECB_ERR_NOT_FOUND ? MISSING : IO_ERROR; + return fclose(f) == 0 ? OCCUPIED : IO_ERROR; +} + +/* Verify every byte, the exact EOF, and the close before publishing the name. */ +static int matches(const char *name, const char *report) +{ + FILE *f = fopen(name, "rb"); + if (!f) return 0; + while (*report && fgetc(f) == *report) ++report; + int exact = !*report && fgetc(f) == EOF && !ferror(f); + return fclose(f) == 0 && exact; +} + +static int publish(const char *report, char *name) +{ + char draft[] = "LOG00.TMP:0"; + unsigned i; + for (i = 1; i <= 99; ++i) { + name[3] = draft[3] = (char)('0' + i / 10); + name[4] = draft[4] = (char)('0' + i % 10); + int live = inspect(name), temp = inspect(draft); + if (live == IO_ERROR || temp == IO_ERROR) return 0; + if (live == OCCUPIED || temp == OCCUPIED) continue; + + /* Old reports and interrupted drafts belong to the disk owner. + Only an unused pair is eligible. rename also refuses collisions. */ + FILE *f = fopen(draft, "w"); + if (!f) return 0; + int written = fputs(report, f) != EOF; + if (fclose(f) != 0 || !written || !matches(draft, report)) return 0; + return rename(draft, name) == 0; + } + printf("ALL REPORT NAMES IN USE\n"); + return 0; +} + +int saveReport(unsigned char sector) +{ + /* One byte string, including the CoCo's CR line endings, goes to both + devices. A paper copy is requested only after publication succeeds. */ + char report[sizeof("MISSION RECORDER\rSECTOR 00\r")]; + char name[] = "LOG00.TXT:0"; + snprintf(report, sizeof(report), "MISSION RECORDER\rSECTOR %02u\r", (unsigned)sector); + while (!publish(report, name)) { + byte key; + printf("SAVE FAILED\nCHECK DRIVE 0; R RETRY OR Q QUIT\n"); + do { key = waitkey(0); } while (key != 'R' && key != 'r' && + key != 'Q' && key != 'q'); + if (key == 'Q' || key == 'q') return 1; + } + name[9] = '\0'; + printf("SAVED %s\n", name); + if (vcc_printer_printf("%s", report) < 0) { + printf("REPORT DELIVERY INCOMPLETE\n"); + return 1; + } + printf("REPORT SENT TO PRINTER PORT\n"); + return 0; +} diff --git a/examples/cmoc/MissionRecorder/vccplus-project.json b/examples/cmoc/MissionRecorder/vccplus-project.json new file mode 100644 index 0000000..6291437 --- /dev/null +++ b/examples/cmoc/MissionRecorder/vccplus-project.json @@ -0,0 +1,57 @@ +{ + "binary": "RECORDER.bin", + "buildTarget": "build", + "cleanTarget": "clean", + "configurations": [ + { + "makeArguments": [], + "name": "Debug" + }, + { + "makeArguments": [ + "VCC_CONFIGURATION=Release" + ], + "name": "Release" + } + ], + "diskImage": "RECORDER.dsk", + "diskTarget": "disk", + "entrySource": "main.c", + "jobs": 4, + "launchCommands": [], + "launchMode": "quickload", + "makefile": "Makefile", + "makefileSettings": { + "compilerOptions": [], + "defines": [], + "diskBootMode": "none", + "diskFiles": [], + "diskImage": "RECORDER.dsk", + "executable": "RECORDER.bin", + "generatedResources": [], + "includePaths": [], + "libraries": [ + "bank", + "gime", + "input", + "bcontrol", + "ssc", + "orch90", + "hirestxt", + "vcccompat", + "decbfile" + ], + "libraryPaths": [], + "libraryProjects": [], + "linkerOptions": [], + "origin": "2000", + "releaseOptimization": "-O2", + "sources": [ + "main.c", + "flight.c", + "report.c" + ], + "stackSpace": 2048, + "limit": "7800" + } +} diff --git a/examples/cmoc/PlanetExpedition/Makefile b/examples/cmoc/PlanetExpedition/Makefile new file mode 100644 index 0000000..270a809 --- /dev/null +++ b/examples/cmoc/PlanetExpedition/Makefile @@ -0,0 +1,38 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# Build with GNU Make and the VCC Plus CMOC toolchain on PATH. +CMOC ?= cmoc +WRITECOCOFILE ?= writecocofile +PERL ?= perl +VCC_CONFIGURATION ?= Debug +ifeq ($(VCC_CONFIGURATION),Release) +OPTIM ?= -O2 +else +OPTIM ?= -O0 -fno-omit-frame-pointer +endif +export VCC_CMOC_COMPAT = 1 +# The IDE supplies its selected library bindings. At the command line the +# same archives are available by name from the bundled toolchain. +LIBRARIES = $(if $(strip $(GUEST_LIBS)),$(GUEST_LIBS),-lsdc -lvcccompat -ldecbfile) +DISKS := EXPED/EXPLORE.DSK EXPED/EARTH.DSK EXPED/MARS.DSK +.PHONY: all build disk clean +.DELETE_ON_ERROR: +all build disk: $(DISKS) + +EXPLORE.BIN: expedition.c Makefile + "$(CMOC)" --coco --intermediate --org=2800 --stack-space=2048 $(OPTIM) -Werror -o $@ $< $(LIBRARIES) + +generated/%/LANDING.TXT: assets/%.txt Makefile + @mkdir -p $(dir $@) + "$(PERL)" -pe 's/\r?\n/\r/' $< > $@ + +EXPED/EXPLORE.DSK: EXPLORE.BIN +EXPED/EARTH.DSK: generated/earth/LANDING.TXT +EXPED/MARS.DSK: generated/mars/LANDING.TXT +$(DISKS): Makefile + @mkdir -p $(dir $@) + "$(PERL)" -e 'print chr(255) x (35*18*256)' > $@ + "$(WRITECOCOFILE)" $@ $(filter-out Makefile,$^) + +clean: + rm -f $(DISKS) EXPLORE.BIN expedition.o expedition.s expedition.lst EXPLORE.map EXPLORE.link + rm -f generated/earth/LANDING.TXT generated/mars/LANDING.TXT diff --git a/examples/cmoc/PlanetExpedition/assets/earth.txt b/examples/cmoc/PlanetExpedition/assets/earth.txt new file mode 100644 index 0000000..0e518bd --- /dev/null +++ b/examples/cmoc/PlanetExpedition/assets/earth.txt @@ -0,0 +1,2 @@ +EARTH: BLUE OCEAN +SPLASH DOWN BESIDE THE BUOY. diff --git a/examples/cmoc/PlanetExpedition/assets/mars.txt b/examples/cmoc/PlanetExpedition/assets/mars.txt new file mode 100644 index 0000000..8a9d5fa --- /dev/null +++ b/examples/cmoc/PlanetExpedition/assets/mars.txt @@ -0,0 +1,2 @@ +MARS: RED RIDGE +LAND BEYOND THE DUST FIELD. diff --git a/examples/cmoc/PlanetExpedition/expedition.c b/examples/cmoc/PlanetExpedition/expedition.c new file mode 100644 index 0000000..0561a82 --- /dev/null +++ b/examples/cmoc/PlanetExpedition/expedition.c @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// The card holds disk images. Each planet disk holds its own LANDING.TXT. +#include +#include +#include + +// Browse the card once. A directory entry describes the image file itself. +static void showChart(void) +{ + SdcEntry entry; + unsigned char result = sdc_list_begin("/*.DSK"); + printf("DISKS ON THE PRACTICE CARD\n"); + if (result == SDC_OK) + while ((result = sdc_list_next(&entry)) == SDC_OK) + if (!(entry.attributes & SDC_DIRECTORY)) + printf(" %s\n", entry.name); + if (result != SDC_END) + printf("CHART UNAVAILABLE (%u)\n", (unsigned)result); +} + +// The controller reports the actual filename, even after a failed mount. +static void showDrive(unsigned char drive) +{ + SdcEntry entry; + unsigned char result = sdc_mounted(drive, &entry); + printf("SDC%u: ", (unsigned)drive); + if (result == SDC_OK) + printf("%s\n", entry.name); + else if (result == SDC_NOT_FOUND) + printf("EMPTY\n"); + else + printf("CANNOT QUERY (%u)\n", (unsigned)result); +} + +static void landingReport(void) +{ + // :1 asks the Disk BASIC ROM for a file inside the mounted planet. + FILE *file = fopen("LANDING.TXT:1", "r"); + char line[40]; + int ok; + if (!file) + { + printf("NO LANDING REPORT ON DRIVE 1\n"); + return; + } + while (fgets(line, sizeof(line), file)) + printf("%s", line); + ok = !ferror(file); + if (fclose(file) == EOF || !ok) + printf("ERROR READING LANDING REPORT\n"); +} + +int main(void) +{ + int key; + unsigned char result; + const char *path; + width(40); + cls(1); + printf("PLANET EXPEDITION\n\n"); + if (sdc_probe() != SDC_OK) + { + printf("CHOOSE THE COCO SDC PROFILE\n"); + return 1; + } + showChart(); + for (;;) + { + printf("\n"); + showDrive(0); + showDrive(1); + printf("\n1 EARTH 2 MARS\n3 TRY MISSING DISK Q QUIT\n"); + do { + key = waitkey(0); + } while (key != '1' && key != '2' && key != '3' && key != 'Q' && key != 'q'); + if (key == 'Q' || key == 'q') + break; + + // No file is open here. Leave drive 0 alone and change only drive 1. + path = key == '1' ? "/EARTH.DSK" : key == '2' ? "/MARS.DSK" : "/MISSING.DSK"; + result = sdc_mount(1, path); + cls(1); + printf("PLANET EXPEDITION\n\n"); + if (result == SDC_OK) + printf("LANDED\n"); + else + printf("COULD NOT MOUNT %s (%u)\n", path, (unsigned)result); + // Read what is actually mounted, including after a rejected change. + landingReport(); + } + printf("EXPEDITION COMPLETE\n"); + return 0; +} diff --git a/examples/cmoc/PlanetExpedition/vccplus-project.json b/examples/cmoc/PlanetExpedition/vccplus-project.json new file mode 100644 index 0000000..21e2181 --- /dev/null +++ b/examples/cmoc/PlanetExpedition/vccplus-project.json @@ -0,0 +1,37 @@ +{ + "entrySource": "expedition.c", + "makefile": "Makefile", + "buildTarget": "build", + "cleanTarget": "clean", + "diskTarget": "disk", + "binary": "EXPLORE.BIN", + "diskImage": "EXPED/EXPLORE.DSK", + "launchMode": "quickload", + "jobs": 3, + "configurations": [ + { + "name": "Debug", + "makeArguments": [] + }, + { + "name": "Release", + "makeArguments": [ + "VCC_CONFIGURATION=Release" + ] + } + ], + "bundledLibraries": [ + { + "library": "sdc", + "linkVariable": "GUEST_LIBS" + }, + { + "library": "vcccompat", + "linkVariable": "GUEST_LIBS" + }, + { + "library": "decbfile", + "linkVariable": "GUEST_LIBS" + } + ] +} diff --git a/examples/cmoc/PlanetSurvey/.gitignore b/examples/cmoc/PlanetSurvey/.gitignore new file mode 100644 index 0000000..61a050a --- /dev/null +++ b/examples/cmoc/PlanetSurvey/.gitignore @@ -0,0 +1,7 @@ +obj/ +SURVEY.bin +SURVEY.dsk +SURVEY.map +SURVEY.link +.vccplus-build/ +generated/ diff --git a/examples/cmoc/PlanetSurvey/Makefile b/examples/cmoc/PlanetSurvey/Makefile new file mode 100644 index 0000000..ac64fdd --- /dev/null +++ b/examples/cmoc/PlanetSurvey/Makefile @@ -0,0 +1,55 @@ +# Generated by VCC Plus — edit Project Settings to regenerate. +# Ordinary GNU Make; no VCC Plus project parser is required to build it. +CMOC ?= cmoc +PERL ?= perl +WRITECOCOFILE ?= writecocofile +INSTALL_LOADER ?= install-coco-boot-loader +VCC_CONFIGURATION ?= Debug +ifeq ($(VCC_CONFIGURATION),Release) +OPTIM ?= -O2 +else +OPTIM ?= -O0 +DEBUG_FRAME ?= -fno-omit-frame-pointer +endif +define VCC_DEFINES + +endef +define VCC_COMPILER_OPTIONS + +endef +define VCC_LINKER_OPTIONS + +endef +export VCC_CMOC_COMPAT = 1 +CPPFLAGS += $(VCC_DEFINES) +CFLAGS += --coco --intermediate --deps --stack-space=2048 $(OPTIM) $(DEBUG_FRAME) $(VCC_COMPILER_OPTIONS) +LDFLAGS += --coco --intermediate --org=2800 $(VCC_LINKER_OPTIONS) +LDLIBS += -lvcccompat -ldecbfile +OBJECTS := obj/main.o +.PHONY: all build clean disk libraries +all: build +build: SURVEY.bin +SURVEY.bin: $(OBJECTS) Makefile + @mkdir -p $(dir $@) + "$(CMOC)" $(LDFLAGS) -o $@ $(OBJECTS) $(LDLIBS) +obj/main.o: main.c Makefile generated/PLANETS.TXT + @mkdir -p $(dir $@) + "$(CMOC)" $(CPPFLAGS) $(CFLAGS) --intdir=$(dir $@) -c -o $@ $< + +generated/PLANETS.TXT &: assets/planets.txt Makefile + @mkdir -p generated + $(PERL) -pe 's/\r?\n/\r/' assets/planets.txt > generated/PLANETS.TXT + test -f generated/PLANETS.TXT + +disk: SURVEY.dsk +SURVEY.dsk: SURVEY.bin generated/PLANETS.TXT Makefile + @mkdir -p $(dir $@) + $(PERL) -e 'print chr(255) x (35*18*256)' > $@ + $(WRITECOCOFILE) $@ SURVEY.bin + $(WRITECOCOFILE) $@ generated/PLANETS.TXT + +clean: + rm -rf obj + rm -f SURVEY.bin SURVEY.map SURVEY.link SURVEY.dsk generated/PLANETS.TXT + +-include $(OBJECTS:.o=.d) diff --git a/examples/cmoc/PlanetSurvey/assets/planets.txt b/examples/cmoc/PlanetSurvey/assets/planets.txt new file mode 100644 index 0000000..86203a0 --- /dev/null +++ b/examples/cmoc/PlanetSurvey/assets/planets.txt @@ -0,0 +1,8 @@ +# PLANET SURVEY / FLIGHT LOG / LOG 0042 +# Read before picking a landing site. +# 1: Check the blue planet from orbit. +# 2: Mark the red planet on the map. +# Pick one of the two reports below. +# Columns: planet|trait,trait|orbit (1 to 8). +EARTH|BLUE,WET|3 +MARS|RED,COLD|4 diff --git a/examples/cmoc/PlanetSurvey/main.c b/examples/cmoc/PlanetSurvey/main.c new file mode 100644 index 0000000..75264c4 --- /dev/null +++ b/examples/cmoc/PlanetSurvey/main.c @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include +#include +#include +#include + +/* Split a writable record such as MARS|RED,COLD|4. Each cursor belongs + to one scan. The tokens point directly into the line read from disk. */ +static int showRecord(char *line) +{ + char *fields, *traits, *end; + char summary[112]; + char *name = strtok_r(line, "|", &fields); + char *list = strtok_r(NULL, "|", &fields); + if (!name || !list) + return 0; + + char *first = strtok_r(list, ",", &traits); + char *second = strtok_r(NULL, ",", &traits); + if (!first || !second || strtok_r(NULL, ",", &traits)) + return 0; + + /* Resume the outer scan exactly where we left it. */ + char *text = strtok_r(NULL, "|", &fields); + if (!text || strtok_r(NULL, "|", &fields) || !isdigit((unsigned char)*text)) + return 0; + errno = 0; + unsigned long orbit = strtoul(text, &end, 10); + if (*end || errno == ERANGE || orbit < 1UL || orbit > 8UL) + return 0; + + int length = snprintf(summary, sizeof(summary), + "SURVEY: %s\nTRAITS: %s AND %s\nORBIT FROM SUN: %lu", + name, first, second, orbit); + if (length < 0 || length >= (int)sizeof(summary)) + return 0; + printf("%s\n", summary); + return 1; +} + +int main(void) +{ + char line[64], choice; + unsigned record = 0; + int tooLong = 0; + cls(1); + printf("PLANET SURVEY\n1 EARTH 2 MARS\n"); + do + choice = waitkey(0); + while (choice != '1' && choice != '2'); + + FILE *log = fopen("PLANETS.TXT", "r"); + if (!log) + { + printf("CANNOT OPEN PLANETS.TXT\n"); + return 1; + } + + /* Skip the flight notes. The first data line is Earth, the second Mars. */ + while (fgets(line, sizeof(line), log)) + { + unsigned length = strcspn(line, "\n"); + if (length == sizeof(line) - 1) + { + tooLong = 1; // Never mistake part of a long line for a new record. + break; + } + line[length] = '\0'; + if (!line[0] || line[0] == '#') + continue; + if (++record == (unsigned)(choice - '0')) + break; + } + + /* An error can end a read loop just as end-of-file can. */ + int diskError = ferror(log); + if (fclose(log) == EOF || diskError) + printf("DISK READ ERROR\n"); + else if (tooLong) + printf("SURVEY LINE TOO LONG\n"); + else if (record != (unsigned)(choice - '0')) + printf("NO MATCHING SURVEY RECORD\n"); + else if (!showRecord(line)) + printf("INVALID SURVEY RECORD\n"); + else + { + printf("SURVEY COMPLETE\n"); + return 0; + } + return 1; +} diff --git a/examples/cmoc/PlanetSurvey/vccplus-project.json b/examples/cmoc/PlanetSurvey/vccplus-project.json new file mode 100644 index 0000000..216bfdf --- /dev/null +++ b/examples/cmoc/PlanetSurvey/vccplus-project.json @@ -0,0 +1,61 @@ +{ + "binary": "SURVEY.bin", + "buildTarget": "disk", + "cleanTarget": "clean", + "configurations": [ + { + "makeArguments": [], + "name": "Debug" + }, + { + "makeArguments": [ + "VCC_CONFIGURATION=Release" + ], + "name": "Release" + } + ], + "diskImage": "SURVEY.dsk", + "diskTarget": "disk", + "entrySource": "main.c", + "jobs": 4, + "launchCommands": [ + "LOADM\"SURVEY\":EXEC" + ], + "launchMode": "disk", + "makefile": "Makefile", + "makefileSettings": { + "compilerOptions": [], + "defines": [], + "diskBootMode": "none", + "diskFiles": [ + "generated/PLANETS.TXT" + ], + "diskImage": "SURVEY.dsk", + "executable": "SURVEY.bin", + "generatedResources": [ + { + "inputs": [ + "assets/planets.txt" + ], + "outputs": [ + "generated/PLANETS.TXT" + ], + "command": "$(PERL) -pe 's/\\r?\\n/\\r/' assets/planets.txt > generated/PLANETS.TXT" + } + ], + "includePaths": [], + "libraries": [ + "vcccompat", + "decbfile" + ], + "libraryPaths": [], + "libraryProjects": [], + "linkerOptions": [], + "origin": "2800", + "releaseOptimization": "-O2", + "sources": [ + "main.c" + ], + "stackSpace": 2048 + } +} diff --git a/examples/cmoc/TalkingPlanetLander/.gitignore b/examples/cmoc/TalkingPlanetLander/.gitignore new file mode 100644 index 0000000..af5dad5 --- /dev/null +++ b/examples/cmoc/TalkingPlanetLander/.gitignore @@ -0,0 +1,6 @@ +obj/ +LANDER.bin +LANDER.dsk +LANDER.map +LANDER.link +.vccplus-build/ diff --git a/examples/cmoc/TalkingPlanetLander/Makefile b/examples/cmoc/TalkingPlanetLander/Makefile new file mode 100644 index 0000000..6cc75c2 --- /dev/null +++ b/examples/cmoc/TalkingPlanetLander/Makefile @@ -0,0 +1,49 @@ +# Generated by VCC Plus — edit Project Settings to regenerate. +# Ordinary GNU Make; no VCC Plus project parser is required to build it. +CMOC ?= cmoc +PERL ?= perl +WRITECOCOFILE ?= writecocofile +INSTALL_LOADER ?= install-coco-boot-loader +VCC_CONFIGURATION ?= Debug +ifeq ($(VCC_CONFIGURATION),Release) +OPTIM ?= -O2 +else +OPTIM ?= -O0 +DEBUG_FRAME ?= -fno-omit-frame-pointer +endif +define VCC_DEFINES + +endef +define VCC_COMPILER_OPTIONS + +endef +define VCC_LINKER_OPTIONS + +endef +export VCC_CMOC_COMPAT = 1 +CPPFLAGS += $(VCC_DEFINES) +CFLAGS += --coco --intermediate --deps --stack-space=2048 $(OPTIM) $(DEBUG_FRAME) $(VCC_COMPILER_OPTIONS) +LDFLAGS += --coco --intermediate --org=2800 $(VCC_LINKER_OPTIONS) +LDLIBS += -lssc -lorch90 -lbcontrol -lvcccompat +OBJECTS := obj/main.o +.PHONY: all build clean disk libraries +all: build +build: LANDER.bin +LANDER.bin: $(OBJECTS) Makefile + @mkdir -p $(dir $@) + "$(CMOC)" $(LDFLAGS) -o $@ $(OBJECTS) $(LDLIBS) +obj/main.o: main.c Makefile + @mkdir -p $(dir $@) + "$(CMOC)" $(CPPFLAGS) $(CFLAGS) --intdir=$(dir $@) -c -o $@ $< + +disk: LANDER.dsk +LANDER.dsk: LANDER.bin Makefile + @mkdir -p $(dir $@) + $(PERL) -e 'print chr(255) x (35*18*256)' > $@ + $(WRITECOCOFILE) $@ LANDER.bin + +clean: + rm -rf obj + rm -f LANDER.bin LANDER.map LANDER.link LANDER.dsk + +-include $(OBJECTS:.o=.d) diff --git a/examples/cmoc/TalkingPlanetLander/README.md b/examples/cmoc/TalkingPlanetLander/README.md new file mode 100644 index 0000000..5f8e584 --- /dev/null +++ b/examples/cmoc/TalkingPlanetLander/README.md @@ -0,0 +1,11 @@ +# Talking Planet Lander + +Start the Disk BASIC system profile. In Cartridges, enable the Multi-Pak and install Speech/Sound in slot 1 and Orchestra-90 in slot 2. Keep the floppy controller in startup slot 4. Speech/Sound needs its PIC and speech ROMs. Orchestra-90 works in sound-only mode. Use normal CoCo CPU speed for the beacon. + +Build and Run in C Development, then press **1** for Earth or **2** for Mars in the emulator window. Listen for a low note on the left and a higher one on the right. The pilot announces the destination and landing. During either phrase, press the primary fire button on either CoCo joystick to print **THRUST**. Each press counts once. With either cartridge omitted the visual landing still works. + +The project uses VCC Plus's optional bounded formatter, Speech/Sound and Orchestra-90 libraries, plus BControl for buttons. The source shows how to poll the guest while the cartridge speaks. The stereo beacon uses foreground playback and briefly occupies the processor. + +Use **Build Disk** for a floppy copy. Mount LANDER.dsk in FD0 and enter `LOADM"LANDER":EXEC`. Building on the command line uses the bundled toolchain on PATH and ordinary Make. + +The original example and VCC Plus guest libraries are licensed GPL-3.0-or-later. BControl retains its upstream license. diff --git a/examples/cmoc/TalkingPlanetLander/main.c b/examples/cmoc/TalkingPlanetLander/main.c new file mode 100644 index 0000000..da73552 --- /dev/null +++ b/examples/cmoc/TalkingPlanetLander/main.c @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include +#include +#include +#include +#include + +// Poll the two primary buttons. Reading buttons alone preserves the audio mux. +static unsigned char buttonDown; +static void checkThruster(void) +{ + unsigned char down = (Joystick_getButtonStates2() & 3) != 3; + if (down && !buttonDown) + printf("THRUST\n"); + buttonDown = down; +} + +// Send one byte at a time so the player can fire while the cartridge is busy. +// The firmware asserts busy after accepting the terminator. Give it time to +// start, then wait for it to finish before sending another announcement. +static unsigned char announce(const char *words) +{ + ssc_phrase phrase; + unsigned int start = getTimer(); + if (ssc_begin_phrase(&phrase, words) != SSC_OK) + return 0; + while (ssc_service(&phrase) == SSC_PENDING) { + checkThruster(); + if ((unsigned int)(getTimer() - start) >= 90) + return 0; + } + start = getTimer(); + while (ssc_status() & SSC_SPEECH_IDLE) { + checkThruster(); + if ((unsigned int)(getTimer() - start) >= 60) + return 0; + } + while (!(ssc_status() & SSC_SPEECH_IDLE)) { + checkThruster(); + if ((unsigned int)(getTimer() - start) >= 600) + return 0; + } + return 1; +} + +// Make an original two-note beacon. At normal CPU speed 16 frames repeat +// about 250 times a second. The right-hand note is one octave higher. +static void beacon(void) +{ + struct orch90_frame block[128]; + unsigned char side, i, repeat; + for (side = 0; side < 2; ++side) { + for (i = 0; i < 128; ++i) { + block[i].left = side ? 128 : (i & 8 ? 152 : 104); + block[i].right = side ? (i & 4 ? 152 : 104) : 128; + } + for (repeat = 0; repeat < 6; ++repeat) + orch90_play(block, 128, ORCH90_CLOCK_NORMAL); + } + orch90_write(128, 128); +} + +int main(void) +{ + char key, message[24]; + unsigned int route; + cls(1); + printf("TALKING PLANET LANDER\n1 EARTH 2 MARS\n"); + do { key = waitkey(0); } while (key != '1' && key != '2'); + snprintf(message, sizeof(message), "DESTINATION %s", key == '1' ? "EARTH" : "MARS"); + printf("%s\nPRESS FIRE FOR THRUST\n", message); + route = ssc_route_audio(); + beacon(); + if (announce(message)) + announce("LANDING COMPLETE"); + ssc_restore_audio(route); + printf("TOUCHDOWN\n"); + return 0; +} diff --git a/examples/cmoc/TalkingPlanetLander/vccplus-project.json b/examples/cmoc/TalkingPlanetLander/vccplus-project.json new file mode 100644 index 0000000..10bef7c --- /dev/null +++ b/examples/cmoc/TalkingPlanetLander/vccplus-project.json @@ -0,0 +1,49 @@ +{ + "binary": "LANDER.bin", + "buildTarget": "build", + "cleanTarget": "clean", + "configurations": [ + { + "makeArguments": [], + "name": "Debug" + }, + { + "makeArguments": [ + "VCC_CONFIGURATION=Release" + ], + "name": "Release" + } + ], + "diskImage": "LANDER.dsk", + "diskTarget": "disk", + "entrySource": "main.c", + "jobs": 4, + "launchCommands": [], + "launchMode": "quickload", + "makefile": "Makefile", + "makefileSettings": { + "compilerOptions": [], + "defines": [], + "diskBootMode": "none", + "diskFiles": [], + "diskImage": "LANDER.dsk", + "executable": "LANDER.bin", + "generatedResources": [], + "includePaths": [], + "libraries": [ + "ssc", + "orch90", + "bcontrol", + "vcccompat" + ], + "libraryPaths": [], + "libraryProjects": [], + "linkerOptions": [], + "origin": "2800", + "releaseOptimization": "-O2", + "sources": [ + "main.c" + ], + "stackSpace": 2048 + } +} diff --git a/examples/cmoc/manual/announcer.c b/examples/cmoc/manual/announcer.c new file mode 100644 index 0000000..414bb3c --- /dev/null +++ b/examples/cmoc/manual/announcer.c @@ -0,0 +1,70 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Mission Announcer. Select ssc, input and bcontrol in Project Settings. */ +#include +#include +#include +#include + +#define VOICE_SLOT 1 +#define ALERT_SLOT 2 +#define MESSAGE_SLOT 3 +#define POLL_LIMIT 30000 + +/* Z + "or" + an unstressed vowel: give our invented planet a voice. */ +static const unsigned char zora[] = { SSC_AL_ZZ, SSC_AL_OR, SSC_AL_AX }; + +int main(void) +{ + unsigned int route, lastSample, now, landings = 0; + unsigned char key, status; + VccInput stick; + + cls(1); + printf("MISSION ANNOUNCER\n"); + route = ssc_route_audio(); + /* Store each recipe once. The two slot numbers belong to separate banks. */ + status = ssc_store_allophones(VOICE_SLOT, zora, sizeof(zora), POLL_LIMIT); + if (status == SSC_OK) + status = ssc_store_phrase(MESSAGE_SLOT, "WELCOME ABOARD", POLL_LIMIT); + if (status == SSC_OK) + status = ssc_store_enveloped_tone(ALERT_SLOT, 0, 420, SSC_ENV_DECAY, + 1800, 18, POLL_LIMIT); + if (status == SSC_OK) { + input_init(&stick, INPUT_RIGHT); + lastSample = getTimer(); + printf("1 ANNOUNCE ZORA\n2 CREW MESSAGE\nFIRE LANDING ALERT\nQ RETURN TO BASIC\n"); + while (status == SSC_OK) { + key = inkey(); + if (key == 'Q' || key == 'q') + break; + if (key == '1') { + status = ssc_play_allophones(VOICE_SLOT, POLL_LIMIT); + if (status == SSC_OK) + printf("APPROACHING ZORA\n"); + } else if (key == '2') { + status = ssc_play_phrase(MESSAGE_SLOT, POLL_LIMIT); + if (status == SSC_OK) + printf("WELCOME ABOARD\n"); + } + /* Joystick readings share the audio mux. Sample once per guest tick. */ + now = getTimer(); + if (now == lastSample) + continue; + lastSample = now; + input_sample(&stick); + /* A press is an edge: holding the button counts as one landing. */ + if (status == SSC_OK && (stick.pressed & INPUT_PRIMARY)) { + status = ssc_play_stored_effect(ALERT_SLOT, POLL_LIMIT); + if (status == SSC_OK) + printf("LANDING ALERT %u\n", ++landings); + } + } + } + /* A partial command may remain after timeout. Reset only on that path. */ + if (status == SSC_TIMEOUT) + ssc_reset(); + ssc_restore_audio(route); + if (status != SSC_OK) + printf("CHECK CARTRIDGE AND FIRMWARE\n"); + return status; +} diff --git a/examples/cmoc/manual/atlas.c b/examples/cmoc/manual/atlas.c new file mode 100644 index 0000000..1d1b169 --- /dev/null +++ b/examples/cmoc/manual/atlas.c @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Planet Atlas creates ATLAS.DAT on drive 0 the first time you run it. +#include +#include +#include +#include +#include + +#define ATLAS_NAME "ATLAS.DAT:0" +#define CARD_SIZE 24 +static const char cards[][CARD_SIZE] = { + "MERCURY: CRATERS", "VENUS: CLOUDS", "EARTH: BLUE SEA", "MARS: RED RIDGE" +}; + +/* Keep any atlas already on the disk. On a fresh disk, write four cards. */ +static FILE *openAtlas(void) +{ + FILE *atlas = fopen(ATLAS_NAME, "r+b"); + int complete; + if (atlas || vcc_file_error() != DECB_ERR_NOT_FOUND) + return atlas; + atlas = fopen(ATLAS_NAME, "wb"); + if (!atlas) + return NULL; + complete = fwrite(cards, CARD_SIZE, 4, atlas) == 4; + if (fclose(atlas) == EOF || !complete) + return NULL; + return fopen(ATLAS_NAME, "r+b"); +} + +/* Read exactly one card from the current position. Leave room for a zero + so even a card that fills all 24 bytes can be displayed as a C string. */ +static int showCard(FILE *atlas) +{ + char card[CARD_SIZE + 1]; + if (fread(card, CARD_SIZE, 1, atlas) != 1) + return 0; + card[CARD_SIZE] = 0; + printf("%s\n", card); + return 1; +} + +static int takeTrip(FILE *atlas, int number) +{ + /* Card numbers begin at 1. Disk offsets begin at 0. */ + long offset = (long)(number - 1) * CARD_SIZE; + long bookmark; + if (fseek(atlas, offset, SEEK_SET) != 0) + return 0; + bookmark = ftell(atlas); // Save the start before reading the card. + if (bookmark < 0) + return 0; + printf("YOUR PICK AT BYTE %ld\n", bookmark); + if (!showCard(atlas)) + return 0; + + printf("HOME BASE\n"); + if (fseek(atlas, 2L * CARD_SIZE, SEEK_SET) != 0 || !showCard(atlas)) + return 0; + printf("BACK TO YOUR BOOKMARK\n"); + if (fseek(atlas, bookmark, SEEK_SET) != 0 || !showCard(atlas)) + return 0; + + rewind(atlas); // The first card is Mercury again. + printf("FIRST CARD\n"); + return ftell(atlas) == 0L && showCard(atlas); +} + +/* Enter a whole record number. Base zero accepts 2 and 0x2 for Venus. */ +static int choosePlanet(void) +{ + for (;;) + { + char *line, *end; + unsigned long number; + printf("PICK A PLANET (1-4), THEN ENTER\n"); + line = readline(); + if (!line) + return 0; + if (!isdigit((unsigned char)*line)) + { + printf("START WITH A DIGIT\n"); + continue; + } + errno = 0; + number = strtoul(line, &end, 0); + if (*end) + printf("EXTRA CHARACTER: %c\n", *end); + else if (errno == ERANGE || number < 1UL || number > 4UL) + printf("CHOOSE A NUMBER FROM 1 TO 4\n"); + else + return (int)number; // Now the value is small enough for an int. + } +} + +/* The last padding byte is a visit flag. A custom card that uses the whole + field for its description has no spare byte; leave its text intact. */ +static int recordVisit(FILE *atlas, int number) +{ + char card[CARD_SIZE]; + long start = (long)(number - 1) * CARD_SIZE; + if (fseek(atlas, start, SEEK_SET) != 0 || fread(card, CARD_SIZE, 1, atlas) != 1) + return 0; + if (!memchr(card, 0, CARD_SIZE - 1) || + (card[CARD_SIZE - 1] != 0 && card[CARD_SIZE - 1] != 'V')) + { + printf("NO ROOM FOR VISIT MARK\n"); + return 1; + } + if (card[CARD_SIZE - 1] == 'V') + { + printf("ALREADY VISITED\n"); + return 1; + } + + // Position the update stream between reading the card and writing its flag. + if (fseek(atlas, start + CARD_SIZE - 1, SEEK_SET) != 0 || + fputc('V', atlas) == EOF || fflush(atlas) == EOF) + return 0; + printf("VISIT SAVED\n"); + return 1; +} + +int main(void) +{ + FILE *atlas; + int number, ok; + cls(1); + atlas = openAtlas(); + if (!atlas) + { + printf("CANNOT OPEN ATLAS.DAT\n"); + return 1; + } + printf("PLANET ATLAS\n1 MERCURY 2 VENUS\n3 EARTH 4 MARS\n"); + number = choosePlanet(); + if (!number) + { + fclose(atlas); + printf("CANNOT READ KEYBOARD\n"); + return 1; + } + + cls(1); + printf("PLANET ATLAS\n\n"); + ok = takeTrip(atlas, number); + if (!ok) + printf("CANNOT READ ATLAS CARD\n"); + else if (!recordVisit(atlas, number)) + { + printf("CANNOT SAVE VISIT\n"); + ok = 0; + } + if (fclose(atlas) == EOF) + ok = 0; + if (ok) + printf("ATLAS CLOSED\n"); + return ok ? 0 : 1; +} diff --git a/examples/cmoc/manual/atlasbackup.c b/examples/cmoc/manual/atlasbackup.c new file mode 100644 index 0000000..b67c6ca --- /dev/null +++ b/examples/cmoc/manual/atlasbackup.c @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Run on a practice disk. This exercise recognizes the four Planet char cards[][CARD_SIZE]. +#include +#include +#include + +#define LIVE "ATLAS.DAT:0" +#define DRAFT "ATLAS.NEW:0" +#define BACKUP "ATLAS.BAK:0" + +#define CARD_SIZE 24 +static const char original[][CARD_SIZE] = { + "MERCURY: CRATERS", "VENUS: CLOUDS", "EARTH: BLUE SEA", "MARS: RED RIDGE" +}; +static const char newMars[CARD_SIZE] = "MARS: DUST STORM"; +static char live[4][CARD_SIZE], draft[4][CARD_SIZE], backup[4][CARD_SIZE]; + +enum { ABSENT, FIRST, SECOND, UNRECOGNIZED, DISK_ERROR }; + +/* A valid edition contains four exact cards. Each may also have a visit mark + in its final byte. Check file length as well as text before changing a name. */ +static int inspect(const char *name, char cards[][CARD_SIZE]) +{ + unsigned i; + FILE *f = fopen(name, "rb"); + if (!f) + return vcc_file_error() == DECB_ERR_NOT_FOUND ? ABSENT : DISK_ERROR; + size_t count = fread(cards, 1, sizeof(original), f); + int extra = fgetc(f); + int failed = ferror(f); + if (fclose(f) == EOF || failed) + return DISK_ERROR; + if (count != sizeof(original) || extra != EOF) + return UNRECOGNIZED; + for (i = 0; i < 4; ++i) + { + char mark = cards[i][CARD_SIZE - 1]; + if (mark != 0 && mark != 'V') + return UNRECOGNIZED; + if (memcmp(cards[i], original[i], CARD_SIZE - 1) != 0) + { + if (i == 3 && memcmp(cards[3], newMars, CARD_SIZE - 1) == 0) + return SECOND; + return UNRECOGNIZED; + } + } + return FIRST; +} + +/* Write only after the caller has checked that the name is unused. */ +static int writeCards(const char *name, const void *cards) +{ + FILE *f = fopen(name, "wb"); + if (!f) + return 0; + int complete = fwrite(cards, 1, sizeof(original), f) == sizeof(original); + return fclose(f) == 0 && complete; +} + +static void reviseMars(char cards[][CARD_SIZE]) +{ + // The old visit mark belongs to the traveler. Keep the last byte. + memcpy(cards[3], newMars, CARD_SIZE - 1); +} + +static int recover(int draftState) +{ + // The live name was missing. Restore the known old edition first. + if (rename(BACKUP, LIVE) != 0) + return 0; + printf("ORIGINAL ATLAS RESTORED\n%s\n", backup[3]); + reviseMars(backup); + if (draftState == SECOND && memcmp(backup, draft, sizeof(original)) == 0) + return remove(DRAFT) == 0; + if (draftState != ABSENT) + printf("KEPT UNEXPECTED ATLAS.NEW\n"); + return 1; +} + +static int saveAtlas(void) +{ + int current = inspect(LIVE, live); + int old = inspect(BACKUP, backup); + int next = inspect(DRAFT, draft); + if (current == DISK_ERROR || old == DISK_ERROR || next == DISK_ERROR) + return 0; + if (current == ABSENT && old == FIRST) + return recover(next); + if (current == SECOND && next == ABSENT) + { + printf("ATLAS ALREADY UPDATED\n%s\n", live[3]); + return 1; + } + if (current == ABSENT && old == ABSENT && next == ABSENT) + { + if (!writeCards(LIVE, original) || inspect(LIVE, live) != FIRST || + memcmp(live, original, sizeof(original)) != 0) + return 0; + current = FIRST; + } + if (current != FIRST || old != ABSENT) + { + printf("CHECK THE THREE ATLAS FILES\n"); + return 0; + } + + reviseMars(live); // Only the copy in RAM has changed. + if (next == ABSENT) + { + if (!writeCards(DRAFT, live)) + return 0; + next = inspect(DRAFT, draft); + } + if (next != SECOND || memcmp(live, draft, sizeof(original)) != 0) + { + printf("CHECK ATLAS.NEW\n"); + return 0; + } + + // Both files are closed. At this checkpoint the old edition is complete + // under BACKUP, and the new edition is complete under DRAFT. + if (rename(LIVE, BACKUP) != 0) + return 0; + printf("BACKUP IN PLACE\nPRESS A KEY TO INSTALL\n"); + waitkey(0); + if (rename(DRAFT, LIVE) != 0) + return 0; + printf("UPDATED ATLAS SAVED\n%s\n", draft[3]); + return 1; +} + +int main(void) +{ + cls(1); + printf("PLANET ATLAS BACKUP\n"); + if (saveAtlas()) + return 0; + printf("SAVE STOPPED - CHECK DISK\n"); + return 1; +} diff --git a/examples/cmoc/manual/beacon.c b/examples/cmoc/manual/beacon.c new file mode 100644 index 0000000..d324a29 --- /dev/null +++ b/examples/cmoc/manual/beacon.c @@ -0,0 +1,41 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Draw a small landing beacon on a CoCo 3. Link bgraph. */ +#include +#include + +/* BGraph's 320x16 routines use 160 bytes per row. We need just 13 rows. */ +enum { SIDE = 13, MIDDLE = 6, STRIDE = 160, INK = 3 }; +static byte stamp[SIDE * STRIDE]; + +int main(void) +{ + byte x, y; + byte *slots = (byte *) 0xFFB0; + byte oldPaper = slots[0] & 63, oldInk = slots[INK] & 63; + if (!hscreen(2)) + return 1; + paletteRGB(0, 0, 0, 0); + paletteRGB(INK, 3, 3, 3); + for (x = 0; x < SIDE; ++x) + { + Primitive_setPixel320x16(x, MIDDLE, INK, stamp); + Primitive_setPixel320x16(MIDDLE, x, INK, stamp); + } + + /* Let Disk BASIC find the visible page. Magnify each stamp dot 3 by 3. */ + for (y = 0; y < SIDE; ++y) + for (x = 0; x < SIDE; ++x) + { + byte dx, dy; + byte color = Primitive_getPixel320x16(x, y, stamp); + for (dy = 0; dy < 3; ++dy) + for (dx = 0; dx < 3; ++dx) + hset(140 + 3 * x + dx, 76 + 3 * y + dy, color); + } + waitkey(FALSE); + hscreen(0); + palette(0, oldPaper); + palette(INK, oldInk); + printf("BEACON CENTER: %u\n", (unsigned) Primitive_getPixel320x16(MIDDLE, MIDDLE, stamp)); + return 0; +} diff --git a/examples/cmoc/manual/cargo.c b/examples/cmoc/manual/cargo.c new file mode 100644 index 0000000..cf946ad --- /dev/null +++ b/examples/cmoc/manual/cargo.c @@ -0,0 +1,39 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Count a delivery on two planets. The manifest stays in guest RAM. */ +#include +#include + +struct Shipment +{ + const char *destination; + byte crates; + byte mealsPerCrate; +}; + +static const struct Shipment manifest[] = +{ + { "EARTH", 12, 20 }, + { "MARS", 8, 15 } +}; + +/* A pointer lets us read one row without copying the whole structure. */ +static word mealsFor(const struct Shipment *shipment) +{ + return (word) shipment->crates * shipment->mealsPerCrate; +} + +int main(void) +{ + word total = 0; + byte row; + + width(40); + for (row = 0; row < sizeof(manifest) / sizeof(manifest[0]); ++row) + { + word meals = mealsFor(&manifest[row]); + printf("%s: %u MEALS\n", manifest[row].destination, meals); + total += meals; + } + printf("TOTAL: %u MEALS\n", total); + return 0; +} diff --git a/examples/cmoc/manual/crew.c b/examples/cmoc/manual/crew.c new file mode 100644 index 0000000..f074314 --- /dev/null +++ b/examples/cmoc/manual/crew.c @@ -0,0 +1,43 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Crew log: each seat holds 1 when occupied and 0 when empty. */ +#include +#include + +static unsigned char storage[96]; + +int main(void) +{ + unsigned char *seats, *larger; + if (!vcc_heap_init(storage, sizeof(storage))) + return 1; + + seats = (unsigned char *) calloc(2, sizeof(*seats)); + if (!seats) + return 1; + printf("CREW AT LAUNCH: %u\n", (unsigned)(seats[0] + seats[1])); + seats[0] = seats[1] = 1; + + /* Keep the current seat list until we know it can grow. */ + larger = (unsigned char *) realloc(seats, 3); + if (!larger) + { + free(seats); + return 1; + } + seats = larger; + seats[2] = 1; + printf("CREW AFTER GROWTH: %u\n", (unsigned)(seats[0] + seats[1] + seats[2])); + + /* The request exceeds the entire 96-byte budget. */ + larger = (unsigned char *) realloc(seats, 200); + if (larger) + { + free(larger); + return 1; + } + printf("NO ROOM FOR 200\n"); + printf("CREW STILL ABOARD: %u\n", (unsigned)(seats[0] + seats[1] + seats[2])); + free(seats); + printf("CREW LOG CLOSED\n"); + return 0; +} diff --git a/examples/cmoc/manual/deal.c b/examples/cmoc/manual/deal.c new file mode 100644 index 0000000..bc98aa3 --- /dev/null +++ b/examples/cmoc/manual/deal.c @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* The deck count belongs to the caller. Link cardgame. */ +#include + +int main(void) +{ + byte deck[3] = { 1, 2, 3 }; + byte count = 3; + byte drawn = pickCardFromDeck(deck, &count); + printf("DREW %u, %u LEFT\n", (unsigned) drawn, (unsigned) count); + return 0; +} diff --git a/examples/cmoc/manual/descent.c b/examples/cmoc/manual/descent.c new file mode 100644 index 0000000..df55c26 --- /dev/null +++ b/examples/cmoc/manual/descent.c @@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Descent Computer. Use the CoCo BASIC float backend and link vcccompat. */ +#include +#include +#include + +/* Print a complete instrument reading or mark the field unavailable. */ +static void reading(const char *label, float value, byte places, const char *unit) +{ + char field[12]; + int length = vcc_fixed(field, sizeof(field), value, places); + if (length < 0 || (unsigned)length >= sizeof(field)) + printf("%s--- %s\n", label, unit); + else + printf("%s%s %s\n", label, field, unit); +} + +static void report(float firstHeight, float lastHeight, float seconds) +{ + float speed; + if (seconds <= 0.0f) { + printf("CHECK RADAR INTERVAL\n"); + return; + } + + /* Falling gives a negative speed. Keep the full value for the estimate. */ + speed = (lastHeight - firstHeight) / seconds; + reading("HEIGHT ", lastHeight, 2, "M"); + reading("SPEED ", speed, 2, "M/S"); + if (speed < 0.0f) + reading("ETA ", lastHeight / -speed, 1, "S"); + else + printf("ETA NO DESCENT\n"); +} + +int main(void) +{ + cls(1); + printf("DESCENT COMPUTER\n\n"); + /* Two radar heights in metres, measured two seconds apart. */ + report(105.50f, 101.75f, 2.0f); + printf("\nRADAR PASS COMPLETE\n"); + return 0; +} diff --git a/examples/cmoc/manual/editlog.c b/examples/cmoc/manual/editlog.c new file mode 100644 index 0000000..28ea01a --- /dev/null +++ b/examples/cmoc/manual/editlog.c @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Insert two keys into a tiny terminal editor. Link ebitor. */ +#include +#include + +static byte readKey(void *cookie) +{ + return inkey(); +} + +int main(void) +{ + char log[32] = ""; + ebitor_Window window = { 32, 15, 0, 0, 0, 0 }; + width(32); + sg4term_init((char *) 0x0400, &window, readKey, NULL, (word *) 0x0112); + Ebitor_init(log, sizeof(log), 32, 15, sg4term_clear, sg4term_locate, + sg4term_getCursorPos, sg4term_print, sg4term_printPrefix, + sg4term_clrtoeol, sg4term_scrollWindowUp, sg4term_scrollWindowDown, + sg4term_waitEditorKey); + Ebitor_setContentLength(0); + Ebitor_locateCursorAtSavedPosition(); + Ebitor_processKey('O'); + Ebitor_processKey('K'); + Ebitor_processKey(ebitor_KEY_ARROW_LEFT); /* Commit the inserted run and move left. */ + Ebitor_saveCursorPosition(); + unsigned count = Ebitor_getContentLength(); + Ebitor_shutdown(); + cls(255); + log[count] = 0; /* Two characters fit comfortably in our buffer. */ + printf("LOG: %s\n", log); + return 0; +} diff --git a/examples/cmoc/manual/fieldlog.c b/examples/cmoc/manual/fieldlog.c new file mode 100644 index 0000000..7797613 --- /dev/null +++ b/examples/cmoc/manual/fieldlog.c @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Work on a practice disk. Each run starts a new FIELD.LOG on drive 0. +#include +#include + +#define LOG_NAME "FIELD.LOG:0" + +/* Each reader starts at the beginning and sees the length saved on disk. */ +static int showLog(void) +{ + char line[40]; + FILE *reader = fopen(LOG_NAME, "r"); + int ok; + if (!reader) + return 0; + while (fgets(line, sizeof(line), reader)) + printf("%s", line); + ok = !ferror(reader); + if (fclose(reader) == EOF) + ok = 0; + return ok; +} + +int main(void) +{ + FILE *writer; + int ok; + cls(1); + printf("PLANET FIELD LOG\n"); + writer = fopen(LOG_NAME, "w"); + if (!writer) + { + printf("CANNOT START FIELD.LOG\n"); + return 1; + } + + /* Publish the first observation while we still hold the writer. */ + ok = fputs("EARTH: BLUE SEA\n", writer) != EOF && fflush(writer) == 0; + if (ok) + { + printf("CHECKPOINT READER SEES:\n"); + ok = showLog(); + } + if (ok) + { + printf("SPACE TO LAND ON MARS\n"); + while (waitkey(0) != ' ') {} + ok = fputs("MARS: RED RIDGE\n", writer) != EOF; + } + + /* Closing delivers the second observation and releases the stream. */ + if (fclose(writer) == EOF) + ok = 0; + if (!ok) + { + printf("CHECK DISK AND LOG\n"); + return 1; + } + printf("FINAL READER SEES:\n"); + if (!showLog()) + { + printf("CANNOT READ FIELD.LOG\n"); + return 1; + } + printf("SURVEY FILED\n"); + return 0; +} diff --git a/examples/cmoc/manual/flightread.bas b/examples/cmoc/manual/flightread.bas new file mode 100644 index 0000000..e8f2991 --- /dev/null +++ b/examples/cmoc/manual/flightread.bas @@ -0,0 +1,7 @@ +10 OPEN "I",#-1,"FLIGHT" +20 IF EOF(-1) THEN 60 +30 LINE INPUT #-1,A$ +40 PRINT A$ +50 GOTO 20 +60 CLOSE #-1 +70 PRINT "END OF FLIGHT" diff --git a/examples/cmoc/manual/flightrecorder.c b/examples/cmoc/manual/flightrecorder.c new file mode 100644 index 0000000..3927c2e --- /dev/null +++ b/examples/cmoc/manual/flightrecorder.c @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Give Mission Control two observations it can read back in recording order. +#include +#include + +static int recordFlight(void) +{ + int status = vcc_tape_open_write("FLIGHT"); + if (status != VCC_TAPE_OK) + return status; + + status = vcc_tape_write_line("EARTH BLUE SEA"); + if (status == VCC_TAPE_OK) + status = vcc_tape_write_line("MARS RED RIDGE"); + /* Closing writes the end-of-file block on a successful recording. */ + int closed = vcc_tape_close(); + return status == VCC_TAPE_OK ? closed : status; +} + +static int replayFlight(void) +{ + char observation[32]; + int status = vcc_tape_open_read("FLIGHT"); + if (status != VCC_TAPE_OK) + return status; + + while ((status = vcc_tape_read_line(observation, sizeof observation)) == VCC_TAPE_OK) + printf("%s\n", observation); + int closed = vcc_tape_close(); + /* A damaged last block also stops the loop. Only EOF completes the flight. */ + return status == VCC_TAPE_EOF ? closed : status; +} + +int main(void) +{ + cls(1); + printf("FLIGHT RECORDER\n"); + printf("W WRITE R READ\n"); + char choice; + do { + choice = waitkey(0); + } while (choice != 'W' && choice != 'w' && choice != 'R' && choice != 'r'); + + int write = choice == 'W' || choice == 'w'; + int status = write ? recordFlight() : replayFlight(); + if (status != VCC_TAPE_OK) { + printf("TAPE ERROR %d\n", status); + return 1; + } + printf("%s\n", write ? "FLIGHT SAVED" : "END OF FLIGHT"); + return 0; +} diff --git a/examples/cmoc/manual/flightreport.c b/examples/cmoc/manual/flightreport.c new file mode 100644 index 0000000..814af65 --- /dev/null +++ b/examples/cmoc/manual/flightreport.c @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Send a text report through the CoCo printer port. No disk file is needed. +#include +#include + +static int printLanding(unsigned visit, const char *planet, const char *observation) +{ + /* Two digits for the visit, a five-character field for the planet. */ + return vcc_printer_printf("%02u %-5s %s\n", visit, planet, observation); +} + +int main(void) +{ + cls(1); + printf("FLIGHT CONTROL\n"); + printf("START CAPTURE IN PRINTER OUTPUT\n"); + printf("PRESS SPACE TO SEND REPORT\n"); + while (waitkey(0) != ' ') {} + + /* Ordinary printf still goes to the screen. These four lines go to the port. */ + if (vcc_printer_printf("TP-10 FLIGHT REPORT\n") < 0 || + printLanding(1, "EARTH", "BLUE SEA") < 0 || + printLanding(2, "MARS", "RED RIDGE") < 0 || + vcc_printer_printf("END OF REPORT\n") < 0) + { + printf("REPORT FORMAT ERROR\n"); + return 1; + } + + /* The guest cannot tell whether the Mac is capturing the port. */ + printf("REPORT SENT TO PRINTER PORT\n"); + return 0; +} diff --git a/examples/cmoc/manual/flightwrite.bas b/examples/cmoc/manual/flightwrite.bas new file mode 100644 index 0000000..98bc9ef --- /dev/null +++ b/examples/cmoc/manual/flightwrite.bas @@ -0,0 +1,5 @@ +10 OPEN "O",#-1,"FLIGHT" +20 PRINT #-1,"EARTH TIDE POOL" +30 PRINT #-1,"MARS DUST DEVIL" +40 CLOSE #-1 +50 PRINT "FLIGHT SAVED" diff --git a/examples/cmoc/manual/flyby.c b/examples/cmoc/manual/flyby.c new file mode 100644 index 0000000..4aa18d4 --- /dev/null +++ b/examples/cmoc/manual/flyby.c @@ -0,0 +1,84 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Stereo Flyby. Link orch90, input and bcontrol, in that order. */ +#include +#include +#include +#include + +#define FRAMES 2048 +#define FIRST_COLUMN 2 +#define LAST_COLUMN 29 +#define STAR_ROW 8 +#define SHIP_ROW 10 + +/* Keep the sample in guest RAM for as long as the interrupt can read it. */ +static struct orch90_frame beacon[FRAMES]; + +static void makeBeacon(void) +{ + static const byte wave[] = { + 128, 146, 162, 172, 176, 172, 162, 146, + 128, 110, 94, 84, 80, 84, 94, 110 + }; + unsigned i; + for (i = 0; i < FRAMES; ++i) { + /* The first note comes from the left. The right note is an octave up. + 128 in both channels is the quiet space between notes. */ + beacon[i].left = i < 768 ? wave[i & 15] : 128; + beacon[i].right = i >= 1024 && i < 1792 ? wave[(i << 1) & 15] : 128; + } +} + +static void mark(byte column, byte row, char symbol) +{ + locate(column, row); + putchar(symbol); +} + +int main(void) +{ + VccInput stick; + unsigned lastUpdate, now; + byte ship = 15, star = LAST_COLUMN, key; + + width(32); + cls(1); + makeBeacon(); + input_init(&stick, INPUT_RIGHT); + printf("STEREO FLYBY\n\n1 TRANSMIT BEACON\nRIGHT STICK STEER Q QUIT\n"); + locate(1, 7); printf("+----------------------------+"); + locate(1, 12); printf("+----------------------------+"); + mark(ship, SHIP_ROW, '^'); + mark(star, STAR_ROW, '*'); + lastUpdate = getTimer(); + for (;;) { + key = inkey(); + if (key == 'Q' || key == 'q') + break; + if (key == '1' && !orch90_active()) { + locate(0, 5); + if (orch90_start(beacon, FRAMES, 1, ORCH90_CLOCK_NORMAL)) + printf("BEACON ON AIR"); + else + printf("PLAYBACK UNAVAILABLE"); + } + /* The guest clock drives the flight display. Audio advances between + updates, even when this loop is busy drawing or reading input. */ + now = getTimer(); + if ((unsigned)(now - lastUpdate) < 4) + continue; + lastUpdate = now; + input_sample(&stick); + mark(ship, SHIP_ROW, ' '); + if (stick.dx < 0 && ship > FIRST_COLUMN) --ship; + if (stick.dx > 0 && ship < LAST_COLUMN) ++ship; + mark(ship, SHIP_ROW, '^'); + mark(star, STAR_ROW, ' '); + star = star == FIRST_COLUMN ? LAST_COLUMN : star - 1; + mark(star, STAR_ROW, '*'); + } + orch90_stop(); + locate(0, 14); + printf("FLYBY COMPLETE\n"); + return 0; +} diff --git a/examples/cmoc/manual/glyph.c b/examples/cmoc/manual/glyph.c new file mode 100644 index 0000000..693d754 --- /dev/null +++ b/examples/cmoc/manual/glyph.c @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Draw letters in the four graphics pages reserved by fresh Disk BASIC. Link hirestxt. */ +#include + +int main(void) +{ + struct HiResTextScreenInit2 setup; + byte *page = (byte *) ((word) * (byte *) 0x00BC << 8); + memset(&setup, 0, sizeof(setup)); + setup.init.numColumns = 51; + setup.init.writeCharAtFuncPtr = writeCharAt_51cols; + setup.init.textScreenBuffer = page; + setup.init.timer = (word *) 0x0112; /* BASIC's 60 Hz clock */ + if (!pmode(4, page)) + return 1; + pcls(0); + screen(1, 1); + initHiResTextScreen2(&setup); + writeString("MARS STATION"); + waitkey(FALSE); + closeHiResTextScreen(); + screen(0, 0); + printf("BACK FROM THE GRAPHICS PAGE\n"); + return 0; +} diff --git a/examples/cmoc/manual/lander.c b/examples/cmoc/manual/lander.c new file mode 100644 index 0000000..f64e5e9 --- /dev/null +++ b/examples/cmoc/manual/lander.c @@ -0,0 +1,121 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Land on the gold pad. Link gime, bgraph and bcontrol. */ +#include +#include +#include + +enum { SPACE, WHITE, CYAN, GOLD, FLAME, BLUE, VIOLET }; +enum { CRAFT_W = 20, CRAFT_H = 16, PAD_LEFT = 220, PAD_RIGHT = 270 }; +typedef struct { unsigned x, y; } Position; + +/* BGraph supplies the line algorithm. Send each pixel to the hidden page. */ +static void pixel(word x, byte y, byte color, void *unused) +{ + (void) unused; + gime_plot(x, y, color); +} + +static void landscape(void) +{ + static const byte ridge[] = {183, 167, 177, 161, 176, 170, 184, 165, 177, 168}; + unsigned i; /* Star and ridge x coordinates extend beyond 255. */ + /* gime_open cleared both pages to SPACE before the first frame. */ + for (i = 0; i < 22; ++i) + gime_plot(7 + i * 14, 8 + (i * 13) % 34, WHITE); + /* The crescent and stars sit above the flight area. */ + gime_fill_rect(258, 18, 12, 2, GOLD); + gime_fill_rect(254, 20, 6, 10, GOLD); + gime_fill_rect(258, 30, 12, 2, GOLD); + gime_fill_rect(0, 184, GIME_WIDTH, GIME_HEIGHT - 184, BLUE); + for (i = 0; i < 9; ++i) + Primitive_line(i * 35, ridge[i], (i + 1) * 35, ridge[i + 1], VIOLET, pixel, 0); + gime_fill_rect(PAD_LEFT, 160, PAD_RIGHT - PAD_LEFT, 2, GOLD); + gime_fill_rect(PAD_LEFT + 3, 162, 2, 12, CYAN); + gime_fill_rect(PAD_RIGHT - 5, 162, 2, 12, CYAN); +} + +static void drawCraft(unsigned x, unsigned y) +{ + gime_fill_rect(x + 7, y, 6, 2, WHITE); + gime_fill_rect(x + 5, y + 2, 10, 5, CYAN); + gime_fill_rect(x + 8, y + 3, 4, 3, BLUE); + gime_fill_rect(x + 2, y + 7, 16, 4, WHITE); + gime_fill_rect(x + 3, y + 11, 2, 4, GOLD); + gime_fill_rect(x + 15, y + 11, 2, 4, GOLD); + gime_fill_rect(x, y + 15, 5, 1, WHITE); + gime_fill_rect(x + 15, y + 15, 5, 1, WHITE); + gime_fill_rect(x + 8, y + 11, 4, 3, FLAME); +} + +static int direction(byte axis, byte lowProbe, byte lowBit, byte highProbe, byte highBit) +{ + /* When a key is held, it takes precedence over this joystick axis. */ + if (isKeyPressed(lowProbe, lowBit)) + return -2; + if (isKeyPressed(highProbe, highBit)) + return 2; + Joystick_selectAnalogMuxInputs(axis); + if (!Joystick_compareAxis(16)) + return -2; + return Joystick_compareAxis(48) ? 2 : 0; +} + +static unsigned move(int value, int delta, int minimum, int maximum) +{ + value += delta; + if (value < minimum) return minimum; + if (value > maximum) return maximum; + return value; +} + +int main(void) +{ + Position craft = {144, 82}, previous[2]; + byte page = 0, initialized = 0, landed = 0, presented = 1; + static const byte colors[] = {0x00, 0x3F, 0x1B, 0x34, 0x26, 0x08, 0x29}; + byte i; + if (!gime_open()) + { + printf("USE A SUPPORTED COCO 3 BASIC SETUP\n"); + return 1; + } + for (i = 0; i < sizeof(colors); ++i) + gime_set_palette(i, colors[i]); + Joystick_disableSound(); + + while (!isKeyPressed(KEY_PROBE_Q, KEY_BIT_Q)) + { + if (initialized < 2) + { + landscape(); /* Each physical page gets the scenery once. */ + ++initialized; + } + else + gime_fill_rect(previous[page].x, previous[page].y, CRAFT_W, CRAFT_H, SPACE); + + craft.x = move(craft.x, direction(0, KEY_PROBE_A, KEY_BIT_A, KEY_PROBE_D, KEY_BIT_D), 0, GIME_WIDTH - CRAFT_W); + craft.y = move(craft.y, direction(1, KEY_PROBE_W, KEY_BIT_W, KEY_PROBE_S, KEY_BIT_S), 44, 160 - CRAFT_H); + drawCraft(craft.x, craft.y); + previous[page] = craft; /* Where to erase when this page comes around again. */ + presented = gime_present(); + if (!presented) + break; + page ^= 1; + if (craft.y == 160 - CRAFT_H && craft.x >= PAD_LEFT && craft.x + CRAFT_W <= PAD_RIGHT) + { + landed = 1; + break; + } + } + + Joystick_selectAnalogMuxInputs(0); + Joystick_enableSound(); + gime_close(); + if (!presented) + { + printf("DISPLAY TIMING UNAVAILABLE\n"); + return 1; + } + printf("%s\n", landed ? "ON THE PAD!" : "FLIGHT ENDED"); + return 0; +} diff --git a/examples/cmoc/manual/message.c b/examples/cmoc/manual/message.c new file mode 100644 index 0000000..03b9a16 --- /dev/null +++ b/examples/cmoc/manual/message.c @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Fit a call sign on a four-character cargo tag. Default CMOC runtime. */ +#include + +static int setTag(char *tag, size_t capacity, const char *name) +{ + size_t length = strlen(name); + if (length >= capacity) + return 0; /* Leave the previous tag intact. */ + memcpy(tag, name, length + 1); /* Copy the terminating zero as well. */ + return 1; +} + +int main(void) +{ + char tag[5] = ""; + if (!setTag(tag, sizeof(tag), "MARS")) + return 1; + printf("TAG: %s, LETTERS: %u\n", tag, (unsigned) strlen(tag)); + if (!setTag(tag, sizeof(tag), "EARTH") && strcmp(tag, "MARS") == 0) + printf("EARTH TOO LONG. KEPT %s\n", tag); + return 0; +} diff --git a/examples/cmoc/manual/pool.c b/examples/cmoc/manual/pool.c new file mode 100644 index 0000000..3234fa2 --- /dev/null +++ b/examples/cmoc/manual/pool.c @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Count on the pool to reject a request larger than its region. Link wydealloc. */ +#include +#include + +static unsigned char storage[64]; + +int main(void) +{ + MemPool pool; + void *small, *tooBig; + if (!MemPool_init(&pool, storage, storage + sizeof(storage))) + return 1; + small = MemPool_alloc(&pool, 8); + tooBig = MemPool_alloc(&pool, 80); + printf("SMALL %s, LARGE %s\n", small ? "OK" : "FAILED", tooBig ? "OK" : "REFUSED"); + MemPool_free(&pool, small); + MemPool_free(&pool, tooBig); + small = MemPool_alloc(&pool, 8); + printf("AFTER FREE: %s\n", small ? "OK" : "FAILED"); + MemPool_free(&pool, small); + return 0; +} diff --git a/examples/cmoc/manual/probe.c b/examples/cmoc/manual/probe.c new file mode 100644 index 0000000..dc2d4a0 --- /dev/null +++ b/examples/cmoc/manual/probe.c @@ -0,0 +1,117 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Survey the gold deposit. Link gime, input and bcontrol. */ +#include +#include +#include + +enum { SKY, WHITE, CYAN, GOLD, MAGENTA, ROCK, SHADOW }; +enum { LAUNCH_Y = 66, DEPOSIT_X = 216, DEPOSIT_Y = 152, MAX_CHARGE = 16 }; + +typedef struct { + unsigned shipX, probeX; + byte probeY; /* Zero when no probe is in flight. */ +} Flight; + +/* The craft and probe fly through clear sky, so a hidden page can erase + its previous sprites without saving any of the scenery beneath them. */ +static void scenery(void) +{ + static const byte horizon[] = {172, 170, 168, 171, 174, 175, 179, 180, 178, 173, + 170, 166, 162, 165, 172, 176, 180, 177, 174, 171}; + unsigned i; + for (i = 0; i < 20; ++i) { + unsigned x = i * 16; + unsigned top = horizon[i]; + gime_fill_rect(x, top, 16, 192 - top, ROCK); + gime_fill_rect(x, top, 16, 1, MAGENTA); + if (i % 3 == 0) gime_fill_rect(x + 6, top + 6, 7, 2, SHADOW); + gime_plot(x + 4, 20 + i * 7 % 23, WHITE); + } + gime_fill_rect(264, 15, 8, 2, GOLD); /* Crescent over the landing site. */ + gime_fill_rect(261, 17, 3, 7, GOLD); + gime_fill_rect(264, 24, 8, 2, GOLD); + gime_fill_rect(DEPOSIT_X + 2, DEPOSIT_Y + 3, 4, 11, CYAN); + gime_fill_rect(DEPOSIT_X + 20, DEPOSIT_Y + 3, 4, 22, CYAN); + gime_fill_rect(7, 7, 52, 8, WHITE); /* Charge gauge surround. */ +} + +static void drawShip(unsigned x) +{ + gime_fill_rect(x + 6, 49, 8, 2, WHITE); + gime_fill_rect(x + 4, 51, 12, 6, CYAN); + gime_fill_rect(x + 8, 52, 5, 3, SHADOW); + gime_fill_rect(x, 57, 20, 4, WHITE); + gime_fill_rect(x + 2, 61, 3, 3, GOLD); + gime_fill_rect(x + 15, 61, 3, 3, GOLD); +} + +int main(void) +{ + static const byte colors[] = {0x00, 0x3f, 0x1b, 0x34, 0x29, 0x08, 0x01}; + VccInput stick; + Flight now = {144, 0, 0}, old[2]; + unsigned launched = 0; + byte ready = 0, charge = 0, limit = 0, charging = 0, found = 0; + byte page = 0, freshPages = 2, i; + + if (!gime_open()) { + printf("USE COCO 3 BASIC WITH 512K OR MORE\n"); + return 1; + } + for (i = 0; i < sizeof(colors); ++i) gime_set_palette(i, colors[i]); + input_init(&stick, INPUT_RIGHT); + + while (!isKeyPressed(KEY_PROBE_Q, KEY_BIT_Q)) { + input_sample(&stick); /* One sample for this entire update. */ + if (stick.dx < 0 && now.shipX >= 2) now.shipX -= 2; + if (stick.dx > 0 && now.shipX < GIME_WIDTH - 20) now.shipX += 2; + + if (stick.pressed & INPUT_PRIMARY) { + ++launched; /* Start one new probe at the craft. */ + now.probeX = now.shipX + 9; + now.probeY = LAUNCH_Y; + limit = LAUNCH_Y + 24 + 4 * ready; + charge = 0; + charging = 1; + } else if (now.probeY) { + if (now.probeY >= limit) now.probeY = 0; + else now.probeY += 2; + } + if (charging && (stick.held & INPUT_PRIMARY) && charge < MAX_CHARGE) + ++charge; /* Build energy for the NEXT probe. */ + if (charging && (stick.released & INPUT_PRIMARY)) { + ready = charge; /* Lock in the range for the next press. */ + charging = 0; + } + if (now.probeY + 3 >= DEPOSIT_Y && now.probeX >= DEPOSIT_X && + now.probeX < DEPOSIT_X + 26) { + found = 1; + now.probeY = 0; + } + + if (freshPages) { + scenery(); + --freshPages; + } else { + gime_fill_rect(old[page].shipX, 49, 20, 15, SKY); + if (old[page].probeY) + gime_fill_rect(old[page].probeX, old[page].probeY, 2, 4, SKY); + } + drawShip(now.shipX); + if (now.probeY) gime_fill_rect(now.probeX, now.probeY, 2, 4, CYAN); + gime_fill_rect(DEPOSIT_X, DEPOSIT_Y, 26, 3, found ? CYAN : GOLD); + gime_fill_rect(9, 9, 48, 4, SHADOW); + gime_fill_rect(9, 9, 3 * (charging ? charge : ready), 4, charging ? GOLD : CYAN); + old[page] = now; + if (!gime_present()) { + gime_close(); + printf("DISPLAY TIMING UNAVAILABLE\n"); + return 1; + } + page ^= 1; + } + gime_close(); + printf("PROBES LAUNCHED: %u\n", launched); + if (found) printf("DEPOSIT SURVEYED\n"); + return 0; +} diff --git a/examples/cmoc/manual/returntrip.c b/examples/cmoc/manual/returntrip.c new file mode 100644 index 0000000..24f8125 --- /dev/null +++ b/examples/cmoc/manual/returntrip.c @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Run twice on the same practice disk. Each flight adds one observation. +#include +#include +#include +#include + +#define LOG_NAME "TRIP.LOG:0" + +static int fly(FILE *log) +{ + char line[32]; + unsigned visits = 0; + const char *planet; + + /* a+ opens even a new log at byte zero so we can read earlier flights. */ + while (fgets(line, sizeof(line), log)) + { + if ((visits == 0 && strcmp(line, "VISIT 1: EARTH\n") == 0) || + (visits == 1 && strcmp(line, "VISIT 2: MARS\n") == 0)) + ++visits; + else + { + printf("UNRECOGNIZED TRIP.LOG\n"); + return 0; + } + } + if (ferror(log)) + return 0; + if (visits == 2) + { + printf("BOTH VISITS ALREADY FILED\n"); + return 1; + } + + /* Move the cursor to the first record. With a+, output still appends. */ + if (fseek(log, 0L, SEEK_SET) != 0) + return 0; + planet = visits ? "MARS" : "EARTH"; + printf("AT BYTE ZERO\nFILING %s\n", planet); + if (fprintf(log, "VISIT %u: %s\n", visits + 1, planet) < 0) + return 0; + + /* This short record is buffered. Keep the stream open if saving fails. */ + while (fflush(log) == EOF) + { + char key; + if (ferror(log) != DECB_ERR_IO) + return 0; + printf("SAVE FAILED\nKEEP THE SAME DISK IN DRIVE 0\n"); + printf("IF PROTECTED, TURN PROTECT OFF\nR: RETRY Q: QUIT\n"); + do { + key = waitkey(0); + } while (key != 'R' && key != 'r' && key != 'Q' && key != 'q'); + if (key == 'Q' || key == 'q') + return 0; + /* Retry just the flush. Printing the observation again could duplicate it. */ + clearerr(log); + printf("RETRYING SAVE\n"); + } + return 1; +} + +int main(void) +{ + FILE *log; + char line[32]; + int ok; + cls(1); + printf("RETURN TRIP\n"); + log = fopen(LOG_NAME, "a+"); + if (!log) + { + printf("CANNOT OPEN TRIP.LOG\n"); + return 1; + } + ok = fly(log); + /* Check the result of closing the stream, even after an explicit flush. */ + if (fclose(log) == EOF) + ok = 0; + if (!ok) + { + printf("CHECK DISK AND LOG\n"); + return 1; + } + + /* A new reader shows what the next flight will find on the disk. */ + log = fopen(LOG_NAME, "r"); + if (!log) + { + printf("CANNOT REOPEN TRIP.LOG\n"); + return 1; + } + printf("REOPENED TRIP.LOG\n"); + while (fgets(line, sizeof(line), log)) + printf("%s", line); + ok = !ferror(log); + if (fclose(log) == EOF) + ok = 0; + if (!ok) + { + printf("CANNOT READ TRIP.LOG\n"); + return 1; + } + return 0; +} diff --git a/examples/cmoc/manual/ridge.c b/examples/cmoc/manual/ridge.c new file mode 100644 index 0000000..77ce68e --- /dev/null +++ b/examples/cmoc/manual/ridge.c @@ -0,0 +1,130 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Two landscapes, one working array. Link bank, gime and hirestxt. */ +#include +#include +#include +#include + +enum { COLUMNS = 20, FIRST_COLUMN = 10, FLOOR = 169 }; +enum { NIGHT, INK, WHITE, GOLD, WINDOW, EARTH_FAR, EARTH_SOIL, EARTH_EDGE, + MARS_FAR, MARS_SOIL, MARS_EDGE }; + +static const byte earth[COLUMNS] = { + 128, 122, 116, 120, 132, 140, 136, 128, 122, 126, + 132, 140, 146, 138, 134, 122, 112, 120, 132, 140 +}; +static const byte mars[COLUMNS] = { + 156, 146, 132, 128, 140, 154, 150, 140, 142, 148, + 152, 146, 136, 126, 118, 130, 142, 154, 146, 138 +}; + +/* Pierre Sarrazin's HiresText font has five ink columns, encoded as zero bits. */ +static void label(unsigned x, byte y, const char *text) +{ + while (*text) { + const byte *glyph = font5x8 + ((unsigned)*text++ - ' ') * 8; + byte row, col; + for (row = 0; row < 8; ++row) + for (col = 0; col < 5; ++col) + if (!(glyph[row] & (0x80 >> col))) + gime_plot(x + col, y + row, WHITE); + x += 6; + } +} + +static byte draw(const byte *ridge, byte onMars, byte column) +{ + char reading[10]; /* "RIDGE $FF" and its terminator. */ + unsigned i, x = column * 16; + byte farRock = onMars ? MARS_FAR : EARTH_FAR; + byte soil = onMars ? MARS_SOIL : EARTH_SOIL; + byte edge = onMars ? MARS_EDGE : EARTH_EDGE; + + gime_clear(NIGHT); + for (i = 0; i < COLUMNS; ++i) { + unsigned left = i * 16; + unsigned farY = 101 + ((i * 7 + (onMars ? 19 : 5)) % 27); + gime_plot(left + 3, 31 + i * 11 % 43, WHITE); + gime_fill_rect(left, farY, 16, FLOOR - farY, farRock); + gime_fill_rect(left, ridge[i], 16, FLOOR - ridge[i], soil); + gime_fill_rect(left, ridge[i], 16, 2, edge); + if ((i & 1) == 0 && ridge[i] + 9 < FLOOR) + gime_fill_rect(left + 3, ridge[i] + 8, 6, 1, farRock); + } + /* A crescent hangs above the distant range. */ + gime_fill_rect(259, 28, 8, 2, edge); + gime_fill_rect(256, 30, 4, 8, edge); + gime_fill_rect(259, 38, 8, 2, edge); + /* A small survey craft and the sounding line beneath it. */ + for (i = 67; i < ridge[column]; i += 6) + gime_plot(x + 8, i, GOLD); + gime_fill_rect(x + 5, 51, 8, 5, WINDOW); + gime_fill_rect(x + 2, 56, 13, 3, WHITE); + gime_fill_rect(x, 59, 16, 3, edge); + gime_fill_rect(x + 4, 62, 2, 3, GOLD); + gime_fill_rect(x + 11, 62, 2, 3, GOLD); + + label(8, 8, onMars ? "MARS SURVEY" : "EARTH SURVEY"); + sprintf(reading, "RIDGE $%02X", (unsigned)ridge[column]); + label(131, 8, reading); + label(258, 8, onMars ? "BANK $29" : "BANK $28"); + gime_fill_rect(8, 19, 304, 1, edge); + gime_fill_rect(0, FLOOR, 320, 192 - FLOOR, INK); + label(8, 176, "A/D FLY SPACE SWAP R RAISE ON MARS Q QUIT"); + return gime_present(); +} + +static byte survey(void) +{ + byte ridge[COLUMNS], column = FIRST_COLUMN, onMars = 0; + unsigned offset; + + /* Seed once. Changing planets must read the saved map, not reseed it. */ + if (!bank_write(0, earth, COLUMNS) || + !bank_write(BANK_PAGE_SIZE, mars, COLUMNS)) + return 0; + for (;;) { + byte key; + offset = onMars ? BANK_PAGE_SIZE : 0u; + if (!bank_read(offset, ridge, COLUMNS) || !draw(ridge, onMars, column)) + return 0; + do { + key = waitkey(0); + if (key >= 'a' && key <= 'z') key -= 'a' - 'A'; + if (key == 'Q') return 1; + if (key == ' ') { onMars ^= 1; break; } + if (key == 'A' && column > 0) { --column; break; } + if (key == 'D' && column + 1 < COLUMNS) { ++column; break; } + if (key == 'R' && onMars && ridge[column] >= 96) { + /* Screen y grows downward. Save just the changed byte. */ + ridge[column] -= 16; + if (!bank_write(offset + column, &ridge[column], 1)) + return 0; + break; + } + } while (1); + } +} + +int main(void) +{ + static const byte colors[] = { + 0x01, 0x00, 0x3f, 0x36, 0x1b, 0x0a, 0x15, 0x1e, 0x21, 0x26, 0x37 + }; + byte i, ok; + if (!bank_open()) { + printf("USE STANDARD COCO 3 BASIC WITH 512K OR MORE\n"); + return 1; + } + if (!gime_open()) { + bank_close(); + printf("GRAPHICS UNAVAILABLE\n"); + return 1; + } + for (i = 0; i < sizeof(colors); ++i) gime_set_palette(i, colors[i]); + ok = survey(); + gime_close(); + bank_close(); + printf("%s\n", ok ? "SURVEY COMPLETE" : "SURVEY TRANSFER OR DISPLAY FAILED"); + return ok ? 0 : 1; +} diff --git a/examples/cmoc/manual/route.c b/examples/cmoc/manual/route.c new file mode 100644 index 0000000..91177c4 --- /dev/null +++ b/examples/cmoc/manual/route.c @@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Three rooms in a straight corridor. Link astar. */ +#include + +int main(void) +{ + AStarNode rooms[3]; + AStarGraph map = { rooms, 3, 1 }; + AStarPathIterator it; + AStarNode *room; + byte i; + for (i = 0; i < 3; ++i) + astar_initNode(rooms + i, NULL, i < 2, FALSE); + if (!astar_searchGrid(&map, 0, 0, 2, 0)) + return 1; + astar_startPathIteration(&it, &map, 2, 0); + printf("BACK FROM GOAL:"); + while ((room = astar_advancePathIteration(&it)) != NULL) + printf(" %u", (unsigned) (room - rooms)); + printf("\n"); + return 0; +} diff --git a/examples/cmoc/manual/stick.c b/examples/cmoc/manual/stick.c new file mode 100644 index 0000000..2902b5b --- /dev/null +++ b/examples/cmoc/manual/stick.c @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Fly the right stick to a position and press its first button. Link bcontrol. */ +#include + +int main(void) +{ + byte axes[4] = { 0, 0, 0, 0 }; + byte buttons; + word start; + printf("MOVE THE RIGHT STICK AND FIRE\n"); + Joystick_disableSound(); + start = getTimer(); + do + { + buttons = Joystick_getButtonStates(); + } while ((buttons & 1) && (word) (getTimer() - start) < 600); + Joystick_getAxisValues(axes, 0x03); + Joystick_selectAnalogMuxInputs(0); + Joystick_enableSound(); + printf("RIGHT X=%u Y=%u\n", (unsigned) axes[0], (unsigned) axes[1]); + printf("BUTTON %s\n", (buttons & 1) ? "UP" : "DOWN"); + return 0; +} diff --git a/examples/cmoc/manual/tone.c b/examples/cmoc/manual/tone.c new file mode 100644 index 0000000..927470e --- /dev/null +++ b/examples/cmoc/manual/tone.c @@ -0,0 +1,14 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Sound a landing signal and give the interrupt vector back. Link bsound. */ +#include + +int main(void) +{ + Player player; + printf("BEACON ON\n"); + Player_init(&player, TRUE, NULL); + Player_sound(130, 12); + Player_shutdown(); + printf("BEACON OFF\n"); + return 0; +} diff --git a/examples/cmoc/planet.c b/examples/cmoc/planet.c new file mode 100644 index 0000000..6cade91 --- /dev/null +++ b/examples/cmoc/planet.c @@ -0,0 +1,29 @@ +/* Earth or Mars -- one key chooses the greeting on a 40-column CoCo 3. */ +#include +#include + +int main(void) +{ + byte choice; + + width(40); + printf("What planet do you live on?\n1) Earth\n2) Mars\n"); + do + { + choice = inkey(); /* No Enter needed. Ignore other keys. */ + } while (choice != '1' && choice != '2'); + + attr(3, 6, FALSE, FALSE); /* White text on background slot 6. */ + if (choice == '1') + { + palette(6, 10); /* Blue */ + printf("Hello Nice Blue Dot World!\n"); + } + else + { + palette(6, 37); /* Red */ + printf("Hello Cold Red Dot World!\n"); + } + attr(0, 0, FALSE, FALSE); /* Back to BASIC's usual colors. */ + return 0; +} diff --git a/license.txt b/license.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/license.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/platforms/macos/App/AboutView.swift b/platforms/macos/App/AboutView.swift new file mode 100644 index 0000000..439cf2e --- /dev/null +++ b/platforms/macos/App/AboutView.swift @@ -0,0 +1,330 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit + +enum AppCredits { + static func resource(_ name: String, extension ext: String) -> URL? { + Bundle.main.url(forResource: name, withExtension: ext, subdirectory: "About") + } + static func text(_ name: String) -> String { + guard let url = resource(name, extension: "txt"), let text = try? String(contentsOf: url, encoding: .utf8) else { + return "This build is missing its bundled \(name) notice. Please rebuild or reinstall the complete application." + } + return text + } + static var hasDiskLibrary: Bool { + guard let resources = Bundle.main.resourceURL else { return false } + return FileManager.default.fileExists(atPath: resources.appendingPathComponent("Toolchain/LICENSES/DECBFILE-NOTICE.txt").path) + } + static var hasStandaloneDiskLibrary: Bool { + guard let resources = Bundle.main.resourceURL else { return false } + return FileManager.default.fileExists(atPath: resources.appendingPathComponent("Toolchain/LICENSES/DSKCON-STANDALONE-NOTICE.txt").path) + } + static var diskLibraryNotice: String { + let core = "The ROM-backed core of decbfile, by Pierre Sarrazin, is public-domain software and retains its upstream no-warranty notice. It provides disk-file access through the Disk BASIC ROM loaded in the emulated CoCo. That ROM is separate third-party software and is not covered by the library’s public-domain dedication or VCC Plus’s GPL license." + guard hasStandaloneDiskLibrary else { return core } + return core + "\n\nThis build also includes Pierre Sarrazin’s standalone floppy disk driver as an optional development library. His upstream notice declares it public domain except for the portions taken from Disk Extended Color BASIC. Those portions are separate third-party code and are not covered by VCC Plus’s GPL license or the library’s public-domain dedication. Their respective owners retain their rights. Linking this driver is an explicit project choice; it allows disk access without keeping Disk BASIC mapped. Rights-holder inquiries or removal requests may be sent to me@brianholman.com." + } + static var developmentTools: String { + let introduction = "CMOC by Pierre Sarrazin · LWTools by William Astle and contributors · mcpp by Kiyoshi Matsui and contributors · GNU Make by the Free Software Foundation and contributors · Perl by Larry Wall and contributors.\n\nCMOC, LWTools and GNU Make are GPL-licensed. mcpp uses a BSD license. Perl is available under the GNU GPL version 1 or later, or the Artistic License. Exact upstream source snapshots and licenses are retained in the repository. The bundled toolchain excludes the separately supplied floating-point ROM. Any included standalone Disk BASIC-derived driver is identified separately below.\n\n" + guard let base = Bundle.main.resourceURL?.appendingPathComponent("Toolchain/LICENSES"), + let files = try? FileManager.default.contentsOfDirectory(at: base, includingPropertiesForKeys: nil) else { + return introduction + "The optional development toolchain is not included in this build." + } + return introduction + (hasDiskLibrary ? diskLibraryNotice + "\n\n" : "") + files.sorted { $0.lastPathComponent < $1.lastPathComponent }.map { + "—— " + $0.lastPathComponent + " ——\n\n" + ((try? String(contentsOf: $0, encoding: .utf8)) ?? "Notice unavailable.") + }.joined(separator: "\n\n") + } + static var version: String { + let info = Bundle.main.infoDictionary ?? [:] + return "Version \(info["CFBundleShortVersionString"] as? String ?? "Development") (build \(info["CFBundleVersion"] as? String ?? "—"))" + } +} + +private struct CreditArtwork: View { + let name: String + var ext = "pdf" + let label: String + var body: some View { + if let url = AppCredits.resource(name, extension: ext), let image = NSImage(contentsOf: url) { + Image(nsImage: image).resizable().scaledToFit().accessibilityLabel(label) + } + } +} + +// Both windows read the same approved notices; no duplicate legal copy in views. +private struct LegalNoticesView: View { + private let notices = [ + ("Copyright & Trademarks", "CopyrightNotice"), + ("Original Artwork", "ArtworkNotice"), + ("ROMs & Third-Party Software", "ROMNotice"), + ("DriveWire protocol", "DriveWireCredit") + ] + var body: some View { + VStack(alignment: .leading, spacing: 20) { + ForEach(notices, id: \.1) { title, resource in + VStack(alignment: .leading, spacing: 8) { + Text(title).font(.headline).accessibilityAddTraits(.isHeader) + Text(AppCredits.text(resource)).textSelection(.enabled) + if resource == "DriveWireCredit" { + Link("DriveWire project and specification", destination: URL(string: "https://github.com/DrPitre/DriveWire")!) + } else if resource == "ArtworkNotice" { + Link("SockMaster’s CoCo 3 and CM-8 illustration on CoCopedia", + destination: URL(string: "https://www.cocopedia.com/wiki/File:COCO-CM8.GIF")!) + } + } + } + if AppCredits.hasDiskLibrary { + VStack(alignment: .leading, spacing: 8) { + Text("Disk File Library").font(.headline).accessibilityAddTraits(.isHeader) + Text(AppCredits.diskLibraryNotice).textSelection(.enabled) + } + } + Link("Contact: me@brianholman.com", destination: URL(string: "mailto:me@brianholman.com")!) + } + } +} + +struct AboutVCCView: View { + @Environment(\.colorScheme) private var colorScheme + @Environment(\.openWindow) private var openWindow + var body: some View { + ScrollViewReader { proxy in + VStack(spacing: 0) { + HStack(spacing: 12) { + Button { proxy.scrollTo("mac-credits", anchor: .top) } label: { Label("Mac credits", systemImage: "desktopcomputer") } + .accessibilityIdentifier("about-mac-credits") + Button { proxy.scrollTo("notices", anchor: .top) } label: { Label("Notices", systemImage: "doc.text") } + .accessibilityIdentifier("about-notices") + Button { proxy.scrollTo("windows-credits", anchor: .top) } label: { Label("Windows credits", systemImage: "person.2") } + .accessibilityIdentifier("about-windows-credits") + Spacer(minLength: 4) + Button { openWindow(id: "credits") } label: { Label("Licenses…", systemImage: "text.book.closed") } + .accessibilityIdentifier("about-licenses") + }.buttonStyle(.bordered).controlSize(.small).padding(14) + Divider() + ScrollView { + VStack(alignment: .leading, spacing: 22) { + HStack(alignment: .top, spacing: 20) { + Image(nsImage: NSApplication.shared.applicationIconImage) + .resizable().scaledToFit().frame(width: 96, height: 96) + .accessibilityLabel("VCC Plus app icon").accessibilityIdentifier("about-app-icon") + VStack(alignment: .leading, spacing: 8) { + Text("VCC Plus OSS").font(.title.bold()).accessibilityAddTraits(.isHeader) + Text(AppCredits.version).foregroundStyle(.secondary) + Button("Release History…") { openWindow(id: "release-history") } + .accessibilityIdentifier("about-release-history") + Text("Designed by Brian Holman").font(.headline) + Text("Sponsored by Dezota LLC").font(.headline) + } + }.id("mac-credits") + VStack(alignment: .leading, spacing: 16) { + Text(""" + VCC Plus brings the wonder of the Color Computer to a new generation—and new possibilities to those who grew up with it. Reimagined for the Mac, it combines classic computing with a browsable software library, an integrated C development environment, and a native interface. + + Built on decades of outstanding work by the Color Computer community and developed with the assistance of OpenAI’s ChatGPT and Codex, VCC Plus connects that rich legacy with today’s tools—honoring the creators, preserving their attributions, and respecting the licenses that make this work possible. + """) + .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + .textSelection(.enabled) + HStack(alignment: .center) { + CreditArtwork(name: "founder", label: "Brian Holman, founder illustration") + .frame(width: 64, height: 85).accessibilityIdentifier("about-founder") + Spacer(minLength: 24) + Link(destination: URL(string: "https://www.dezota.com")!) { + CreditArtwork(name: colorScheme == .dark ? "dezota-dark" : "dezota", label: "Dezota LLC corporate logo").frame(width: 156, height: 36) + }.buttonStyle(.plain).help("Open the Dezota LLC website").accessibilityLabel("Dezota LLC website") + .accessibilityIdentifier("about-sponsor") + }.frame(maxWidth: .infinity) + } + Divider() + LegalNoticesView().id("notices") + Divider() + VStack(alignment: .leading, spacing: 18) { + Text("Original Windows VCC").font(.title2.bold()).accessibilityAddTraits(.isHeader) + CreditArtwork(name: "windows-vcc", ext: "bmp", label: "Original VCC logo") + .frame(height: 82).frame(maxWidth: .infinity) + HStack(spacing: 24) { + CreditArtwork(name: "windows-founders", ext: "bmp", label: "Artwork from the original Windows About window").frame(width: 130, height: 100) + VStack(alignment: .leading, spacing: 8) { + Text("VCC — Virtual Color Computer").font(.headline) + Text("Windows VCC Version 2.1.10.0").foregroundStyle(.secondary) + Text("Another classic computer canceled before it's time!").italic() + } + } + Text(AppCredits.text("WindowsAbout")).textSelection(.enabled) + Link("Original VCC project", destination: URL(string: "https://github.com/VCCE/VCC")!) + }.id("windows-credits") + }.frame(maxWidth: 700, alignment: .leading).padding(24).frame(maxWidth: .infinity) + } + } + }.frame(minWidth: 620, minHeight: 520) + } +} + +struct LicenseCreditsView: View { + @State private var selected: String? = "Overview" + private let notices = [ + ("Overview", "VCC Plus Notices"), + ("GPL", "GNU General Public License"), + ("ThirdPartyNotices", "Third-Party Notices"), + ("WindowsAbout", "Original Windows VCC"), + ("DevelopmentTools", "C Development Tools") + ] + var body: some View { + HSplitView { + List(selection: $selected) { + Section("Documents") { + ForEach(notices, id: \.0) { key, title in + Label(title, systemImage: key == "GPL" ? "text.book.closed" : "doc.text") + .padding(.vertical, 5).tag(key) + .accessibilityIdentifier("license-document-" + key) + } + } + }.listStyle(.sidebar).frame(minWidth: 180, idealWidth: 210, maxWidth: 250) + .accessibilityLabel("License documents") + VStack(alignment: .leading, spacing: 0) { + Text(notices.first { $0.0 == (selected ?? "Overview") }?.1 ?? "VCC Plus Notices") + .font(.headline).padding(18).accessibilityAddTraits(.isHeader) + Divider() + ScrollView { + Group { + if selected == nil || selected == "Overview" { LegalNoticesView() } + else { Text(selected == "DevelopmentTools" ? AppCredits.developmentTools : AppCredits.text(selected!)).textSelection(.enabled) } + }.frame(maxWidth: .infinity, alignment: .leading).padding(20) + }.id(selected) + }.frame(minWidth: 420, maxWidth: .infinity, maxHeight: .infinity) + }.frame(minWidth: 640, minHeight: 500) + } +} + +private struct KeyboardHelpSection { + let title: String + let symbol: String + let commands: [(String, String)] + let paragraphs: [String] + func matches(_ query: String) -> Bool { + query.isEmpty || ([title] + commands.flatMap { [$0.0, $0.1] } + paragraphs) + .contains { $0.localizedCaseInsensitiveContains(query) } + } +} + +struct KeyboardHelpView: View { + @State private var search = "" + private let sections: [KeyboardHelpSection] = [ + KeyboardHelpSection(title: "Focus & CoCo keys", symbol: "keyboard", commands: [ + ("⌘1", "Show Emulator — reopen or bring it forward"), + ("⌥⌘K", "Focus the CoCo display"), + ("⌥⌘U", "Focus Mac controls") + ], paragraphs: [ + "Use Input → Focus Mac Controls to leave the CoCo display, then Tab and Shift-Tab to move through native controls. Enable Keyboard navigation in macOS System Settings → Keyboard if needed. Space activates a focused button; Escape dismisses a menu or popover. Input → Focus CoCo Display returns typing to the guest.", + "System view’s Devices list and the Media, Machine and Input menus provide native alternatives to the illustrated controls. VoiceOver can read the Mac controls, labels and media status. It cannot interpret arbitrary CoCo graphics or applications; Copy CoCo Screen Text works only in supported text modes.", + "Return → ENTER · Escape → BREAK · Home → CLEAR · Delete → backspace/left · Arrow keys → CoCo arrows · F1/F2 → CoCo F1/F2. Use Fn or Globe with function keys if macOS assigns them to hardware controls.", + "Input → Keyboard and Joysticks offers Natural, CoCo and Compact layouts. Natural uses the Mac’s typed characters; CoCo follows physical US CoCo key positions. In Compact mode, Tab supplies CLEAR and the unshifted grave key supplies BREAK. Control and Option supply the CoCo Control and Alt keys.", + "Keyboard joystick assignments reserve their configured direction/fire keys. Change the port’s input source when you need those keys for typing. Held keys are released when the display loses focus." + ]), + KeyboardHelpSection(title: "Machine", symbol: "cpu", commands: [ + ("⇧⌘O", "Choose a CoCo 3 system ROM"), + ("⇧⌘P", "Configuration Profiles"), + ("⌘,", "Machine Settings"), + ("⇧⌘F", "Emulator window: toggle fast-forward (sound is silenced)"), + ("⌘Q", "Quit, with unsaved-media protection") + ], paragraphs: [ + "Windows VCC’s F3–F12 application shortcuts are not mapped wholesale on Mac. Use Run/Pause and Restart in the toolbar, Display for video output, Machine for fast-forward and CPU settings, Cartridge for devices, and View for full screen. F1/F2 remain guest keys." + ]), + KeyboardHelpSection(title: "Media", symbol: "externaldrive", commands: [ + ("⌘O", "Open Media; choose its destination"), + ("⇧⌘B", "Load and run a CoCo binary"), + ("⇧⌘D", "Floppy Disks"), + ("⇧⌘T", "Cassette") + ], paragraphs: [ + "Drop one media file onto the main display, a System drive or cartridge, or a drive row. Choose the destination and confirm. File → Open Recent Media remembers the last 12 successful file selections. Clear Recent Media removes history, not files or mounted media." + ]), + KeyboardHelpSection(title: "Display", symbol: "display", commands: [ + ("⇧⌘E", "Expand/return the monitor in System view"), + ("⇧⌘S", "Save the active CoCo picture as a PNG") + ], paragraphs: [ + "Display → Display Settings offers sharp, smooth and integer-pixel scaling, plus optional scanlines. These remembered Mac preferences preserve the running session. Save CoCo Screen captures the current active picture as a PNG at native resolution without scaling, scanlines or the surrounding window; the CoCo keeps running while you choose where to save." + ]), + KeyboardHelpSection(title: "BASIC Development", symbol: "terminal", commands: [ + ("⌃⇧H", "Quick Help for the command at the insertion point"), + ("Option-click a command", "Open its BASIC reference topic"), + ("⌃Space", "Show BASIC keyword completions"), + ("Tab", "Accept a faint keyword suggestion"), + ("⌘F in the reference", "Find a command or topic") + ], paragraphs: [ + "Develop → BASIC Quick Reference is available offline. Browse syntax, parameters, related commands and error explanations. RGB-DOS and SDC-DOS additions are labeled separately. A topic stays open while you edit.", + "Open Example creates a separate editable workspace with its own recovery draft. Opening it does not load or run anything. Use Run when ready; the existing safeguards apply before replacing the CoCo program. Only the workspace that most recently loaded a program controls its BASIC debugger." + ]), + KeyboardHelpSection(title: "Debugger", symbol: "ladybug", commands: [ + ("⌥⌘D", "Show Debugger"), + ("⌥⌘R", "Pause / continue execution"), + ("⌥⌘I", "Step one instruction while paused") + ], paragraphs: []), + KeyboardHelpSection(title: "Find in a source editor", symbol: "magnifyingglass", commands: [ + ("⌘F", "Find in the current BASIC, C or assembly file"), + ("⌥⌘F", "Find and replace in this file"), + ("⌘G", "Select the next match"), + ("⇧⌘G", "Select the previous match"), + ("⌘E", "Use the selected source text for Find"), + ("Escape", "Close the find bar and return to the source") + ], paragraphs: [ + "Replace edits one selected match. Replace All in File edits the current file in one Undo step. You can search a read-only header. To search across C project files, choose the magnifying-glass tab in the left sidebar." + ]), + KeyboardHelpSection(title: "C Development", symbol: "curlybraces.square", commands: [ + ("⌥⌘C", "Open C Development"), + ("⇧⌘F", "C workspace: Find in Project") + ], paragraphs: [ + "Build uses the current editor contents, including unsaved edits. Save All writes your files to disk. For a source-debug build, set a breakpoint on an executable line, run to it, then use the C stepping controls, call stack, Variables and Watches. Open Debugger to inspect individual machine instructions, registers or memory." + ]), + KeyboardHelpSection(title: "Clipboard", symbol: "doc.on.clipboard", commands: [ + ("⌘C / ⌘V", "Copy screen / paste text when the CoCo display has focus"), + ("⇧⌘C / ⇧⌘V", "Explicit CoCo screen copy / text paste") + ], paragraphs: [ + "Edit offers BASIC Merge and Replace, with confirmation. Wait at the BASIC prompt first. Neither starts the program. Text paste executes Return only where the clipboard contains a newline. Cancel Paste, Pause or a CoCo key stops remaining input; already entered text is retained. BASIC lines are limited to 249 characters to prevent truncation." + ]), + ] + var body: some View { + VStack(spacing: 0) { + HStack(spacing: 12) { + Label("Find a shortcut or topic", systemImage: "keyboard").font(.headline) + Spacer() + TextField("Search keyboard help", text: $search).textFieldStyle(.roundedBorder) + .frame(maxWidth: 260).accessibilityLabel("Search keyboard help") + .accessibilityIdentifier("keyboard-help-search") + }.padding(16) + Divider() + ScrollView { + VStack(alignment: .leading, spacing: 18) { + Text("Click the CoCo display before typing. Native text fields keep their usual Mac editing shortcuts.") + .foregroundStyle(.secondary) + ForEach(sections.filter { $0.matches(search.trimmingCharacters(in: .whitespacesAndNewlines)) }, id: \.title) { section in + SecondaryCard { + Label(section.title, systemImage: section.symbol).font(.headline) + .accessibilityAddTraits(.isHeader) + Grid(alignment: .leading, horizontalSpacing: 20, verticalSpacing: 9) { + ForEach(section.commands, id: \.0) { key, action in + GridRow { + Text(key).font(.system(.body, design: .monospaced)) + .frame(width: 110, alignment: .leading) + Text(action).frame(maxWidth: .infinity, alignment: .leading) + } + } + } + if !section.paragraphs.isEmpty { + SecondaryHelp(title: section.title == "Focus & CoCo keys" ? "Navigation and CoCo key layouts" : "Using " + section.title.lowercased()) { + ForEach(section.paragraphs, id: \.self) { paragraph in + Text(paragraph).fixedSize(horizontal: false, vertical: true) + } + } + } + } + } + if !sections.contains(where: { $0.matches(search.trimmingCharacters(in: .whitespacesAndNewlines)) }) { + Label("No matching shortcuts or topics", systemImage: "magnifyingglass") + .foregroundStyle(.secondary).padding(.vertical, 20) + } + }.padding(20).frame(maxWidth: 760, alignment: .leading).frame(maxWidth: .infinity) + } + }.frame(minWidth: 620, minHeight: 500) + } +} diff --git a/platforms/macos/App/ArchiveInlinePreview.swift b/platforms/macos/App/ArchiveInlinePreview.swift new file mode 100644 index 0000000..a2a2fd9 --- /dev/null +++ b/platforms/macos/App/ArchiveInlinePreview.swift @@ -0,0 +1,240 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import ImageIO +import SwiftUI +import UniformTypeIdentifiers + +/// ImageIO can be decoding a large diagram when the user moves through several rows. +/// Only one bitmap is decoded at a time, and superseded selections skip the decode. +actor ArchivePreviewDecoder { + static let shared = ArchivePreviewDecoder() + + func read(_ url: URL, format: String, number: Int) throws -> ArchiveInlineContent { + try Task.checkCancellation() + if format == "image" { return try ArchiveInlineContent.loadImage(at: url, number: number) } + return try ArchiveInlineContent.loadText(at: url) + } +} + +enum ArchiveInlineContent: Sendable { + case image(CGImage) + case text(String) + case worksheet(String) + + /// Decode away from the main actor. Some original diagrams are over 260 megapixels. + static func loadImage(at url: URL, number: Int = 1) throws -> Self { + let options = [kCGImageSourceShouldCache: false] as CFDictionary + guard number > 0, let source = CGImageSourceCreateWithURL(url as CFURL, options), + let type = CGImageSourceGetType(source) as String?, + [UTType.jpeg, .png, .gif, .tiff, .bmp, .webP].contains(where: { $0.identifier == type }) else { + throw PreviewError.image + } + if let image = thumbnail(source, index: number - 1) { return .image(image) } + if type == UTType.tiff.identifier, number == 1, + let corrected = tiffWithoutDuplicatePalette(at: url), let image = thumbnail(corrected, index: 0) { + return .image(image) + } + throw PreviewError.image + } + + private static func thumbnail(_ source: CGImageSource, index: Int) -> CGImage? { + let options = [kCGImageSourceShouldCache: false] as CFDictionary + guard index < CGImageSourceGetCount(source), + let properties = CGImageSourceCopyPropertiesAtIndex(source, index, options) as? [CFString: Any], + let width = properties[kCGImagePropertyPixelWidth] as? Int, width > 0, + let height = properties[kCGImagePropertyPixelHeight] as? Int, height > 0 else { + return nil + } + + // Bound the decoded bitmap to 16 megapixels, retaining aspect and EXIF orientation. + let ratio = min(1, sqrt(16_000_000 / (Double(width) * Double(height)))) + let longest = max(1, Int((Double(max(width, height)) * ratio).rounded(.down))) + let thumbnailOptions: [CFString: Any] = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: longest, + kCGImageSourceShouldCacheImmediately: true + ] + return CGImageSourceCreateThumbnailAtIndex(source, index, thumbnailOptions as CFDictionary) + } + + /// The Glenside IDE schematic has two ColorMap tags in its classic TIFF directory. + /// Keep the first palette, as libtiff does, in a bounded in-memory copy for ImageIO. + private static func tiffWithoutDuplicatePalette(at url: URL) -> CGImageSource? { + let limit = 8 * 1024 * 1024 + guard let size = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize, size <= limit, + var bytes = try? Data(contentsOf: url), bytes.count >= 8, bytes.count <= limit else { return nil } + let littleEndian = bytes.starts(with: [0x49, 0x49, 42, 0]) + guard littleEndian || bytes.starts(with: [0x4d, 0x4d, 0, 42]) else { return nil } + func integer(at start: Int, count: Int) -> Int { + (0..= 8, directory + 2 <= bytes.count else { return nil } + let count = integer(at: directory, count: 2) + let first = directory + 2 + let end = first + count * 12 + guard count >= 2, end + 4 <= bytes.count else { return nil } + for entry in stride(from: first + 12, to: end, by: 12) { + guard integer(at: entry - 12, count: 2) == 320, integer(at: entry, count: 2) == 320 else { continue } + let values = integer(at: entry + 4, count: 4) + guard (6...(3 * 65_536)).contains(values), values.isMultiple(of: 3), + (values / 3).nonzeroBitCount == 1, + [entry - 12, entry].allSatisfy({ tag in + let palette = integer(at: tag + 8, count: 4) + return integer(at: tag + 2, count: 2) == 3 && integer(at: tag + 4, count: 4) == values + && palette >= 8 && palette + 2 * values <= bytes.count + }) else { return nil } + // Slide just the remaining directory entries and the next-directory pointer. + // Strip offsets and all data elsewhere in the file retain their positions. + let rest = bytes[(entry + 12)..<(end + 4)] + bytes.replaceSubrange(entry..<(entry + rest.count), with: rest) + bytes[directory + (littleEndian ? 0 : 1)] = UInt8(truncatingIfNeeded: count - 1) + bytes[directory + (littleEndian ? 1 : 0)] = UInt8((count - 1) >> 8) + return CGImageSourceCreateWithData(bytes as CFData, nil) + } + return nil + } + + static func loadText(at url: URL) throws -> Self { + let limit = 8 * 1024 * 1024 + guard let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize, size <= limit else { throw PreviewError.text } + let data = try Data(contentsOf: url, options: .mappedIfSafe) + guard data.count <= limit else { throw PreviewError.text } + // A number of the Archive's floppy-era text files have NUL/EOF sector padding. + let text: String? + if data.starts(with: [0xff, 0xfe]) || data.starts(with: [0xfe, 0xff]) { + text = String(data: data, encoding: .utf16) + } else { + var end = data.endIndex + while end > data.startIndex { + let last = data[end - 1] + guard last == 0 || last == 0x1a || last == 0xff else { break } + end -= 1 + } + if !data[end...].contains(0) && !data[end...].contains(0x1a) { end = data.endIndex } + let bytes = data[..= 5).accessibilityLabel("Zoom in") + Spacer() + }.padding(6) + Divider() + GeometryReader { geometry in + let width = CGFloat(image.width), height = CGFloat(image.height) + let fit = min(1, min(geometry.size.width / width, geometry.size.height / height)) + let scale = fit * pow(2.0, CGFloat(zoom)) + ScrollView([.horizontal, .vertical]) { + Image(image, scale: 1, label: Text(title)) + .resizable() + .frame(width: width * scale, height: height * scale) + .accessibilityIdentifier("archive-inline-image") + .frame(minWidth: geometry.size.width, minHeight: geometry.size.height) + } + } + } + } +} + +private struct ArchiveInlineText: NSViewRepresentable { + let text: String + let worksheet: Bool + let title: String + + func makeNSView(context: Context) -> NSScrollView { + let scroll = NSTextView.scrollableTextView() + guard let view = scroll.documentView as? NSTextView else { return scroll } + view.isEditable = false + view.isSelectable = true + view.isRichText = false + view.usesFindBar = true + view.isIncrementalSearchingEnabled = true + view.textContainerInset = NSSize(width: 12, height: 10) + view.font = .monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular) + view.textColor = .textColor + view.backgroundColor = .textBackgroundColor + view.setAccessibilityIdentifier("archive-inline-text") + return scroll + } + + func updateNSView(_ scroll: NSScrollView, context: Context) { + guard let view = scroll.documentView as? NSTextView else { return } + view.setAccessibilityLabel(title) + guard view.string != text else { return } + view.string = text + scroll.hasHorizontalScroller = worksheet + view.isHorizontallyResizable = worksheet + view.textContainer?.widthTracksTextView = !worksheet + if worksheet, let font = view.font { + // The indexed worksheet starts each row with its original row number. Align + // columns for reading while keeping the original tabs in a copied selection. + var widths: [CGFloat] = [] + for row in text.split(separator: "\n") { + for (index, cell) in row.components(separatedBy: "\t").enumerated() { + if index == widths.count { widths.append(0) } + widths[index] = max(widths[index], (cell as NSString).size(withAttributes: [.font: font]).width) + } + } + var location: CGFloat = 0 + let style = NSMutableParagraphStyle() + style.lineBreakMode = .byClipping + style.tabStops = widths.map { width in + location += ceil(width) + 18 + return NSTextTab(textAlignment: .left, location: location) + } + let width = location + 2 * (view.textContainerInset.width + 6) + view.textContainer?.containerSize = NSSize(width: width, height: CGFloat.greatestFiniteMagnitude) + view.setFrameSize(NSSize(width: max(scroll.contentSize.width, width), height: view.frame.height)) + view.textStorage?.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: (text as NSString).length)) + } + view.setSelectedRange(NSRange(location: 0, length: 0)) + scroll.contentView.scroll(to: .zero) + scroll.reflectScrolledClipView(scroll.contentView) + } +} diff --git a/platforms/macos/App/ArchiveLibraryCatalog.swift b/platforms/macos/App/ArchiveLibraryCatalog.swift new file mode 100644 index 0000000..327e269 --- /dev/null +++ b/platforms/macos/App/ArchiveLibraryCatalog.swift @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import CryptoKit +import Foundation + +struct ArchiveMemberRange: Hashable, Sendable { + let offset, compressedBytes: Int64 + let method: Int + let archiveBytes: Int64 +} + +struct ArchiveReaderSection: Sendable { + let number: Int + let label: String? + let text: String +} + +struct ArchiveDocument: Identifiable, Hashable, Sendable { + let id: String + let title: String + let collection: String + let sourceURL: URL + let memberPath: String? + let pageCount: Int? + let deliveryURL: URL? + let deliveryBytes: Int64? + var format: String = "pdf" + var sourceBytes: Int64? + var memberRange: ArchiveMemberRange? + var deliverySHA256: String? { deliveryURL == nil ? nil : id } + var citation: String { cite(nil, at: sourceURL) } + + func cite(_ locator: String?, at url: URL) -> String { + ([title, memberPath, locator, "Color Computer Archive", url.absoluteString] as [String?]) + .compactMap { $0 }.joined(separator: " · ") + } +} + +struct ArchiveHit: Identifiable, Hashable, Sendable { + let id: String + let document: ArchiveDocument + let page: Int? + let locator: String + let ocr: Bool + let sourceURL: URL + var locationNumber: Int = 1 + var citation: String { document.cite(locator, at: sourceURL) } +} + +struct ArchiveExample: Identifiable, Hashable, Sendable { + let title: String + let kind: String + let language: String + let author: String + let provenance: String + let source: String + let sourceSHA256: String + var id: String { sourceSHA256 } +} + +enum ArchiveLibraryError: LocalizedError { + case missing, incompatible, input(String), damaged + var errorDescription: String? { + switch self { + case .missing: return "This build has no Archive search index. Install a build with the index or prepare it using the knowledge tools before rebuilding." + case .incompatible: return "This Archive index belongs to a different database or version. Rebuild with a compatible Archive Library index." + case .input(let message): return message + case .damaged: return "The Archive index could not be read. Replace it with a verified copy and rebuild the app." + } + } +} + +/// Native and MCP clients use one serialized read-only connection. SQLite periodically +/// checks the current task for cancellation, including while ranking a common term. +actor ArchiveLibraryCatalog { + static let shared = ArchiveLibraryCatalog(url: Bundle.main.url(forResource: "ArchiveLibrary", withExtension: "sqlite", subdirectory: "ArchiveLibrary")) + private let url: URL? + private var connection: LibrarySQLite? + private var hasReaderSections = false + + init(url: URL?) { self.url = url } + + private func database() throws -> LibrarySQLite { + try Task.checkCancellation() + if let connection { return connection } + guard let url, url.isFileURL, FileManager.default.fileExists(atPath: url.path) else { throw ArchiveLibraryError.missing } + let db = try LibrarySQLite(url: url, cancellable: true, describeError: { _ in ArchiveLibraryError.damaged }) + try db.execute("PRAGMA trusted_schema=OFF") + try db.execute("PRAGMA query_only=ON") + guard try db.rows("PRAGMA application_id").first?["application_id"] == String(0x56434341), + let version = try db.rows("PRAGMA user_version").first?["user_version"], + ["1", "2"].contains(version) else { throw ArchiveLibraryError.incompatible } + hasReaderSections = version == "2" + connection = db + return db + } + + func collections() throws -> [String] { + try database().rows(""" + SELECT collection FROM document + UNION SELECT collection || '/' || issue_year AS collection FROM document + WHERE issue_year IS NOT NULL AND substr(collection,-5) != '/' || issue_year + ORDER BY collection COLLATE NOCASE,collection + """) + .compactMap { $0["collection"] } + } + + private func scope(_ collection: String?) throws -> (sql: String, values: [String]) { + guard let collection, !collection.isEmpty else { return ("", []) } + guard collection.utf8.count <= 2048, !collection.contains("\0") else { throw ArchiveLibraryError.input("Invalid Archive collection.") } + return (" AND (d.collection=? OR instr(d.collection, ? || '/')=1 OR d.collection || '/' || d.issue_year=?)", [collection, collection, collection]) + } + + private func bounds(_ limit: Int, _ offset: Int) throws -> [String] { + guard (1...50).contains(limit), (0...250_000).contains(offset) else { throw ArchiveLibraryError.input("Archive pages allow 1–50 results and offsets up to 250,000.") } + return [String(limit), String(offset)] + } + + func browse(collection: String?, limit: Int, offset: Int) throws -> [ArchiveDocument] { + let filter = try scope(collection) + let values = try filter.values + bounds(limit, offset) + let rows = try database().rows(""" + SELECT d.* FROM document d WHERE 1=1 \(filter.sql) + ORDER BY d.title COLLATE NOCASE,d.sha256 LIMIT ? OFFSET ? + """, values) + return try rows.map(document) + } + + private static let compounds = ["module directory", "width 80", "width 40", "disk basic", "extended basic"] + + private func match(_ query: String) throws -> String { + guard query.count <= 256, !query.contains("\0") else { throw ArchiveLibraryError.input("Use at most 256 characters for an Archive search.") } + let words = query.lowercased().split { !$0.isLetter && !$0.isNumber }.map(String.init) + guard !words.isEmpty, words.count <= 16 else { throw ArchiveLibraryError.input("Enter between one and sixteen words or numbers.") } + let required = words.map { "\"\($0)\"" }.joined(separator: " AND ") + let pairs = Set(zip(words, words.dropFirst()).map { $0 + " " + $1 }) + let boosts = Self.compounds.filter(pairs.contains).map { "\"vccphrase\($0.replacingOccurrences(of: " ", with: ""))\"" } + guard !boosts.isEmpty else { return required } + return "(\(required)) OR ((\(required)) AND (\(boosts.joined(separator: " OR "))))" + } + + func search(query: String, collection: String?, limit: Int, offset: Int) throws -> [ArchiveHit] { + let expression = try match(query) + let filter = try scope(collection) + let values = try [expression] + filter.values + bounds(limit, offset) + let rows = try database().rows(""" + SELECT d.*,p.page_number,p.page_label,p.locator_kind,p.is_ocr + FROM page_terms JOIN page p ON p.id=page_terms.rowid JOIN document d ON d.id=p.document_id + WHERE page_terms MATCH ? \(filter.sql) + ORDER BY bm25(page_terms,1.0,4.0),p.id LIMIT ? OFFSET ? + """, values) + return try rows.map(hit) + } + + func citation(id: String) throws -> ArchiveHit? { + let fields = id.components(separatedBy: ":") + guard fields.count == 4, fields[0] == "sha256", Self.isSHA(fields[1]), + let n = Int32(fields[3]), n > 0, String(n) == fields[3] else { return nil } + let rows = try database().rows(""" + SELECT d.*,p.page_number,p.page_label,p.locator_kind,p.is_ocr + FROM document d JOIN page p ON p.document_id=d.id + WHERE d.sha256=? AND p.locator_kind=? AND p.page_number=? + """, Array(fields[1...3])) + return try rows.first.map(hit) + } + + private static func isSHA(_ value: String) -> Bool { + value.utf8.count == 64 && value.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) } + } + + private func document(_ row: [String: String]) throws -> ArchiveDocument { + guard let sha = row["sha256"], Self.isSHA(sha), let title = row["title"], let collection = row["collection"], + let link = row["source_url"].flatMap(URL.init(string:)), link.scheme == "https", + link.host == "colorcomputerarchive.com", link.path.hasPrefix("/repo/Documents/"), + link.user == nil, link.password == nil, link.port == nil else { throw ArchiveLibraryError.damaged } + let delivery = row["delivery_url"].flatMap(URL.init(string:)) + var memberRange: ArchiveMemberRange? + if let offset = row["member_offset"].flatMap(Int64.init), + let compressed = row["member_compressed_bytes"].flatMap(Int64.init), + let method = row["member_method"].flatMap(Int.init), + let bytes = row["archive_bytes"].flatMap(Int64.init) { + memberRange = ArchiveMemberRange(offset: offset, compressedBytes: compressed, method: method, archiveBytes: bytes) + } + return ArchiveDocument(id: sha, title: title, collection: collection, sourceURL: link, + memberPath: row["member_path"], pageCount: row["page_count"].flatMap(Int.init), + deliveryURL: delivery, deliveryBytes: delivery == nil ? nil : row["byte_size"].flatMap(Int64.init), + format: row["format"] ?? "pdf", sourceBytes: row["byte_size"].flatMap(Int64.init), memberRange: memberRange) + } + + private func hit(_ row: [String: String]) throws -> ArchiveHit { + let doc = try document(row) + guard let kind = row["locator_kind"], let number = row["page_number"].flatMap(Int.init), number > 0 else { throw ArchiveLibraryError.damaged } + let label = row["page_label"].flatMap { $0.isEmpty ? nil : $0 } + let locator: String + var source = doc.sourceURL + switch kind { + case "pdf_page": + if let label, label != String(number) { + locator = "PDF page \(number) (label \(label))" + } else { + locator = "PDF page \(number)" + } + if doc.memberPath == nil, var parts = URLComponents(url: source, resolvingAgainstBaseURL: false) { + parts.fragment = "page=\(number)" + if let link = parts.url { source = link } + } + case "worksheet": locator = label ?? "Worksheet \(number)" + case "section": locator = label ?? "Section \(number)" + case "image": locator = label ?? "Image \(number)" + default: throw ArchiveLibraryError.damaged + } + return ArchiveHit(id: "sha256:\(doc.id):\(kind):\(number)", document: doc, + page: kind == "pdf_page" ? number : nil, locator: locator, + ocr: row["is_ocr"] == "1", sourceURL: source, locationNumber: number) + } + + func readerSection(documentID: String, number: Int) throws -> ArchiveReaderSection? { + guard Self.isSHA(documentID), number > 0 else { return nil } + let db = try database() + guard hasReaderSections else { return nil } + let rows = try db.rows(""" + SELECT p.page_label,s.text FROM document d JOIN page p ON p.document_id=d.id + JOIN reader_section s ON s.page_id=p.id WHERE d.sha256=? AND p.page_number=? + """, [documentID, String(number)]) + guard let row = rows.first, let text = row["text"] else { return nil } + return ArchiveReaderSection(number: number, label: row["page_label"], text: text) + } + + func examples(documentID: String, page: Int) throws -> [ArchiveExample] { + guard Self.isSHA(documentID), page > 0 else { return [] } + let rows = try database().rows(""" + SELECT * FROM reviewed_example WHERE original_sha256=? AND ? BETWEEN first_page AND last_page + ORDER BY title,source_sha256 + """, [documentID, String(page)]) + return try rows.map(reviewedExample) + } + + func basicExample(sourceSHA256: String) throws -> ArchiveExample? { + guard Self.isSHA(sourceSHA256) else { return nil } + let rows = try database().rows("SELECT * FROM reviewed_example WHERE source_sha256=? AND kind='basic_program' LIMIT 1", [sourceSHA256]) + return try rows.first.map(reviewedExample) + } + + private func reviewedExample(_ row: [String: String]) throws -> ArchiveExample { + guard let title = row["title"], let kind = row["kind"], let language = row["language"], + let author = row["author"], let provenance = row["provenance"], let source = row["source"], + let sha = row["source_sha256"], + SHA256.hash(data: Data(source.utf8)).map({ String(format: "%02x", $0) }).joined() == sha else { + throw ArchiveLibraryError.damaged + } + return ArchiveExample(title: title, kind: kind, language: language, author: author, + provenance: provenance, source: source, sourceSHA256: sha) + } +} diff --git a/platforms/macos/App/ArchiveLibraryReader.swift b/platforms/macos/App/ArchiveLibraryReader.swift new file mode 100644 index 0000000..fead9a8 --- /dev/null +++ b/platforms/macos/App/ArchiveLibraryReader.swift @@ -0,0 +1,627 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import PDFKit +import Compression + +struct ArchiveAssetReceipt: Sendable { + let url: URL + let sha256: String + let bytes: Int64 + let fileExtension: String + let memberRange: ArchiveMemberRange? + + init?(document: ArchiveDocument) { + let sha = document.id + guard sha.utf8.count == 64, sha.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }) else { return nil } + if document.format == "pdf" { + guard let url = document.deliveryURL, let bytes = document.deliveryBytes, + bytes > 0, bytes <= 4 * 1024 * 1024 * 1024, Self.acceptsPDF(url) else { return nil } + self.url = url + self.bytes = bytes + fileExtension = "pdf" + memberRange = nil + } else { + guard let bytes = document.sourceBytes, bytes > 0, bytes <= 128 * 1024 * 1024, + Self.acceptsSource(document.sourceURL) else { return nil } + let ext: String + if let member = document.memberPath { + guard let range = document.memberRange, (0...1_073_741_824).contains(range.archiveBytes), + range.offset >= 0, range.compressedBytes > 0, range.compressedBytes <= range.archiveBytes, + range.offset <= range.archiveBytes - range.compressedBytes, + range.method == 8 || (range.method == 0 && range.compressedBytes == bytes), + document.sourceURL.pathExtension.lowercased() == "zip" else { return nil } + ext = (member as NSString).pathExtension.lowercased() + memberRange = range + } else { + ext = document.sourceURL.pathExtension.lowercased() + memberRange = nil + } + switch document.format { + case "image" where ["jpg","jpeg","gif","png","tif","tiff"].contains(ext): break + case "text" where ["txt","bas"].contains(ext): break + default: return nil + } + url = document.sourceURL + self.bytes = bytes + fileExtension = ext + } + sha256 = sha + } + + private static func acceptsPDF(_ url: URL) -> Bool { + SoftwareLibraryInstaller.acceptsDownloadURL(url) && url.path.hasPrefix("/dl/software/CoCoLibrary/Documents/") + && url.pathExtension.lowercased() == "pdf" + } + + private static func acceptsSource(_ url: URL) -> Bool { + url.scheme == "https" && url.host == "colorcomputerarchive.com" && url.user == nil && url.password == nil + && (url.port == nil || url.port == 443) && url.query == nil && url.fragment == nil + && url.path.hasPrefix("/repo/Documents/") && !url.pathComponents.contains("..") && !url.pathComponents.contains(".") + && !url.path.contains("\\") && !url.path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + } + + func acceptsResponseURL(_ url: URL) -> Bool { + fileExtension == "pdf" ? Self.acceptsPDF(url) : Self.acceptsSource(url) + } + + var rangeHeader: String? { + memberRange.map { "bytes=\($0.offset)-\($0.offset + $0.compressedBytes - 1)" } + } + + /// Servers may return the complete ZIP instead of honoring a byte-range request. + func responseSize(_ response: HTTPURLResponse) -> Int64? { + guard let final = response.url, acceptsResponseURL(final) else { return nil } + guard let range = memberRange else { return response.statusCode == 200 ? bytes : nil } + if response.statusCode == 200 { return range.archiveBytes } + let header = "bytes \(range.offset)-\(range.offset + range.compressedBytes - 1)/\(range.archiveBytes)" + return response.statusCode == 206 && response.value(forHTTPHeaderField: "Content-Range") == header ? range.compressedBytes : nil + } +} + +private enum ArchiveReaderError: LocalizedError { + case changed, unavailable, location, space, download, page + var errorDescription: String? { + switch self { + case .changed: return "The downloaded file does not match the edition in the Archive index." + case .unavailable: return "This edition is available at the Archive source." + case .location: return "The Archive file could not be cached. Check the free space and permissions." + case .space: return "There is not enough free space to cache this Archive file." + case .download: return "The Archive file could not be downloaded. Check your connection and try again." + case .page: return "This PDF could not be opened at the cited page. Use the Archive source to inspect the original." + } + } +} + +enum ArchiveReadProgress: Sendable { + case checking, downloading(Int64, Int64), verifying +} + +actor ArchiveAssetCache { + #if VCC_UI_TESTING + static let shared: ArchiveAssetCache = { + let directory = ProcessInfo.processInfo.environment["VCC_ARCHIVE_TEST_CACHE"].map { URL(fileURLWithPath: $0, isDirectory: true) } + ?? FileManager.default.temporaryDirectory.appendingPathComponent("VCCArchiveUITest-" + UUID().uuidString, isDirectory: true) + return ArchiveAssetCache(directory: directory) + }() + #else + static let shared = ArchiveAssetCache() + #endif + private let directory: URL? + private let configuration: URLSessionConfiguration + + init(directory: URL? = nil, configuration: URLSessionConfiguration? = nil) { + self.directory = directory + if let configuration { + self.configuration = configuration + } else { + let config = URLSessionConfiguration.ephemeral + config.timeoutIntervalForRequest = 45 + config.timeoutIntervalForResource = 3600 + config.urlCache = nil + self.configuration = config + } + } + + func localCopy(_ receipt: ArchiveAssetReceipt, progress: @escaping @Sendable (ArchiveReadProgress) -> Void) async throws -> URL { + try Task.checkCancellation() + let fm = FileManager.default + let directory = self.directory ?? AppIdentity.supportDirectory.appendingPathComponent( + receipt.fileExtension == "pdf" ? "ArchiveLibrary/PDFs" : "ArchiveLibrary/Assets", isDirectory: true) + try fm.createDirectory(at: directory, withIntermediateDirectories: true) + let info = try directory.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) + guard info.isDirectory == true, info.isSymbolicLink != true else { throw ArchiveReaderError.location } + let target = directory.appendingPathComponent(receipt.sha256 + "." + receipt.fileExtension) + progress(.checking) + if let attributes = try? fm.attributesOfItem(atPath: target.path) { + guard attributes[.type] as? FileAttributeType == .typeRegular else { throw ArchiveReaderError.location } + if (attributes[.size] as? NSNumber)?.int64Value == receipt.bytes, + try SoftwareLibraryManualCache.fingerprint(target) == receipt.sha256 { return target } + } + let transferBytes = receipt.memberRange?.compressedBytes ?? receipt.bytes + let disk = try fm.attributesOfFileSystem(forPath: directory.path) + let free = (disk[.systemFreeSize] as? NSNumber)?.int64Value + let reserved: Int64 = 32 * 1024 * 1024 + (receipt.memberRange == nil ? 0 : receipt.bytes) + if let free, free < transferBytes + reserved { throw ArchiveReaderError.space } + var request = URLRequest(url: receipt.url) + request.setValue("VCCPlus/ArchiveLibrary", forHTTPHeaderField: "User-Agent") + request.setValue("identity", forHTTPHeaderField: "Accept-Encoding") + request.setValue(receipt.rangeHeader, forHTTPHeaderField: "Range") + let temporary = directory.appendingPathComponent(UUID().uuidString + ".download") + defer { try? fm.removeItem(at: temporary) } + let observer = ArchiveAssetTransfer(receipt: receipt, available: free.map { $0 - reserved }, destination: temporary, progress: progress) + progress(.downloading(0, transferBytes)) + let http = try await observer.download(request, configuration: configuration) + try Task.checkCancellation() + progress(.verifying) + // Only atomically replace the cached edition after its final bytes have been verified. + let staged = directory.appendingPathComponent(UUID().uuidString + ".partial") + defer { try? fm.removeItem(at: staged) } + if let range = receipt.memberRange { + try Self.unpack(range, from: temporary, offset: http.statusCode == 206 ? 0 : range.offset, to: staged, bytes: receipt.bytes) + } else { + try fm.moveItem(at: temporary, to: staged) + } + guard try SoftwareLibraryManualCache.fingerprint(staged) == receipt.sha256 else { throw ArchiveReaderError.changed } + try Task.checkCancellation() + if fm.fileExists(atPath: target.path) { + guard try fm.attributesOfItem(atPath: target.path)[.type] as? FileAttributeType == .typeRegular else { throw ArchiveReaderError.location } + _ = try fm.replaceItemAt(target, withItemAt: staged) + } else { try fm.moveItem(at: staged, to: target) } + return target + } + + /// No archive paths become local filenames. Decode only the indexed member body + /// and cap both compressed input and output, including the full-ZIP HTTP 200 path. + private static func unpack(_ range: ArchiveMemberRange, from source: URL, offset: Int64, to output: URL, bytes: Int64) throws { + let input = try FileHandle(forReadingFrom: source) + defer { try? input.close() } + try input.seek(toOffset: UInt64(offset)) + try Data().write(to: output, options: .withoutOverwriting) + let writer = try FileHandle(forWritingTo: output) + defer { try? writer.close() } + var written: Int64 = 0 + func write(_ chunk: Data?) throws { + try Task.checkCancellation() + guard let chunk else { return } + written += Int64(chunk.count) + guard written <= bytes else { throw ArchiveReaderError.changed } + try writer.write(contentsOf: chunk) + } + let decoder = range.method == 8 ? try OutputFilter(.decompress, using: .zlib, writingTo: write) : nil + var remaining = range.compressedBytes + while remaining > 0 { + try Task.checkCancellation() + guard let chunk = try input.read(upToCount: Int(min(remaining, 65536))), !chunk.isEmpty else { throw ArchiveReaderError.changed } + remaining -= Int64(chunk.count) + if let decoder { try decoder.write(chunk) } else { try write(chunk) } + } + try decoder?.finalize() + guard written == bytes else { throw ArchiveReaderError.changed } + } +} + +private final class ArchiveAssetTransfer: NSObject, URLSessionDownloadDelegate, @unchecked Sendable { + private let receipt: ArchiveAssetReceipt + private let available: Int64? + private let destination: URL + private let progress: @Sendable (ArchiveReadProgress) -> Void + private let lock = NSLock() // Synchronizes task registration, cancellation, and completion. + private var continuation: CheckedContinuation? + // Foundation invokes the callbacks below on this session's serial delegate queue. + private var rejection: ArchiveReaderError? + private var lastReport: UInt64 = 0 + private var response: HTTPURLResponse? + + init(receipt: ArchiveAssetReceipt, available: Int64?, destination: URL, progress: @escaping @Sendable (ArchiveReadProgress) -> Void) { + self.receipt = receipt + self.available = available + self.destination = destination + self.progress = progress + } + + func download(_ request: URLRequest, configuration: URLSessionConfiguration) async throws -> HTTPURLResponse { + // The async download(for:) helper does not forward incremental download + // callbacks. An explicit delegate task also lets us enforce the byte cap in flight. + let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) + defer { session.invalidateAndCancel() } + let task = session.downloadTask(with: request) + let result = try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (reply: CheckedContinuation) in + lock.withLock { + guard !Task.isCancelled else { reply.resume(throwing: CancellationError()); return } + continuation = reply + task.resume() + } + } + } onCancel: { + if self.lock.withLock({ self.continuation != nil }) { task.cancel() } + } + try Task.checkCancellation() + return result + } + + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { + guard let url = request.url, receipt.acceptsResponseURL(url) else { completionHandler(nil); return } + var redirected = request + redirected.setValue(receipt.rangeHeader, forHTTPHeaderField: "Range") + redirected.setValue("identity", forHTTPHeaderField: "Accept-Encoding") + completionHandler(redirected) + } + + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + guard rejection == nil, let http = downloadTask.response as? HTTPURLResponse, let expected = receipt.responseSize(http) else { + rejection = rejection ?? .download + return + } + guard available.map({ expected <= $0 }) ?? true else { rejection = .space; return } + do { + guard (try location.resourceValues(forKeys: [.fileSizeKey]).fileSize).map(Int64.init) == expected else { + rejection = .changed + return + } + // Foundation removes its temporary file when this delegate method returns. + try FileManager.default.moveItem(at: location, to: destination) + response = http + } catch { rejection = .location } + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + let reply = lock.withLock { + let reply = continuation + continuation = nil + return reply + } + if let rejection { reply?.resume(throwing: rejection) } + else if (error as? URLError)?.code == .cancelled { reply?.resume(throwing: CancellationError()) } + else if error == nil, let response { reply?.resume(returning: response) } + else { reply?.resume(throwing: ArchiveReaderError.download) } + } + + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + guard let response = downloadTask.response as? HTTPURLResponse, let expected = receipt.responseSize(response) else { + rejection = .download + downloadTask.cancel() + return + } + guard totalBytesWritten <= expected, totalBytesExpectedToWrite <= expected else { + rejection = .changed + downloadTask.cancel() + return + } + if let available, expected > available { + rejection = .space + downloadTask.cancel() + return + } + let now = DispatchTime.now().uptimeNanoseconds + guard lastReport == 0 || now - lastReport >= 120_000_000 || totalBytesWritten == expected else { return } + lastReport = now + progress(.downloading(totalBytesWritten, expected)) + } +} + +@MainActor +final class ArchiveReaderModel: ObservableObject { + let view = PDFView() + @Published private(set) var referenceID: String? + @Published private(set) var document: PDFDocument? + @Published private(set) var preview: ArchiveInlineContent? + @Published private(set) var sectionLabel: String? + @Published private(set) var cancelled = false + @Published private(set) var progress: ArchiveReadProgress? + @Published private(set) var error: String? + @Published private(set) var page = 1 + @Published var find = "" { didSet { if find != oldValue { resetFind() } } } + @Published private(set) var findMessage: String? + @Published private(set) var isFinding = false + private var request: Task? + private var findTask: Task? + private var findRequestID = UUID() + private var requestID = UUID() + private var localURL: URL? + private var lastMatch: (page: Int, range: NSRange)? + private var pendingPage = 1 + let remembersPage: Bool + private let cache: ArchiveAssetCache + private let catalog: ArchiveLibraryCatalog + + init(remembersPage: Bool, cache: ArchiveAssetCache = .shared, catalog: ArchiveLibraryCatalog = .shared) { + self.remembersPage = remembersPage + self.cache = cache + self.catalog = catalog + view.displayMode = .singlePageContinuous + view.autoScales = true + view.displaysPageBreaks = true + view.setAccessibilityLabel("Archive PDF") + } + func stop() { + requestID = UUID(); request?.cancel(); request = nil; progress = nil + resetFind() + } + func reset() { + stop() + document = nil; view.document = nil; preview = nil; sectionLabel = nil + referenceID = nil; error = nil; localURL = nil; page = 1; find = ""; cancelled = false + } + func cancel() { + stop() + cancelled = true + } + func retry(_ record: ArchiveDocument) { + open(record, page: pendingPage) + } + private func rememberPage() { + if remembersPage, let referenceID { UserDefaults.standard.set(page, forKey: "archive-library.page." + referenceID) } + } + static func savedPage(for id: String) -> Int { max(UserDefaults.standard.integer(forKey: "archive-library.page." + id), 1) } + func updatePage() { + guard let document, let current = view.currentPage, current.document === document else { return } + let index = document.index(for: current) + guard index >= 0, index < document.pageCount else { return } + page = index + 1 + rememberPage() + } + func go(to number: Int) { + guard let document, number > 0, number <= document.pageCount, let target = document.page(at: number - 1) else { return } + view.go(to: target); updatePage() + } + func open(_ record: ArchiveDocument, page number: Int) { + if referenceID == record.id { + if document != nil { go(to: number); return } + if preview != nil && page == number { return } + if progress != nil && (record.format == "pdf" || number == pendingPage) { + pendingPage = number + return + } + } + reset() + referenceID = record.id + pendingPage = number + let identity = requestID + progress = .checking + request = Task { + do { + switch record.format { + case "pdf", "image", "text": + guard let receipt = ArchiveAssetReceipt(document: record) else { throw ArchiveReaderError.unavailable } + let url = try await cache.localCopy(receipt) { event in + Task { @MainActor in + guard self.requestID == identity, self.progress != nil else { return } + self.progress = event + } + } + try Task.checkCancellation() + if record.format == "pdf" { + let parsed = await Task.detached(priority: .userInitiated) { PDFDocument(url: url) }.value + try Task.checkCancellation() + let target = pendingPage + guard let parsed, !parsed.isLocked, target > 0, target <= parsed.pageCount else { throw ArchiveReaderError.page } + localURL = url; document = parsed; view.document = parsed; view.autoScales = true; go(to: target) + } else { + let content = try await ArchivePreviewDecoder.shared.read(url, format: record.format, number: number) + try Task.checkCancellation() + page = number; preview = content; rememberPage() + } + default: + guard let section = try await catalog.readerSection(documentID: record.id, number: number) else { + throw ArchiveReaderError.unavailable + } + try Task.checkCancellation() + page = section.number; sectionLabel = section.label + preview = record.format == "office-xls" ? .worksheet(section.text) : .text(section.text) + rememberPage() + } + progress = nil + } catch { + guard requestID == identity else { return } + progress = nil + if !Task.isCancelled { self.error = error.localizedDescription } + } + } + } + private func resetFind() { + findRequestID = UUID(); findTask?.cancel(); findTask = nil; isFinding = false; findMessage = nil; lastMatch = nil + } + func findNext() { + guard let localURL, let document, !isFinding, !find.isEmpty else { return } + let text = find, current = page + let start = lastMatch.flatMap { $0.page == page ? NSMaxRange($0.range) : nil } ?? 0 + let identity = UUID(); findRequestID = identity; isFinding = true; findMessage = nil + findTask = Task { + let result = await Self.nextMatch(in: localURL, text: text, page: current, start: start) + guard !Task.isCancelled, findRequestID == identity, self.document === document else { return } + isFinding = false + guard let (number, range) = result, let target = document.page(at: number - 1), let selection = target.selection(for: range) else { + findMessage = "No matching text in the PDF’s text layer."; return + } + view.setCurrentSelection(selection, animate: false); view.go(to: selection); updatePage(); lastMatch = (number, range) + } + } + private nonisolated static func nextMatch(in url: URL, text: String, page: Int, start: Int) async -> (Int, NSRange)? { + guard let doc = PDFDocument(url: url), doc.pageCount > 0, page > 0, page <= doc.pageCount else { return nil } + for offset in 0...doc.pageCount { + if Task.isCancelled { return nil } + let index = (page - 1 + offset) % doc.pageCount + let match: NSRange? = autoreleasepool { + guard let raw = doc.page(at: index)?.string as NSString? else { return nil } + let lower = offset == 0 ? min(start, raw.length) : 0 + let upper = offset == doc.pageCount ? min(start, raw.length) : raw.length + let range = raw.range(of: text, options: [.caseInsensitive], range: NSRange(location: lower, length: upper - lower)) + return range.location == NSNotFound ? nil : range + } + if let match { return (index + 1, match) } + } + return nil + } +} + +private struct ArchivePDFSurface: NSViewRepresentable { + let view: PDFView + func makeNSView(context: Context) -> PDFView { view } + func updateNSView(_ nsView: PDFView, context: Context) {} +} + +struct ArchiveReaderPane: View { + let record: ArchiveDocument + let hit: ArchiveHit? + @ObservedObject var reader: ArchiveReaderModel + let requestedPage: Int + let catalog: ArchiveLibraryCatalog + @Environment(\.openWindow) private var openWindow + @State private var examples: [ArchiveExample] = [] + @State private var exampleError: String? + @State private var loadedExampleKey: String? + @State private var copies: String? + @State private var pageField = "1" + @FocusState private var findFocused: Bool + + private var isCurrent: Bool { reader.referenceID == record.id } + private var loaded: Bool { isCurrent && reader.document != nil } + private var visiblePage: Int? { + guard record.format == "pdf" else { return nil } + return loaded ? reader.page : (hit?.page ?? requestedPage) + } + private var exampleKey: String { record.id + "/" + String(visiblePage ?? 0) } + private var atHit: Bool { + guard let hit else { return false } + if loaded || (isCurrent && reader.preview != nil) { return hit.locationNumber == reader.page } + return true + } + private var source: URL { + if atHit, let hit { return hit.sourceURL } + guard record.memberPath == nil, record.sourceURL.pathExtension.lowercased() == "pdf", let visiblePage, + var parts = URLComponents(url: record.sourceURL, resolvingAgainstBaseURL: false) else { return record.sourceURL } + parts.fragment = "page=\(visiblePage)"; return parts.url ?? record.sourceURL + } + private var citation: String { + if atHit, let hit { return hit.citation } + return record.cite(visiblePage.map { "PDF page \($0)" } ?? (isCurrent ? reader.sectionLabel : nil), at: source) + } + var body: some View { + VStack(alignment: .leading, spacing: 0) { + VStack(alignment: .leading, spacing: 5) { + Text(record.collection.replacingOccurrences(of: "/", with: " › ")).font(.caption).foregroundStyle(.secondary) + Text(record.title).font(.title3.weight(.semibold)).lineLimit(3).textSelection(.enabled) + if let member = record.memberPath { Text("ZIP member · " + member).font(.caption).textSelection(.enabled) } + if atHit, let hit { Label(hit.locator + (hit.ocr ? " · OCR match" : ""), systemImage: "text.magnifyingglass").font(.caption).foregroundStyle(.secondary) } + if loadedExampleKey == exampleKey, !examples.isEmpty { exampleActions } + if let exampleError { Text(exampleError).font(.caption).foregroundStyle(.secondary) } + }.padding(12) + Divider() + if loaded, let pdf = reader.document { + VStack(spacing: 7) { + HStack { + Button { reader.go(to: reader.page - 1) } label: { Image(systemName: "chevron.left") }.accessibilityLabel("Previous PDF page").disabled(reader.page <= 1) + TextField("Page", text: $pageField).frame(width: 46).accessibilityLabel("PDF page number").onSubmit { + if let n = Int(pageField) { reader.go(to: min(max(n, 1), pdf.pageCount)) }; pageField = String(reader.page) + } + Text("of \(pdf.pageCount)").foregroundStyle(.secondary) + Button { reader.go(to: reader.page + 1) } label: { Image(systemName: "chevron.right") }.accessibilityLabel("Next PDF page").disabled(reader.page >= pdf.pageCount) + Spacer() + Button { reader.view.zoomOut(nil) } label: { Image(systemName: "minus.magnifyingglass") }.accessibilityLabel("Zoom out") + Button { reader.view.zoomIn(nil) } label: { Image(systemName: "plus.magnifyingglass") }.accessibilityLabel("Zoom in") + Button("Fit") { reader.view.autoScales = true }.accessibilityLabel("Fit page") + } + HStack { + Button { findFocused = true } label: { Image(systemName: "magnifyingglass") } + .buttonStyle(.borderless).keyboardShortcut("f").accessibilityLabel("Focus Find in PDF") + TextField("Find in PDF", text: $reader.find).focused($findFocused).onSubmit { reader.findNext() }.accessibilityIdentifier("archive-pdf-find") + if reader.isFinding { ProgressView().controlSize(.small) } + Button("Find Next") { reader.findNext() }.keyboardShortcut("g").disabled(reader.find.isEmpty || reader.isFinding) + } + if let message = reader.findMessage { Text(message).font(.caption).foregroundStyle(.secondary) } + }.padding(8) + ArchivePDFSurface(view: reader.view).id(ObjectIdentifier(reader.view)).accessibilityIdentifier("archive-pdf-surface") + .onReceive(NotificationCenter.default.publisher(for: .PDFViewPageChanged, object: reader.view)) { _ in reader.updatePage() } + } else if isCurrent, let preview = reader.preview { + if let count = record.pageCount, count > 1 { + HStack { + Button { reader.open(record, page: reader.page - 1) } label: { Image(systemName: "chevron.left") } + .accessibilityLabel("Previous section").disabled(reader.page <= 1) + TextField("Section", text: $pageField).frame(width: 44).accessibilityLabel("Section number").onSubmit { + if let n = Int(pageField) { reader.open(record, page: min(max(n, 1), count)) } + pageField = String(reader.page) + } + Text("of \(count)") + Button { reader.open(record, page: reader.page + 1) } label: { Image(systemName: "chevron.right") } + .accessibilityLabel("Next section").disabled(reader.page >= count) + if let label = reader.sectionLabel { Text(label).lineLimit(2).help(label) } + Spacer(minLength: 0) + }.padding(8) + } + ArchiveInlinePreview(content: preview, title: record.title) + .id(record.id + "/" + String(reader.page)) + } else { + VStack(spacing: 12) { + if isCurrent, let progress = reader.progress { + switch progress { + case .checking: ProgressView("Opening document…") + case .verifying: ProgressView("Verifying download…") + case .downloading(let done, let total): + ProgressView(value: Double(done), total: Double(total)) { Text("Downloading…") } + Text(ByteCountFormatter.string(fromByteCount: done, countStyle: .file) + " of " + ByteCountFormatter.string(fromByteCount: total, countStyle: .file)).font(.caption).monospacedDigit() + } + Button("Cancel") { reader.cancel() } + } else if isCurrent, reader.error != nil || reader.cancelled { + Text(reader.error ?? "Loading cancelled.").multilineTextAlignment(.center) + Button("Try Again") { reader.retry(record) } + } else { + ProgressView("Opening document…") + } + }.padding(16).frame(maxWidth: .infinity, maxHeight: .infinity) + } + Divider() + HStack { + VStack(alignment: .leading, spacing: 3) { + Text("Color Computer Archive").font(.caption).foregroundStyle(.secondary) + Link("Archive source", destination: source) + } + Spacer() + if let copies { Text(copies).font(.caption).foregroundStyle(.secondary) } + Button("Copy Citation") { copy(citation, success: "Citation copied") }.accessibilityIdentifier("archive-copy-citation") + }.padding(10) + } + .onChange(of: reader.page, initial: true) { _, value in pageField = String(value) } + .task(id: hit?.id ?? record.id) { + guard !Task.isCancelled else { return } + reader.open(record, page: requestedPage) + } + .task(id: exampleKey) { + examples = []; loadedExampleKey = nil; exampleError = nil; copies = nil + guard let page = visiblePage else { return } + do { + let entries = try await catalog.examples(documentID: record.id, page: page) + try Task.checkCancellation() + examples = entries; loadedExampleKey = exampleKey + } catch { if !Task.isCancelled { exampleError = "Example information could not be read." } } + } + } + @ViewBuilder private var exampleActions: some View { + if let first = examples.first, examples.count == 1 { + HStack { + Button(first.kind == "snippet" ? "Copy Snippet" : "Copy Example") { copy(first.source, success: "Source copied") } + .help(first.title + " · " + first.author + "\n" + first.provenance) + if first.kind == "basic_program" { Button("Open in BASIC Editor") { openExample(first) } } + Menu { Text(first.title); Text(first.language); Text(first.author); Text(first.provenance) } label: { Image(systemName: "info.circle") } + .menuStyle(.borderlessButton).fixedSize().accessibilityLabel("Example source information") + } + } else { + Menu("Examples on this page") { + ForEach(examples) { item in + Menu(item.title) { + Button(item.kind == "snippet" ? "Copy Snippet" : "Copy Example") { copy(item.source, success: "Source copied") } + if item.kind == "basic_program" { Button("Open in BASIC Editor") { openExample(item) } } + Divider(); Text(item.author); Text(item.language); Text(item.provenance) + } + } + }.fixedSize().accessibilityIdentifier("archive-examples") + } + } + private func openExample(_ item: ArchiveExample) { openWindow(id: "basic-example", value: "archive/" + item.sourceSHA256) } + private func copy(_ text: String, success: String) { + let pasteboard = NSPasteboard.general + pasteboard.clearContents(); copies = pasteboard.setString(text, forType: .string) ? success : "Copy failed" + } +} diff --git a/platforms/macos/App/ArchiveLibraryView.swift b/platforms/macos/App/ArchiveLibraryView.swift new file mode 100644 index 0000000..123cfe4 --- /dev/null +++ b/platforms/macos/App/ArchiveLibraryView.swift @@ -0,0 +1,294 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI + +private struct ArchiveCollection: Identifiable { + let id: String + let name: String + let children: [Self]? + + static func tree(_ paths: [String]) -> [Self] { + var descendants: [String: Set] = [:] + for path in paths { + var parent = "" + for component in path.split(separator: "/") { + let child = parent.isEmpty ? String(component) : parent + "/" + component + descendants[parent, default: []].insert(child); parent = child + } + } + func items(_ parent: String) -> [Self] { + (descendants[parent] ?? []).sorted { $0.localizedStandardCompare($1) == .orderedAscending }.map { path in + Self(id: path, name: String(path.split(separator: "/").last ?? ""), children: descendants[path] == nil ? nil : items(path)) + } + } + return items("") + } +} + +private struct ArchiveBrowseRequest: Equatable { let collection: String; let offset: Int; let retry: Int } +private struct ArchiveSearchRequest: Equatable { let query: String; let collection: String?; let offset: Int; let retry: Int } +private struct ArchiveResultGroup: Identifiable { + let document: ArchiveDocument + var hits: [ArchiveHit] + var id: String { document.id } +} + +@MainActor +final class ArchiveLibraryQuery: ObservableObject { + @Published var text: String + init(_ text: String = "") { self.text = text } +} + +struct ArchiveLibraryView: View { + @AppStorage("archive-library.collection") private var collection = "" + @AppStorage("archive-library.browse-selection") private var browseID: String? + @AppStorage("archive-library.browse-offset") private var browseOffset = 0 + @AppStorage("archive-library.scope") private var localScope = false + @State private var collections: [ArchiveCollection] = [] + @State private var documents: [ArchiveDocument] = [] + @State private var hits: [ArchiveHit] = [] + @State private var searchID: String? + @State private var searchOffset = 0 + @StateObject private var archiveQuery: ArchiveLibraryQuery + @State private var browseMore = false + @State private var searchMore = false + @State private var browseBusy = true + @State private var searchBusy = false + @State private var browseError: String? + @State private var searchError: String? + @State private var retry = 0 + @State private var compactReader = false + @State private var showCollections = false + @State private var searchBrowseCollection: String? + @State private var searchFolder: String? + @FocusState private var queryFocused: Bool + @StateObject private var browseReader: ArchiveReaderModel + @StateObject private var searchReader: ArchiveReaderModel + private let batch = 35 + private let catalog: ArchiveLibraryCatalog + + init(catalog: ArchiveLibraryCatalog = .shared, query: ArchiveLibraryQuery? = nil, searchReader: ArchiveReaderModel? = nil) { + self.catalog = catalog + _browseReader = StateObject(wrappedValue: ArchiveReaderModel(remembersPage: true, catalog: catalog)) + _archiveQuery = StateObject(wrappedValue: query ?? ArchiveLibraryQuery()) + _searchReader = StateObject(wrappedValue: searchReader ?? ArchiveReaderModel(remembersPage: false, catalog: catalog)) + } + + private var query: String { archiveQuery.text } + private var searching: Bool { !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } + private var browseDocument: ArchiveDocument? { documents.first { $0.id == browseID } } + private var hit: ArchiveHit? { hits.first { $0.id == searchID } } + private var selected: ArchiveDocument? { searching ? hit?.document : browseDocument } + private var reader: ArchiveReaderModel { searching ? searchReader : browseReader } + private var requestedPage: Int { searching ? (hit?.locationNumber ?? 1) : browseID.map(ArchiveReaderModel.savedPage) ?? 1 } + private var sidebarPath: String { searching ? (searchFolder ?? collection) : collection } + private var scopePath: String? { + if searching, let searchFolder, !searchFolder.isEmpty { return searchFolder } + return !collection.isEmpty ? collection : (searchBrowseCollection ?? browseDocument?.collection) + } + private var key: ArchiveSearchRequest { .init(query: query, collection: localScope ? scopePath : nil, offset: searchOffset, retry: retry) } + + var body: some View { + GeometryReader { geometry in + let narrow = geometry.size.width < 790 + let side = geometry.size.width >= 990 + VStack(spacing: 0) { + header(narrow: narrow, sidebar: side) + Divider() + HSplitView { + if side { sidebar.frame(minWidth: 150, idealWidth: 180, maxWidth: 220) } + if !narrow || !compactReader { listing.frame(minWidth: narrow ? 180 : 220, idealWidth: 290, maxWidth: narrow ? .infinity : 365) } + if !narrow || compactReader { + // An empty reader must accept the full pane height, just like the PDF reader. + detail.frame(minWidth: narrow ? 230 : 330, maxWidth: .infinity, maxHeight: .infinity) + } + } + }.frame(maxWidth: .infinity, maxHeight: .infinity) + } + .frame(minWidth: 430, minHeight: 320) + .task(id: retry) { + do { let paths = try await catalog.collections(); try Task.checkCancellation(); collections = ArchiveCollection.tree(paths) } + catch { if !Task.isCancelled { browseError = error.localizedDescription } } + } + .task(id: ArchiveBrowseRequest(collection: collection, offset: browseOffset, retry: retry)) { await loadBrowse() } + .task(id: key) { await loadSearch(key) } + .onChange(of: query) { old, new in + if old.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !new.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + searchBrowseCollection = browseDocument?.collection + if browseReader.progress != nil { browseReader.stop() } + } + searchID = nil; searchOffset = 0; compactReader = false; searchReader.reset() + if !searching { searchBrowseCollection = nil; searchFolder = nil } + } + .onChange(of: localScope) { _, _ in searchOffset = 0; searchID = nil; compactReader = false; searchReader.reset() } + .onChange(of: browseID) { _, id in + if id == nil { browseReader.reset() } + else if !searching { compactReader = true } + } + .onChange(of: searchID) { _, id in + if id == nil { searchReader.reset() } + else if searching { compactReader = true } + } + .onDisappear { browseReader.stop(); searchReader.stop() } + } + + private func header(narrow: Bool, sidebar side: Bool) -> some View { + HStack { + if narrow, compactReader { + Button { compactReader = false } label: { Label(searching ? "Results" : "Browse", systemImage: "chevron.left") } + } else if !side { + Button { showCollections.toggle() } label: { Label("Collections", systemImage: "sidebar.left") } + .popover(isPresented: $showCollections) { sidebar.frame(width: 255, height: 360) } + } + HStack(spacing: 5) { + Button { queryFocused = true } label: { Image(systemName: "magnifyingglass").foregroundStyle(.secondary) } + .buttonStyle(.plain).keyboardShortcut("f", modifiers: [.command, .shift]).accessibilityLabel("Focus Archive search") + TextField("Search Archive", text: $archiveQuery.text).textFieldStyle(.plain).focused($queryFocused) + .accessibilityLabel("Search Archive").accessibilityIdentifier("archive-search") + Button { archiveQuery.text = ""; queryFocused = true } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary) } + .buttonStyle(.plain).accessibilityLabel("Clear Archive search") + .opacity(query.isEmpty ? 0 : 1).disabled(query.isEmpty).accessibilityHidden(query.isEmpty) + }.padding(6).background(.quaternary, in: RoundedRectangle(cornerRadius: 6)) + Picker("Search scope", selection: $localScope) { + Text("Entire Archive").tag(false) + Text(scopePath?.split(separator: "/").last.map(String.init) ?? "Current collection").tag(true).disabled(scopePath == nil) + }.labelsHidden().frame(width: narrow ? 115 : 160).accessibilityLabel("Archive search scope") + Button { MCPArchiveAccess.shared.show() } label: { Image(systemName: "link") } + .help("Archive Search connection for MCP").accessibilityLabel("Archive Search connection for MCP") + }.padding(8) + } + + private var sidebar: some View { + VStack(alignment: .leading, spacing: 0) { + Button { chooseCollection("") } label: { + Label("All Documents", systemImage: "books.vertical") + .fontWeight(sidebarPath.isEmpty ? .semibold : .regular) + .frame(maxWidth: .infinity, alignment: .leading).padding(6) + .background(sidebarPath.isEmpty ? Color.accentColor.opacity(0.13) : .clear, in: RoundedRectangle(cornerRadius: 5)) + }.buttonStyle(.plain).padding(7).accessibilityAddTraits(sidebarPath.isEmpty ? .isSelected : []) + List(selection: Binding(get: { sidebarPath.isEmpty ? nil : sidebarPath }, set: { if let value = $0 { chooseCollection(value) } })) { + Section("Collections") { + OutlineGroup(collections, children: \.children) { folder in + Label(folder.name, systemImage: folder.children == nil ? "folder" : "folder.fill").tag(folder.id) + } + } + }.listStyle(.sidebar).accessibilityLabel("Archive collections") + } + } + + private func chooseCollection(_ path: String) { + showCollections = false + if searching { + if path != sidebarPath { searchID = nil; searchReader.reset() } + searchFolder = path; searchOffset = 0; localScope = !path.isEmpty; compactReader = false + return + } + guard path != collection else { return } + collection = path; browseID = nil; browseOffset = 0; compactReader = false; browseReader.reset() + } + + private var listing: some View { + VStack(alignment: .leading, spacing: 0) { + HStack { + Text(searching ? "Matching pages" : (collection.isEmpty ? "All Documents" : String(collection.split(separator: "/").last ?? ""))).font(.headline) + Spacer() + if searching ? searchBusy : browseBusy { ProgressView().controlSize(.small) } + }.padding(10) + Divider() + if let error = searching ? searchError : browseError { + VStack(spacing: 8) { Text(error).multilineTextAlignment(.center); Button("Try Again") { retry += 1 } }.padding().frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + // Keeping the browse List mounted preserves its scroll position and selection through a search. + ZStack { + browseList.opacity(searching ? 0 : 1).allowsHitTesting(!searching).accessibilityHidden(searching).disabled(searching) + if searching { resultsList } + } + Divider() + HStack { + Button { moveBatch(-1) } label: { Image(systemName: "chevron.left") }.accessibilityLabel("Previous results").disabled((searching ? searchOffset : browseOffset) == 0) + let count = searching ? hits.count : documents.count + if count > 0 { let offset = searching ? searchOffset : browseOffset; Text("\(offset + 1)–\(offset + count)").font(.caption).monospacedDigit() } + Button { moveBatch(1) } label: { Image(systemName: "chevron.right") }.accessibilityLabel("Next results").disabled(!(searching ? searchMore : browseMore)) + Spacer() + }.padding(8) + } + } + } + + private var browseList: some View { + List(selection: $browseID) { + ForEach(documents) { doc in + VStack(alignment: .leading, spacing: 3) { + Text(doc.title).lineLimit(2) + Text(doc.collection.replacingOccurrences(of: "/", with: " › ")).font(.caption).foregroundStyle(.secondary).lineLimit(1) + }.padding(.vertical, 2).frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(doc.id) + .simultaneousGesture(TapGesture().onEnded { browseID = doc.id; compactReader = true }) + } + }.accessibilityLabel("Browse Archive documents").accessibilityIdentifier("archive-browse-list") + .onKeyPress(.return, action: readSelectedWithKeyboard) + .overlay { if documents.isEmpty, !browseBusy { ContentUnavailableView("No documents in this collection", systemImage: "books.vertical") } } + } + + private var groups: [ArchiveResultGroup] { + var ordered: [ArchiveResultGroup] = []; var indices: [String: Int] = [:] + for item in hits { + if let index = indices[item.document.id] { ordered[index].hits.append(item) } + else { indices[item.document.id] = ordered.count; ordered.append(.init(document: item.document, hits: [item])) } + } + return ordered + } + private var resultsList: some View { + List(selection: $searchID) { + ForEach(groups) { group in + Section { + ForEach(group.hits) { result in + HStack { Text(result.locator); if result.ocr { Text("OCR").font(.caption).foregroundStyle(.secondary) } } + .frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(result.id) + .simultaneousGesture(TapGesture().onEnded { searchID = result.id; compactReader = true }) + } + } header: { Text(group.document.title).lineLimit(3).textCase(nil) } + } + }.accessibilityLabel("Matching Archive pages").accessibilityIdentifier("archive-results-list") + .onKeyPress(.return, action: readSelectedWithKeyboard) + .overlay { if hits.isEmpty, !searchBusy { ContentUnavailableView("No matching pages", systemImage: "magnifyingglass") } } + } + + @ViewBuilder private var detail: some View { + if let selected { + ArchiveReaderPane(record: selected, hit: searching ? hit : nil, reader: reader, requestedPage: requestedPage, catalog: catalog) + } else { ContentUnavailableView("Choose a document", systemImage: "book.pages", description: Text("Browse a collection or search the Archive.")) } + } + private func moveBatch(_ direction: Int) { + if searching { searchOffset = max(0, searchOffset + direction * batch); searchID = nil } + else { browseOffset = max(0, browseOffset + direction * batch); browseID = nil } + } + private func readSelectedWithKeyboard() -> KeyPress.Result { + guard selected != nil else { return .ignored } + // On compact layouts Return can reopen the current row after Back. + Task { @MainActor in compactReader = true } + return .handled + } + private func loadBrowse() async { + let request = ArchiveBrowseRequest(collection: collection, offset: browseOffset, retry: retry) + browseBusy = true; browseError = nil + do { + let rows = try await catalog.browse(collection: collection.isEmpty ? nil : collection, limit: batch + 1, offset: browseOffset) + try Task.checkCancellation() + guard request == ArchiveBrowseRequest(collection: collection, offset: browseOffset, retry: retry) else { return } + documents = Array(rows.prefix(batch)); browseMore = rows.count > batch + if !documents.contains(where: { $0.id == browseID }) { browseID = nil } + browseBusy = false + } catch { if !Task.isCancelled { browseError = error.localizedDescription; browseBusy = false } } + } + private func loadSearch(_ request: ArchiveSearchRequest) async { + searchError = nil; hits = []; searchMore = false + guard searching else { searchBusy = false; return } + searchBusy = true + do { + try await Task.sleep(for: .milliseconds(180)) + let rows = try await catalog.search(query: request.query, collection: request.collection, limit: batch + 1, offset: request.offset) + try Task.checkCancellation(); guard key == request else { return } + hits = Array(rows.prefix(batch)); searchMore = rows.count > batch + if !hits.contains(where: { $0.id == searchID }) { searchID = nil }; searchBusy = false + } catch { if !Task.isCancelled { searchError = error.localizedDescription; searchBusy = false } } + } +} diff --git a/platforms/macos/App/AssemblyBuildService.swift b/platforms/macos/App/AssemblyBuildService.swift new file mode 100644 index 0000000..0a9b265 --- /dev/null +++ b/platforms/macos/App/AssemblyBuildService.swift @@ -0,0 +1,316 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +struct AssemblyDiagnostic: Hashable, Sendable { + let path: String + let line: Int + let message: String +} + +struct AssemblyBuildFailure: LocalizedError { + let message: String + let diagnostics: [AssemblyDiagnostic] + init(_ message: String, diagnostics: [AssemblyDiagnostic] = []) { + self.message = message + self.diagnostics = diagnostics + } + var errorDescription: String? { message } +} + +struct AssemblyInstructionLocation: Hashable, Sendable { + let path: String + let line: Int + let address: UInt16 + let bytes: [UInt8] +} + +struct AssemblyBuildArtifact: Sendable { + let id: UUID + let snapshot: AssemblyProjectSnapshot + let binaryData: Data + let entry: UInt16 + let ranges: [ClosedRange] + let listing: String + let symbols: String + let buildLog: String + let instructions: [AssemblyInstructionLocation] +} + +/// Export accepts the full DECB address space. The machine's loader separately +/// decides whether a given block and entry are safe in its current RAM mapping. +private struct AssemblyImage { + let entry: UInt16 + let ranges: [ClosedRange] + let bytes: [Int: UInt8] + init(_ data: Data) throws { + var offset = 0, ranges: [ClosedRange] = [], memory: [Int: UInt8] = [:] + var entry: UInt16?, ambiguous = false + while offset + 5 <= data.count { + let type = data[offset], length = Int(data[offset + 1]) * 256 + Int(data[offset + 2]) + let start = Int(data[offset + 3]) * 256 + Int(data[offset + 4]) + offset += 5 + if type == 255 { + guard length == 0, offset == data.count else { throw AssemblyBuildFailure("Malformed DECB execution record.") } + entry = UInt16(start) + break + } + guard type == 0, length <= data.count - offset else { throw AssemblyBuildFailure("Malformed DECB load block.") } + if length > 0 { + let end = start + length - 1 + ranges.append(UInt16(start)...UInt16(min(end, 65535))) + if end > 65535 { ranges.append(0...UInt16(end - 65536)); ambiguous = true } + for index in 0.. Data { + let properties = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) + guard properties.isRegularFile == true, properties.isSymbolicLink != true, + let size = properties.fileSize, size <= limit else { + throw AssemblyBuildFailure("The file is missing, linked, or exceeds its size limit: " + url.lastPathComponent) + } + let handle = try FileHandle(forReadingFrom: url) + defer { try? handle.close() } + let bytes = try handle.read(upToCount: limit + 1) ?? Data() + guard bytes.count <= limit else { throw AssemblyBuildFailure("File grew beyond its size limit.") } + return bytes + } + + func withWorkspace(_ body: @escaping @Sendable (URL, DevelopmentProcessControl) throws -> T) async throws -> T { + let control = DevelopmentProcessControl() + return try await withTaskCancellationHandler { + try await Task.detached(priority: .userInitiated) { + try control.checkCancellation() + let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCC-Development-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + defer { try? FileManager.default.removeItem(at: root) } + let result = try body(root, control) + try control.checkCancellation() + return result + }.value + } onCancel: { control.cancel() } + } + + func run(_ name: String, _ arguments: [String], in folder: URL, + control: DevelopmentProcessControl, cpu: AssemblyCPU = .mc6809) throws -> (status: Int32, text: String) { + let bin = toolchain.appendingPathComponent("bin") + let executable = bin.appendingPathComponent(name) + guard FileManager.default.isExecutableFile(atPath: executable.path) else { + throw AssemblyBuildFailure("The bundled development tool is missing: " + name) + } + let environment = ["PATH": bin.path + ":/usr/bin:/bin", "LC_ALL": "C", "TMPDIR": folder.path, + "LWASM": "lwasm", "LWLINK": "lwlink", "ASFLAGS": "--" + cpu.rawValue, + "VCC_TOOLCHAIN": toolchain.path] + return try control.run(executable: executable, arguments: arguments, directory: folder, + environment: environment, timeout: 120) + } + + /// BASIC already produced a fresh tokenized disk. Stage only that image so a + /// failed tool invocation cannot alter a mounted disk or the chosen destination. + func bootableBASICDisk(_ disk: Data, name: String) async throws -> Data { + guard let name = BASICExportName.normalized(name) else { throw AssemblyBuildFailure("Invalid Disk BASIC program name.") } + return try await withWorkspace { root, control in + let url = root.appendingPathComponent("export.dsk") + try disk.write(to: url) + try installBootLoader(.basic(name), in: root, control: control) + return try Self.readFile(url, limit: 35 * 18 * 256) + } + } + + func installBootLoader(_ program: DevelopmentDiskProgram, in root: URL, control: DevelopmentProcessControl) throws { + // Both callers validate the on-disk name before it becomes a C literal. + let command = program.bootCommand.replacingOccurrences(of: "\"", with: "\\\"") + let source = "#define COMMAND \"\(command)\"\n" + CMOCMakefileSettings.dosBootLoaderSource + try Data(source.utf8).write(to: root.appendingPathComponent("loader.c")) + let compiled = try run("cmoc", ["--dos", "-O0", "--limit=2800", "-o", "loader.bin", "loader.c"], in: root, control: control) + guard compiled.status == 0 else { throw AssemblyBuildFailure("Could not build the DOS bootloader.\n" + compiled.text) } + let installed = try run("install-coco-boot-loader", ["export.dsk", "loader.bin"], in: root, control: control) + guard installed.status == 0 else { throw AssemblyBuildFailure("Could not install the DOS bootloader.\n" + installed.text) } + } + +} + +struct AssemblyBuildService: Sendable { + let tools: DevelopmentBuildTools + init(toolchain: URL = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/Toolchain")) { + tools = DevelopmentBuildTools(toolchain: toolchain) + } + + func build(_ snapshot: AssemblyProjectSnapshot) async throws -> AssemblyBuildArtifact { + try await tools.withWorkspace { root, control in + try snapshot.validate() + let workspace = root.appendingPathComponent("src") + let output = root.appendingPathComponent("out") + try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true) + for (path, data) in snapshot.files { + try control.checkCancellation() + let url = workspace.appendingPathComponent(path) + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: url, options: .withoutOverwriting) + } + var log = "", listings: [String] = [], symbols = "" + var objects: [String] = [], modules: [(object: String, records: String)] = [] + func invoke(_ tool: String, _ args: [String]) throws -> String { + let result = try tools.run(tool, args, in: workspace, control: control, cpu: snapshot.cpu) + let command = ([tool] + args).joined(separator: " ") + if log.utf8.count < 512 * 1024 { log += command + "\n" + result.text + "\n" } + guard result.status == 0 else { + throw AssemblyBuildFailure(command + "\n" + result.text, diagnostics: Self.diagnostics(result.text, files: snapshot.files)) + } + return result.text + } + var binaryURL = output.appendingPathComponent("program.bin") + let settings = snapshot.settings + if let makefile = settings.makefile, let binary = settings.binary { + _ = try invoke("make", ["-B", "-f", "./" + makefile, "MAKE=make", "--", settings.target ?? "all"]) + binaryURL = workspace.appendingPathComponent(binary) + guard binaryURL.resolvingSymlinksInPath().path == workspace.resolvingSymlinksInPath().appendingPathComponent(binary).path else { + throw AssemblyBuildFailure("The Makefile must produce a regular binary within the build folder.") + } + log += "Custom Make declares the CPU target in its recipe. Its instruction set and source locations are unverified. Use the machine debugger.\n" + } else { + let linked = settings.linkScript != nil + _ = try invoke("lwasm", ["--version"]) + for (index, path) in ([snapshot.mainPath] + (settings.modules ?? [])).enumerated() { + let stem = "../out/module" + String(index) + let object = stem + ".o" + let flags = ["--project-inputs", "--" + snapshot.cpu.rawValue, linked ? "--obj" : "--decb", "--error-format=gcc", "-I."] + let fileArg = "./" + path + _ = try invoke("lwasm", flags + ["--tabs=0", "--list=" + stem + ".lst", "--project-map=" + stem + ".lines", + "--symbol-dump=" + stem + ".sym", "-o", linked ? object : "../out/program.bin", fileArg]) + let records = try DevelopmentBuildTools.readFile(workspace.appendingPathComponent(stem + ".lines"), limit: 4 * 1024 * 1024) + let list = try DevelopmentBuildTools.readFile(workspace.appendingPathComponent(stem + ".lst"), limit: 8 * 1024 * 1024) + let listing = String(decoding: list, as: UTF8.self) + guard listings.reduce(listing.utf8.count, { $0 + $1.utf8.count }) <= 16 * 1024 * 1024 else { + throw AssemblyBuildFailure("Combined listings exceed 16 MB.") + } + modules.append((object, String(decoding: records, as: UTF8.self))) + listings.append(listing) + if linked { objects.append(object) } + else { + symbols = String(decoding: try DevelopmentBuildTools.readFile(workspace.appendingPathComponent(stem + ".sym"), limit: 4 * 1024 * 1024), as: UTF8.self) + } + } + if let script = settings.linkScript { + _ = try invoke("lwlink", ["--version"]) + _ = try invoke("lwlink", ["--decb", "--script=./" + script, "--map=../out/link.map", "-o", "../out/program.bin"] + objects) + symbols = String(decoding: try DevelopmentBuildTools.readFile(output.appendingPathComponent("link.map"), limit: 4 * 1024 * 1024), as: UTF8.self) + } + } + let binary = try DevelopmentBuildTools.readFile(binaryURL, limit: BinaryFile.limit) + let image = try AssemblyImage(binary) + var instructions: [AssemblyInstructionLocation] = [] + for (object, records) in modules { + try control.checkCancellation() + var sections: [String: CMOCSourceMap.VerifiedSection]? + if settings.linkScript != nil { + do { + let data = try DevelopmentBuildTools.readFile(workspace.appendingPathComponent(object), limit: 8 * 1024 * 1024) + sections = try CMOCSourceMap.verifiedSections(object: data, objectName: object, linkMap: Data(symbols.utf8), binary: binary).sections + } catch { + log += "Source locations unavailable for " + object + ". " + error.localizedDescription + "\n" + continue + } + } + instructions += Self.locations(records, files: snapshot.files, image: image, sections: sections) + } + // Repeated include expansions or two rows claiming a PC are ambiguous. + let addresses = Dictionary(grouping: instructions, by: \.address) + let lines = Dictionary(grouping: instructions) { $0.path + "\n" + String($0.line) } + let verified = instructions.filter { addresses[$0.address]?.count == 1 && lines[$0.path + "\n" + String($0.line)]?.count == 1 } + return AssemblyBuildArtifact(id: UUID(), snapshot: snapshot, binaryData: binary, entry: image.entry, + ranges: image.ranges, listing: listings.joined(separator: "\n"), symbols: symbols, buildLog: log, instructions: verified) + } + } + + func diskImage(for artifact: AssemblyBuildArtifact, name: String, dosBoot: Bool = false) async throws -> Data { + let dosName = name.uppercased() + guard dosName.range(of: #"\A[A-Z0-9][A-Z0-9_-]{0,7}\z"#, options: .regularExpression) != nil else { + throw AssemblyBuildFailure("Use a Disk BASIC name of one to eight letters or digits, with optional hyphens or underscores.") + } + return try await tools.withWorkspace { root, control in + let image = root.appendingPathComponent("export.dsk") + try Data(repeating: 0xff, count: 35 * 18 * 256).write(to: image) + if dosBoot { + try tools.installBootLoader(.binary(dosName), in: root, control: control) + } + let file = dosName + ".BIN" + try artifact.binaryData.write(to: root.appendingPathComponent(file)) + let result = try tools.run("writecocofile", ["export.dsk", file], in: root, control: control) + guard result.status == 0 else { throw AssemblyBuildFailure(result.text) } + return try DevelopmentBuildTools.readFile(image, limit: 35 * 18 * 256) + } + } + + private static func diagnostics(_ text: String, files: [String: Data]) -> [AssemblyDiagnostic] { + let pattern = try! NSRegularExpression(pattern: #"^(.+?):([0-9]+): (?:error|warning): (.+)$"#) + return text.components(separatedBy: .newlines).compactMap { row in + guard let fields = groups(pattern, row), let number = Int(fields[2]), + let path = sourcePath(fields[1], in: Set(files.keys)) else { return nil } + return AssemblyDiagnostic(path: path, line: number, message: fields[3]) + } + } + + private static func groups(_ regex: NSRegularExpression, _ row: String) -> [String]? { + let ns = row as NSString + guard let match = regex.firstMatch(in: row, range: NSRange(location: 0, length: ns.length)) else { return nil } + return (0..) -> String? { + var token = token + while token.hasPrefix("./") { token.removeFirst(2) } + guard !token.isEmpty else { return nil } + let candidates = inputs.filter { path in + path == token || path.hasSuffix("/" + token) + } + return candidates.count == 1 ? candidates.first : nil + } + + /// Physical source names, lines and section names come directly from LWASM. + /// The display listing abbreviates names and can include macro expansions. + private static func locations(_ records: String, files: [String: Data], image: AssemblyImage, + sections: [String: CMOCSourceMap.VerifiedSection]?) -> [AssemblyInstructionLocation] { + var result: [AssemblyInstructionLocation] = [] + for row in records.split(whereSeparator: \.isNewline) { + let fields = row.split(separator: "\t", omittingEmptySubsequences: false) + guard fields.count == 5, let line = Int(fields[1]), line > 0, let offset = Int(fields[3], radix: 16), + (0..<65536).contains(offset) else { continue } + let path = String(fields[0]), digits = Array(fields[4]) + guard files[path] != nil, (2...16).contains(digits.count), digits.count.isMultiple(of: 2) else { continue } + let original = stride(from: 0, to: digits.count, by: 2).compactMap { UInt8(String(digits[$0...($0 + 1)]), radix: 16) } + guard original.count * 2 == digits.count else { continue } + let address: Int, bytes: [UInt8] + if let sections { + guard let section = sections[String(fields[2])], let final = section.final, + offset + original.count <= section.original.count, + section.original[offset..<(offset + original.count)].elementsEqual(original) else { continue } + address = section.base + offset + bytes = Array(final[offset..<(offset + original.count)]) + } else { + guard fields[2].isEmpty else { continue } + address = offset + bytes = original + } + guard address + bytes.count <= 65536, + bytes.enumerated().allSatisfy({ image.bytes[address + $0.offset] == $0.element }) else { continue } + result.append(.init(path: path, line: line, address: UInt16(address), bytes: bytes)) + } + return result + } +} diff --git a/platforms/macos/App/AssemblyDevelopmentFiles.swift b/platforms/macos/App/AssemblyDevelopmentFiles.swift new file mode 100644 index 0000000..c6207e7 --- /dev/null +++ b/platforms/macos/App/AssemblyDevelopmentFiles.swift @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +struct AssemblyBuffer: Codable, Identifiable, Sendable { + var id = UUID() + var path: String + var text: String + var saved: String? + var dirty: Bool { saved.map { !text.utf8.elementsEqual($0.utf8) } ?? true } +} + +struct AssemblyWorkspaceDocument: Codable, Identifiable, Sendable { + var id = UUID() + var title: String + var directory: URL? + var isProject = false + var mainPath: String + var buffers: [AssemblyBuffer] + var selectedPath: String + var cpu: AssemblyCPU = .mc6809 + var breakpoints = Set() + var paths: [String] = [] + var inputPaths: [String]? + + static let starterTitle = "Hello World — Earth or Mars" + static let starterSource = DevelopmentStarterSource.planet(withExtension: "asm") + ?? "; The Earth or Mars example is missing. Reinstall VCC Plus to restore it.\n" + + static func example(title: String, source: String, cpu: AssemblyCPU) -> Self { + let file = AssemblyBuffer(path: "main.asm", text: source, saved: nil) + return Self(title: title, mainPath: file.path, buffers: [file], selectedPath: file.path, cpu: cpu) + } + + static func open(_ url: URL, folder: Bool) throws -> Self { + let physical = URL(fileURLWithPath: try CMOCProject.physicalURL(url).path, isDirectory: folder) + let snapshot = try folder ? AssemblyProjectSnapshot.read(directory: physical) : AssemblyProjectSnapshot.readSource(at: physical) + guard let data = snapshot.files[snapshot.mainPath], let text = String(data: data, encoding: .utf8) else { + throw AssemblyBuildFailure("The entry source must be a UTF-8 text file.") + } + return Self(title: physical.lastPathComponent, directory: folder ? physical : physical.deletingLastPathComponent(), + isProject: folder, mainPath: snapshot.mainPath, + buffers: [.init(path: snapshot.mainPath, text: text, saved: text)], selectedPath: snapshot.mainPath, + paths: editablePaths(snapshot), inputPaths: Array(snapshot.files.keys)) + } + + static func editablePaths(_ snapshot: AssemblyProjectSnapshot) -> [String] { + snapshot.files.keys.filter { + ["asm", "s", "inc", "lwasm", "link", "lw", "json", "mk"].contains(URL(fileURLWithPath: $0).pathExtension.lowercased()) || + $0 == snapshot.settings.linkScript || $0 == snapshot.settings.makefile || $0 == "Makefile" || $0 == snapshot.mainPath + }.sorted() + } + + func checkedURL(_ path: String) throws -> URL { + try CMOCProject.validateRelativePath(path) + guard let directory else { throw AssemblyBuildFailure("Save the source before opening relative files.") } + let url = directory.appendingPathComponent(path) + let candidate = FileManager.default.fileExists(atPath: url.path) ? url : url.deletingLastPathComponent() + // directory was canonicalized at Open/Save. Foundation standardization + // may shorten /private/var to /var; compare the two physical spellings. + guard try CMOCProject.physicalURL(candidate).path == candidate.path, + (try? FileManager.default.destinationOfSymbolicLink(atPath: url.path)) == nil else { + throw AssemblyBuildFailure("The project path now points through a symbolic link: " + path) + } + return url + } + + func snapshot() throws -> AssemblyProjectSnapshot { + guard let directory else { + guard let entry = buffers.first(where: { $0.path == mainPath }) else { throw AssemblyBuildFailure("Entry source is missing.") } + return .single(source: entry.text, path: mainPath, cpu: cpu) + } + var overlays: [String: String] = [:] + for buffer in buffers { + let url = try checkedURL(buffer.path) + if let saved = buffer.saved { + guard try CMOCProject.readText(url, maximumBytes: CMOCProject.maximumSourceBytes) == saved else { + throw AssemblyBuildFailure("\(buffer.path) changed on disk. Reload it or save your edits separately.") + } + } else if FileManager.default.fileExists(atPath: url.path) { + throw AssemblyBuildFailure("\(buffer.path) appeared on disk. Reload it before building.") + } + if buffer.dirty { overlays[buffer.path] = buffer.text } + } + if isProject { return try .read(directory: directory, mainPath: mainPath, overlays: overlays, cpu: cpu) } + return try .readSource(at: checkedURL(mainPath), overlays: overlays, cpu: cpu) + } +} + +struct AssemblyRecovery: Codable, Sendable { + var version = 1 + var documents: [AssemblyWorkspaceDocument] + var active: UUID + + func write(to url: URL) throws { + let data = try JSONEncoder().encode(self) + guard data.count <= 64 * 1024 * 1024 else { throw AssemblyBuildFailure("Assembly drafts exceed the 64 MB recovery limit. Save and close completed documents.") } + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: url, options: .atomic) + } + + static func read(from url: URL) throws -> Self { + let values = try url.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey]) + guard values.isRegularFile == true, let size = values.fileSize, size <= 64 * 1024 * 1024 else { throw CocoaError(.fileReadTooLarge) } + let saved = try JSONDecoder().decode(Self.self, from: Data(contentsOf: url)) + guard saved.version == 1, saved.documents.contains(where: { $0.id == saved.active }), + Set(saved.documents.map(\.id)).count == saved.documents.count else { throw CocoaError(.fileReadCorruptFile) } + var bufferIDs = Set() + for doc in saved.documents { + guard doc.buffers.contains(where: { $0.path == doc.selectedPath }), + doc.buffers.contains(where: { $0.path == doc.mainPath }), + Set(doc.buffers.map(\.path)).count == doc.buffers.count else { throw CocoaError(.fileReadCorruptFile) } + for buffer in doc.buffers { + try CMOCProject.validateRelativePath(buffer.path) + guard bufferIDs.insert(buffer.id).inserted else { throw CocoaError(.fileReadCorruptFile) } + } + } + return saved + } +} diff --git a/platforms/macos/App/AssemblyDevelopmentModel.swift b/platforms/macos/App/AssemblyDevelopmentModel.swift new file mode 100644 index 0000000..4770083 --- /dev/null +++ b/platforms/macos/App/AssemblyDevelopmentModel.swift @@ -0,0 +1,660 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import SwiftUI + +@MainActor +final class AssemblyDevelopmentModel: ObservableObject { + struct SourceLine: Hashable, Codable, Sendable { + let path: String + let line: Int + } + struct Selection { let id = UUID(); let buffer: UUID; let range: NSRange } + enum Action { case assemble, run, debug, exportBinary(URL), exportDisk(URL, String, dosBoot: Bool) } + struct Attachment { + let document: UUID + let artifact: AssemblyBuildArtifact + var expected: VCCMachineSnapshot + var guards: [UInt16: Data] + } + + let machine: MachineModel + let service: AssemblyBuildService + private(set) var recoveryURL: URL + private let recoveryQueue = DispatchQueue(label: "VCCPlus.AssemblyRecovery") + private var recoveryTask: Task? + @Published private(set) var documents: [AssemblyWorkspaceDocument] + @Published private(set) var activeID: UUID + @Published private(set) var artifact: AssemblyBuildArtifact? + @Published private(set) var diagnostics: [AssemblyDiagnostic] = [] + @Published var message = "Ready to assemble." + @Published var buildLog = "" + @Published private(set) var working = false + @Published private(set) var cursor = 0 + @Published private(set) var selection: Selection? + @Published private(set) var executionLine: SourceLine? + @Published private(set) var execution = "" + @Published private(set) var commanding = false + @Published private(set) var attached = false + @Published private(set) var paused = false + @Published private(set) var displayRequest = 0 + private var cursors: [UUID: Int] = [:] + private var fileRequest = UUID() + private var work: Task? + private var revision = UUID() + var workspaceRevision: UUID { revision } + @Published private(set) var sourceRevision = UUID() + private var connection: Attachment? + // Remember ownership across source edits so a repeat Run can replace our own bytes immediately. + private var owner: (document: UUID, generation: UInt64, revision: UInt64)? + private var reading = false + private var checking = false + private var nextCheck = Date.distantPast + private var index: Int { documents.firstIndex { $0.id == activeID }! } + var document: AssemblyWorkspaceDocument { documents[index] } + var buffer: AssemblyBuffer { document.buffers.first { $0.path == document.selectedPath }! } + var cpu: AssemblyCPU { document.cpu } + + init(machine: MachineModel, service: AssemblyBuildService = .init(), recoveryURL: URL? = nil) { + self.machine = machine; self.service = service + self.recoveryURL = recoveryURL ?? machine.developmentRunDirectory.deletingLastPathComponent().appendingPathComponent("Assembly Workspace/Drafts.json") + let first = AssemblyWorkspaceDocument.example(title: AssemblyWorkspaceDocument.starterTitle, source: AssemblyWorkspaceDocument.starterSource, cpu: .mc6809) + documents = [first]; activeID = first.id + while FileManager.default.fileExists(atPath: self.recoveryURL.path) { + do { + let saved = try AssemblyRecovery.read(from: self.recoveryURL) + documents = saved.documents; activeID = saved.active + message = "Restored assembly workspace." + break + } catch { + // Preserve an unreadable record at its original location. New sessions + // use a neighboring recovery file that is discovered on the next launch. + self.recoveryURL = self.recoveryURL.deletingPathExtension().appendingPathExtension("recovered.json") + message = "The previous Assembly draft file could not be read. It has been preserved separately." + } + } + indexLabels() + } + + static func lineRange(_ line: Int, text: String) -> NSRange? { + guard line > 0 else { return nil } + let ns = text as NSString + var start = 0 + for _ in 1.. = []) throws -> Set { + guard !working, !commanding, !edits.isEmpty else { throw AssemblyBuildFailure("workspace_busy") } + var updated = document + let originalStops = updated.breakpoints + for edit in edits { + let before = undo ? edit.after : edit.before + let after = undo ? edit.before : edit.after + guard snapshot.files[edit.path] == Data(before.utf8) else { throw AssemblyBuildFailure("revision_conflict") } + if let index = updated.buffers.firstIndex(where: { $0.path == edit.path }) { + guard updated.buffers[index].text.utf8.elementsEqual(before.utf8) else { throw AssemblyBuildFailure("revision_conflict") } + updated.buffers[index].text = after + } else { + // An unopened file in the live snapshot has no draft overlay. + guard !undo else { throw AssemblyBuildFailure("revision_conflict") } + updated.buffers.append(.init(path: edit.path, text: after, saved: before)) + } + updated.breakpoints = updated.breakpoints.filter { stop in + guard stop.path == edit.path else { return true } + guard let a = Self.lineRange(stop.line, text: before), let b = Self.lineRange(stop.line, text: after) else { return false } + return (before as NSString).substring(with: a).utf8.elementsEqual((after as NSString).substring(with: b).utf8) + } + } + updated.breakpoints.formUnion(restoreStops) + documents[index] = updated + fileRequest = UUID() + sourceRevision = UUID() + restoreCursor() + invalidate("Source changed. Assemble the reviewed project revision.") + scheduleRecovery() + return originalStops.subtracting(updated.breakpoints) + } + + func setCPU(_ target: AssemblyCPU) { + guard cpu != target else { return } + documents[index].cpu = target + sourceRevision = UUID() + invalidate("Build target changed. Assemble to refresh the listing and source stops.") + scheduleRecovery() + } + private func cancelPending() { + revision = UUID(); work?.cancel(); work = nil; working = false + } + func cancelBuild() { invalidate("Assembly cancelled.") } + private func invalidate(_ reason: String) { + cancelPending(); artifact = nil; diagnostics = [] + if let conn = connection, conn.document == activeID { + machine.clearAssembly(expected: conn.expected); connection = nil + } + attached = false; paused = false; execution = ""; executionLine = nil; message = reason; indexLabels() + } + + func selectFile(_ path: String, line: Int? = nil) { + let doc = document, request = UUID() + fileRequest = request + if doc.buffers.contains(where: { $0.path == path }) { displayFile(path, line: line); return } + Task { + do { + let text = try await Task.detached { + try CMOCProject.readText(doc.checkedURL(path), maximumBytes: CMOCProject.maximumSourceBytes) + }.value + guard activeID == doc.id, fileRequest == request else { return } + if !document.buffers.contains(where: { $0.path == path }) { + documents[index].buffers.append(.init(path: path, text: text, saved: text)); indexLabels() + } + displayFile(path, line: line) + } catch { message = error.localizedDescription } + } + } + private func displayFile(_ path: String, line: Int?) { + if document.selectedPath != path { + documents[index].selectedPath = path; restoreCursor() + } + if let line, let range = Self.lineRange(line, text: buffer.text) { + moveCursor(range.location) + selection = .init(buffer: buffer.id, range: range) + } + scheduleRecovery() + } + private func restoreCursor() { + cursor = min(cursors[buffer.id] ?? 0, buffer.text.utf16.count) + selection = .init(buffer: buffer.id, range: NSRange(location: cursor, length: 0)) + } + func editSettings() { + guard document.isProject else { return } + let path = AssemblyProjectSnapshot.configurationFilename + if document.paths.contains(path) || document.buffers.contains(where: { $0.path == path }) { selectFile(path); return } + let text = "{\n \"main\": \"main.asm\"\n}\n" + documents[index].buffers.append(.init(path: path, text: text, saved: nil)) + documents[index].paths.append(path) + sourceRevision = UUID() + displayFile(path, line: nil); invalidate("Edit project settings, then assemble to validate them.") + } + func reload() { + let doc = document, file = buffer + if file.dirty { + let alert = NSAlert(); alert.messageText = "Replace edits with the saved \(file.path)?" + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Reload") + guard alert.runModal() == .alertSecondButtonReturn else { return } + } + Task { + do { + let text = try await Task.detached { try CMOCProject.readText(doc.checkedURL(file.path), maximumBytes: CMOCProject.maximumSourceBytes) }.value + guard activeID == doc.id, buffer.id == file.id, buffer.text == file.text, + let i = document.buffers.firstIndex(where: { $0.id == file.id }) else { return } + documents[index].buffers[i] = .init(path: file.path, text: text, saved: text) + sourceRevision = UUID() + invalidate("Reloaded \(file.path)."); scheduleRecovery() + } catch { message = error.localizedDescription } + } + } + private var protectedSourceURLs: [URL] { + var urls = [recoveryURL] + for doc in documents { + guard let root = doc.directory else { continue } + let paths = Set(doc.inputPaths ?? doc.paths).union(doc.buffers.map(\.path)) + urls += paths.map { root.appendingPathComponent($0) } + } + return urls + } + + func save(to copy: URL? = nil) { + let doc = document, file = buffer + Task { + do { + let url = try copy ?? doc.checkedURL(file.path) + var protected = protectedSourceURLs + var expected: Data? + if copy == nil { + // Only Save Source may replace the selected source file. + protected.removeAll { $0.standardizedFileURL == url.standardizedFileURL } + expected = file.saved.map { Data($0.utf8) } + if expected == nil, FileManager.default.fileExists(atPath: url.path) { + throw AssemblyBuildFailure("The source appeared on disk. Reload it or Save a Copy.") + } + } + try await machine.writeDevelopmentFile(Data(file.text.utf8), to: url, protecting: protected, + allowEmpty: true, replacing: expected) + guard let d = documents.firstIndex(where: { $0.id == doc.id }), + let i = documents[d].buffers.firstIndex(where: { $0.id == file.id }) else { return } + if doc.directory == nil { + documents[d].directory = try CMOCProject.physicalURL(url.deletingLastPathComponent()) + documents[d].mainPath = url.lastPathComponent; documents[d].selectedPath = url.lastPathComponent + documents[d].buffers[i].path = url.lastPathComponent; documents[d].title = url.lastPathComponent + documents[d].breakpoints.removeAll() + if activeID == doc.id { invalidate("Source saved.") } + } + if doc.directory == nil || copy == nil { documents[d].buffers[i].saved = file.text } + message = "Saved \(url.lastPathComponent)."; scheduleRecovery() + } catch { message = error.localizedDescription } + } + } + + @Published private(set) var labelLocations: [(String, SourceLine)] = [] + private var labelTask: Task? + private func indexLabels() { + labelTask?.cancel() + let doc = document, snapshot = artifact?.snapshot + labelTask = Task { + do { try await Task.sleep(nanoseconds: 120_000_000) } catch { return } + let result = await Task.detached(priority: .utility) { + let words = AssemblyReference.shared.vocabulary(target6309: doc.cpu == .hd6309) + var sources = [String: String]() + for (path, bytes) in snapshot?.files ?? [:] { + let ext = URL(fileURLWithPath: path).pathExtension.lowercased() + if ["asm", "s", "lwasm", "inc"].contains(ext) { sources[path] = String(data: bytes, encoding: .utf8) } + } + for file in doc.buffers where file.path == doc.mainPath || ["asm", "s", "lwasm", "inc"].contains(URL(fileURLWithPath: file.path).pathExtension.lowercased()) { + sources[file.path] = file.text + } + return sources.flatMap { path, text in + AssemblyEditorSyntax.labels(in: text, vocabulary: words).map { ($0.0, SourceLine(path: path, line: $0.1)) } + }.sorted { ($0.0, $0.1.path, $0.1.line) < ($1.0, $1.1.path, $1.1.line) } + }.value + if !Task.isCancelled, activeID == doc.id { labelLocations = result } + } + } + func goToDefinition() { + let words = AssemblyReference.shared.vocabulary(target6309: cpu == .hd6309) + guard let term = AssemblyEditorSyntax.token(in: buffer.text, offset: cursor, vocabulary: words) else { + message = "Place the caret on a label."; return + } + let matches = labelLocations.filter { $0.0 == term } + guard matches.count == 1, let match = matches.first else { + message = matches.isEmpty ? "No label definition found for \(term)." : "Multiple definitions for \(term). Choose a location in Labels." + return + } + selectFile(match.1.path, line: match.1.line) + } + + private func scheduleRecovery() { + recoveryTask?.cancel() + recoveryTask = Task { + do { try await Task.sleep(nanoseconds: 350_000_000) } catch { return } + let state = AssemblyRecovery(documents: documents, active: activeID), url = recoveryURL + recoveryQueue.async { + do { try state.write(to: url) } + catch { Task { @MainActor in self.message = "Could not preserve assembly drafts: " + error.localizedDescription } } + } + } + } + func prepareToQuit() -> Bool { + cancelPending(); recoveryTask?.cancel() + let state = AssemblyRecovery(documents: documents, active: activeID) + do { try recoveryQueue.sync { try state.write(to: recoveryURL) }; return true } + catch { + message = "Could not preserve assembly drafts: " + error.localizedDescription + let alert = NSAlert(); alert.messageText = "Could not save Assembly drafts"; alert.informativeText = message + alert.runModal(); return false + } + } + + static func codeGuards(_ instructions: [AssemblyInstructionLocation]) -> [UInt16: Data] { + Dictionary(grouping: instructions, by: \.address).compactMapValues { candidates in + guard candidates.count == 1, let first = candidates.first, !first.bytes.isEmpty else { return nil } + return Data(first.bytes) + } + } + static func location(_ stop: SourceLine, in artifact: AssemblyBuildArtifact) -> AssemblyInstructionLocation? { + let candidates = artifact.instructions.filter { $0.path == stop.path && $0.line == stop.line } + guard candidates.count == 1, let candidate = candidates.first, + artifact.instructions.filter({ $0.address == candidate.address }).count == 1 else { return nil } + return candidate + } + func toggleBreakpoint() { + guard !commanding else { return } + let stop = SourceLine(path: buffer.path, line: cursorLine) + if document.breakpoints.contains(stop) { documents[index].breakpoints.remove(stop) } + else { + guard let artifact, Self.location(stop, in: artifact) != nil else { + message = "Assemble first and choose a line with one verified instruction. Use the listing for ambiguous or data lines."; return + } + documents[index].breakpoints.insert(stop) + } + applyStops() + } + func clearStops() { + guard !commanding else { return } + documents[index].breakpoints.removeAll(); applyStops() + } + private func applyStops() { + scheduleRecovery() + guard let conn = connection, conn.document == activeID else { return } + let points = document.breakpoints.compactMap { Self.location($0, in: conn.artifact)?.address } + validateForControl(conn) { + self.machine.updateAssembly(breakpoints: points, guards: conn.guards, expected: conn.expected) { snapshot in + self.finishCommand(snapshot, connection: conn) + } + } + } + + func perform(_ action: Action) { + guard !commanding, !working else { return } + let doc = document, request = UUID(), previous = artifact + revision = request; working = true; diagnostics = []; message = "Preparing assembly inputs…" + work = Task { + defer { if revision == request { working = false; work = nil } } + do { + let snapshot = try await Task.detached { try doc.snapshot() }.value + try check(request, doc.id) + documents[index].inputPaths = Array(snapshot.files.keys) + let result: AssemblyBuildArtifact + if let previous, previous.snapshot == snapshot { result = previous } + else { + if let makefile = snapshot.settings.makefile { + let alert = NSAlert(); alert.messageText = "Run this project’s Makefile?" + alert.informativeText = "\(doc.title) will execute \(makefile), target \(snapshot.settings.target ?? "all"), with your account’s permissions. ASFLAGS supplies the selected CPU target. The recipe controls the resulting binary. Without a verified source map, use the machine debugger." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Run Make") + guard alert.runModal() == .alertSecondButtonReturn else { throw CancellationError() } + } + message = "Assembling for the \(cpu.rawValue)…" + result = try await service.build(snapshot) + try check(request, doc.id) + if doc.directory != nil { + guard try await Task.detached(operation: { try doc.snapshot() }).value == snapshot else { + throw AssemblyBuildFailure("Assembly inputs changed during the build. Assemble again.") + } + } + } + try check(request, doc.id) + artifact = result; buildLog = result.buildLog; documents[index].paths = AssemblyWorkspaceDocument.editablePaths(snapshot) + indexLabels(); message = "Assembled · " + Self.summary(result) + switch action { + case .assemble: break + case .run, .debug: + let debug: Bool + if case .debug = action { debug = true } else { debug = false } + try await launch(result, doc: doc, request: request, debug: debug) + case .exportBinary(let url): try await write(result.binaryData, url: url, request: request, doc: doc.id) + case .exportDisk(let url, let name, let dosBoot): + let disk = try await service.diskImage(for: result, name: name, dosBoot: dosBoot) + try check(request, doc.id) + if doc.directory != nil, try await Task.detached(operation: { try doc.snapshot() }).value != snapshot { + throw AssemblyBuildFailure("Project inputs changed during disk export. Assemble again.") + } + try await write(disk, url: url, request: request, doc: doc.id) + } + } catch { + guard revision == request else { return } + let failure = (error as? AssemblyBuildFailure)?.diagnostics ?? [] + let reason = error is CancellationError ? "Assembly cancelled." : error.localizedDescription + invalidate(reason); buildLog = reason; diagnostics = failure + } + } + } + private func check(_ request: UUID, _ doc: UUID) throws { + try Task.checkCancellation() + guard revision == request && activeID == doc else { throw CancellationError() } + } + private func write(_ data: Data, url: URL, request: UUID, doc: UUID) async throws { + try check(request, doc) + do { + try await machine.writeDevelopmentFile(data, to: url, protecting: protectedSourceURLs) + } catch { + if revision == request { message = error.localizedDescription } + return + } + try check(request, doc); message = "Exported \(url.lastPathComponent)." + } + static func summary(_ artifact: AssemblyBuildArtifact) -> String { + let ranges = artifact.ranges.map { String(format: "$%04X–$%04X", $0.lowerBound, $0.upperBound) }.joined(separator: ", ") + return "Load " + ranges + String(format: " · Entry $%04X", artifact.entry) + } + func acceptSharedBuild(_ build: AssemblyBuildArtifact) { + artifact = build; diagnostics = []; buildLog = build.buildLog + message = "Assembled · " + Self.summary(build) + indexLabels() + } + + func launchShared(_ build: AssemblyBuildArtifact, stillGranted: @escaping () -> Bool, + confirm: ((String) -> Bool)? = nil) async throws -> VCCMachineSnapshot { + guard !working, !commanding, artifact?.id == build.id, stillGranted() else { + throw AssemblyBuildFailure("The shared build is no longer current.") + } + working = true + let request = revision, priorProgram = machine.assemblyProgramRevision + defer { if revision == request { working = false } } + try await launch(build, doc: document, request: request, debug: false, stillGranted: stillGranted, confirm: confirm) + guard let connection, connection.artifact.id == build.id, connection.expected.debuggerProgramRevision != priorProgram, stillGranted() else { throw AssemblyBuildFailure(message) } + return connection.expected + } + + private func launch(_ artifact: AssemblyBuildArtifact, doc: AssemblyWorkspaceDocument, request: UUID, debug: Bool, stillGranted: (() -> Bool)? = nil, confirm: ((String) -> Bool)? = nil) async throws { + let generation = machine.basicDebug.generation, program = machine.assemblyProgramRevision + let mapping = machine.assemblyMappingFingerprint + let sameOwner = owner?.document == doc.id && owner?.generation == generation && owner?.revision == program + guard machine.state == .paused || machine.state == .running else { + message = "Start a Disk BASIC, Hard Drive BASIC or CoCoSDC machine before running. The build is ready for export."; return + } + if let confirm, !sameOwner { + guard confirm(Self.summary(artifact)) else { throw CancellationError() } + } else if !sameOwner { + let alert = NSAlert(); alert.messageText = "Load this assembly program into the CoCo?" + alert.informativeText = Self.summary(artifact) + "\n\nLoading replaces guest program memory and takes over any active development session. Save any BASIC program or variables you want to keep." + if stillGranted != nil { + alert.informativeText += "\n\nWhile this program runs, the connected assistant can read the CoCo text screen and send up to 64 individual letters, digits or spaces. Its run receipt can include the last text screen when the program returns to BASIC." + } + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: debug ? "Debug from Entry" : "Run") + guard alert.runModal() == .alertSecondButtonReturn else { message = "Launch cancelled. The build is ready."; return } + } + try check(request, doc.id) + if doc.directory != nil, try await Task.detached(operation: { try doc.snapshot() }).value != artifact.snapshot { + throw AssemblyBuildFailure("Inputs changed before launch. Assemble again.") + } + try check(request, doc.id) + guard stillGranted?() != false else { throw CancellationError() } + let points = doc.breakpoints.compactMap { Self.location($0, in: artifact)?.address } + guard points.count == doc.breakpoints.count else { + message = "An armed line no longer has one executable instruction. Remove that source stop before launching."; return + } + let guards = Self.codeGuards(artifact.instructions) + commanding = true + let result: VCCMachineSnapshot? = await withCheckedContinuation { continuation in + machine.launchAssembly(artifact.binaryData, breakpoints: points, guards: guards, pauseAtEntry: debug, + requires6309: doc.cpu == .hd6309, expectedGeneration: generation, expectedRevision: program, expectedMapping: mapping, shared: stillGranted != nil) { + continuation.resume(returning: $0) + } + } + commanding = false + guard let result, result.errorMessage == nil else { + if revision == request { message = result?.errorMessage ?? machine.fileError ?? "The CoCo is busy or unavailable." }; return + } + owner = (doc.id, result.generation, result.debuggerProgramRevision) + guard revision == request, activeID == doc.id else { machine.clearAssembly(expected: result); return } + connection = .init(document: doc.id, artifact: artifact, expected: result, guards: guards) + attached = true; paused = result.state == .paused + message = "Loaded · " + Self.summary(artifact) + if !debug { displayRequest += 1 } + refresh() + } + + func pause() { + guard attached, !commanding, let conn = connection, conn.document == activeID else { return } + commanding = true + machine.pauseAssembly(expected: conn.expected) { snapshot in + self.finishCommand(snapshot, connection: conn) + } + } + func control(step: Bool) { + guard paused, let conn = connection, conn.document == activeID, !commanding else { return } + validateForControl(conn) { + self.machine.controlAssembly(step: step, expected: conn.expected) { snapshot in + self.finishCommand(snapshot, connection: conn) + } + } + } + private func validateForControl(_ conn: Attachment, command: @escaping @MainActor () -> Void) { + let doc = document, request = revision + commanding = true + Task { + do { + let inputs = try await Task.detached { try doc.snapshot() }.value + guard request == revision, activeID == doc.id, connection?.artifact.id == conn.artifact.id else { commanding = false; return } + guard inputs == conn.artifact.snapshot else { throw AssemblyBuildFailure("Project inputs changed. Run again to reconnect source debugging.") } + command() + } catch { + commanding = false + if revision == request { invalidate(error.localizedDescription) } + } + } + } + private func finishCommand(_ snapshot: VCCMachineSnapshot?, connection conn: Attachment) { + commanding = false + guard connection?.artifact.id == conn.artifact.id else { return } + guard let snapshot, snapshot.errorMessage == nil else { + invalidate(snapshot?.errorMessage ?? machine.fileError ?? "The machine changed. Run again to reconnect.") + return + } + connection?.expected = snapshot + paused = snapshot.state == .paused; refresh() + } + + func refresh() { + if let build = artifact, document.directory != nil, !checking, !working, !commanding, Date() >= nextCheck { + nextCheck = Date().addingTimeInterval(2); checking = true + let doc = document, request = revision + Task { + let copy = await Task.detached { try? doc.snapshot() }.value + checking = false + if revision == request, activeID == doc.id, artifact?.id == build.id, copy != build.snapshot { + invalidate("A project input changed on disk. Reload any open changed file and assemble again.") + } + } + } + guard let conn = connection, conn.document == activeID, !reading, !commanding else { return } + if machine.state == .running { + guard machine.assemblyAttached, machine.basicDebug.generation == conn.expected.generation, + machine.assemblyProgramRevision == conn.expected.debuggerProgramRevision, + machine.assemblyMappingFingerprint == conn.expected.debuggerMappingFingerprint else { + invalidate("The running program or memory mapping changed. Run again to reconnect."); return + } + if paused { paused = false } + if executionLine != nil { executionLine = nil } + if execution != "Running" { execution = "Running" } + return + } + reading = true + machine.readDebugger(address: 0, followPC: true, memoryAddress: 0x0400) { [weak self] capture in + guard let self else { return }; reading = false + guard connection?.artifact.id == conn.artifact.id, activeID == conn.document, let capture else { return } + let snapshot = capture.machine + guard snapshot.generation == conn.expected.generation, snapshot.debuggerProgramRevision == conn.expected.debuggerProgramRevision, + snapshot.debuggerMappingFingerprint == conn.expected.debuggerMappingFingerprint, + snapshot.debuggerAssemblyAttached else { + invalidate("Machine program or memory mapping changed. Run again to reconnect source debugging."); return + } + connection?.expected = snapshot + let stopped = snapshot.state == .paused + if paused != stopped { paused = stopped } + guard stopped else { + if executionLine != nil { executionLine = nil } + if execution != "Running" { execution = "Running" }; return + } + let memory = capture.logicalMemory, available = capture.logicalMemoryAvailable + for (address, bytes) in conn.guards { + let start = Int(address), end = start + bytes.count + guard end <= memory.count, end <= available.count, available[start..> 8) } + let cc = capture.registers["CC"]?.uint8Value + let reg = String(format: "PC $%04X", pc) + (a.map { String(format: " · A $%02X", $0) } ?? "") + (cc.map { String(format: " · CC $%02X", $0) } ?? "") + let status = (next.map { "Paused · \($0.path):\($0.line)" } ?? "Paused · no verified source line") + " · " + reg + if execution != status { execution = status } + if executionLine != next { + executionLine = next + if let next { selectFile(next.path, line: next.line) } + } + } + } +} diff --git a/platforms/macos/App/AssemblyDevelopmentView.swift b/platforms/macos/App/AssemblyDevelopmentView.swift new file mode 100644 index 0000000..5e669d8 --- /dev/null +++ b/platforms/macos/App/AssemblyDevelopmentView.swift @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import SwiftUI +import UniformTypeIdentifiers + +struct AssemblyDevelopmentView: View { + @ObservedObject var model: AssemblyDevelopmentModel + @Environment(\.openWindow) private var openWindow + @StateObject private var finder = SourceFind() + @StateObject private var pool = AssemblyEditorPool() + @State private var details = false + @State private var detailPane = "Listing" + @State private var diskExport = false + @State private var diskName = "FIRST" + @State private var diskBoot = false + @State private var settingsHelp = false + private var locked: Bool { model.working || model.commanding } + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + HStack { + Label("Assembly Development", systemImage: "cpu").font(.title2.bold()) + Spacer() + Button(action: reference) { Label("Quick Reference", systemImage: "book.closed") } + .keyboardShortcut("?", modifiers: [.command, .option]).accessibilityIdentifier("assembly-reference") + Button { openWindow(id: "debugger") } label: { Label("Debugger", systemImage: "ladybug") } + .help("Inspect registers, flags, memory, trace and Graphics Preview") + }.padding(.horizontal, 14).padding(.vertical, 10) + Divider() + HStack { + Menu("File") { + Button("New Source") { model.openExample(title: "Untitled", source: "", target6309: false) } + Button(AssemblyWorkspaceDocument.starterTitle) { + model.openExample(title: AssemblyWorkspaceDocument.starterTitle, source: AssemblyWorkspaceDocument.starterSource, target6309: false) + } + Divider() + Button("Local Assistant Access…") { MCPAssembly.shared.show(model, editors: pool) } + Button("Open Source…") { open(folder: false) } + Button("Open Project Folder…") { open(folder: true) } + Button("Project Settings…") { settingsHelp = true }.disabled(!model.document.isProject) + Divider() + Button("Save Source", action: save).keyboardShortcut("s") + Button("Save a Copy…") { saveCopy() } + Button("Reload from Disk") { model.reload() }.disabled(model.document.directory == nil) + Button("Close Document") { model.closeDocument() } + }.fixedSize().accessibilityIdentifier("assembly-file") + Picker("Document", selection: Binding(get: { model.activeID }, set: model.select)) { + ForEach(model.documents) { doc in + Text(doc.title + (doc.buffers.contains(where: \.dirty) ? " •" : "")).tag(doc.id) + } + }.labelsHidden().accessibilityLabel("Assembly document").accessibilityIdentifier("assembly-document") + Spacer() + Picker("Target", selection: Binding(get: { model.cpu }, set: model.setCPU)) { + Text("MC6809").tag(AssemblyCPU.mc6809) + Text("HD6309").tag(AssemblyCPU.hd6309) + }.fixedSize().accessibilityIdentifier("assembly-cpu") + }.disabled(model.commanding).padding(.horizontal, 14).padding(.vertical, 6) + HStack(spacing: 8) { + Button { model.perform(.assemble) } label: { Label("Assemble", systemImage: "hammer") } + .keyboardShortcut("b").accessibilityIdentifier("assembly-assemble").disabled(locked) + Button { model.perform(.run) } label: { Label("Run", systemImage: "play.fill") } + .keyboardShortcut("r").buttonStyle(.borderedProminent).accessibilityIdentifier("assembly-run").disabled(locked) + Button { model.perform(.debug) } label: { Label("Debug from Entry", systemImage: "playpause") } + .accessibilityIdentifier("assembly-debug-entry").disabled(locked) + if model.working && !model.commanding { + Button("Cancel") { model.cancelBuild() }.accessibilityIdentifier("assembly-cancel") + } + Spacer() + Menu("Export") { + Button("Export Binary…") { export(disk: false) }.accessibilityIdentifier("assembly-export-binary") + Button("Export Disk Image…") { diskBoot = false; diskExport = true }.accessibilityIdentifier("assembly-export-disk") + }.disabled(locked).fixedSize().accessibilityIdentifier("assembly-export") + }.padding(.horizontal, 14).padding(.vertical, 5) + Divider() + HStack(spacing: 8) { + if model.document.paths.count > 1 || model.document.isProject { + Menu(model.buffer.path) { + ForEach(model.document.paths, id: \.self) { path in Button(path) { model.selectFile(path) } } + }.fixedSize().accessibilityLabel("Project files") + } else { Label(model.buffer.path, systemImage: "doc.text") } + Text("Line \(model.cursorLine)").foregroundStyle(.secondary) + Spacer() + SourceFindButton(finder: finder) + Menu("Labels") { + Button("Go to Definition", action: model.goToDefinition) + Divider() + ForEach(Array(model.labelLocations.prefix(500).enumerated()), id: \.offset) { _, item in + Button("\(item.0) · \(item.1.path):\(item.1.line)") { model.selectFile(item.1.path, line: item.1.line) } + } + }.fixedSize() + Button { pool.complete(model.buffer.id) } label: { Label("Complete", systemImage: "text.badge.plus") } + .help("Complete at the caret (Control–Space)").accessibilityIdentifier("assembly-complete") + Button { model.toggleBreakpoint() } label: { + Label(model.document.breakpoints.contains(.init(path: model.buffer.path, line: model.cursorLine)) ? "Remove Stop" : "Set Stop", + systemImage: "record.circle") + }.disabled(locked).help("Toggle a breakpoint before this source instruction").accessibilityIdentifier("assembly-breakpoint") + if !model.document.breakpoints.isEmpty { + Menu("Stops (\(model.document.breakpoints.count))") { + Button("Clear All Stops", action: model.clearStops) + Divider() + ForEach(model.document.breakpoints.sorted { ($0.path, $0.line) < ($1.path, $1.line) }, id: \.self) { stop in + Button("\(stop.path):\(stop.line)") { model.selectFile(stop.path, line: stop.line) } + } + }.fixedSize() + } + }.font(.callout).padding(.horizontal, 14).padding(.vertical, 5) + SourceFindBar(finder: finder, source: model.buffer.text, readOnly: false) + AssemblyEditor(finder: finder, model: model, pool: pool, lookup: reference).frame(minHeight: 130) + if model.document.title == AssemblyWorkspaceDocument.starterTitle { + Text("Run, then press 1 for Earth or 2 for Mars in the emulator. After the greeting, you can type BASIC commands at the OK prompt.") + .font(.callout).foregroundStyle(.secondary).padding(.horizontal, 14).padding(.top, 6) + } else if model.document.title == "First Program — Change a Screen Cell" { + Text("In Disk BASIC’s 32-column display, this is POKE &H0400,&H8F. Step LDA to change A, then STA to change the first screen cell.") + .font(.callout).foregroundStyle(.secondary).padding(.horizontal, 14).padding(.top, 6) + } + HStack { + Button("Pause", action: model.pause).disabled(!model.attached || model.paused || locked).accessibilityIdentifier("assembly-pause") + Button("Step") { model.control(step: true) }.disabled(!model.paused || locked).accessibilityIdentifier("assembly-step") + Button("Continue") { model.control(step: false) }.disabled(!model.paused || locked).accessibilityIdentifier("assembly-continue") + Text(model.execution).font(.system(.caption, design: .monospaced)).textSelection(.enabled) + .accessibilityIdentifier("assembly-execution") + Spacer() + }.padding(.horizontal, 14).padding(.vertical, 7) + Divider() + Text(model.message).font(.callout).textSelection(.enabled).accessibilityIdentifier("assembly-status") + .padding(.horizontal, 14).padding(.top, 7) + if !model.diagnostics.isEmpty { + ScrollView { + VStack(alignment: .leading) { + ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, item in + Button("\(item.path):\(item.line) \(item.message)") { model.selectFile(item.path, line: item.line) } + .buttonStyle(.link).accessibilityIdentifier("assembly-diagnostic") + } + }.frame(maxWidth: .infinity, alignment: .leading) + }.frame(maxHeight: 74).padding(.horizontal, 14) + } + DisclosureGroup("Build details", isExpanded: $details) { + Picker("Build details", selection: $detailPane) { + ForEach(["Listing", "Symbols", "Log"], id: \.self) { Text($0) } + }.pickerStyle(.segmented).labelsHidden().frame(maxWidth: 320) + ScrollView([.vertical, .horizontal]) { + Text(detailPane == "Log" ? model.buildLog : (detailPane == "Listing" ? model.artifact?.listing : model.artifact?.symbols) ?? "") + .font(.system(.caption, design: .monospaced)).textSelection(.enabled) + }.frame(maxWidth: .infinity, minHeight: 45, maxHeight: 150, alignment: .topLeading) + }.padding(.horizontal, 14).padding(.vertical, 7) + }.frame(minWidth: 690, minHeight: 420) + .focusedSceneValue(\.sourceFind, finder) + .onDisappear { MCPAssembly.shared.close(for: model) } + .onChange(of: model.displayRequest) { _, _ in + openWindow(id: "machine") + DispatchQueue.main.async { model.machine.focusDisplay() } + } + .onChange(of: model.documents.map { $0.buffers.map(\.id) }) { _, ids in pool.forget(except: Set(ids.joined())) } + .task { + while !Task.isCancelled { + model.refresh() + try? await Task.sleep(nanoseconds: 350_000_000) + } + } + .sheet(isPresented: $diskExport) { + VStack(alignment: .leading, spacing: 14) { + Text("Export Disk Image").font(.headline) + TextField("Disk BASIC filename", text: $diskName).accessibilityIdentifier("assembly-disk-name") + Text("Use 1–8 letters or digits, without an extension.").font(.caption).foregroundStyle(.secondary) + Toggle("Install DOS bootloader", isOn: $diskBoot).accessibilityIdentifier("assembly-export-dos") + if let name = BASICExportName.normalized(diskName) { + Text(DevelopmentDiskProgram.binary(name).instructions(dos: diskBoot)) + .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("assembly-export-commands") + } + HStack { + Spacer(); Button("Cancel") { diskExport = false } + Button("Choose Location…") { + diskExport = false; DispatchQueue.main.async { export(disk: true) } + }.keyboardShortcut(.defaultAction).disabled(BASICExportName.normalized(diskName) == nil) + } + }.padding(20).frame(width: 440) + } + .sheet(isPresented: $settingsHelp) { + VStack(alignment: .leading, spacing: 12) { + Text("Project Settings").font(.title2.bold()) + Text("Edit vccplus-assembly.json in the source editor. Assemble validates and uses your changes. Save writes them to the project.") + Text("Set main to the entry source. For linked objects, add modules (additional source paths) and linkScript (the LWLINK script path).") + Text("To run an existing Makefile, set makefile, target and binary to the recipe, target name and output path. Each fresh build asks before executing the recipe.") + HStack { + Spacer(); Button("Cancel") { settingsHelp = false } + Button("Edit Settings") { settingsHelp = false; model.editSettings() }.keyboardShortcut(.defaultAction) + } + }.padding(20).frame(width: 460) + } + } + private func reference() { + let extended = model.cpu == .hd6309 + let term = AssemblyReference.shared.topic(in: model.buffer.text, at: model.cursor, target6309: extended) + AssemblyReferenceSelection.shared.show(term ?? "", target6309: extended) + openWindow(id: "assembly-reference") + } + private func open(folder: Bool) { + let panel = NSOpenPanel(); panel.canChooseDirectories = folder; panel.canChooseFiles = !folder + panel.allowsMultipleSelection = false + if !folder { panel.allowedContentTypes = ["asm", "s", "lwasm", "inc"].compactMap { UTType(filenameExtension: $0) } } + guard panel.runModal() == .OK, let url = panel.url else { return } + model.open(url, folder: folder) + } + private func save() { if model.document.directory == nil { saveCopy() } else { model.save() } } + private func saveCopy() { + let panel = NSSavePanel() + panel.nameFieldStringValue = (model.buffer.path as NSString).lastPathComponent + guard panel.runModal() == .OK, let url = panel.url else { return }; model.save(to: url) + } + private func export(disk: Bool) { + let panel = NSSavePanel() + let name = BASICExportName.normalized(diskName) ?? "FIRST" + if disk { panel.message = DevelopmentDiskProgram.binary(name).instructions(dos: diskBoot) } + panel.nameFieldStringValue = disk ? "\(name).dsk" : (model.document.mainPath as NSString).lastPathComponent.components(separatedBy: ".").dropLast().joined(separator: ".") + ".bin" + guard panel.runModal() == .OK, let url = panel.url else { return } + model.perform(disk ? .exportDisk(url, name, dosBoot: diskBoot) : .exportBinary(url)) + } +} diff --git a/platforms/macos/App/AssemblyEditor.swift b/platforms/macos/App/AssemblyEditor.swift new file mode 100644 index 0000000..77cb589 --- /dev/null +++ b/platforms/macos/App/AssemblyEditor.swift @@ -0,0 +1,251 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import SwiftUI + +enum AssemblyEditorSyntax { + enum Kind { case label, mnemonic, directive, literal, operand, comment } + struct Token { let range: NSRange; let kind: Kind } + private static let words = try! NSRegularExpression(pattern: + #"(?:"[^"\r\n]*"|'[^'\r\n]*'|;[^\r\n]*|\$[0-9A-Fa-f]+|%[01]+|[A-Za-z_.@?][A-Za-z0-9_.$@?]*:?|\d+)"#) + static func tokens(in line: String, vocabulary: Set) -> [Token] { + let ns = line as NSString + if line.trimmingCharacters(in: .whitespaces).hasPrefix("*") { + return [.init(range: NSRange(location: 0, length: ns.length), kind: .comment)] + } + var opcodeSeen = false, labelSeen = false + return words.matches(in: line, range: NSRange(location: 0, length: ns.length)).map { match in + let word = ns.substring(with: match.range) + let kind: Kind + if word.hasPrefix(";") { kind = .comment } + else if ["\"", "'", "$", "%"].contains(where: { word.hasPrefix($0) }) || word.first?.isNumber == true { kind = .literal } + else if !opcodeSeen && !labelSeen && (word.hasSuffix(":") || match.range.location == 0) { + kind = .label + labelSeen = true + } else if !opcodeSeen { + opcodeSeen = true + let upper = word.uppercased() + kind = AssemblyReference.shared.isDirective(upper) ? .directive : (vocabulary.contains(upper) ? .mnemonic : .operand) + } else { kind = .operand } + return Token(range: match.range, kind: kind) + } + } + + static func token(in source: String, offset: Int, vocabulary: Set) -> String? { + let text = source as NSString + let pos = min(max(0, offset), text.length) + let line = text.lineRange(for: NSRange(location: pos, length: 0)) + let contents = text.substring(with: line) as NSString + let local = pos - line.location + guard let token = tokens(in: contents as String, vocabulary: vocabulary).first(where: { + NSLocationInRange(local, $0.range) || local == NSMaxRange($0.range) + }), [.operand, .mnemonic, .label, .directive].contains(token.kind) else { return nil } + return contents.substring(with: token.range).trimmingCharacters(in: CharacterSet(charactersIn: ":")) + } + + static func labels(in text: String, vocabulary: Set) -> [(String, Int)] { + text.components(separatedBy: "\n").enumerated().compactMap { index, line in + guard let label = tokens(in: line, vocabulary: vocabulary).first, label.kind == .label else { return nil } + return ((line as NSString).substring(with: label.range).trimmingCharacters(in: CharacterSet(charactersIn: ":")), index + 1) + } + } +} + +@MainActor +private final class AssemblyTextView: NSTextView, SourceFindEditor { + weak var sourceFind: SourceFind? + let documentUndo = UndoManager() + override var undoManager: UndoManager? { documentUndo } + var lookup: (() -> Void)? + var definition: (() -> Void)? + var target6309 = false + override func performKeyEquivalent(with event: NSEvent) -> Bool { + let modifiers = event.modifierFlags.intersection([.command, .control, .option, .shift]) + if event.keyCode == 49 && modifiers == [.control] { complete(nil); return true } + if event.charactersIgnoringModifiers == "j", modifiers == [.command, .control] { definition?(); return true } + return super.performKeyEquivalent(with: event) + } + override func menu(for event: NSEvent) -> NSMenu? { + guard let menu = super.menu(for: event)?.copy() as? NSMenu else { return nil } + menu.addItem(.separator()) + for (title, action) in [("Look Up in Assembly Quick Reference", #selector(lookUpInstruction)), + ("Go to Label Definition", #selector(goToLabel)), + ("Complete", #selector(complete(_:)))] { + let item = NSMenuItem(title: title, action: action, keyEquivalent: "") + item.target = self + menu.addItem(item) + } + return menu + } + @objc private func lookUpInstruction() { lookup?() } + @objc private func goToLabel() { definition?() } + override func cancelOperation(_ sender: Any?) { + if sourceFind?.cancel(from: self) != true { + _ = nextResponder?.tryToPerform(#selector(NSResponder.cancelOperation(_:)), with: sender) + } + } + override func completions(forPartialWordRange charRange: NSRange, + indexOfSelectedItem index: UnsafeMutablePointer?) -> [String]? { + guard selectedRange().length == 0, !hasMarkedText() else { return [] } + index?.pointee = -1 + return AssemblyReference.shared.completions(in: string, at: selectedRange().location, target6309: target6309) + } + override func insertCompletion(_ word: String, forPartialWordRange charRange: NSRange, movement: Int, isFinal flag: Bool) { + guard flag, movement != NSTextMovement.cancel.rawValue, !hasMarkedText(), + selectedRange().length == 0, NSMaxRange(charRange) == selectedRange().location, + completions(forPartialWordRange: charRange, indexOfSelectedItem: nil)?.contains(word) == true else { return } + breakUndoCoalescing() + insertText(word, replacementRange: charRange) + breakUndoCoalescing() + undoManager?.setActionName("Complete Assembly") + } +} + +@MainActor +final class AssemblyEditorPool: ObservableObject { + fileprivate var editors: [UUID: AssemblyTextView] = [:] + func complete(_ id: UUID) { + guard let editor = editors[id] else { return } + editor.window?.makeFirstResponder(editor); editor.complete(nil) + } + func canReplace(_ buffers: [AssemblyBuffer]) -> Bool { + buffers.allSatisfy { buffer in + guard let editor = editors[buffer.id], editor.delegate != nil else { return true } + return !editor.hasMarkedText() && editor.string.utf8.elementsEqual(buffer.text.utf8) + } + } + func replaceReviewedLine(in buffer: AssemblyBuffer, range: NSRange, with replacement: String) -> Bool { + guard let editor = editors[buffer.id], editor.delegate != nil, !editor.hasMarkedText(), + editor.string.utf8.elementsEqual(buffer.text.utf8) else { return false } + editor.breakUndoCoalescing() + editor.insertText(replacement, replacementRange: range) + editor.breakUndoCoalescing() + editor.documentUndo.setActionName("Assistant Assembly Edit") + return true + } + func forget(except ids: Set) { editors = editors.filter { ids.contains($0.key) } } +} + +struct AssemblyEditor: NSViewRepresentable { + let finder: SourceFind + @ObservedObject var model: AssemblyDevelopmentModel + let pool: AssemblyEditorPool + let lookup: () -> Void + func makeCoordinator() -> Coordinator { Coordinator(model: model) } + func makeNSView(context: Context) -> NSScrollView { + let scroll = NSScrollView() + scroll.hasVerticalScroller = true + scroll.borderType = .bezelBorder + scroll.autohidesScrollers = true + return scroll + } + func updateNSView(_ scroll: NSScrollView, context: Context) { + let doc = model.buffer + let editor: AssemblyTextView + let coord = context.coordinator + if let existing = pool.editors[doc.id] { editor = existing } + else { + editor = AssemblyTextView(frame: .zero) + editor.isRichText = false + editor.isAutomaticQuoteSubstitutionEnabled = false + editor.isAutomaticDashSubstitutionEnabled = false + editor.isAutomaticTextReplacementEnabled = false + editor.isAutomaticSpellingCorrectionEnabled = false + editor.isContinuousSpellCheckingEnabled = false + editor.allowsUndo = true + editor.font = .monospacedSystemFont(ofSize: 13, weight: .regular) + editor.textContainerInset = NSSize(width: 8, height: 8) + editor.isVerticallyResizable = true; editor.autoresizingMask = [.width] + editor.textContainer?.widthTracksTextView = true + editor.setAccessibilityLabel("Assembly source") + editor.setAccessibilityIdentifier("assembly-source") + pool.editors[doc.id] = editor + } + finder.editor = editor + let changedDocument = scroll.documentView !== editor + if changedDocument { + if let previous = scroll.documentView as? AssemblyTextView { + previous.delegate = nil; previous.lookup = nil; previous.definition = nil + } + scroll.documentView = editor + editor.frame.size.width = scroll.contentSize.width + coord.bufferID = doc.id + } + coord.updating = true + defer { coord.updating = false } + let changedSource = !editor.string.utf8.elementsEqual(doc.text.utf8) + let target = model.cpu == .hd6309 + let changedTarget = editor.target6309 != target + editor.target6309 = target + if changedSource { editor.string = doc.text; editor.documentUndo.removeAllActions() } + editor.delegate = coord + editor.lookup = lookup; editor.definition = model.goToDefinition + if changedDocument || changedSource || changedTarget { coord.color(editor) } + if let request = model.selection, request.buffer == doc.id, request.id != coord.lastSelection { + coord.lastSelection = request.id + let range = NSIntersectionRange(request.range, NSRange(location: 0, length: editor.string.utf16.count)) + editor.setSelectedRange(range); editor.scrollRangeToVisible(range) + } + let active = model.executionLine + if changedDocument || changedSource || coord.markedLine != active { + coord.markedLine = active + let length = editor.string.utf16.count + editor.layoutManager?.removeTemporaryAttribute(.backgroundColor, forCharacterRange: NSRange(location: 0, length: length)) + if let active, active.path == doc.path, let range = AssemblyDevelopmentModel.lineRange(active.line, text: doc.text) { + editor.layoutManager?.addTemporaryAttribute(.backgroundColor, value: NSColor.systemGreen.withAlphaComponent(0.22), forCharacterRange: range) + } + } + } + static func dismantleNSView(_ scroll: NSScrollView, coordinator: Coordinator) { + if let editor = scroll.documentView as? AssemblyTextView { + editor.delegate = nil; editor.lookup = nil; editor.definition = nil + } + } + @MainActor final class Coordinator: NSObject, NSTextViewDelegate { + let model: AssemblyDevelopmentModel + var updating = false + var bufferID: UUID? + var lastSelection: UUID? + var markedLine: AssemblyDevelopmentModel.SourceLine? + init(model: AssemblyDevelopmentModel) { self.model = model } + private var changedCharacters: NSRange? + func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool { + changedCharacters = replacementString.map { NSRange(location: affectedCharRange.location, length: $0.utf16.count) } + return true + } + func textDidChange(_ notification: Notification) { + guard !updating, let view = notification.object as? AssemblyTextView, bufferID == model.buffer.id else { return } + model.edit(view.string) + color(view, changed: changedCharacters) + changedCharacters = nil + } + func textViewDidChangeSelection(_ notification: Notification) { + guard !updating, let view = notification.object as? NSTextView, bufferID == model.buffer.id else { return } + model.moveCursor(view.selectedRange().location) + } + fileprivate func color(_ editor: AssemblyTextView, changed: NSRange? = nil) { + let ns = editor.string as NSString + let layout = editor.layoutManager + let range = changed.flatMap { NSMaxRange($0) <= ns.length ? ns.lineRange(for: $0) : nil } ?? NSRange(location: 0, length: ns.length) + layout?.removeTemporaryAttribute(.foregroundColor, forCharacterRange: range) + let words = AssemblyReference.shared.vocabulary(target6309: editor.target6309) + var pos = range.location + while pos < NSMaxRange(range) { + let row = ns.lineRange(for: NSRange(location: pos, length: 0)) + for token in AssemblyEditorSyntax.tokens(in: ns.substring(with: row), vocabulary: words) { + let color: NSColor + switch token.kind { + case .label: color = .systemPurple + case .mnemonic: color = .systemBlue + case .directive: color = .systemTeal + case .literal: color = .systemOrange + case .operand: color = .labelColor + case .comment: color = .secondaryLabelColor + } + layout?.addTemporaryAttribute(.foregroundColor, value: color, + forCharacterRange: NSRange(location: pos + token.range.location, length: token.range.length)) + } + pos = NSMaxRange(row) + } + } + } +} diff --git a/platforms/macos/App/AssemblyProject.swift b/platforms/macos/App/AssemblyProject.swift new file mode 100644 index 0000000..975c13e --- /dev/null +++ b/platforms/macos/App/AssemblyProject.swift @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +enum AssemblyCPU: String, CaseIterable, Codable, Sendable { + case mc6809 = "6809" + case hd6309 = "6309" +} + +struct AssemblyProjectSnapshot: Equatable, Sendable { + static let configurationFilename = "vccplus-assembly.json" + + struct Settings: Codable, Equatable, Sendable { + var main: String? + var modules: [String]? + var linkScript: String? + var makefile: String? + var target: String? + var binary: String? + } + + let mainPath: String + let files: [String: Data] + let cpu: AssemblyCPU + let settings: Settings + + static func single(source: String, path: String = "main.asm", cpu: AssemblyCPU = .mc6809) -> Self { + Self(mainPath: path, files: [path: Data(source.utf8)], cpu: cpu, settings: Settings()) + } + + static func read(directory: URL, mainPath: String = "main.asm", overlays: [String: String] = [:], + cpu: AssemblyCPU = .mc6809) throws -> Self { + var files = try CMOCProject.files(in: directory) + for (path, text) in overlays { + try CMOCProject.validateRelativePath(path) + files[path] = try CMOCProject.sourceBytes(text) + } + let settings = try files[configurationFilename].map { + try JSONDecoder().decode(Settings.self, from: $0) + } ?? Settings() + let entry = settings.main ?? mainPath + if let binary = settings.binary { files.removeValue(forKey: binary) } + let snapshot = Self(mainPath: entry, files: files, cpu: cpu, settings: settings) + try snapshot.validate() + return snapshot + } + + /// A loose source may live in Documents or Downloads. Only follow its literal + /// include chain; never enumerate or copy unrelated neighboring files. + static func readSource(at url: URL, overlays: [String: String] = [:], cpu: AssemblyCPU = .mc6809) throws -> Self { + let root = try CMOCProject.physicalURL(url.deletingLastPathComponent()).standardizedFileURL + let main = url.lastPathComponent + var files: [String: Data] = [:], scanned = Set(), total = 0 + var pending = [(path: main, binary: false)] + let directive = try NSRegularExpression(pattern: + #"(?i)^(?:[^\s*;]+\s+|\s+)(include|incl|use|lib|includebin)\s+(?:"([^"]+)"|'([^']+)'|([^\s,;]+))"#) + while let input = pending.popLast() { + try Task.checkCancellation() + try CMOCProject.validateRelativePath(input.path) + let file = root.appendingPathComponent(input.path) + if files[input.path] == nil { + let data: Data + if let overlay = overlays[input.path] { + data = try CMOCProject.sourceBytes(overlay) + } else { + guard file.standardizedFileURL.path == file.resolvingSymlinksInPath().standardizedFileURL.path else { + throw AssemblyBuildFailure("Copy linked inputs into the source folder before assembling.") + } + guard FileManager.default.fileExists(atPath: file.path) || input.path == main else { continue } + data = try DevelopmentBuildTools.readFile(file, limit: CMOCProject.maximumFileBytes) + } + total += data.count + guard total <= CMOCProject.maximumProjectBytes, files.count < 20_000 else { + throw AssemblyBuildFailure("The included source files exceed the project snapshot limit.") + } + files[input.path] = data + } + guard !input.binary, scanned.insert(input.path).inserted, let data = files[input.path] else { continue } + guard data.count <= CMOCProject.maximumSourceBytes, let source = String(data: data, encoding: .utf8) else { + throw AssemblyBuildFailure("Choose UTF-8 source files of at most 1 MB.") + } + for line in source.components(separatedBy: .newlines) { + let ns = line as NSString + guard let match = directive.firstMatch(in: line, range: NSRange(location: 0, length: ns.length)), + let index = (2...4).first(where: { match.range(at: $0).location != NSNotFound }) else { continue } + let operand = ns.substring(with: match.range(at: index)) + let included = file.deletingLastPathComponent().appendingPathComponent(operand).standardizedFileURL + guard !operand.hasPrefix("/"), included.path.hasPrefix(root.path + "/") else { + throw AssemblyBuildFailure("Keep assembly includes inside the source folder: " + operand) + } + var relative = String(included.path.dropFirst(root.path.count + 1)) + // Match LWASM's search order: the including file's folder first, + // then the root supplied by -I. A buffer may exist before saving. + if overlays[relative] == nil && !FileManager.default.fileExists(atPath: included.path) { + let fallback = root.appendingPathComponent(operand).standardizedFileURL + if fallback.path.hasPrefix(root.path + "/") { + relative = String(fallback.path.dropFirst(root.path.count + 1)) + } + } + pending.append((relative, ns.substring(with: match.range(at: 1)).lowercased() == "includebin")) + } + } + let snapshot = Self(mainPath: main, files: files, cpu: cpu, settings: Settings()) + try snapshot.validate() + return snapshot + } + + func validate() throws { + let modules = [mainPath] + (settings.modules ?? []) + guard modules.count <= 128, Set(modules).count == modules.count else { + throw AssemblyBuildFailure("Use up to 128 distinct assembly modules.") + } + for path in files.keys { try CMOCProject.validateRelativePath(path) } + for path in modules + [settings.makefile, settings.linkScript].compactMap({ $0 }) { + try CMOCProject.validateRelativePath(path) + guard files[path] != nil else { throw AssemblyBuildFailure("The project is missing " + path) } + } + for module in modules { + guard let data = files[module], data.count <= CMOCProject.maximumSourceBytes, + !data.contains(0), String(data: data, encoding: .utf8) != nil else { + throw AssemblyBuildFailure("Choose UTF-8 assembly modules of at most 1 MB without NUL characters.") + } + } + if let makefile = settings.makefile { + guard settings.modules == nil, settings.linkScript == nil, let binary = settings.binary, + binary.lowercased().hasSuffix(".bin"), ![mainPath, makefile].contains(binary) else { + throw AssemblyBuildFailure("For custom Make, set makefile, target and binary. Use modules and linkScript for native linked builds.") + } + try CMOCProject.validateRelativePath(binary) + try CMOCProjectConfiguration.validateTarget(settings.target ?? "all") + } else if settings.binary != nil || settings.target != nil { + throw AssemblyBuildFailure("A custom binary path or target requires a Makefile.") + } + if !(settings.modules ?? []).isEmpty, settings.linkScript == nil { + throw AssemblyBuildFailure("Set linkScript to a project-relative LWLINK script with a load address and entry.") + } + } +} diff --git a/platforms/macos/App/AssemblyReference.swift b/platforms/macos/App/AssemblyReference.swift new file mode 100644 index 0000000..7f0a17f --- /dev/null +++ b/platforms/macos/App/AssemblyReference.swift @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +enum AssemblyReferenceCategory: String, CaseIterable { + case instructions = "Instructions" + case registers = "Registers & Flags" + case addressing = "Addressing Modes" + case directives = "LWASM Directives" + case examples = "CoCo Examples" + case dialect = "Dialect & Compatibility" +} + +enum AssemblyOperandForm { + case inherent, value, memory, indexed, relative, immediate, pair, stack, bit, maskMemory, transfer, directive, topic + + var description: String { + switch self { + case .inherent: return "No operand" + case .value: return "#literal · address" + case .memory: return "address" + case .indexed: return "offset,index" + case .relative: return "target label" + case .immediate: return "#mask" + case .pair: return "source register,destination register" + case .stack: return "register[,register…] · #mask" + case .bit: return "A|B|CC,source bit,destination bit,direct address" + case .maskMemory: return "#mask,address · #mask,offset,X" + case .transfer: return "r+,r+ · r-,r- · r+,r · r,r+" + case .directive, .topic: return "" + } + } +} + +struct AssemblyReferenceEntry: Identifiable { + let id: String + let name: String + let category: AssemblyReferenceCategory + let only6309: Bool + let aliases: [String] + let form: AssemblyOperandForm + let syntax: String + let operation: String + let flags: String + let detail: String + let links: [String] + let citations: [String] + let terms: [String] + let example: String? + + init(_ name: String, _ category: AssemblyReferenceCategory, only6309: Bool = false, + aliases: [String] = [], form: AssemblyOperandForm = .topic, syntax: String = "", + operation: String, flags: String = "", detail: String = "", links: [String] = [], + citations: [String], terms: [String] = [], example: String? = nil) { + self.name = name + self.category = category + self.id = "\(category).\(name.lowercased().replacingOccurrences(of: " ", with: "-"))" + self.only6309 = only6309 + self.aliases = aliases + self.form = form + self.syntax = syntax.isEmpty ? form.description : syntax + self.operation = operation + self.flags = flags + self.detail = detail + self.links = links + self.citations = citations + self.terms = terms + self.example = example + } +} + +struct AssemblyReferenceExampleRequest: Codable, Hashable { + var id = UUID() + let title: String + let source: String + let target6309: Bool +} + +struct AssemblyReference { + static let shared = AssemblyReference() + let entries: [AssemblyReferenceEntry] + private let byTerm: [String: AssemblyReferenceEntry] + private let commonWords: Set + private let allWords: Set + + init() { + entries = (Self.instructions() + Self.topics()).sorted { $0.name < $1.name } + var index: [String: AssemblyReferenceEntry] = [:] + var common = Set(), all = Set() + for entry in entries { + for word in [entry.name] + entry.aliases { + index[word.uppercased()] = entry + if entry.category == .instructions || entry.category == .directives { + all.insert(word.uppercased()) + if !entry.only6309 { common.insert(word.uppercased()) } + } + } + index[entry.id.uppercased()] = entry + } + byTerm = index + commonWords = common + allWords = all + } + + func entry(_ term: String) -> AssemblyReferenceEntry? { byTerm[term.uppercased()] } + + func vocabulary(target6309: Bool) -> Set { target6309 ? allWords : commonWords } + + func search(_ query: String, target6309: Bool?, category: AssemblyReferenceCategory?) -> [AssemblyReferenceEntry] { + let words = query.lowercased().split(whereSeparator: \.isWhitespace) + let result = entries.filter { entry in + guard (target6309 != false || !entry.only6309), category == nil || entry.category == category else { return false } + let fields = [entry.name, entry.operation, entry.flags, entry.detail] + entry.aliases + entry.terms + let haystack = fields.joined(separator: " ").lowercased() + return words.allSatisfy { haystack.contains($0) } + } + if let exact = entry(query), let i = result.firstIndex(where: { $0.id == exact.id }) { + var ranked = result + ranked.insert(ranked.remove(at: i), at: 0) + return ranked + } + return result + } +} diff --git a/platforms/macos/App/AssemblyReferenceContext.swift b/platforms/macos/App/AssemblyReferenceContext.swift new file mode 100644 index 0000000..ad59818 --- /dev/null +++ b/platforms/macos/App/AssemblyReferenceContext.swift @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +extension AssemblyReference { + func isDirective(_ word: String) -> Bool { entry(word)?.category == .directives } + + private struct LineFields { + let opcode: String + let operand: String + let atMnemonic: Bool + let partial: String + } + + /// LWASM's first column is the optional label field. NSTextView supplies UTF-16 offsets. + private func fields(_ source: String, _ offset: Int) -> LineFields? { + let text = source as NSString + guard offset >= 0, offset <= text.length else { return nil } + let range = text.lineRange(for: NSRange(location: offset, length: 0)) + let line = text.substring(with: range) as NSString + let caret = offset - range.location + let before = line.substring(to: caret) + let trimmed = before.drop(while: \.isWhitespace) + guard !trimmed.hasPrefix("*"), !trimmed.hasPrefix(";") else { return nil } + // Only a prefix of the operand is needed. Never suggest into a string or a comment. + guard !before.contains(";"), !before.contains("\""), !before.contains("'") else { return nil } + func space(_ i: Int) -> Bool { [9,10,13,32].contains(line.character(at: i)) } + var i = 0 + if i < line.length, !space(i) { + while i < line.length && !space(i) { i += 1 } + if caret <= i { return nil } + } + while i < line.length && space(i) { i += 1 } + let start = i + while i < line.length && !space(i) && line.character(at: i) != 59 { i += 1 } + let opcode = line.substring(with: NSRange(location: start, length: i - start)).uppercased() + if caret <= i { + let length = max(0, caret - start) + return .init(opcode: opcode, operand: "", atMnemonic: true, + partial: line.substring(with: NSRange(location: start, length: length)).uppercased()) + } + let tail = (before as NSString).substring(from: i) + .trimmingPrefixWhitespace + // LWASM's ordinary syntax permits trailing comments after the operand, even without a semicolon. + guard !["FCC","FCN","FCS"].contains(entry(opcode)?.name ?? ""), !tail.contains(where: \.isWhitespace), !tail.hasPrefix("*") else { return nil } + let partial = String(tail.reversed().prefix { $0.isLetter || $0.isNumber || $0 == "_" }.reversed()) + return .init(opcode: opcode, operand: tail, atMnemonic: false, partial: partial) + } + + func topic(in source: String, at offset: Int, target6309: Bool) -> String? { + guard let fields = fields(source, offset), let entry = entry(fields.opcode), + vocabulary(target6309: target6309).contains(fields.opcode) else { return nil } + return entry.name + } + + func completions(in source: String, at offset: Int, target6309: Bool) -> [String] { + guard let fields = fields(source, offset) else { return [] } + let words = vocabulary(target6309: target6309) + if fields.atMnemonic { + return words.filter { $0.hasPrefix(fields.partial) }.sorted() + } + guard words.contains(fields.opcode), let item = entry(fields.opcode) else { return [] } + let parts = fields.operand.uppercased().components(separatedBy: ",") + let candidates: [String] + let byteRegs = ["A","B","CC","DP"] + (target6309 ? ["E","F"] : []) + let wordRegs = ["X","Y","D","S","U","PC"] + (target6309 ? ["W","V"] : []) + switch item.form { + case .pair: + guard parts.count <= 2 else { return [] } + if parts.count == 2 && !target6309 { + if byteRegs.contains(parts[0]) { candidates = byteRegs } + else if wordRegs.contains(parts[0]) { candidates = wordRegs } + else { return [] } + } else { + // The HD6309 register arithmetic family has unpredictable PC operands. + let regs = byteRegs + wordRegs + (target6309 ? ["0"] : []) + candidates = ["TFR","EXG"].contains(item.name) ? regs : regs.filter { $0 != "PC" } + } + case .transfer: + guard parts.count <= 2 else { return [] } + let regs = ["D","X","Y","U","S"] + if parts.count == 2 { + let sourceReg = parts[0].trimmingCharacters(in: CharacterSet(charactersIn: "+-")) + guard regs.contains(sourceReg) else { return [] } + } + if fields.opcode != "TFM" { candidates = regs } + else { + let suffixes: [String] + if parts.count == 1 { suffixes = ["","+","-"] } + else if parts[0].hasSuffix("+") { suffixes = ["","+"] } + else if parts[0].hasSuffix("-") { suffixes = ["-"] } + else { suffixes = ["+"] } + guard !fields.operand.hasSuffix("+"), !fields.operand.hasSuffix("-") else { return [] } + candidates = regs.flatMap { reg in suffixes.map { reg + $0 } } + } + case .stack: + guard !fields.operand.hasPrefix("#") else { return [] } + let regs = ["A","B","D","CC","DP","PC","X","Y",item.name.hasSuffix("S") ? "U" : "S"] + candidates = regs.filter { !parts.dropLast().contains($0) } + case .bit: + if parts.count == 1 { candidates = ["A","B","CC"] } + else if parts.count == 2 || parts.count == 3 { candidates = (0...7).map(String.init) } + else if parts.count == 4 { candidates = labels(in: source) } else { return [] } + case .indexed, .memory, .value, .maskMemory: + if item.form != .maskMemory && fields.operand.hasPrefix("#") { + guard item.form == .value && parts.count == 1 else { return [] } + } + let index = item.form == .maskMemory ? 2 : 1 + guard parts.count <= index + 1 else { return [] } + if parts.count == index + 1 { + let displacement = parts[index - 1].trimmingCharacters(in: CharacterSet(charactersIn: "[")) + var regs = ["X","Y","U","S"] + guard target6309 || !["E","F","W"].contains(displacement) else { return [] } + let registerOffset = ["A","B","D","E","F","W"].contains(displacement) + if !registerOffset && !displacement.isEmpty { regs.append("PCR") } + if target6309 && !registerOffset { regs.append("W") } + guard !fields.operand.hasSuffix("+") && !fields.operand.hasSuffix("]") else { return [] } + if parts.last?.hasPrefix("-") == true { regs = regs.filter { $0 != "PCR" && ($0 != "W" || parts.last?.hasPrefix("--") == true) } } + candidates = regs + } else if parts.count == index || (item.form == .maskMemory && parts.count == 1) { + candidates = labels(in: source) + } else { return [] } + case .relative: + guard !fields.operand.hasPrefix("#"), parts.count == 1 else { return [] } + candidates = labels(in: source) + case .immediate: candidates = labels(in: source) + case .directive, .topic, .inherent: return [] + } + return candidates.filter { $0.uppercased().hasPrefix(fields.partial.uppercased()) }.sorted() + } + + private func labels(in source: String) -> [String] { + var names = Set() + for line in source.split(whereSeparator: \.isNewline) { + guard let first = line.first, first.isLetter || first == "_" else { continue } + names.insert(String(line.prefix { $0.isLetter || $0.isNumber || $0 == "_" })) + } + return names.sorted() + } +} + +private extension String { + var trimmingPrefixWhitespace: String { String(drop(while: \.isWhitespace)) } +} diff --git a/platforms/macos/App/AssemblyReferenceInstructions.swift b/platforms/macos/App/AssemblyReferenceInstructions.swift new file mode 100644 index 0000000..0918ed3 --- /dev/null +++ b/platforms/macos/App/AssemblyReferenceInstructions.swift @@ -0,0 +1,207 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +extension AssemblyReference { + static func instructions() -> [AssemblyReferenceEntry] { + var entries: [AssemblyReferenceEntry] = [] + let same = "CC is preserved." + let nz = "N reflects the sign bit. Z marks a zero result." + let logic = nz + " V clears. C is preserved." + let add = nz + " V marks signed overflow. C marks unsigned carry." + let sub = nz + " V marks signed overflow. C marks a borrow." + func instruction(_ name: String, _ hd: Bool, _ form: AssemblyOperandForm, _ operation: String, + _ flags: String, _ pages: String, aliases: [String] = [], detail: String = "", + links: [String] = [], example: String? = nil) { + let citation = "Atkinson (2009), pp. " + pages + var citations = [citation] + if name == "TFM" { citations.append("VCC Plus, Native Debugger, HD6309 Step") } + if !hd { citations.append("Motorola (1981), Appendix A, " + name.trimmingCharacters(in: .decimalDigits)) } + citations.append("Astle, LWTools 4.25, ch. 3") + var related = links + switch form { + case .value, .memory, .indexed, .maskMemory: related.append("Indexed") + case .relative: related.append("Relative") + case .immediate: related.append("Immediate") + case .bit: related.append("Direct") + default: break + } + if !related.contains("Condition codes") { related.append("Condition codes") } + entries.append(.init(name, .instructions, only6309: hd, aliases: aliases, form: form, + operation: operation, flags: flags, detail: detail, links: related, + citations: citations, example: example)) + } + // Available registers differ across both instruction families and processors. + for (op, portable, extra) in [ + ("LD","A B D X Y U S","E F W Q"), ("ST","A B D X Y U S","E F W Q"), + ("ADD","A B D","E F W"), ("ADC","A B","D"), ("SUB","A B D","E F W"), ("SBC","A B","D"), + ("CMP","A B D X Y U S","E F W"), ("AND","A B","D"), ("OR","A B","D"), + ("EOR","A B","D"), ("BIT","A B","D") + ] { + let base = portable.components(separatedBy: " ") + for reg in base + extra.components(separatedBy: " ") { + let byte = ["A","B","E","F"].contains(reg) + let operation: String, flags: String, pages: String + var detail = "", lesson: String? + switch op { + case "LD": + operation = "Copy the operand into \(reg). Use # for a literal or read \(byte ? "one byte" : reg == "Q" ? "four bytes" : "two bytes") from the addressed memory." + flags = logic; pages = byte ? "90" : reg == "Q" ? "94" : "91" + if reg == "A" { + detail = "LDA #$20 places $20 in A. LDA $0400 reads the byte at $0400. LDA ,X+ reads at X, then advances X by one. The remaining CC bits keep their values. Immediate LDA takes 2 cycles. Extended LDA takes 5 on MC6809 or HD6309 emulation mode and 4 in HD6309 native mode. Indexed timing depends on the postbyte." + lesson = "cell" + } else if reg == "W" { + detail = "LDW #$1234 encodes as 10 86 12 34. E becomes $12 and F becomes $34 in either HD6309 execution mode." + lesson = "word" + } + case "ST": + operation = "Copy \(reg) to the destination address. Multi-byte stores write the high byte first." + flags = logic; pages = byte ? "127" : reg == "Q" ? "130" : "128" + if reg == "A" { lesson = "cell" } + case "ADD", "ADC": + operation = "Add the operand" + (op == "ADC" ? " and incoming carry" : "") + " to \(reg). Keep the low \(byte ? 8 : 16) bits in \(reg)." + flags = add + (byte ? " H records carry from bit 3." : " H is preserved.") + pages = op == "ADC" ? (byte ? "5" : "6") : (byte ? "8" : "9") + case "SUB", "SBC", "CMP": + operation = "Subtract the operand" + (op == "SBC" ? " and incoming borrow" : "") + " from \(reg). " + (op == "CMP" ? "Keep \(reg) intact for a later branch." : "Write the difference to \(reg).") + flags = sub + (byte ? " H is undefined." : "") + pages = op == "CMP" ? (byte ? "50" : "51") : op == "SBC" ? (byte ? "122" : "123") : (byte ? "131" : "132") + if op == "CMP" { lesson = "signed" } + default: + let action = ["AND":"Keep bits set in both inputs.", "OR":"Set bits present in either input.", + "EOR":"Set bits where the inputs differ.", "BIT":"Test the bits of \(reg) selected by the operand."][op]! + operation = action + (op == "BIT" ? " Preserve both inputs." : " Combine \(reg) with the operand and save the result in \(reg).") + flags = logic + pages = ["AND":byte ? "12" : "14", "OR":byte ? "106" : "108", + "EOR":byte ? "62" : "63", "BIT":byte ? "32" : "33"][op]! + } + instruction(op + reg, !base.contains(reg), op == "ST" ? .memory : .value, + operation, flags, pages, detail: detail, links: [reg], example: lesson) + } + } + + for (op, extra, operation, flags, pages) in [ + ("ASL","D","Shift one place left and fill bit 0 with zero.",nz + " C receives the old top bit. V is N XOR C.","16–17"), + ("ASR","D","Shift right, preserving the sign bit.",nz + " C receives the old bit 0. V is preserved.","18–19"), + ("LSR","D W","Shift right, bringing zero into the top bit.","N clears. Z marks zero. C receives the old bit 0. V is preserved.","98–99"), + ("ROL","D W","Shift left, moving the old carry into bit 0.",nz + " C receives the old top bit. V is N XOR C.","116–117"), + ("ROR","D W","Shift right, moving the old carry into the top bit.",nz + " C receives the old bit 0. V is preserved.","118–119"), + ("CLR","D E F W","Write zero.","Z sets. N, V and C clear.","48–49"), + ("COM","D E F W","Invert every bit.",nz + " C sets and V clears.","53–54"), + ("NEG","D","Subtract the value from zero.",nz + " C sets for a nonzero input. V marks negation of the most negative value.","102–103"), + ("INC","D E F W","Add one.",nz + " V sets on crossing from maximum positive to minimum negative. C is preserved.","67–68"), + ("DEC","D E F W","Subtract one.",nz + " V sets on crossing from minimum negative to maximum positive. C is preserved.","57–58"), + ("TST","D E F W","Test the value while preserving it.",logic,"140–141") + ] { + for reg in ["","A","B"] + extra.components(separatedBy: " ") { + let hd = !["","A","B"].contains(reg) + let destination = reg.isEmpty ? "a memory byte" : "register " + reg + instruction(op + reg, hd, reg.isEmpty ? .memory : .inherent, + "Operate on \(destination). " + operation, flags + (["ASL","ASR"].contains(op) && !hd ? " H is undefined." : ""), pages, + aliases: op == "ASL" ? ["LSL" + reg] : [], example: op == "DEC" ? "count" : nil) + } + } + + for (suffix, condition, page, longPage) in [ + ("CC","C is clear (unsigned higher or equal after a compare)",21,71), ("CS","C is set (unsigned lower)",22,72), + ("EQ","Z is set (equal)",24,73), ("NE","Z is clear (unequal)",40,83), + ("GE","N equals V (signed greater or equal)",25,74), ("GT","Z is clear and N equals V (signed greater)",26,75), + ("LE","Z is set or N differs from V (signed less or equal)",35,78), ("LT","N differs from V (signed less)",38,81), + ("HI","C and Z are both clear (unsigned higher)",27,76), ("LS","C or Z is set (unsigned lower or equal)",37,80), + ("MI","N is set (negative)",39,82), ("PL","N is clear (nonnegative)",42,84), + ("VC","V is clear (no signed overflow)",46,88), ("VS","V is set (signed overflow)",47,89), + ("RA","always",43,85), ("RN","never",44,86), ("SR","call",45,87) + ] { + for long in [false,true] { + let prefix = long ? "LB" : "B" + let action: String + switch suffix { + case "RA": action = "Continue at the target. A branch to its own label forms a hold loop." + case "RN": action = "Read the displacement and continue at the next instruction." + case "SR": action = "Push the following instruction’s address on S, then continue at the target. RTS returns to the caller." + default: action = "Continue at the target when " + condition + ". Otherwise execute the next instruction." + } + let aliases = suffix == "CC" ? [prefix + "HS"] : suffix == "CS" ? [prefix + "LO"] : [] + instruction(prefix + suffix, false, .relative, action, same, String(long ? longPage : page), + aliases: aliases, detail: "The signed \(long ? 16 : 8)-bit displacement is relative to the following instruction.", + example: suffix == "NE" ? "count" : suffix == "SR" ? "call" : "signed") + } + } + for (reg, flag) in [("X",true),("Y",true),("S",false),("U",false)] { + instruction("LEA" + reg, false, .indexed, "Calculate an indexed address and place it in \(reg). Indirect addressing reads a pointer before producing the address.", + flag ? "Only Z changes, to indicate a zero address." : same, "95", links: [reg]) + } + for (op, action, flags, page) in [ + ("ADDR","Add source to destination.",add,10), ("ADCR","Add source and carry to destination.",add,7), + ("SUBR","Subtract source from destination.",sub,133), ("SBCR","Subtract source and borrow from destination.",sub,124), + ("CMPR","Compare destination minus source, preserving both.",sub,52), ("ANDR","Apply bitwise AND to the destination using the source.",logic,15), + ("ORR","Apply bitwise OR to the destination using the source.",logic,109), + ("EORR","Toggle destination bits selected by the source.",logic,64) + ] { + instruction(op, true, .pair, action, flags, String(page), + detail: "The destination selects the width. A word source supplies its low byte to a byte destination. For a word destination A/B supply D, E/F supply W, CC is zero-extended and DP supplies the high byte. PC is undefined in this family. See Atkinson, p. 143.", links: ["W"]) + } + for (op, action, page) in [("AIM","AND",11),("OIM","OR",105),("EIM","exclusive OR",61),("TIM","AND",139)] { + instruction(op, true, .maskMemory, "Combine the literal mask and the addressed byte with \(action). " + (op == "TIM" ? "Use the result only to test flags." : "Write the result to that address."), logic, String(page)) + } + for (op, action, page) in [("BAND","AND",20),("BIAND","AND with the inverted source",29),("BOR","OR",41),("BIOR","OR with the inverted source",31),("BEOR","exclusive OR",23),("BIEOR","exclusive OR with the inverted source",30),("LDBT","copy",92),("STBT","store",129)] { + let description = op == "STBT" ? "Copy the selected register bit to the destination bit in direct-page memory." : + "Combine the selected memory bit with the destination register bit using \(action). Only the destination bit changes." + instruction(op, true, .bit, description, "CC can change when a destination bit in CC is selected.", String(page)) + } + for (stack, other) in [("S","U"),("U","S")] { + for push in [true,false] { + let prefix = push ? "PSH" : "PUL" + instruction(prefix + stack, false, .stack, push ? "Save selected registers on \(stack). The stack grows toward lower addresses." : + "Restore selected registers from \(stack), advancing the stack pointer. Pulling PC transfers control.", + push ? same : "Pulling CC replaces all its flags.", push ? "110" : "113", + detail: "Select CC, A, B, DP, X, Y, \(other) or PC. LWASM also accepts D for A and B. Hardware determines the register order.", links: [stack], example: "call") + instruction(prefix + stack + "W", true, .inherent, push ? "Push both bytes of W onto \(stack), subtracting two from the pointer." : + "Pull two bytes into W from \(stack), advancing the pointer by two.", + same, String((push ? 111 : 114) + (stack == "S" ? 0 : 1)), links: ["W",stack]) + } + } + instruction("TFM", true, .transfer, "Copy W bytes between addresses held in D, X, Y, U or S. Each suffix advances, retreats or holds its pointer after a byte. W counts down to zero. Without interruption the transfer costs 6 cycles plus 3 per byte.", same, "136", + aliases: ["COPY","COPY+","COPY-","TFRP","TFRM","IMP","IMPLODE","TFRS","EXP","EXPAND","TFRR"], + detail: "LWASM’s alternative spellings take two bare registers. COPY/COPY+/TFRP advance both, COPY-/TFRM retreat both, IMP/IMPLODE/TFRS advance the source and EXP/EXPAND/TFRR advance the destination. In VCC Plus, debugger Step finishes the block. Continue can hit a breakpoint again between bytes.", + links: ["HD6309 modes","W"], example: "transfer") + for (name, action, page) in [("EXG","Exchange the contents of the two registers.","65–66"),("TFR","Copy the source register to the destination.","137–138")] { + instruction(name, false, .pair, action, "Writing CC replaces its flags.", page, + detail: "Use equal-width registers on the MC6809. The HD6309 has additional registers and defined mixed-width behavior. Writing PC transfers control.", links: ["D","W"]) + } + for (name, operation, flags, page) in [ + ("ANDCC","Keep only CC bits selected by the mask.","Any CC bit can clear.",13),("ORCC","Set each CC bit selected by the mask.","Any CC bit can set.",107), + ("CWAI","AND CC with the mask, stack the full interrupt context on S, then wait for an eligible interrupt.","The mask updates CC. E sets for the stacked full context.",55), + ("LDMD","Write the low two mode-control bits of MD.",same,93), + ("BITMD","Test the masked trap status bits of MD. Reading a selected sticky error clears it.","Z sets if no selected error was pending.",34) + ] { + instruction(name, name.hasSuffix("MD"), .immediate, operation, flags, String(page), links: name.hasSuffix("MD") ? ["HD6309 modes"] : []) + } + for (name, action, page) in [("JMP","Set PC to the effective address.",69),("JSR","Push the return address on S, then set PC to the effective address.",70)] { + instruction(name, false, .memory, action, same, String(page), example: "call") + } + for (name, action, flags, page) in [ + ("ABX","Add the unsigned byte in B to X.",same,4), + ("DAA","Adjust A after adding packed BCD bytes, using H and C from the addition.",nz + " C reports decimal carry. V is undefined.",56), + ("MUL","Multiply unsigned A by B and place the 16-bit product in D.","Z marks a zero product. C receives product bit 7.",100), + ("NOP","Advance to the following instruction.",same,104), + ("RTS","Pull the return address from S into PC and advance S by two.",same,121), + ("RTI","Pull CC and the return state from S. Stacked E determines whether to restore a full frame.","Restores saved CC.",120), + ("SEX","Copy B’s sign bit across A to extend B into D.",nz + " V and C are preserved.",125), + ("SEXW","Copy W’s sign bit across D to extend W into Q.",nz + " V and C are preserved.",126), + ("SYNC","Wait for an interrupt request. Even a masked request can release the wait.",same,135) + ] { + instruction(name, name == "SEXW", .inherent, action, flags, String(page), example: name == "RTS" ? "call" : nil) + } + for (name, vector) in [("SWI","FFFA"),("SWI2","FFF4"),("SWI3","FFF2")] { + instruction(name, false, .inherent, "Save a full interrupt frame on S and fetch the new PC from $\(vector).", + "E sets." + (name == "SWI" ? " I and F set after stacking." : " I and F keep their values."), "134", links: ["HD6309 modes","RTI"]) + } + for (name, dividend, divisor, quotient, remainder, page) in [("DIVD","D","byte","B","A",59),("DIVQ","Q","word","W","D",60)] { + instruction(name, true, .value, "Divide signed \(dividend) by a signed \(divisor). The quotient goes in \(quotient) and the remainder in \(remainder). A zero divisor traps.", + "For an in-range quotient, N and Z describe it, V clears, and C receives its low bit. Signed overflow sets V. Range overflow preserves the dividend and clears N, Z and C.", + String(page), detail: name == "DIVQ" ? "VCC Plus’s retained core has differences in DIVQ overflow and carry handling. Treat these flags as processor documentation." : "", links: ["MD"]) + } + instruction("MULD", true, .value, "Multiply signed D by a signed 16-bit operand and store the 32-bit product in Q.",nz + " V and C clear.","101", links: ["Q"]) + return entries + } +} diff --git a/platforms/macos/App/AssemblyReferenceTopics.swift b/platforms/macos/App/AssemblyReferenceTopics.swift new file mode 100644 index 0000000..e03a1a2 --- /dev/null +++ b/platforms/macos/App/AssemblyReferenceTopics.swift @@ -0,0 +1,206 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +struct AssemblyReferenceLesson { + let id: String + let name: String + let predict: String + let observation: String + let assumptions: String + let body: String + var hd = false + + var source: String { + "; " + name + "\n; " + assumptions + "\n; " + predict + "\n org $3f00\n" + body + "\n end start\n" + } + var testedScope: String { + hd ? "Assembled for HD6309. Debugger outcomes checked in emulation and native modes. MC6809 assembly rejection checked." : + "Assembled for both targets. Debugger outcomes checked on MC6809 and in HD6309 emulation and native modes." + } + var request: AssemblyReferenceExampleRequest { .init(title: name, source: source, target6309: hd) } + + static let all: [Self] = [ + .init(id: "cell", name: "First Program — Change a Screen Cell", + predict: "After the load, what is in A? At which step does the display change?", + observation: "A becomes $8F on the first step. The next step writes $8F to the upper-left cell, the same store as POKE &H0400,&H8F.", + assumptions: "Disk BASIC 32-column text screen at $0400. No ROM calls, direct-page operands or subroutine stack use.", + body: "start lda #$8f\n sta $0400\nhold bra hold"), + .init(id: "count", name: "Count and branch", + predict: "How many times will BNE jump back after starting B at three?", + observation: "BNE jumps twice. On the third decrement B is zero, Z sets, and the branch falls through to hold.", + assumptions: "Observe B, Z and PC. No display, ROM calls, direct-page operands or subroutine stack use.", + body: "start ldb #3\nagain decb\n bne again\nhold bra hold"), + .init(id: "call", name: "Pass a value to a subroutine", + predict: "Where does RTS return, and what value does the caller receive?", + observation: "JSR saves the address of the store. INCA turns 7 into 8. RTS restores PC and S. The caller writes 8 at result.", + assumptions: "Uses writable RAM for a private stack below stacktop and an output byte at result. No ROM calls, direct-page operands or display assumptions.", + body: "start lds #stacktop\n lda #7\n jsr plusone\n sta result\nhold bra hold\nplusone inca\n rts\nresult fcb 0\n zmb 64\nstacktop equ *"), + .init(id: "page", name: "Draw on a hidden page", + predict: "Will storing $AA change the text screen or the PMODE preview at $1A00?", + observation: "In Graphics Preview select At Address, Mapped CPU, $1A00, PMODE 1, Set 0. The first byte supplies four color-index-2 pixels. The CPU writes through its current memory map. The video chip continues reading its selected buffer in physical RAM, so the text display stays as it was.", + assumptions: "Disk BASIC text display. Uses $1A00 as writable scratch RAM. No video mode change, ROM calls, direct-page operands or subroutine stack use.", + body: "start lda #$aa\n sta $1a00\nhold bra hold"), + .init(id: "signed", name: "Compare signed and unsigned", + predict: "Is $FF lower or higher than $01? Predict the next PC at BLT and BHI.", + observation: "CMPA leaves A at $FF and produces N=1, V=0, C=0, Z=0. BLT lands at signed and BHI lands at both. $FF is signed −1 and unsigned 255.", + assumptions: "Observe PC and CC only. No display, ROM calls, direct-page operands or subroutine stack use.", + body: "start lda #$ff\n cmpa #1\n blt signed\nmiss bra miss\nsigned bhi both\n bra miss\nboth bra both"), + .init(id: "word", name: "Split a word into E and F", + predict: "Which half of W will contain $12?", + observation: "Step LDW. W becomes $1234, E becomes $12 and F becomes $34. Z, N and V clear.", + assumptions: "HD6309, emulation or native mode. No display, ROM calls, direct-page operands or subroutine stack use.", + body: "start ldw #$1234\nhold bra hold", hd: true), + .init(id: "transfer", name: "Copy three bytes with TFM", + predict: "How far will X and Y advance when W starts at three?", + observation: "One debugger Step on TFM copies $A5, $5A, $42 to target. X and Y advance by three and W ends at zero. Inspect target in mapped memory.", + assumptions: "HD6309, either mode. Separate source and destination in RAM. No display, ROM calls, direct-page operands or subroutine stack use.", + body: "start ldx #table\n ldy #target\n ldw #3\n tfm x+,y+\nhold bra hold\ntable fcb $a5,$5a,$42\ntarget zmb 3", hd: true) + ] +} + +extension AssemblyReference { + static let bibliography = [ + "Atkinson (2009)": "Darren Atkinson. Motorola 6809 and Hitachi 6309 Programmer’s Reference. 2009. Part I contains the instruction discussions, Part II the HD6309 mode and register notes.", + "Motorola (1981)": "Motorola, Inc. MC6809–MC6809E 8-Bit Microprocessor Programming Manual. M6809PM (AD), original issue March 1981, reprinted May 1983. Chapters 1–2 and Appendix A.", + "Burke (1993)": "Chris Burke. The 6309 Book: Inside the 6309 Microprocessor. Second edition. Burke & Burke, 1993.", + "Barden (1983)": "William Barden, Jr. TRS-80 Color Computer Assembly Language Programming. Radio Shack, 1983.", + "Tepolt (1987)": "Laurence A. Tepolt. Assembly Language Programming for the CoCo 3. TEPCO, 1987.", + "Astle": "William Astle and LWTools contributors. LW Tool Chain. Manual accompanying LWTools 4.25, chapter 3, LWASM.", + "VCC Plus": "VCC Plus. Native Debugger and Debugger Memory Tools. Project documentation and regression programs for Graphics Preview and whole-instruction TFM Step." + ] + + static func topics() -> [AssemblyReferenceEntry] { + var entries: [AssemblyReferenceEntry] = [] + let motorola = "Motorola (1981), ch. 1", addressing = "Motorola (1981), ch. 2" + let dialect = "Astle, LWTools 4.25, ch. 3" + for (name, purpose, hd) in [ + ("A","Eight-bit accumulator. A forms the high byte of D.",false), ("B","Eight-bit accumulator. B forms the low byte of D.",false), + ("D","Sixteen-bit accumulator built from A (high) and B (low). Writing D immediately changes both halves.",false), + ("X","Sixteen-bit index register. Use X to address a table or traverse bytes.",false), + ("Y","Sixteen-bit index register. X and Y can walk independent buffers.",false), + ("U","Sixteen-bit user stack pointer, also available as an index register. PSHU and PULU use this stack.",false), + ("S","Sixteen-bit hardware stack pointer. JSR, interrupts and PSHS use memory below S. Initialize a writable stack before making a standalone call.",false), + ("PC","Program counter. Branches, jumps, calls and returns change the address of the next instruction.",false), + ("DP","Direct-page register. Its byte supplies the upper address bits of a direct operand. LWASM SETDP describes your assumption during assembly.",false), + ("E","Eight-bit accumulator and high byte of the HD6309 W register. CC.E is a separate flag.",true), + ("F","Eight-bit accumulator and low byte of W. CC.F is the fast-interrupt mask.",true), + ("W","Sixteen-bit accumulator combining E (high) and F (low). TFM uses W as a byte count.",true), + ("Q","Thirty-two-bit accumulator. From most to least significant its bytes are A, B, E, F. D is the high word and W the low word.",true), + ("V","Additional 16-bit HD6309 register used in register operations. CC.V is a separate overflow flag.",true), + ("MD","Mode register. LDMD controls execution mode and FIRQ stacking. BITMD tests the latched illegal-instruction and division-by-zero status.",true) + ] { + entries.append(.init(name, .registers, only6309: hd, operation: purpose, links: hd ? ["HD6309 modes"] : ["Condition codes"], + citations: [hd ? "Burke (1993), register file" : motorola])) + } + entries.append(.init("Condition codes", .registers, aliases: ["CC"], operation: "CC holds eight one-bit values. E marks an entire interrupt frame. F masks FIRQ, H is half carry, I masks IRQ. N is negative, Z zero, V signed overflow and C carry or borrow.", + detail: "Branch choices depend on how the previous instruction defined these bits. For example, Z=1 after CMP means equal; C=1 after CMP means unsigned lower. An undefined bit cannot support a portable decision.", links: ["BGE","BCC","CMPA"], citations: [motorola], terms: ["flags","carry","zero","loop"], example: "signed")) + for (name, meaning, links) in [ + ("CC.C","Carry or borrow. An unsigned addition sets C when the sum exceeds the register. A comparison sets C when the unsigned left operand is lower.",["BCS","ADCA"]), + ("CC.V","Signed overflow. For example, adding one to $7F produces $80 in a byte and sets V.",["BVS","BGE"]), + ("CC.Z","Zero. Many arithmetic and load instructions set Z when the result is zero. After a compare, BEQ uses Z to test equality.",["BEQ","BNE"]), + ("CC.N","Negative. For operations that set N from the result, it copies the most significant bit. A signed comparison also needs V.",["BMI","BLT"]), + ("CC.I","Interrupt request mask. Set I to mask IRQ. Clear I to permit IRQ when the external request is active.",["ANDCC","ORCC"]), + ("CC.H","Half carry. An eight-bit addition places the carry from bit 3 here. DAA uses H to adjust a packed decimal result.",["DAA","ADDA"]), + ("CC.F","Fast interrupt request mask. Set F to mask FIRQ. A saved CC value can restore the previous mask.",["ANDCC","RTI"]), + ("CC.E","Entire state stacked. RTI checks E in the saved condition byte to choose between the short and full interrupt frames.",["RTI","SWI"]) + ] { + entries.append(.init(name, .registers, operation: meaning, links: links, citations: [motorola])) + } + entries.append(.init("HD6309 modes", .registers, only6309: true, operation: "The HD6309 starts in emulation mode. Many instructions take fewer cycles in native mode. LDMD #1 selects native mode with the ordinary short FIRQ frame. Mode selection is independent of the LWASM target.", + detail: "MD bit 0 selects native mode. Bit 1 selects full FIRQ stacking. A native full-state interrupt frame includes E and F; the mode on return must agree with the frame. Cycle counts also depend on indexed postbytes, branch outcomes and transfer lengths. In VCC Plus, Step completes a TFM instruction across its byte transfers.", + links: ["MD","LDMD","BITMD","TFM","RTI"], citations: ["Atkinson (2009), pp. 2, 120, 136, 144","Burke (1993), mode register","VCC Plus, Native Debugger, HD6309 Step"])) + for (name, operation, syntax, terms) in [ + ("Immediate","Use the following operand bytes as the value.", "LDA #$20", ["literal","#"]), + ("Direct","Join DP with the 8-bit operand to make the memory address. With DP=$12, LDA <$34 reads $1234.","LDA <$34", ["direct page","<"]), + ("Extended","Use the full 16-bit address in the instruction. LDA >$0400 reads a byte there.","LDA >$0400", [">","absolute"]), + ("Indexed","Calculate an address from a register and an offset. LDA ,X+ reads at the original X then increments X by one. Use ,X++ for a two-byte advance. Indexed operands can also use A, B or D as signed offsets.","LDA ,X+ · LDD 2,S · LDA B,Y", [",X+",",X++","auto increment","offset"]), + ("Indirect","Use square brackets to fetch a two-byte pointer at the intermediate address, then access the final address. Use a two-byte increment when walking a pointer table.","LDA [,X++] · JMP [$4000]", ["pointer","brackets"]), + ("Relative","Add a signed displacement to PC after the operand. Branch targets are labels. Indexed PC-relative data references use PCR in LWASM.","BNE again · LDA table,PCR", ["relative","PCR","loop"]), + ("Inherent","The opcode specifies the operation and its operands. INCA, for example, acts on A.","INCA", ["no operand"]), + ("HD6309 indexed","E, F and W can supply offsets for X, Y, U or S. W also supports ,W, offset,W, ,W++ and ,--W, including their indirect forms.", "LDA E,X · LDA ,W++", ["W index",",W++"]) + ] { + entries.append(.init(name, .addressing, only6309: name.hasPrefix("HD"), syntax: syntax, operation: operation, detail: name == "Extended" ? "On the CoCo 3, the address in STA >$1A00 selects a byte through the CPU memory map. The MMU chooses the physical 8 KiB block and preserves the low 13 address bits. Use Mapped CPU in the debugger to inspect that store." : "", links: ["LDA"], + citations: (name == "Extended" ? ["Tepolt (1987), p. 20, fig. 3-4"] : []) + [name.hasPrefix("HD") ? "Atkinson (2009), p. 148" : addressing, dialect], terms: terms)) + } + for (names, syntax, text) in [ + ("ORG","ORG address","Set the address of the following output. In DECB an origin determines where a data block loads."), + ("FCB .BYTE .DB","FCB byte[,byte…]","Emit each expression as one byte. The listing shows data at the current location."), + ("FDB .WORD .DW","FDB word[,word…]","Emit 16-bit words, high byte first."), ("FQB .4BYTE .QUAD","FQB value","Emit 32-bit quantities, high byte first."), + ("FCC .ASCII .STR","FCC /text/","Emit character bytes between matching delimiters."), + ("FCN FCZ .ASCIZ .STRZ","FCN /text/","Emit a string followed by a zero byte."), + ("FCS .ASCIS .STRS","FCS /text/","Emit a string with the high bit set in its last character."), + ("RMB .BLKB .DS .RS","RMB count","Advance the location counter by a number of bytes. Use ZMB when the load image must contain zeros."), + ("RMD RMW","RMD count","Reserve 16-bit words."), ("RMQ","RMQ count","Reserve 32-bit values."), + ("ZMB BSZ FZB","ZMB count","Emit the requested number of zero bytes."), ("ZMD","ZMD count","Emit zero-filled words."), + ("ZMQ","ZMQ count","Emit zero-filled four-byte quantities."), ("EQU =","name EQU expression","Assign a fixed value to a symbol."), + ("SET","name SET expression","Assign a symbol a value that later SET statements may change."), + ("SETDP","SETDP page","Tell the assembler the assumed direct page. Guest software must establish the matching DP value."), + ("END .END","END entry","Finish the assembly and specify the DECB execution address. END itself emits no machine instruction."), + ("INCLUDE INCL LIB USE","INCLUDE filename","Read another source file at this location."), + ("INCLUDEBIN","INCLUDEBIN filename","Copy bytes from a binary file into the assembly output."), + ("ALIGN","ALIGN boundary","Advance to a boundary divisible by the supplied value."), ("FILL","FILL byte,count","Emit the given byte repeatedly."), + ("SECTION SECT .AREA","SECTION name","Begin a section in an object module. The linker determines final placement."), + ("ENDSECT ENDSECTION","ENDSECT","Finish the current object section."), + ("EXTERN EXTERNAL IMPORT","name EXTERN","Declare a name defined in another object module."), + ("EXPORT .GLOBL","EXPORT name","Expose a symbol to other object modules."), + ("MACRO MACR","name MACRO","Begin defining a sequence of source lines for later expansion."), ("ENDM","ENDM","Finish a macro definition."), + ("REORG","REORG","Restore the location associated with the previous ORG."), + ("PHASE","PHASE expression","Give following code a different logical address for labels and expressions while retaining its output placement."), + ("DEPHASE","DEPHASE","Resume the original address calculation after PHASE."), + ("FDBS","FDBS word[,word…]","Emit 16-bit values low byte first, opposite to the processor’s normal word order."), + ("INCLUDESTR","INCLUDESTR string","Treat the contents of the given string as additional assembler source."), + ("EXTDEP","name EXTDEP","Mark an external symbol as a link dependency without emitting storage for it."), + ("ERROR","ERROR message","Report an assembly error with the supplied text."), + ("WARNING MSG","WARNING message","Report a warning with the supplied text."), + ("IFEQ","IFEQ expression","Include the following block when the expression equals zero."), + ("IFNE IF","IFNE expression","Include the block when the expression is nonzero."), + ("IFLT","IFLT expression","Include the block when the expression is negative."), + ("IFLE","IFLE expression","Include the block when the expression is zero or negative."), + ("IFGT","IFGT expression","Include the block when the expression is positive."), + ("IFGE","IFGE expression","Include the block when the expression is zero or positive."), + ("IFDEF","IFDEF symbol","Test whether a symbol has already been defined."), + ("IFNDEF","IFNDEF symbol","Test whether a symbol is still undefined."), + ("IFPRAGMA IFOPT","IFPRAGMA option","Include a block according to the current pragma setting."), + ("IFSTR","IFSTR comparison,arguments","Include a block according to the specified string comparison."), + ("ELSE","ELSE","Select the alternate branch of a conditional assembly block."), + ("ENDC ENDIF","ENDC","Close the current conditional assembly block."), + ("IFP1","IFP1","Legacy pass-number conditional. LWASM warns that it cannot reproduce pass-one assembly semantics."), + ("IFP2","IFP2","Legacy pass-number conditional. LWASM warns that it cannot reproduce pass-two assembly semantics."), + ("STRUCT","name STRUCT","Begin a structure layout. Field labels describe offsets in its instances."), + ("ENDS ENDSTRUCT","ENDS","Close a structure definition."), + ("SETSTR","SETSTR name=string","Set an assembler string variable."), + ("DTS","DTS","Emit a textual build timestamp. Its value changes with the host clock."), + ("DTB","DTB","Emit six host-local date and time bytes."), + ("*PRAGMAPUSH","*PRAGMAPUSH","Save pragma settings on the assembler’s pragma stack."), + ("*PRAGMAPOP","*PRAGMAPOP","Restore saved pragma settings."), + ("PRAGMA *PRAGMA **PRAGMA OPT","PRAGMA option","Change a LWASM dialect option. A target-changing pragma affects subsequent assembly.") + ] { + let words = names.components(separatedBy: " ") + entries.append(.init(words[0], .directives, aliases: Array(words.dropFirst()), form: .directive, syntax: syntax, operation: text, + detail: "LWASM directive. Its effects take place during assembly.", links: ["END","ORG"].filter { $0 != words[0] }, + citations: [dialect], example: ["ORG","FCB","END"].contains(words[0]) ? "call" : nil)) + } + entries.append(.init("Assembler conveniences", .dialect, aliases: ["ASRQ","CLRQ","COMQ","LSLE","LSLF","LSLQ","LSRQ","NEGE","NEGF","NEGW","NEGQ","TSTQ"], + operation: "LWASM can expand convenience operations into several instructions when the corresponding pragma is active. The listing gives the actual expansion. A 6809 emulation of CLRD, for example, executes CLRA and CLRB separately.", + detail: "6809 expansions include ASLD, ASRD, CLRD, COMD, LSLD, LSRD, NEGD and TSTD. These names also identify real HD6309 operations. Additional 6309 convenience spellings include ASRQ, CLRQ, COMQ, LSLE, LSLF, LSLQ, LSRQ, NEGE, NEGF, NEGW, NEGQ and TSTQ. MC6800 compatibility is a separate optional dialect.", + links: ["CLRD","PRAGMA"], citations: [dialect])) + entries.append(.init("MC6800 compatibility", .dialect, + aliases: "ABA CBA CLC CLF CLI CLIF CLV CPX DES DEX DEY INS INX INY SBA SEC SEF SEI SEIF SEV TAB TAP TBA TPA TSX TXS WAI".components(separatedBy: " "), + operation: "These optional LWASM spellings expand to 6809 encodings with the 6800compat pragma. Expansion can require several instructions. Inspect the listing when stepping.", links: ["PRAGMA"], citations: [dialect])) + entries.append(.init("Compatibility directives", .dialect, aliases: ["NAM","PAG","PAGE","SPC","TTL",".BANK",".MODULE"], + operation: "LWASM accepts these listing and tool-compatibility directives without generating code.", links: ["FCB"], citations: [dialect])) + entries.append(.init("ASM-09 dialect", .dialect, aliases: ["IFC","IFNC","EXITM","EXIT"], + operation: "The ASM-09 compatibility dialect adds string equality and inequality conditionals and an early macro exit.", links: ["MACRO"], citations: [dialect])) + entries.append(.init("OS-9 output directives", .dialect, aliases: ["OS9","MOD","EMOD"], + operation: "OS9 encodes SWI2 followed by a service byte for OS-9 or object output. MOD and EMOD frame an OS-9 module. Assembly Development runs standalone Disk BASIC block images.", links: ["SWI2","END"], citations: [dialect])) + entries.append(.init("Undocumented and emulator opcodes", .dialect, aliases: ["HCF","RHF","RESET","HALT","BREAK","LOG"], operation: "LWASM lists HCF, RHF and RESET for certain 6809 encodings. Behavior outside the documented instruction set can differ by chip. BREAK and LOG are emulator extensions. VCC Plus’s Mac decoder also excludes the optional HALT/BREAK encodings.", + links: ["NOP"], citations: ["Atkinson (2009), p. 153",dialect,"VCC Plus, Native Debugger, disassembly"], terms: ["HCF","RHF","RESET","HALT","BREAK","LOG"])) + for lesson in AssemblyReferenceLesson.all { + entries.append(.init(lesson.name, .examples, only6309: lesson.hd, operation: lesson.predict, + detail: lesson.observation + "\n\n" + lesson.assumptions, + links: [lesson.id == "page" ? "Extended" : lesson.hd ? "W" : "LDA"], citations: (lesson.id == "page" ? ["Tepolt (1987), pp. 20 and 23, figs. 3-4 and 4-1"] : []) + [lesson.hd ? "Atkinson (2009), pp. 91, 136" : "Barden (1983), addressing and subroutines", lesson.id == "page" ? "VCC Plus, Debugger Memory Tools, hidden drawing page" : dialect], + example: lesson.id)) + } + return entries + } +} diff --git a/platforms/macos/App/AssemblyReferenceView.swift b/platforms/macos/App/AssemblyReferenceView.swift new file mode 100644 index 0000000..c6c41ec --- /dev/null +++ b/platforms/macos/App/AssemblyReferenceView.swift @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI + +@MainActor final class AssemblyReferenceSelection: ObservableObject { + static let shared = AssemblyReferenceSelection() + struct Lookup { + let token = UUID() + let term: String? + let target6309: Bool + } + @Published private(set) var lookup: Lookup? + func show(_ term: String?, target6309: Bool) { lookup = .init(term: term, target6309: target6309) } +} + +struct AssemblyReferenceView: View { + let openExample: (AssemblyReferenceExampleRequest) -> Void + @ObservedObject private var selection = AssemblyReferenceSelection.shared + @FocusState private var searchFocused: Bool + @State private var query = "" + @State private var target6309: Bool? + @State private var category: AssemblyReferenceCategory? + @State private var selected: String? = AssemblyReference.shared.entry("LDA")?.id + @State private var scrollRequest = UUID() + @State private var bibliography = false + @State private var citationKey = "" + private let catalog = AssemblyReference.shared + + var body: some View { + let matches = catalog.search(query, target6309: target6309, category: category) + let current = matches.first { $0.id == selected } ?? matches.first + VStack(spacing: 0) { + HStack { + TextField("Search instructions, registers, or tasks", text: $query) + .textFieldStyle(.roundedBorder).focused($searchFocused) + .accessibilityLabel("Search assembly reference").accessibilityIdentifier("assembly.reference.search") + Picker("Processor", selection: $target6309) { + Text("Both CPUs").tag(nil as Bool?) + Text("MC6809").tag(Optional(false)) + Text("HD6309").tag(Optional(true)) + }.labelsHidden().accessibilityLabel("Processor").fixedSize().accessibilityIdentifier("assembly.reference.processor") + Button { citationKey = ""; bibliography = true } label: { Image(systemName: "books.vertical") } + .help("Bibliography").accessibilityLabel("Bibliography") + }.padding(10) + Divider() + HSplitView { + VStack(spacing: 0) { + Picker("Category", selection: $category) { + Text("All Topics").tag(nil as AssemblyReferenceCategory?) + ForEach(AssemblyReferenceCategory.allCases, id: \.self) { Text($0.rawValue).tag(Optional($0)) } + }.labelsHidden().accessibilityLabel("Category").accessibilityIdentifier("assembly.reference.category").padding(8) + ScrollViewReader { proxy in + List(matches, selection: $selected) { item in + HStack { + Text(item.name) + if item.only6309 { Text("6309").font(.caption2).foregroundStyle(.secondary) } + }.tag(item.id).id(item.id) + } + .accessibilityLabel("Reference topics").accessibilityIdentifier("assembly.reference.topics") + .onChange(of: scrollRequest, initial: true) { _, _ in + if let id = current?.id { proxy.scrollTo(id, anchor: .center) } + } + } + }.frame(minWidth: 170, idealWidth: 225, maxWidth: 330) + if let item = current { + ScrollView { + VStack(alignment: .leading, spacing: 14) { + Text(item.category.rawValue + " · " + (item.only6309 ? "HD6309" : "MC6809 and HD6309")).font(.caption).foregroundStyle(.secondary) + Text(item.name).font(.title.bold()) + if !item.aliases.isEmpty { Text("Also spelled " + item.aliases.joined(separator: ", ")).foregroundStyle(.secondary) } + if !item.syntax.isEmpty { Text(item.syntax).font(.system(.body, design: .monospaced)).textSelection(.enabled) } + Text(item.operation).textSelection(.enabled) + if !item.flags.isEmpty { + Text("Condition codes").font(.headline) + Text(item.flags).textSelection(.enabled) + } + if !item.detail.isEmpty { + if item.category == .instructions { + DisclosureGroup("Instruction details") { Text(item.detail).textSelection(.enabled).padding(.top, 4) } + } else { Text(item.detail).textSelection(.enabled) } + } + if let id = item.example, let lesson = AssemblyReferenceLesson.all.first(where: { $0.id == id }) { + if item.category == .examples { + Text(lesson.testedScope).font(.caption).foregroundStyle(.secondary) + Text(lesson.source).font(.system(.caption, design: .monospaced)).textSelection(.enabled) + } + Button("Open Example", systemImage: "square.and.pencil") { openExample(lesson.request) } + .help("Open an editable copy of " + lesson.name).accessibilityIdentifier("assembly.reference.openExample") + } + if !item.links.isEmpty { + Text("Related topics").font(.headline) + ForEach(item.links.filter { catalog.entry($0).map { target6309 != false || !$0.only6309 } ?? false }, id: \.self) { link in + Button(link) { navigate(to: link) }.buttonStyle(.link) + } + } + DisclosureGroup("Sources") { + VStack(alignment: .leading, spacing: 6) { + ForEach(item.citations, id: \.self) { source in + Button(source) { + citationKey = AssemblyReference.bibliography.keys.first { source.hasPrefix($0) } ?? "" + bibliography = true + }.buttonStyle(.link) + } + }.frame(maxWidth: .infinity, alignment: .leading).padding(.top, 4) + } + }.padding(20).frame(maxWidth: .infinity, alignment: .leading) + }.id(item.id).accessibilityIdentifier("assembly.reference.detail") + } else { + ContentUnavailableView.search(text: query).frame(maxWidth: .infinity) + } + } + }.frame(minWidth: 610, minHeight: 380) + .background { + Button("Find in Assembly Reference") { searchFocused = true } + .keyboardShortcut("f", modifiers: .command).hidden().accessibilityHidden(true) + } + .onChange(of: selection.lookup?.token, initial: true) { _, _ in + guard let request = selection.lookup else { return } + target6309 = request.target6309 + if let term = request.term { navigate(to: term) } + else { query = ""; category = nil } + } + .onChange(of: current?.id) { _, id in selected = id } + .sheet(isPresented: $bibliography) { + VStack(alignment: .leading, spacing: 16) { + Text("Bibliography").font(.title.bold()) + ScrollViewReader { proxy in + ScrollView { + VStack(alignment: .leading, spacing: 14) { + ForEach(AssemblyReference.bibliography.keys.sorted(), id: \.self) { key in + Text(AssemblyReference.bibliography[key] ?? "").textSelection(.enabled).id(key) + } + Divider() + Text("Color Computer Archive preserves historical publications consulted for this reference. The explanations and teaching programs here were written for VCC Plus.").foregroundStyle(.secondary) + } + }.onAppear { if !citationKey.isEmpty { proxy.scrollTo(citationKey, anchor: .top) } } + } + HStack { Spacer(); Button("Done") { bibliography = false }.keyboardShortcut(.defaultAction) } + }.padding(22).frame(width: 520, height: 405) + } + } + + private func navigate(to term: String) { + category = nil + if let entry = catalog.entry(term) { query = ""; selected = entry.id } + else { query = term; selected = nil } + scrollRequest = UUID() + } +} diff --git a/platforms/macos/App/BASICDevelopmentModel.swift b/platforms/macos/App/BASICDevelopmentModel.swift new file mode 100644 index 0000000..581e5f9 --- /dev/null +++ b/platforms/macos/App/BASICDevelopmentModel.swift @@ -0,0 +1,531 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import Combine +import CryptoKit +import UniformTypeIdentifiers + +enum BASICExportKind: String, Identifiable, Sendable { + case disk, cassette + var id: String { rawValue } + var fileExtension: String { self == .disk ? "dsk" : "cas" } + var title: String { self == .disk ? "Export Disk" : "Export Cassette" } + func instructions(name: String, dosBoot: Bool) -> String { + self == .disk ? DevelopmentDiskProgram.basic(name).instructions(dos: dosBoot) + : "Open the cassette and press Play. Type CLOAD\"\(name)\", then type RUN on the next line." + } + var symbol: String { self == .disk ? "externaldrive" : "recordingtape" } +} + +enum BASICExportName { + static func normalized(_ text: String) -> String? { + let value = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard (1...8).contains(value.utf8.count), value.utf8.allSatisfy({ + (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) + }) else { return nil } + return value.uppercased() + } + static func suggestion(for url: URL?) -> String { + guard let url else { return "HELLO" } + let bytes = url.deletingPathExtension().lastPathComponent.utf8.filter { + (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) + }.prefix(8) + return bytes.isEmpty ? "HELLO" : String(decoding: bytes, as: UTF8.self).uppercased() + } +} + +struct BASICEditorAction: Identifiable { + enum Operation { case replace(source: String, undoName: String), select(NSRange) } + let id = UUID() + let expectedSource: String + let operation: Operation +} + +@MainActor +final class BASICDevelopmentModel: ObservableObject { + weak var assistantEditor: BASICTextView? + let machine: MachineModel + let directory: URL + let workspaceID = UUID() + private var untitledTitle = "Untitled BASIC" + private(set) var sourceRevision = 0 + @Published var source = BASICLanguage.sample { + didSet { + if !source.utf8.elementsEqual(oldValue.utf8) { + sourceRevision += 1 + diagnostics = []; clearInspection() + if armedSource != nil { + armedSource = nil; stoppedLine = nil; stoppedToken = nil; runtimeErrorLine = nil; runtimeErrorCode = "" + debugStatus = "Source changed. Breakpoints will apply on the next Run; the CoCo program is unchanged." + detachOwnedDebug() + } + } + if !restoring { scheduleRecovery() } + } + } + @Published private(set) var diagnostics: [BASICLanguage.Diagnostic] = [] + @Published private(set) var editorAction: BASICEditorAction? + @Published private(set) var fileURL: URL? + @Published private(set) var savedSource = BASICLanguage.sample + @Published private(set) var busy = false + @Published var message: String? + @Published private(set) var status = "Ready to edit. Nothing has been loaded into the CoCo." + @Published var hint: String? + @Published var completionRequest = UUID() + @Published var documentID = UUID() + @Published var editorOffset = 0 + private var fileFingerprint: String? + private var knownGuestSource: String? + @Published private(set) var breakpoints: Set = [] + @Published private(set) var stoppedLine: Int? + @Published private(set) var stoppedToken: NSRange? + @Published private(set) var stepping = false + @Published private(set) var callerAvailable = false + @Published private(set) var runtimeErrorLine: Int? + @Published private(set) var runtimeErrorCode = "" + @Published private(set) var debugStatus = "Click beside a numbered line to set a breakpoint." + @Published private(set) var variables: [BASICVariable] = [] + @Published private(set) var inspectionAvailable = false + @Published private(set) var inspectionStatus = "Pause at a BASIC breakpoint to inspect variables." + @Published private(set) var watches: [String] = [] + @Published var watchEntry = "" + @Published var watchError: String? + private var inspectionRequest = UUID() + private var armedSource: String? + private var debugObservation: AnyCancellable? + var canContinue: Bool { machine.basicWorkspaceOwner == workspaceID && canTransfer && machine.state == .paused && machine.basicDebug.attached && source == armedSource } + var canStep: Bool { canContinue && stoppedLine != nil } + var canStepOut: Bool { canStep && callerAvailable } + var editorLocked: Bool { busy || stepping } + private var recoveryTask: Task? + private var restoring = false + var dirty: Bool { !source.utf8.elementsEqual(savedSource.utf8) } + var title: String { fileURL?.lastPathComponent ?? untitledTitle } + var canTransfer: Bool { !busy && !machine.busy && (machine.state == .running || machine.state == .paused) } + struct Draft: Codable { + var source: String + var savedSource: String + var filePath: String? + var fingerprint: String? + var watches: [String]? + } + init(machine: MachineModel, directory: URL, initialSource: String? = nil, title: String? = nil) { + self.machine = machine; self.directory = directory + if let initialSource { source = initialSource; savedSource = initialSource } + if let title { untitledTitle = title } + restoreRecovery() + debugObservation = machine.$basicDebug.combineLatest(machine.$basicWorkspaceOwner).sink { [weak self] value, owner in + guard let self else { return } + if owner != self.workspaceID { + if self.armedSource != nil { + self.armedSource = nil; self.stoppedLine = nil; self.stoppedToken = nil + self.stepping = false; self.callerAvailable = false + self.runtimeErrorLine = nil; self.runtimeErrorCode = ""; self.clearInspection() + self.debugStatus = "Another BASIC workspace controls the CoCo. These breakpoints apply on your next Run." + } + return + } + // @Published sends before MachineModel stores the new value. + // Defer the read until that snapshot has been fully accepted. + Task { [weak self] in self?.refreshInspection() } + self.stoppedLine = self.armedSource == self.source && value.attached ? value.line : nil + self.stoppedToken = self.stoppedLine != nil ? value.sourceRange : nil + self.stepping = self.armedSource == self.source && value.attached && value.stepping + self.refreshRuntimeState(value) + if self.armedSource != nil && !value.attached { + self.armedSource = nil + self.debugStatus = value.status.isEmpty ? "BASIC debugging ended after the machine changed." : value.status + } else if self.armedSource != nil { + self.debugStatus = value.line.map { "Paused at BASIC line \($0). Continue keeps variables and open files." } + ?? (value.status.isEmpty ? "BASIC breakpoints are active." : value.status) + } + } + } + private func detachOwnedDebug() { + guard machine.basicWorkspaceOwner == workspaceID else { return } + machine.basicWorkspaceOwner = nil + machine.detachBASICDebug() + } + private func refreshRuntimeState(_ value: MachineModel.BASICDebugState) { + let attached = machine.basicWorkspaceOwner == workspaceID && armedSource == source && value.attached + callerAvailable = attached && value.canStepOut + runtimeErrorLine = attached ? value.errorLine : nil + runtimeErrorCode = attached ? value.errorCode : "" + } + func clearInspection() { + inspectionRequest = UUID(); variables = []; inspectionAvailable = false + inspectionStatus = "Pause at a BASIC breakpoint or completed statement to inspect variables." + } + func refreshInspection() { + let stop = machine.basicDebug + guard machine.basicWorkspaceOwner == workspaceID, armedSource == source, stop.attached, stop.paused, !stop.stepping, + stop.line != nil || stop.atPrompt else { clearInspection(); return } + let text = source, request = UUID(); inspectionRequest = request + Task { + let (values, error) = await machine.inspectBASIC(source: text, stop: stop) + guard inspectionRequest == request, source == text, armedSource == text, + machine.basicWorkspaceOwner == workspaceID, machine.basicDebug == stop else { return } + variables = values ?? []; inspectionAvailable = values != nil + inspectionStatus = error ?? (values?.isEmpty == true ? "No variables have been assigned yet." : "Read-only · BASIC uses the first two characters of a name.") + } + } + func addWatch() { + guard let watch = BASICWatch(watchEntry) else { + watchError = "Use a variable name or numeric subscripts, such as A, NAME$ or A(2,3). Expressions are not evaluated."; return + } + guard watches.count < 128 || watches.contains(watch.canonical) else { watchError = "Up to 128 watches are supported."; return } + if !watches.contains(watch.canonical) { watches.append(watch.canonical) } + watchEntry = ""; watchError = nil; persistDraft() + } + func removeWatch(_ name: String) { watches.removeAll { $0 == name }; persistDraft() } + func watchValue(_ name: String) -> String { + inspectionAvailable ? (BASICWatch(name)?.value(in: variables) ?? "Invalid watch") : "Waiting for a BASIC stop" + } + static func fingerprint(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() } + static func readText(_ url: URL) throws -> (String, String) { + let values = try url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) + guard values.isRegularFile == true, let count = values.fileSize, count <= BASICLanguage.maximumSourceBytes else { + throw CocoaError(.fileReadTooLarge) + } + let data = try Data(contentsOf: url) + guard data.count <= BASICLanguage.maximumSourceBytes, !data.contains(0), + let text = String(data: data, encoding: .utf8) else { throw CocoaError(.fileReadInapplicableStringEncoding) } + return (text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n"), fingerprint(data)) + } + private func restoreRecovery() { + let url = directory.appendingPathComponent("Draft.json") + guard FileManager.default.fileExists(atPath: url.path) else { return } + do { + let values = try url.resourceValues(forKeys: [.fileSizeKey]) + guard let count = values.fileSize, count <= BASICLanguage.maximumSourceBytes * 12 else { throw CocoaError(.fileReadTooLarge) } + let draft = try JSONDecoder().decode(Draft.self, from: Data(contentsOf: url)) + guard draft.source.utf8.count <= BASICLanguage.maximumSourceBytes, + draft.savedSource.utf8.count <= BASICLanguage.maximumSourceBytes else { throw CocoaError(.fileReadTooLarge) } + restoring = true + source = draft.source; savedSource = draft.savedSource; fileURL = draft.filePath.map { URL(fileURLWithPath: $0) } + watches = Array((draft.watches ?? []).compactMap { BASICWatch($0)?.canonical }.prefix(128)) + fileFingerprint = draft.fingerprint; restoring = false + status = "Restored your BASIC workspace. The CoCo has not been changed." + } catch { message = "The saved BASIC workspace could not be restored: \(error.localizedDescription)" } + } + private func scheduleRecovery() { + recoveryTask?.cancel() + recoveryTask = Task { [weak self] in + do { try await Task.sleep(for: .milliseconds(350)) } catch { return } + self?.persistDraft() + } + } + func persistDraft() { + recoveryTask?.cancel() + guard source.utf8.count <= BASICLanguage.maximumSourceBytes else { message = "BASIC source is limited to 1 MB."; return } + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let value = Draft(source: source, savedSource: savedSource, filePath: fileURL?.path, fingerprint: fileFingerprint, watches: watches) + try JSONEncoder().encode(value).write(to: directory.appendingPathComponent("Draft.json"), options: .atomic) + } catch { message = "Could not save the recovery draft: \(error.localizedDescription)" } + } + func confirmDiscard(applyDiscard: Bool = true) -> Bool { + guard !busy else { message = "Wait for the BASIC operation to finish."; return false } + guard dirty else { persistDraft(); return true } + let alert = NSAlert(); alert.messageText = "Save changes to \(title)?" + alert.informativeText = "Save your readable BASIC source on the Mac before replacing it or quitting." + alert.addButton(withTitle: "Save"); alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard Changes") + switch alert.runModal() { + case .alertFirstButtonReturn: return save() + case .alertThirdButtonReturn: + if applyDiscard { source = savedSource; persistDraft() }; return true + default: return false + } + } + func newProgram() { + guard !busy, confirmDiscard() else { return } + fileURL = nil; fileFingerprint = nil; savedSource = BASICLanguage.sample; source = BASICLanguage.sample + breakpoints = []; armedSource = nil; stoppedLine = nil; detachOwnedDebug() + documentID = UUID(); message = nil; hint = nil; status = "New example. Nothing has been loaded into the CoCo."; persistDraft() + } + func open() { + guard !busy, confirmDiscard(applyDiscard: false) else { return } + let panel = NSOpenPanel(); panel.title = "Open BASIC Source"; panel.allowsMultipleSelection = false + panel.canChooseDirectories = false + panel.message = "Choose readable, line-numbered BASIC text. Tokenized disk or cassette files are not source text." + panel.allowedContentTypes = [.plainText, UTType(filenameExtension: "bas") ?? .plainText] + guard panel.runModal() == .OK, let url = panel.url else { return } + openSource(at: url) + } + @discardableResult func openSource(at url: URL) -> Bool { + guard !busy else { return false } + do { + let (text, hash) = try Self.readText(url) + fileURL = url; fileFingerprint = hash; savedSource = text; source = text + breakpoints = []; armedSource = nil; stoppedLine = nil; detachOwnedDebug() + documentID = UUID(); message = nil; hint = nil; status = "Opened \(url.lastPathComponent). The CoCo has not been changed."; persistDraft() + return true + } catch { message = "Could not open BASIC source: \(error.localizedDescription)"; return false } + } + @discardableResult func save(as: Bool = false) -> Bool { + guard !busy, source.utf8.count <= BASICLanguage.maximumSourceBytes else { return false } + var target = fileURL + if target == nil || `as` { + let panel = NSSavePanel(); panel.title = "Save BASIC Source"; panel.nameFieldStringValue = fileURL?.lastPathComponent ?? "HelloCoCo.bas" + panel.allowedContentTypes = [UTType(filenameExtension: "bas") ?? .plainText]; panel.canCreateDirectories = true + guard panel.runModal() == .OK, let url = panel.url else { return false }; target = url + } + guard let target else { return false } + return saveSource(to: target) + } + @discardableResult func saveSource(to target: URL) -> Bool { + guard !busy, source.utf8.count <= BASICLanguage.maximumSourceBytes else { return false } + do { + if target == fileURL, let fingerprint = fileFingerprint { + let existing = try? Self.readText(target).1 + if existing != fingerprint { + let alert = NSAlert(); alert.messageText = "The BASIC source changed outside VCC Plus." + alert.informativeText = "Replace the file with your editor text? Choose Cancel to keep both and use Save As." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Replace File") + guard alert.runModal() == .alertSecondButtonReturn else { return false } + } + } + let data = Data(source.utf8); try data.write(to: target, options: .atomic) + fileURL = target; fileFingerprint = Self.fingerprint(data); savedSource = source + message = nil; status = "Saved \(target.lastPathComponent)."; persistDraft(); return true + } catch { message = "Could not save BASIC source: \(error.localizedDescription)"; return false } + } + private var cursorBreakpointLine: Int? { + let text = source as NSString + guard editorOffset >= 0, editorOffset <= text.length else { return nil } + let range = text.lineRange(for: NSRange(location: editorOffset, length: 0)) + return BASICLanguage.analyze(text.substring(with: range)).lines.first?.number + } + var cursorBreakpointHelp: String { + guard let line = cursorBreakpointLine else { return "Place the insertion point on a numbered BASIC statement to set a breakpoint" } + return BreakpointRuler.actionName(line, set: breakpoints.contains(line)) + } + func toggleBreakpointAtCursor() { + guard let line = cursorBreakpointLine else { + message = "Place the insertion point on a numbered BASIC statement first."; return + } + toggleBreakpoint(line) + } + func toggleBreakpoint(_ line: Int) { + guard !busy else { return } + if breakpoints.contains(line) { breakpoints.remove(line) } + else { + let matches = BASICLanguage.analyze(source).lines.filter { $0.number == line } + guard matches.count == 1, let entry = matches.first, + NSMaxRange(entry.labelRange) < NSMaxRange(entry.range), + !(source as NSString).substring(with: NSRange(location: NSMaxRange(entry.labelRange), length: NSMaxRange(entry.range) - NSMaxRange(entry.labelRange))) + .trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + message = "Breakpoints need a unique line number with a BASIC statement."; return + } + guard breakpoints.count < 1024 else { message = "At most 1024 BASIC breakpoints are supported."; return } + breakpoints.insert(line) + } + updateBreakpoints() + } + func clearBreakpoints() { + guard !busy else { return }; breakpoints = []; updateBreakpoints() + } + private func updateBreakpoints() { + message = nil + let text = source, points = breakpoints + // Before the first transfer these are editor intentions only. An + // atomic Run installs the program and its points together. + guard canTransfer, knownGuestSource != nil, machine.basicWorkspaceOwner == workspaceID else { + debugStatus = points.isEmpty ? "No BASIC breakpoints." : "\(points.count) breakpoint(s) will apply on Run."; return + } + busy = true + Task { + defer { busy = false } + let configured = await machine.configureBASICBreakpoints(points, source: text) + guard machine.basicWorkspaceOwner == workspaceID, source == text else { return } + if configured { + armedSource = text + stoppedLine = machine.basicDebug.line; stoppedToken = machine.basicDebug.sourceRange + refreshInspection() + debugStatus = stoppedLine.map { "Paused at BASIC line \($0)." } ?? "BASIC breakpoints are active." + } else { + armedSource = nil; stoppedLine = nil; detachOwnedDebug() + debugStatus = "Editor and CoCo differ. These breakpoints will apply on the next Run." + } + } + } + func stepProgram(over: Bool, out: Bool = false) { + guard out ? canStepOut : canStep else { return } + let text = source; busy = true; message = nil + Task { + defer { busy = false } + let succeeded = out ? await machine.stepOutBASIC(source: text) : await machine.stepBASIC(source: text, over: over) + if !succeeded { + message = machine.fileError ?? "The BASIC stop is no longer current." + } + } + } + func cancelStep() { guard stepping else { return }; machine.pause() } + func continueProgram() { + guard canContinue else { return } + let text = source; busy = true; message = nil + Task { + defer { busy = false } + if !((await machine.continueBASIC(source: text))) { message = machine.fileError ?? "The BASIC stop is no longer current." } + } + } + func checkSource() { + guard !busy, editorAction == nil else { return } + let analysis = BASICLanguage.analyze(source) + diagnostics = analysis.diagnostics; message = nil + status = analysis.diagnostics.isEmpty + ? "No source-structure issues found. BASIC checks statement syntax when the program runs." + : "Source check found \(analysis.diagnostics.count) \(analysis.diagnostics.count == 1 ? "issue" : "issues"). Select an issue to show its source line." + } + func goToLine(_ number: Int) { + guard !busy, editorAction == nil else { return } + let analysis = BASICLanguage.analyze(source) + let matches = analysis.lines.filter { $0.number == number } + guard (0...63999).contains(number), matches.count == 1, let line = matches.first else { + message = matches.count > 1 ? "BASIC line \(number) is duplicated. Check Source before navigating." + : "No BASIC line \(number) exists in this source. Use a program line number, not an editor row." + return + } + message = nil + editorAction = .init(expectedSource: source, operation: .select(line.range)) + status = "BASIC line \(number)." + } + func selectDiagnostic(_ diagnostic: BASICLanguage.Diagnostic) { + guard !busy, editorAction == nil, diagnostics.contains(where: { $0.id == diagnostic.id }) else { return } + editorAction = .init(expectedSource: source, operation: .select(diagnostic.range)) + } + func renumber(start: Int, increment: Int) { + guard !busy, editorAction == nil else { return } + do { + let result = try BASICLanguage.renumber(source, start: start, step: increment) + message = nil; diagnostics = [] + guard result.source != source else { status = "The program already uses those line numbers."; return } + editorAction = .init(expectedSource: source, operation: .replace(source: result.source, undoName: "Renumber BASIC")) + status = "Renumbered \(result.lineCount) lines and \(result.changedReferences) references. Undo restores the previous source." + } catch { + diagnostics = BASICLanguage.analyze(source).diagnostics + message = error.localizedDescription + } + } + func editorActionHandled(id: UUID, applied: Bool) { + guard editorAction?.id == id else { return } + if applied, case .replace(_, let name) = editorAction?.operation, name == "Renumber BASIC", !breakpoints.isEmpty { + breakpoints = []; armedSource = nil; stoppedLine = nil; detachOwnedDebug() + debugStatus = "Line numbers changed. Set breakpoints on the renumbered program." + } + editorAction = nil + if !applied { message = "The source or insertion point changed before the edit could be applied. Try the action again." } + } + private func validateSourceStructure(_ text: String) -> Bool { + let analysis = BASICLanguage.analyze(text) + diagnostics = analysis.diagnostics + guard !analysis.hasErrors else { + message = "Fix the source errors below before loading or exporting. Select an issue to show its source line." + return false + } + return true + } + var suggestedExportName: String { BASICExportName.suggestion(for: fileURL) } + func chooseExport(_ kind: BASICExportKind, name: String, dosBoot: Bool) { + Task { _ = await performExport(kind, name: name, dosBoot: dosBoot, destination: nil) } + } + /// The save panel and regression checks share one production export path. + @discardableResult func exportImage(_ kind: BASICExportKind, name: String, dosBoot: Bool = false, to destination: URL) async -> Bool { + await performExport(kind, name: name, dosBoot: dosBoot, destination: destination) + } + private func performExport(_ kind: BASICExportKind, name: String, dosBoot: Bool, destination: URL?) async -> Bool { + guard canTransfer else { message = "Start the bundled CoCo BASIC setup before exporting."; return false } + guard let name = BASICExportName.normalized(name) else { + message = "Use 1–8 letters or numbers for the CoCo program name, without an extension."; return false + } + let text = source, sourceURL = fileURL + guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + message = "Enter a line-numbered BASIC program before exporting."; return false + } + guard validateSourceStructure(text) else { return false } + busy = true; message = nil; persistDraft() + defer { busy = false } + guard let data = await machine.exportBASICSource(text, name: name, cassette: kind == .cassette) else { + message = machine.fileError ?? "Could not prepare the BASIC export."; return false + } + var target = destination + if target == nil { + let panel = NSSavePanel(); panel.title = kind.title + panel.nameFieldStringValue = name + "." + kind.fileExtension + panel.allowedContentTypes = [UTType(filenameExtension: kind.fileExtension) ?? .data] + panel.canCreateDirectories = true; panel.isExtensionHidden = false + panel.message = kind.instructions(name: name, dosBoot: dosBoot) + guard panel.runModal() == .OK, let chosen = panel.url else { return false }; target = chosen + } + guard let target else { return false } + do { + let output = kind == .disk && dosBoot ? try await DevelopmentBuildTools().bootableBASICDisk(data, name: name) : data + try await machine.writeBASICExport(output, to: target, sourceURL: sourceURL) + status = "Exported \(target.lastPathComponent). " + kind.instructions(name: name, dosBoot: dosBoot) + return true + } catch { message = "Could not export BASIC: \(error.localizedDescription)"; return false } + } + func transfer(run: Bool) { + Task { _ = await performTransfer(run: run) } + } + + /// Both the editor and the reviewed run use the same source validation and replacement confirmation. + func performTransfer(run: Bool, reviewIsCurrent: (() -> Bool)? = nil) async -> (VCCMachineSnapshot, String)? { + guard canTransfer else { return nil } + let text = source + guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { message = "Enter a line-numbered BASIC program first."; return nil } + guard validateSourceStructure(text) else { return nil } + busy = true; message = nil; persistDraft() + defer { busy = false } + let prior = reviewIsCurrent == nil ? nil : await machine.mcpMachineSnapshot() + guard reviewIsCurrent?() != false else { return nil } + guard let existing = await machine.readBASICSource() else { message = machine.fileError ?? "Could not inspect BASIC memory."; return nil } + if machine.assemblyAttached || (!existing.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && existing != knownGuestSource) { + let alert = NSAlert(); alert.messageText = machine.assemblyAttached ? "Take over the assembly session with BASIC?" : "Replace the BASIC program in the CoCo?" + alert.informativeText = "This replaces program memory and clears its variables. Mounted media and machine settings are kept. Use Read from CoCo first if you want to save that program." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: run ? "Replace and Run" : "Replace and Load") + guard alert.runModal() == .alertSecondButtonReturn else { return nil } + } + guard reviewIsCurrent?() != false, source == text else { return nil } + guard let snapshot = await machine.loadBASICSource(text, run: run, breakpoints: breakpoints, + review: prior.map { ($0, existing) }) else { message = machine.fileError ?? "BASIC transfer failed."; return nil } + machine.basicWorkspaceOwner = workspaceID + let loadedSource = reviewIsCurrent == nil ? await machine.readBASICSource() : snapshot.assistantLoadedSource + guard machine.basicWorkspaceOwner == workspaceID, source == text else { return nil } + knownGuestSource = loadedSource + armedSource = machine.basicDebug.attached ? text : nil + refreshRuntimeState(machine.basicDebug) + stoppedLine = machine.basicDebug.line; stoppedToken = machine.basicDebug.sourceRange + refreshInspection() + if machine.basicDebug.attached { + debugStatus = stoppedLine.map { "Paused at BASIC line \($0). Continue keeps variables and open files." } + ?? (breakpoints.isEmpty ? "No BASIC breakpoints." : "BASIC breakpoints are active.") + } else { + debugStatus = machine.basicDebug.status.isEmpty ? "BASIC debugging is detached." : machine.basicDebug.status + } + status = run ? "Loaded directly into BASIC memory and started. Use CoCo Break to stop a running program." : "Loaded directly into BASIC memory. Use LIST or RUN in the CoCo." + return loadedSource.map { (snapshot, $0) } + } + func readFromCoCo() { + guard canTransfer, confirmDiscard(applyDiscard: false) else { return } + busy = true; message = nil + Task { + defer { busy = false } + guard let text = await machine.readBASICSource() else { message = machine.fileError ?? "Could not read BASIC memory."; return } + fileURL = nil; fileFingerprint = nil; savedSource = ""; source = text; knownGuestSource = text + breakpoints = []; armedSource = nil; stoppedLine = nil; detachOwnedDebug() + documentID = UUID(); hint = nil; status = "Read from CoCo memory. Save a source copy on the Mac to keep it."; persistDraft() + } + } + func statusMessage(_ value: String) { status = value } + func cursorChanged(_ offset: Int) { + editorOffset = offset + if let keyword = BASICReferenceContext.keyword(in: source, at: offset), + let catalog = try? BASICReferenceCatalog.bundled.get() { + let candidates = catalog.entries.filter { $0.keyword == keyword } + let entry = candidates.first { $0.dialect == machine.basicReferenceDialect } + ?? candidates.first { $0.dialect == .common } + ?? candidates.first { $0.dialect == .disk } + hint = entry?.syntax.first + } else { hint = BASICLanguage.hint(source, at: offset) } + } +} diff --git a/platforms/macos/App/BASICDevelopmentView.swift b/platforms/macos/App/BASICDevelopmentView.swift new file mode 100644 index 0000000..21d4b79 --- /dev/null +++ b/platforms/macos/App/BASICDevelopmentView.swift @@ -0,0 +1,820 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit + +struct BASICDevelopmentView: View { + @ObservedObject var model: BASICDevelopmentModel + @StateObject private var finder = SourceFind() + let reference: BASICReferenceModel? + @ObservedObject private var menu: MachineMenuState + @Environment(\.openWindow) private var openWindow + @State private var exportKind: BASICExportKind? + @State private var editingSheet: BASICEditingSheet? + @State private var diagnosticsExpanded = true + @State private var pendingEditingAction: (() -> Void)? + @State private var pendingExport: (kind: BASICExportKind, name: String, dosBoot: Bool)? + init(model: BASICDevelopmentModel, reference: BASICReferenceModel? = nil) { + self.model = model; self.reference = reference; menu = model.machine.menuState + } + private func quickHelp(_ keyword: String?) { + if let keyword { reference?.show(keyword: keyword, dialect: model.machine.basicReferenceDialect) } + openWindow(id: "basic-reference") + } + private var unavailable: Bool { model.busy || menu.values.busy || ![VCCMachineState.running, .paused].contains(menu.values.state) } + var body: some View { + GeometryReader { geometry in + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 12) { + Image(systemName: "terminal").font(.largeTitle).foregroundStyle(.tint) + VStack(alignment: .leading, spacing: 3) { + Text("BASIC Development").font(.title2.bold()) + Text("Edit on your Mac · Run in your CoCo").font(.callout).foregroundStyle(.secondary) + } + Spacer() + Button { openWindow(id: "basic-reference") } label: { Label("Reference", systemImage: "book.closed") } + .accessibilityIdentifier("basic.reference.open") + Button { openWindow(id: "machine") } label: { Label("Show CoCo", systemImage: "desktopcomputer") } + .accessibilityIdentifier("basic.show-machine") + }.padding(16) + Divider() + HStack(spacing: 10) { + Button { model.newProgram() } label: { Label("New", systemImage: "doc.badge.plus") }.accessibilityIdentifier("basic.new") + Button { model.open() } label: { Label("Open…", systemImage: "folder") }.accessibilityIdentifier("basic.open") + Button { model.save() } label: { Label("Save", systemImage: "square.and.arrow.down") } + .keyboardShortcut("s", modifiers: .command).accessibilityIdentifier("basic.save") + Menu { + Button("Save As…") { model.save(as: true) } + Button("Local Assistant Access…", systemImage: "link") { MCPAccess.shared.show(for: model) } + .accessibilityIdentifier("basic.assistant.access") + Divider() + Button("Export Disk…", systemImage: "externaldrive") { exportKind = .disk } + .disabled(unavailable).accessibilityIdentifier("basic.export-disk") + Button("Export Cassette…", systemImage: "recordingtape") { exportKind = .cassette } + .disabled(unavailable).accessibilityIdentifier("basic.export-cassette") + } label: { Image(systemName: "ellipsis.circle") }.menuStyle(.borderlessButton).frame(width: 25).help("Show more BASIC file actions").accessibilityLabel("More file actions").accessibilityIdentifier("basic.file-actions") + Spacer(minLength: 12) + Button { model.readFromCoCo() } label: { Label("Read from CoCo", systemImage: "arrow.down.doc") } + .disabled(unavailable).accessibilityIdentifier("basic.read") + Button { model.transfer(run: false) } label: { Label("Load into CoCo", systemImage: "arrow.up.doc") } + .disabled(unavailable).accessibilityIdentifier("basic.load") + Button { model.transfer(run: true) } label: { Label("Run", systemImage: "play.fill") } + .buttonStyle(.borderedProminent).disabled(unavailable).accessibilityIdentifier("basic.run") + }.controlSize(.regular).padding(.horizontal,16).padding(.vertical,10).disabled(model.editorLocked) + HStack { + Label(model.title, systemImage: "doc.text").fontWeight(.medium).lineLimit(1) + if model.dirty { Text("Edited").foregroundStyle(.secondary) } + Spacer() + SourceFindButton(finder: finder) + Button { model.toggleBreakpointAtCursor() } label: { Image(systemName: "record.circle") } + .help(model.cursorBreakpointHelp) + .accessibilityLabel(model.cursorBreakpointHelp) + .accessibilityIdentifier("basic.toggle-breakpoint").disabled(model.editorLocked) + Button { model.continueProgram() } label: { Label("Continue", systemImage: "play.fill") } + .disabled(!model.canContinue).accessibilityIdentifier("basic.continue") + Button { model.stepProgram(over: false) } label: { Image(systemName: "arrow.down.to.line") } + .help("Run one BASIC statement, following GOSUB into its subroutine") + .accessibilityLabel("Step Into BASIC statement").accessibilityIdentifier("basic.step-into") + .disabled(!model.canStep) + Button { model.stepProgram(over: true) } label: { Image(systemName: "arrow.turn.up.right") } + .help("Run one BASIC statement, continuing through a GOSUB unless a breakpoint is hit") + .accessibilityLabel("Step Over BASIC subroutine").accessibilityIdentifier("basic.step-over") + .disabled(!model.canStep) + Button { model.stepProgram(over: false, out: true) } label: { Image(systemName: "arrow.up.to.line") } + .help("Run until this GOSUB returns to its caller or a breakpoint is hit") + .accessibilityLabel("Step Out of BASIC subroutine").accessibilityIdentifier("basic.step-out") + .disabled(!model.canStepOut) + if model.stepping { + Button { model.cancelStep() } label: { Image(systemName: "pause.fill") } + .help("Pause the current BASIC step").accessibilityLabel("Pause BASIC step") + .accessibilityIdentifier("basic.pause-step") + } + Menu { + Button("Clear All Breakpoints", systemImage: "record.circle") { model.clearBreakpoints() } + .disabled(model.breakpoints.isEmpty).accessibilityIdentifier("basic.clear-breakpoints") + Divider() + Button("Check Source", systemImage: "checkmark.circle") { model.checkSource(); diagnosticsExpanded = true } + .accessibilityIdentifier("basic.check-source") + Button("Go to Line…", systemImage: "arrow.turn.down.right") { editingSheet = .goToLine } + .accessibilityIdentifier("basic.go-to-line") + Button("Renumber…", systemImage: "list.number") { editingSheet = .renumber } + .accessibilityIdentifier("basic.renumber") + } label: { Label("Editing", systemImage: "pencil.line") } + .disabled(model.editorLocked).accessibilityIdentifier("basic.editing-actions") + Button { model.completionRequest = UUID() } label: { Label("Complete", systemImage: "text.badge.plus") } + .help("Complete a BASIC keyword (Control–Space)").accessibilityIdentifier("basic.complete") + .disabled(model.editorLocked) + }.font(.callout).padding(.horizontal,16).padding(.bottom,8) + Divider() + if let message = model.message { + Label(message, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.orange) + .textSelection(.enabled).padding(10).frame(maxWidth:.infinity,alignment:.leading) + .background(.orange.opacity(0.08)).accessibilityIdentifier("basic.message") + } + if let line = model.runtimeErrorLine { + HStack(spacing: 10) { + Label("BASIC \(model.runtimeErrorCode.isEmpty ? "runtime" : model.runtimeErrorCode) error on line \(line)", systemImage: "exclamationmark.circle.fill") + .foregroundStyle(.red).accessibilityIdentifier("basic.runtime-error") + Text("The program ended. Continue returns to the prompt.").foregroundStyle(.secondary) + Spacer(minLength: 0) + Button { reference?.showError(code: model.runtimeErrorCode); openWindow(id: "basic-reference") } label: { + Image(systemName: "questionmark.circle") + }.help("Explain this BASIC error").accessibilityLabel("Explain BASIC error") + .accessibilityIdentifier("basic.reference.error") + Button("Show Line \(line)") { model.goToLine(line) } + .disabled(model.editorLocked).accessibilityIdentifier("basic.show-runtime-error") + }.font(.callout).padding(10).background(.red.opacity(0.06)) + } + SourceFindBar(finder: finder, source: model.source, readOnly: model.editorLocked) + BASICSourceEditor(finder: finder, text: $model.source, readOnly: model.editorLocked, completionRequest: model.completionRequest, + editorAction: model.editorAction, breakpoints: model.breakpoints, stoppedLine: model.stoppedLine, stoppedToken: model.stoppedToken, + toggleBreakpoint: model.toggleBreakpoint, + actionHandled: { id, applied in model.editorActionHandled(id: id, applied: applied) }, + cursorChanged: model.cursorChanged, assistance: { model.statusMessage($0) }, quickHelp: quickHelp, + attach: { model.assistantEditor = $0 }) + .id(model.documentID).frame(minHeight:120).accessibilityIdentifier("basic.editor") + HStack(spacing: 8) { + Image(systemName: model.stoppedLine == nil ? "record.circle" : "arrow.right.circle.fill") + .foregroundStyle(model.stoppedLine == nil ? Color.secondary : Color.orange) + Text(model.debugStatus).font(.caption).lineLimit(2) + .accessibilityIdentifier("basic.debug-status") + Spacer() + if !model.breakpoints.isEmpty { + Text("\(model.breakpoints.count) breakpoint\(model.breakpoints.count == 1 ? "" : "s")") + .font(.caption).foregroundStyle(.secondary) + } + }.padding(.horizontal, 12).padding(.vertical, 7) + // Reserve the window chrome and a useful editor height before + // allocating rows to the independently scrolling inspector. + BASICInspectionView(model: model, valuesHeight: max(36, min(160, + geometry.size.height - 560 - (!model.diagnostics.isEmpty && diagnosticsExpanded ? 130 : 0)))) + if !model.diagnostics.isEmpty { + Divider() + DisclosureGroup(isExpanded: $diagnosticsExpanded) { + ScrollView { + LazyVStack(alignment: .leading, spacing: 5) { + ForEach(model.diagnostics) { diagnostic in + Button { model.selectDiagnostic(diagnostic) } label: { + HStack(alignment: .top, spacing: 8) { + Image(systemName: diagnostic.severity == .error ? "exclamationmark.circle" : "exclamationmark.triangle") + .foregroundStyle(diagnostic.severity == .error ? Color.red : Color.orange) + Text("Row \(diagnostic.row)").monospacedDigit().fontWeight(.medium) + Text(diagnostic.message).frame(maxWidth: .infinity, alignment: .leading) + }.contentShape(Rectangle()) + }.buttonStyle(.plain).font(.callout).disabled(model.editorLocked) + .accessibilityLabel("Source row \(diagnostic.row): \(diagnostic.message). Go to source.") + .accessibilityIdentifier("basic.diagnostic.\(diagnostic.id)") + } + }.padding(.vertical, 6) + }.frame(maxHeight: 100) + } label: { + Text("Source checks · \(model.diagnostics.count)").font(.callout.bold()) + }.padding(.horizontal, 14).padding(.vertical, 8) + .accessibilityIdentifier("basic.diagnostics") + } + HStack(alignment:.top,spacing:8) { + Image(systemName: "info.circle").foregroundStyle(.secondary) + Text(model.hint ?? "Return continues line numbering. Tab accepts a faint keyword suggestion; Control–Space shows all matches.") + .font(.system(.caption,design:.monospaced)).textSelection(.enabled) + .frame(maxWidth:.infinity,alignment:.leading).accessibilityIdentifier("basic.hint") + Button { quickHelp(BASICReferenceContext.keyword(in: model.source, at: model.editorOffset)) } label: { + Label("Quick Help", systemImage: "questionmark.circle") + }.keyboardShortcut("h", modifiers: [.control, .shift]) + .help("Look up the command at the insertion point (Control–Shift–H)") + .accessibilityIdentifier("basic.reference.context") + }.padding(10).frame(minHeight:42,alignment:.top) + Divider() + VStack(alignment:.leading,spacing:5) { + HStack(alignment:.top) { + if model.busy { ProgressView().controlSize(.small) } + Text(model.status).font(.callout).textSelection(.enabled).accessibilityIdentifier("basic.status") + } + Text("Direct loading supports Disk BASIC, Hard Drive BASIC and CoCo SDC at the BASIC OK prompt. Use CoCo Break to stop before replacing a running program. Read from CoCo retrieves program text, not variables.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal:false,vertical:true) + .accessibilityIdentifier("basic.preset-support") + }.padding(14) + }.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + }.frame(minWidth:850,minHeight:560) + .focusedSceneValue(\.sourceFind, finder) + .onDisappear { model.persistDraft() } + .sheet(item: $editingSheet, onDismiss: { + let action = pendingEditingAction; pendingEditingAction = nil; action?() + }) { kind in + BASICEditingOptions(kind: kind, + goToLine: { number in + pendingEditingAction = { model.goToLine(number) }; editingSheet = nil + }, + renumber: { start, increment in + pendingEditingAction = { model.renumber(start: start, increment: increment) }; editingSheet = nil + }, + cancel: { editingSheet = nil }) + } + .sheet(item: $exportKind, onDismiss: { + if let request = pendingExport { + pendingExport = nil; model.chooseExport(request.kind, name: request.name, dosBoot: request.dosBoot) + } + }) { kind in + BASICExportOptions(kind: kind, initialName: model.suggestedExportName, + confirm: { name, boot in pendingExport = (kind, name, boot); exportKind = nil }, + cancel: { exportKind = nil }) + } + } +} + +private enum BASICEditingSheet: String, Identifiable { + case goToLine, renumber + var id: String { rawValue } +} + +private struct BASICEditingOptions: View { + let kind: BASICEditingSheet + let goToLine: (Int) -> Void + let renumber: (Int, Int) -> Void + let cancel: () -> Void + @State private var line = "10" + @State private var increment = "10" + @FocusState private var firstFieldFocused: Bool + private var firstNumber: Int? { Int(line.trimmingCharacters(in: .whitespaces)) } + private var step: Int? { Int(increment.trimmingCharacters(in: .whitespaces)) } + private var valid: Bool { + guard let firstNumber, (0...63999).contains(firstNumber) else { return false } + return kind == .goToLine || step.map { (1...63999).contains($0) } == true + } + var body: some View { + VStack(alignment: .leading, spacing: 16) { + Label(kind == .goToLine ? "Go to BASIC Line" : "Renumber Program", + systemImage: kind == .goToLine ? "arrow.turn.down.right" : "list.number").font(.title2.bold()) + if kind == .goToLine { + Text("Find a BASIC line number in your editor source. This does not move the running CoCo program.") + .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + TextField("BASIC line number", text: $line).textFieldStyle(.roundedBorder) + .focused($firstFieldFocused).accessibilityIdentifier("basic.go-line-number") + } else { + Text("Renumber the entire editor program and update its recognized line references. Strings, comments, and DATA values stay unchanged.") + .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 10) { + GridRow { + Text("Start at") + TextField("Starting line number", text: $line).textFieldStyle(.roundedBorder) + .focused($firstFieldFocused).accessibilityIdentifier("basic.renumber-start") + } + GridRow { + Text("Increment") + TextField("Line number increment", text: $increment).textFieldStyle(.roundedBorder) + .accessibilityIdentifier("basic.renumber-increment") + } + } + Text("The CoCo program is not changed. You can undo this edit with ⌘Z.") + .font(.callout).fixedSize(horizontal: false, vertical: true) + } + Text(kind == .goToLine ? "BASIC line numbers range from 0 to 63999." : "Use line numbers from 0 to 63999 and a positive increment. Source problems must be corrected before renumbering.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + HStack { + Spacer() + Button("Cancel", action: cancel).keyboardShortcut(.cancelAction) + Button(kind == .goToLine ? "Go to Line" : "Renumber") { + guard let firstNumber, valid else { return } + if kind == .goToLine { goToLine(firstNumber) } + else if let step { renumber(firstNumber, step) } + }.keyboardShortcut(.defaultAction).disabled(!valid) + .accessibilityIdentifier("basic.editing-confirm") + } + }.padding(22).frame(width: 430).task { firstFieldFocused = true } + } +} + +private struct BASICExportOptions: View { + let kind: BASICExportKind + let confirm: (String, Bool) -> Void + let cancel: () -> Void + @State private var name: String + @State private var dosBoot = false + @FocusState private var nameFocused: Bool + init(kind: BASICExportKind, initialName: String, confirm: @escaping (String, Bool) -> Void, cancel: @escaping () -> Void) { + self.kind = kind; self.confirm = confirm; self.cancel = cancel + _name = State(initialValue: initialName) + } + private var validName: String? { BASICExportName.normalized(name) } + var body: some View { + VStack(alignment: .leading, spacing: 16) { + Label(kind.title, systemImage: kind.symbol).font(.title2.bold()) + Text(kind == .disk + ? "Create a fresh 35-track Disk BASIC disk with your current editor program." + : "Create a cassette image with your current editor program.") + .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + VStack(alignment: .leading, spacing: 6) { + TextField("CoCo program name", text: $name).textFieldStyle(.roundedBorder) + .focused($nameFocused).accessibilityIdentifier("basic.export-name") + Text("Use 1–8 letters or numbers, without an extension. The CoCo name will be uppercase.") + .font(.caption).foregroundStyle(.secondary) + } + if let validName { + Label(kind == .disk ? validName + ".BAS" : validName, systemImage: "doc.text") + .font(.system(.callout, design: .monospaced)) + } + if kind == .disk { + Toggle("Install DOS bootloader", isOn: $dosBoot) + .accessibilityIdentifier("basic.export-dos") + } + if let validName { + Text(kind.instructions(name: validName, dosBoot: dosBoot)) + .accessibilityIdentifier("basic.export-commands") + .font(.callout).fixedSize(horizontal: false, vertical: true) + } + HStack { + Spacer() + Button("Cancel", action: cancel).keyboardShortcut(.cancelAction) + Button("Choose Location…") { if let validName { confirm(validName, dosBoot) } } + .keyboardShortcut(.defaultAction).disabled(validName == nil) + .accessibilityIdentifier("basic.export-location") + } + }.padding(22).frame(width: 430).task { nameFocused = true } + } +} + +/// Stable AppKit text editor: only explicit document changes reset Undo. +struct BASICSourceEditor: NSViewRepresentable { + let finder: SourceFind + @Binding var text: String + let readOnly: Bool + let completionRequest: UUID + let editorAction: BASICEditorAction? + let breakpoints: Set + let stoppedLine: Int? + let stoppedToken: NSRange? + let toggleBreakpoint: (Int) -> Void + let actionHandled: (UUID, Bool) -> Void + let cursorChanged: (Int) -> Void + let assistance: (String) -> Void + let quickHelp: (String?) -> Void + var attach: (BASICTextView) -> Void = { _ in } + func makeCoordinator() -> Coordinator { Coordinator(self) } + func makeNSView(context: Context) -> NSScrollView { + let scroll=NSScrollView(); scroll.hasVerticalScroller=true; scroll.hasHorizontalScroller=true; scroll.autohidesScrollers=true + // AppKit ruler decorations must not paint into the surrounding SwiftUI + // toolbar, inspector or footer when this representable resizes. + scroll.wantsLayer = true; scroll.layer?.masksToBounds = true + let editor=BASICTextView(frame:.zero) + // Highlighting and breakpoint geometry use TextKit 1. Establish it + // before setting up the unwrapped container, even for an empty draft. + _ = editor.layoutManager + attach(editor) + editor.delegate=context.coordinator; editor.string=text; editor.allowsUndo=true; editor.isRichText=false + editor.isAutomaticQuoteSubstitutionEnabled=false; editor.isAutomaticDashSubstitutionEnabled=false + editor.isAutomaticTextReplacementEnabled=false; editor.isAutomaticSpellingCorrectionEnabled=false + editor.isContinuousSpellCheckingEnabled=false; editor.isGrammarCheckingEnabled=false + editor.isVerticallyResizable=true; editor.isHorizontallyResizable=true + editor.minSize=NSSize(width:0,height:0); editor.maxSize=NSSize(width:CGFloat.greatestFiniteMagnitude,height:CGFloat.greatestFiniteMagnitude) + editor.textContainer?.widthTracksTextView=false + editor.textContainer?.containerSize=editor.maxSize + editor.autoresizingMask = [.width] + editor.textContainerInset=NSSize(width:16,height:14) + editor.font = .monospacedSystemFont(ofSize:14,weight:.regular) + editor.backgroundColor = .textBackgroundColor; editor.textColor = .textColor + finder.editor = editor + editor.setAccessibilityLabel("BASIC source editor") + editor.setAccessibilityIdentifier("basic.source-text") + editor.assistance=assistance; editor.quickHelp = quickHelp; scroll.documentView=editor + scroll.verticalRulerView = BASICBreakpointRuler(textView: editor) + scroll.hasVerticalRuler = true; scroll.rulersVisible = true + editor.configureDebug(points: breakpoints, stoppedLine: stoppedLine, token: stoppedToken, toggle: toggleBreakpoint) + context.coordinator.highlight(editor) + return scroll + } + func updateNSView(_ scroll:NSScrollView,context:Context) { + context.coordinator.parent=self + guard let editor=scroll.documentView as? BASICTextView else { return } + finder.editor = editor + editor.assistance=assistance; editor.quickHelp = quickHelp; editor.isEditable = !readOnly + editor.refreshInlineSuggestion() + if !editor.string.utf8.elementsEqual(text.utf8) { + editor.string=text; editor.undoManager?.removeAllActions(); context.coordinator.highlight(editor) + } + editor.configureDebug(points: breakpoints, stoppedLine: stoppedLine, token: stoppedToken, toggle: toggleBreakpoint) + if let action = editorAction, context.coordinator.actionID != action.id { + context.coordinator.actionID = action.id + let coordinator = context.coordinator + DispatchQueue.main.async { [weak editor, weak coordinator] in + guard let coordinator else { return } + let applied = editor?.applyEditorAction(action) ?? false + coordinator.parent.actionHandled(action.id, applied) + } + } + if context.coordinator.completionRequest != completionRequest { + context.coordinator.completionRequest=completionRequest + DispatchQueue.main.async { [weak editor] in + guard let editor, editor.isEditable else { return } + editor.window?.makeFirstResponder(editor); editor.complete(nil) + } + } + } + @MainActor final class Coordinator: NSObject,NSTextViewDelegate { + var parent:BASICSourceEditor + var completionRequest:UUID + var actionID:UUID? + init(_ parent:BASICSourceEditor) { self.parent=parent; completionRequest=parent.completionRequest } + func textDidChange(_ notification:Notification) { + guard let editor=notification.object as? BASICTextView else { return } + parent.text=editor.string; highlight(editor); reportCursor(editor) + editor.configureDebug(points: parent.breakpoints, stoppedLine: parent.stoppedLine, token: parent.stoppedToken, toggle: parent.toggleBreakpoint) + } + func textViewDidChangeSelection(_ notification:Notification) { + guard let editor=notification.object as? BASICTextView else { return }; reportCursor(editor) + } + func reportCursor(_ editor:NSTextView) { + let offset=editor.selectedRange().location + DispatchQueue.main.async { [weak self,weak editor] in + guard let self,let editor,editor.selectedRange().location == offset else { return }; self.parent.cursorChanged(offset) + } + } + func textView(_ textView:NSTextView,shouldChangeTextIn affectedCharRange:NSRange,replacementString:String?) -> Bool { + guard let replacementString else { return true } + let current=textView.string as NSString + guard affectedCharRange.location <= current.length, NSMaxRange(affectedCharRange) <= current.length else { return false } + guard current.replacingCharacters(in:affectedCharRange,with:replacementString).utf8.count <= BASICLanguage.maximumSourceBytes else { + parent.assistance("BASIC source is limited to 1 MB."); return false + }; return true + } + func highlight(_ editor:NSTextView) { + guard let storage=editor.textStorage else { return } + storage.beginEditing() + let full=NSRange(location:0,length:storage.length) + storage.addAttributes([.foregroundColor:NSColor.textColor,.font:NSFont.monospacedSystemFont(ofSize:14,weight:.regular)],range:full) + for span in BASICLanguage.spans(editor.string) { + let color:NSColor + switch span.kind { + case .keyword: color = .systemPurple + case .number: color = .systemBlue + case .string: color = .systemRed + case .comment: color = .secondaryLabelColor + case .data: color = .systemBrown + } + storage.addAttribute(.foregroundColor,value:color,range:span.range) + } + storage.endEditing() + editor.typingAttributes=[.foregroundColor:NSColor.textColor,.font:NSFont.monospacedSystemFont(ofSize:14,weight:.regular)] + } + } +} + +/// Native completion with an explicit acceptance operation, so Escape and moving +/// through candidates never alter the source or its Undo history. +final class BASICTextView: NSTextView, SourceFindEditor { + weak var sourceFind: SourceFind? + var assistance:((String)->Void)? + var quickHelp: ((String?) -> Void)? + private var helpOffset: Int? + override func menu(for event: NSEvent) -> NSMenu? { + let menu = super.menu(for: event) ?? NSMenu() + helpOffset = characterIndexForInsertion(at: convert(event.locationInWindow, from: nil)) + let item = NSMenuItem(title: "Quick Help for BASIC Command", action: #selector(showCommandHelp), keyEquivalent: "") + item.target = self + menu.insertItem(.separator(), at: 0); menu.insertItem(item, at: 0) + return menu + } + @objc private func showCommandHelp() { + quickHelp?(BASICReferenceContext.keyword(in: string, at: helpOffset ?? selectedRange().location)) + helpOffset = nil + } + override func mouseDown(with event: NSEvent) { + if event.modifierFlags.contains(.option), event.clickCount == 1 { + let offset = characterIndexForInsertion(at: convert(event.locationInWindow, from: nil)) + if let keyword = BASICReferenceContext.keyword(in: string, at: offset) { + quickHelp?(keyword); return + } + } + super.mouseDown(with: event) + } + private var sourceForCompletion:String? + private var completion:BASICLanguage.Completion? + private var completionOffset=0 + private(set) var numberedRows: [BASICLanguage.NumberedLine] = [] + private(set) var breakpointLines: Set = [] + private var decoratedSource = "" + private var executionLine: Int? + private var executionToken: NSRange? + func configureDebug(points: Set, stoppedLine: Int?, token: NSRange? = nil, toggle: @escaping (Int) -> Void) { + let ruler = enclosingScrollView?.verticalRulerView as? BASICBreakpointRuler + ruler?.onClick = toggle + ruler?.active = isEditable + ruler?.points = points + let sourceChanged = decoratedSource != string + let lineChanged = executionLine != stoppedLine || executionToken != token + guard sourceChanged || lineChanged || breakpointLines != points else { return } + decoratedSource = string; breakpointLines = points; executionLine = stoppedLine; executionToken = token + if sourceChanged { numberedRows = BASICLanguage.analyze(string).lines } + let full = NSRange(location: 0, length: (string as NSString).length) + layoutManager?.removeTemporaryAttribute(.backgroundColor, forCharacterRange: full) + if let stoppedLine, let row = numberedRows.first(where: { $0.number == stoppedLine }) { + layoutManager?.addTemporaryAttribute(.backgroundColor, value: NSColor.systemYellow.withAlphaComponent(0.2), forCharacterRange: row.range) + if let token, token.location >= row.range.location, NSMaxRange(token) <= NSMaxRange(row.range) { + layoutManager?.addTemporaryAttribute(.backgroundColor, value: NSColor.systemOrange.withAlphaComponent(0.5), forCharacterRange: token) + } + if lineChanged { scrollRangeToVisible(token ?? row.range) } + } + ruler?.invalidateMarkers() + } + private(set) var inlineSuggestion: BASICLanguage.InlineCompletion? + private var inlineSource = "" + private var inlineSelection = NSRange(location: NSNotFound, length: 0) + private var inlineDismissed = false + + func refreshInlineSuggestion() { + let selection = selectedRange() + if let sourceForCompletion, + sourceForCompletion != string || selection != NSRange(location: completionOffset, length: 0) { + self.sourceForCompletion = nil; completion = nil + } + if inlineSource != string || inlineSelection != selection { + inlineDismissed = false + inlineSource = string; inlineSelection = selection + } + inlineSuggestion = isEditable && !hasMarkedText() && selection.length == 0 && !inlineDismissed && sourceForCompletion == nil + ? BASICLanguage.inlineCompletion(string, at: selection.location) : nil + setAccessibilityHelp(inlineSuggestion.map { "Suggested keyword \($0.word). Press Tab to accept or Escape to dismiss." } + ?? "Numbered BASIC source. Return continues line numbering. Control–Space shows keyword completions.") + needsDisplay = true + } + override func didChangeText() { + super.didChangeText() + refreshInlineSuggestion() + } + override func setSelectedRange(_ charRange: NSRange, affinity: NSSelectionAffinity, stillSelecting flag: Bool) { + super.setSelectedRange(charRange, affinity: affinity, stillSelecting: flag) + refreshInlineSuggestion() + } + override func becomeFirstResponder() -> Bool { + let result = super.becomeFirstResponder(); refreshInlineSuggestion(); return result + } + override func resignFirstResponder() -> Bool { + let result = super.resignFirstResponder(); needsDisplay = true; return result + } + override func draw(_ dirtyRect: NSRect) { + super.draw(dirtyRect) + guard isEditable, !hasMarkedText(), window?.firstResponder === self, + let window, let suggestion = inlineSuggestion, + inlineSource == string, inlineSelection == selectedRange() else { return } + // Draw separately: previews never enter text storage, saves, transfers, + // accessibility's source value, or the Undo history. + let screenRect = firstRect(forCharacterRange: selectedRange(), actualRange: nil) + let rect = convert(window.convertFromScreen(screenRect), from: nil) + (suggestion.suffix as NSString).draw(at: rect.origin, withAttributes: [ + .font: font ?? NSFont.monospacedSystemFont(ofSize: 14, weight: .regular), + .foregroundColor: NSColor.secondaryLabelColor + ]) + } + override func insertTab(_ sender: Any?) { + refreshInlineSuggestion() + guard let suggestion = inlineSuggestion else { super.insertTab(sender); return } + breakUndoCoalescing() + insertText(suggestion.word, replacementRange: suggestion.range) + breakUndoCoalescing() + undoManager?.setActionName("Complete BASIC Keyword") + } + override func cancelOperation(_ sender: Any?) { + if inlineSuggestion != nil { + inlineDismissed = true; refreshInlineSuggestion() + } else { + // AppKit owns a native completion popup's Escape. Cached candidates + // alone do not mean that a popup is still handling the command. + sourceForCompletion = nil; completion = nil + if sourceFind?.cancel(from: self) != true { + // cancelOperation is optional; NSTextView need not implement a + // superclass method for this standard text command. + _ = nextResponder?.tryToPerform(#selector(NSResponder.cancelOperation(_:)), with: sender) + } + } + } + override func insertNewline(_ sender: Any?) { + guard isEditable, !hasMarkedText(), selectedRange().length == 0, + let insertion = BASICLanguage.nextLineInsertion(string, at: selectedRange().location) else { + super.insertNewline(sender); return + } + breakUndoCoalescing() + insertText(insertion, replacementRange: selectedRange()) + breakUndoCoalescing() + undoManager?.setActionName("Insert BASIC Line") + } + /// Apply an explicit source edit through AppKit so the ordinary Undo stack, + /// source binding, selection and syntax highlighting remain synchronized. + @discardableResult func applyEditorAction(_ action: BASICEditorAction, revealReplacementAt offset: Int? = nil) -> Bool { + guard isEditable, !hasMarkedText(), string == action.expectedSource else { return false } + switch action.operation { + case .replace(let source, let undoName): + guard source.utf8.count <= BASICLanguage.maximumSourceBytes else { return false } + if source != string { + breakUndoCoalescing() + insertText(source, replacementRange: NSRange(location: 0, length: (string as NSString).length)) + breakUndoCoalescing() + guard string == source else { return false } + undoManager?.setActionName(undoName) + } + if let offset { + setSelectedRange(NSRange(location: min(max(0, offset), (source as NSString).length), length: 0)) + } + case .select(let range): + let length = (string as NSString).length + guard range.location >= 0, range.location <= length, + range.length >= 0, range.length <= length - range.location else { return false } + setSelectedRange(range) + } + scrollRangeToVisible(selectedRange()) + window?.makeFirstResponder(self) + return true + } + override func complete(_ sender:Any?) { + guard prepareCompletion() else { return }; super.complete(sender) + } + @discardableResult func prepareCompletion() -> Bool { + sourceForCompletion=nil; completion=nil + guard isEditable,!hasMarkedText(),selectedRange().length == 0, + let next=BASICLanguage.completion(string,at:selectedRange().location) else { + assistance?("Type the beginning of a BASIC keyword, then choose Complete."); return false + } + sourceForCompletion=string; completion=next; completionOffset=selectedRange().location + refreshInlineSuggestion() + assistance?("\(next.words.count) BASIC keyword suggestions. Return accepts; Escape cancels.") + return true + } + override var rangeForUserCompletion:NSRange { sourceForCompletion == string ? completion?.range ?? NSRange(location:NSNotFound,length:0) : NSRange(location:NSNotFound,length:0) } + override func completions(forPartialWordRange charRange:NSRange,indexOfSelectedItem index:UnsafeMutablePointer?) -> [String]? { + guard sourceForCompletion == string, completion?.range == charRange else { return [] } + // Highlight the first choice so Return accepts it immediately. + // insertCompletion still refuses provisional list navigation. + index?.pointee = 0; return completion?.words + } + override func insertCompletion(_ word:String,forPartialWordRange charRange:NSRange,movement:Int,isFinal flag:Bool) { + guard flag else { return } + defer { sourceForCompletion=nil; completion=nil; refreshInlineSuggestion() } + guard movement != NSTextMovement.cancel.rawValue,isEditable,!hasMarkedText(),sourceForCompletion == string, + selectedRange() == NSRange(location:completionOffset,length:0),completion?.range == charRange, + completion?.words.contains(word) == true else { return } + breakUndoCoalescing(); insertText(word,replacementRange:charRange); breakUndoCoalescing() + undoManager?.setActionName("Complete BASIC Keyword") + } + override func performKeyEquivalent(with event:NSEvent) -> Bool { + let modifiers=event.modifierFlags.intersection([.command,.control,.option,.shift]) + if event.keyCode == 49,modifiers == [.control] { complete(nil); return true } + return super.performKeyEquivalent(with:event) + } +} + +/// Visual gutter plus the native toolbar action provide mouse and keyboard +/// alternatives. Line numbers remain ordinary editable source text. +final class BASICBreakpointRuler: BreakpointRuler { + private weak var editor: BASICTextView? + init(textView: BASICTextView) { + editor = textView + super.init(scrollView: textView.enclosingScrollView!, orientation: .verticalRuler) + clientView = textView; ruleThickness = 30 + setAccessibilityLabel("BASIC breakpoint gutter") + setAccessibilityHelp("Click beside a numbered statement to toggle its breakpoint. The toolbar offers the same action at the insertion point.") + } + required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + private func targets() -> [(Int, NSRect)] { + guard let editor, let layout = editor.layoutManager, let container = editor.textContainer else { return [] } + let origin = editor.textContainerOrigin + // Horizontal scrolling must not change which rows appear in the gutter. + let viewport = NSRect(x: 0, y: editor.visibleRect.minY - origin.y, + width: max(1, editor.bounds.width), height: editor.visibleRect.height) + let glyphs = layout.glyphRange(forBoundingRect: viewport, in: container) + let visible = layout.characterRange(forGlyphRange: glyphs, actualGlyphRange: nil) + return editor.numberedRows.compactMap { row in + guard NSLocationInRange(row.labelRange.location, visible) else { return nil } + let glyph = layout.glyphIndexForCharacter(at: row.labelRange.location) + let fragment = layout.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil) + let point = convert(NSPoint(x: 0, y: fragment.midY + editor.textContainerOrigin.y), from: editor) + return (row.number, NSRect(x: 8, y: point.y - 6, width: 12, height: 12)) + } + } + override var wantsDefaultClipping: Bool { true } + override func draw(_ dirtyRect: NSRect) { + // NSRulerView's standard edge treatment can extend outside its frame. + // This gutter has no native ruler ticks or markers: draw its own edge. + NSGraphicsContext.saveGraphicsState() + NSBezierPath(rect: bounds).addClip() + drawHashMarksAndLabels(in: dirtyRect) + NSColor.separatorColor.setFill() + NSRect(x: bounds.maxX - 1, y: bounds.minY, width: 1, height: bounds.height).fill() + NSGraphicsContext.restoreGraphicsState() + } + override func drawHashMarksAndLabels(in rect: NSRect) { + NSColor.windowBackgroundColor.setFill(); bounds.fill() + guard let editor else { return } + for (line, target) in targets() where target.intersects(bounds) { + let path = NSBezierPath(ovalIn: target) + if editor.breakpointLines.contains(line) { NSColor.systemRed.setFill(); path.fill() } + else { NSColor.separatorColor.setStroke(); path.lineWidth = 1; path.stroke() } + } + } + override func visibleRows() -> [Row] { + targets().compactMap { line, marker in + let hit = marker.insetBy(dx: -8, dy: -3).intersection(bounds) + return hit.isEmpty ? nil : (line, hit) + } + } +} + +private struct BASICInspectionView: View { + @ObservedObject var model: BASICDevelopmentModel + let valuesHeight: CGFloat + @State private var expanded = true + @State private var showingWatches = false + var body: some View { + Divider() + DisclosureGroup(isExpanded: $expanded) { + VStack(alignment: .leading, spacing: 6) { + HStack { + Picker("Inspect", selection: $showingWatches) { + Text("Variables").tag(false); Text("Watches").tag(true) + }.pickerStyle(.segmented).labelsHidden().frame(width: 210).accessibilityIdentifier("basic.inspector-tabs") + Text(model.inspectionStatus).font(.caption).foregroundStyle(.secondary).lineLimit(2) + .accessibilityIdentifier("basic.inspection-status") + Spacer(minLength: 0) + Button { model.refreshInspection() } label: { Image(systemName: "arrow.clockwise") } + .accessibilityLabel("Refresh BASIC variables").help("Refresh values at the current BASIC stop") + .disabled(!model.inspectionAvailable).accessibilityIdentifier("basic.refresh-variables") + } + if showingWatches { + HStack { + TextField("Variable or array element, e.g. NAME$ or A(2)", text: $model.watchEntry) + .textFieldStyle(.roundedBorder).onSubmit { model.addWatch() } + .accessibilityIdentifier("basic.watch-entry") + Button { model.addWatch() } label: { Label("Add", systemImage: "plus") } + .disabled(model.watchEntry.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + .accessibilityIdentifier("basic.add-watch") + } + if let error = model.watchError { Text(error).font(.caption).foregroundStyle(.orange) } + } + ScrollView { + LazyVStack(alignment: .leading, spacing: 5) { + if showingWatches { + if model.watches.isEmpty { Text("Watch a variable or a specific array element without changing the program.").foregroundStyle(.secondary) } + ForEach(model.watches, id: \.self) { name in + HStack(alignment: .top) { + Text(name).fontWeight(.medium).frame(width: 160, alignment: .leading) + Text(model.watchValue(name)).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) + .accessibilityIdentifier("basic.watch-value.\(name)") + Button { model.removeWatch(name) } label: { Image(systemName: "minus.circle") } + .buttonStyle(.borderless).help("Remove watch \(name)").accessibilityLabel("Remove watch \(name)") + }.font(.system(.callout, design: .monospaced)) + } + } else if model.variables.isEmpty { + Text(model.inspectionAvailable ? "Variables appear here as statements assign them." : "Run to a breakpoint or use Step to see current values.") + .foregroundStyle(.secondary) + } else { + ForEach(model.variables) { variable in BASICVariableView(variable: variable) } + } + }.frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 4).padding(.horizontal, 8) + }.frame(height: max(36, valuesHeight - (showingWatches ? 60 : 0))) + .accessibilityIdentifier("basic.inspector-values") + }.padding(.top, 6) + } label: { + Label("Variables and Watches", systemImage: "list.bullet.rectangle").font(.callout.bold()) + }.padding(.horizontal, 14).padding(.vertical, 8) + } +} +private struct BASICVariableView: View { + let variable: BASICVariable + @State private var expanded = false + @State private var page = 0 + private let pageSize = 32 + private var first: Int { min(page * pageSize, max(0, variable.elements.count - 1) / pageSize * pageSize) } + var body: some View { + if variable.dimensions.isEmpty { + row(variable.name, variable.value) + } else { + VStack(alignment: .leading, spacing: 4) { + Button { expanded.toggle() } label: { + HStack { + Image(systemName: expanded ? "chevron.down" : "chevron.right").frame(width: 12) + Text(variable.title).fontWeight(.medium).frame(width: 140, alignment: .leading) + Text(variable.value).frame(maxWidth: .infinity, alignment: .leading) + }.font(.system(.callout, design: .monospaced)).padding(.vertical, 3).contentShape(Rectangle()) + }.buttonStyle(.plain).accessibilityIdentifier("basic.array.\(variable.name)") + .accessibilityLabel("Array \(variable.title)").accessibilityValue(expanded ? "Expanded" : "Collapsed") + .help("Show array elements. Bounds are inclusive; subscripts start at zero.") + if expanded { + VStack(alignment: .leading, spacing: 4) { + ForEach(first.. pageSize { + HStack { + Button("Previous", systemImage: "chevron.left") { page = max(0, page - 1) }.disabled(first == 0) + Text("\(first + 1)–\(min(first + pageSize, variable.elements.count)) of \(variable.elements.count)").font(.caption) + Button("Next", systemImage: "chevron.right") { page = first / pageSize + 1 }.disabled(first + pageSize >= variable.elements.count) + } + } + }.padding(.leading, 20) + } + } + } + } + private func row(_ name: String, _ value: String) -> some View { + HStack(alignment: .top) { + Text(name).fontWeight(.medium).frame(width: 160, alignment: .leading) + Text(value).frame(maxWidth: .infinity, alignment: .leading) + .accessibilityIdentifier("basic.variable-value.\(name)") + }.font(.system(.callout, design: .monospaced)).textSelection(.enabled) + } +} diff --git a/platforms/macos/App/BASICLanguage.swift b/platforms/macos/App/BASICLanguage.swift new file mode 100644 index 0000000..04217ac --- /dev/null +++ b/platforms/macos/App/BASICLanguage.swift @@ -0,0 +1,453 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// Editor assistance only. The core's ROM-aware tokenizer remains authoritative. +enum BASICLanguage { + enum Kind { case keyword, number, string, comment, data } + struct Span { let range: NSRange; let kind: Kind; let word: String } + struct Completion: Equatable { let range: NSRange; let words: [String] } + static let maximumSourceBytes = 1_048_576 + static let sample = DevelopmentStarterSource.planet(withExtension: "bas") + ?? "10 REM EARTH OR MARS EXAMPLE MISSING - REINSTALL VCC PLUS\n" + // Verified command/function names for the bundled CoCo 3 + Disk BASIC + // dictionaries. GOTO/GOSUB are conveniences for the GO + TO/SUB tokens. + static let words: [String] = { + let names = "FOR GOTO GOSUB GO REM IF DATA PRINT ON INPUT END NEXT DIM READ RUN RESTORE RETURN STOP POKE CONT LIST CLEAR NEW CLOAD CSAVE OPEN CLOSE LLIST SET RESET CLS MOTOR SOUND AUDIO EXEC SKIPF DEL EDIT TRON TROFF DEF LET LINE PCLS PSET PRESET SCREEN PCLEAR COLOR CIRCLE PAINT GET PUT DRAW PCOPY PMODE PLAY DLOAD RENUM TAB TO SUB THEN NOT STEP OFF ELSE USING DIR DRIVE FIELD FILES KILL LOAD LSET MERGE RENAME RSET SAVE WRITE VERIFY UNLOAD DSKINI BACKUP COPY DSKI$ DSKO$ DOS WIDTH PALETTE HSCREEN LPOKE HCLS HCOLOR HPAINT HCIRCLE HLINE HGET HPUT HBUFF HPRINT ERR BRK LOCATE HSTAT HSET HRESET HDRAW CMP RGB ATTR LPEEK BUTTON HPOINT ERNO ERLIN SIN COS TAN ATN LOG EXP SQR SGN ABS INT RND USR PEEK LEN STR$ VAL ASC CHR$ EOF JOYSTK LEFT$ RIGHT$ MID$ POINT INKEY$ MEM INSTR TIMER PPOINT STRING$ CVN FREE LOC LOF MKN$ AS AND OR FN FIX POS HEX$ VARPTR" + let unique = Set(names.split(separator: " ").map { String($0) }) + return unique.sorted { left, right in + if left.count == right.count { return left < right } + return left.count > right.count + } + }() + + // Command descriptions and editor hints share the offline reference. + // The ROM-aware tokenizer remains authoritative for executable syntax. + static let signatures: [String: String] = { + guard let catalog = try? BASICReferenceCatalog.bundled.get() else { return [:] } + var result: [String: String] = [:] + for dialect in [BASICReferenceDialect.common, .disk] { + for entry in catalog.entries where entry.dialect == dialect && result[entry.keyword] == nil { + result[entry.keyword] = entry.syntax.first + } + } + return result + }() + /// Quoted strings, comments and DATA values are opaque to completion. + static func spans(_ source: String) -> [Span] { + guard source.utf8.count <= maximumSourceBytes else { return [] } + let u = Array(source.utf16), upper = Array(source.uppercased().utf16) + // Case folding can change non-ASCII length. Such text is invalid for the + // guest tokenizer but must remain harmless while being edited. + guard upper.count == u.count else { return [] } + let tokens = words.map { ($0, Array($0.utf16)) } + var result: [Span] = [], i = 0 + func append(_ start: Int, _ end: Int, _ kind: Kind, _ word: String = "") { + result.append(Span(range: NSRange(location: start, length: end-start), kind: kind, word: word)) + } + while i < u.count { + let start = i + if u[i] == 34 { + i += 1; while i < u.count && u[i] != 34 && u[i] != 10 && u[i] != 13 { i += 1 } + if i < u.count && u[i] == 34 { i += 1 }; append(start,i,.string); continue + } + if u[i] == 39 { + while i < u.count && u[i] != 10 && u[i] != 13 { i += 1 }; append(start,i,.comment); continue + } + if let token = tokens.first(where: { i+$0.1.count <= upper.count && upper[i.. Completion? { + let u = Array(source.utf16) + guard source.utf8.count <= maximumSourceBytes, caret >= 0, caret <= u.count else { return nil } + let tokens = spans(source) + guard !tokens.contains(where: { span in + switch span.kind { + case .string, .comment, .data: return caret > span.range.location && caret <= NSMaxRange(span.range) + default: return false + } + }) else { return nil } + func word(_ c: UInt16) -> Bool { (65...90).contains(c) || (97...122).contains(c) || c == 36 } + var start = caret, end = caret + while start > 0 && word(u[start-1]) { start -= 1 } + while end < u.count && word(u[end]) { end += 1 } + guard start < caret else { return nil } + let prefix = String(decoding: u[start.. InlineCompletion? { + let text = source as NSString + guard caret > 0, caret <= text.length, + caret == text.length || [10, 13].contains(text.character(at: caret)), + let completion = completion(source, at: caret), completion.words.count == 1, + NSMaxRange(completion.range) == caret, completion.range.length >= 2, + let word = completion.words.first, word.utf16.count > completion.range.length else { return nil } + // Avoid offering a keyword for the alphabetic tail of a variable (A1PRI). + if completion.range.location > 0 { + let prior = text.character(at: completion.range.location - 1) + if (48...57).contains(prior) { + let line = text.lineRange(for: completion.range) + let before = text.substring(with: NSRange(location: line.location, length: completion.range.location - line.location)) + guard before.allSatisfy({ $0.isNumber || $0 == " " || $0 == "\t" }) else { return nil } + } + } + return InlineCompletion(range: completion.range, word: word, + suffix: String(word.dropFirst(completion.range.length))) + } + + /// Return at a completed numbered line follows its preceding increment, + /// or uses ten. Inserting between lines fits into the available numeric gap. + static func nextLineInsertion(_ source: String, at caret: Int) -> String? { + let text = source as NSString + guard source.utf8.count <= maximumSourceBytes, caret > 0, caret <= text.length else { return nil } + let range = text.lineRange(for: NSRange(location: caret, length: 0)) + var end = NSMaxRange(range) + while end > range.location && [10, 13].contains(text.character(at: end - 1)) { end -= 1 } + guard caret == end else { return nil } + let analysis = analyze(source) + guard let current = analysis.lines.first(where: { $0.range.location == range.location }), + current.number < 63999 else { return nil } + let bodyStart = NSMaxRange(current.labelRange) + guard bodyStart < end, + !text.substring(with: NSRange(location: bodyStart, length: end - bodyStart)) + .trimmingCharacters(in: .whitespaces).isEmpty else { return nil } + let used = Set(analysis.lines.map(\.number)) + let previous = analysis.lines.last(where: { $0.range.location < range.location }) + let increment = previous.map { current.number - $0.number }.flatMap { $0 > 0 ? $0 : nil } ?? 10 + let following = analysis.lines.first(where: { $0.range.location > range.location }) + if let following, following.number <= current.number { return nil } + let limit = min(63999, following.map { $0.number - 1 } ?? 63999) + guard limit > current.number else { return nil } + let gap = limit - current.number + 1 + let step = following != nil && increment >= gap ? max(1, gap / 2) : increment + var candidate = min(current.number + step, limit) + while candidate <= limit && used.contains(candidate) { candidate += 1 } + if candidate > limit { + candidate = current.number + 1 + while candidate <= limit && used.contains(candidate) { candidate += 1 } + } + guard candidate <= limit else { return nil } + let newline = source.contains("\r\n") ? "\r\n" : source.contains("\r") && !source.contains("\n") ? "\r" : "\n" + return newline + String(candidate) + " " + } + static func hint(_ source: String, at caret: Int) -> String? { + let text = source as NSString + guard caret >= 0, caret <= text.length, source.utf8.count <= maximumSourceBytes else { return nil } + let line = text.lineRange(for: NSRange(location:caret,length:0)) + let prior = spans(source).filter { $0.range.location >= line.location && NSMaxRange($0.range) <= caret && $0.kind == .keyword } + // These tokens continue the enclosing statement rather than introducing + // a new signature. They still have independently browsable help entries. + let fragments: Set = ["TO", "STEP", "THEN", "ELSE", "AS", "AND", "OR", "NOT"] + return prior.reversed().filter { !fragments.contains($0.word) }.compactMap { signatures[$0.word] }.first + } +} + +extension BASICLanguage { + enum Severity { case error, warning } + struct Diagnostic: Identifiable, Equatable { + let row: Int + let range: NSRange + let message: String + let severity: Severity + var id: String { "\(row):\(range.location):\(message)" } + } + struct NumberedLine { + let row: Int, number: Int + let range: NSRange, labelRange: NSRange + } + struct Analysis { + let lines: [NumberedLine] + let diagnostics: [Diagnostic] + var hasErrors: Bool { diagnostics.contains { $0.severity == .error } } + } + struct RenumberResult { let source: String; let lineCount: Int; let changedReferences: Int } + struct AssistanceError: LocalizedError { + let message: String + var errorDescription: String? { message } + } + private struct Reference { let range: NSRange; let target: Int } + private struct Inspection { var lines: [NumberedLine] = []; var diagnostics: [Diagnostic] = []; var references: [Reference] = [] } + private struct Atom { + let text: String, range: NSRange + let numeric: Bool + } + // Exact command-before-function ordering from CoCo 3/Disk BASIC. This is + // deliberately separate from completion's longest-spelling-first list. + // An unmatched identifier consumes its alphanumeric tail, so XGOTO is a + // variable, while FORI=1TO5 contains FOR and TO. Function names stay atomic. + private static let scanWords = ("FOR GO REM ' ELSE IF DATA PRINT ON INPUT END NEXT DIM READ RUN RESTORE RETURN STOP POKE CONT LIST CLEAR NEW CLOAD CSAVE OPEN CLOSE LLIST SET RESET CLS MOTOR SOUND AUDIO EXEC SKIPF TAB( TO SUB THEN NOT STEP OFF + - * / ^ AND OR > = < DEL EDIT TRON TROFF DEF LET LINE PCLS PSET PRESET SCREEN PCLEAR COLOR CIRCLE PAINT GET PUT DRAW PCOPY PMODE PLAY DLOAD RENUM FN USING DIR DRIVE FIELD FILES KILL LOAD LSET MERGE RENAME RSET SAVE WRITE VERIFY UNLOAD DSKINI BACKUP COPY DSKI$ DSKO$ DOS WIDTH PALETTE HSCREEN LPOKE HCLS HCOLOR HPAINT HCIRCLE HLINE HGET HPUT HBUFF HPRINT ERR BRK LOCATE HSTAT HSET HRESET HDRAW CMP RGB ATTR SGN INT ABS USR RND SIN PEEK LEN STR$ VAL ASC CHR$ EOF JOYSTK LEFT$ RIGHT$ MID$ POINT INKEY$ MEM ATN COS TAN EXP FIX LOG POS SQR HEX$ VARPTR INSTR TIMER PPOINT STRING$ CVN FREE LOC LOF MKN$ AS LPEEK BUTTON HPOINT ERNO ERLIN").split(separator: " ").map { (String($0), Array($0.utf16)) } + private static let scanWordsByFirst = Dictionary(grouping: scanWords, by: { $0.1[0] }) + private static func isDigit(_ c: UInt16) -> Bool { (48...57).contains(c) } + private static func isAlpha(_ c: UInt16) -> Bool { (65...90).contains(c) || (97...122).contains(c) } + private static func scan(_ units: [UInt16], from: Int, to: Int) -> [Atom] { + var result: [Atom] = [], i = from + func add(_ text: String, _ start: Int, _ end: Int, numeric: Bool = false) { + result.append(.init(text: text, range: NSRange(location:start,length:end-start), numeric:numeric)) + } + while i < to { + let begin = i, c = units[i] + if c == 32 || c == 9 { i += 1; continue } + if c == 34 { + i += 1; while i < to && units[i] != 34 { i += 1 } + if i < to { i += 1 }; add("",begin,i); continue + } + if c == 39 { break } + if isDigit(c) { + i += 1; while i < to && isDigit(units[i]) { i += 1 } + add(String(decoding:units[begin..= 97 && c <= 122 ? c-32 : c]?.first(where: { word in + i+word.1.count <= to && zip(units[i..= 97 && raw <= 122 ? raw-32 : raw) == target + } + }) { + i += word.1.count + if word.0 == "REM" { break } + add(word.0,begin,i) + if word.0 == "DATA" { + var quoted = false + while i < to { + if units[i] == 34 { quoted.toggle() } + if units[i] == 58 && !quoted { break }; i += 1 + } + } + continue + } + i += 1 + if isAlpha(c) { + while i < to && (isAlpha(units[i]) || isDigit(units[i])) { i += 1 } + // $ belongs to the variable name, never a reference operand. + if i < to && units[i] == 36 { i += 1 } + } + add(String(decoding:units[begin.. Inspection { + var output = Inspection() + let units = Array(source.utf16) + func report(_ row: Int, _ range: NSRange, _ text: String, _ severity: Severity = .error) { + output.diagnostics.append(.init(row:row,range:range,message:text,severity:severity)) + } + guard source.utf8.count <= maximumSourceBytes else { + report(1,NSRange(location:0,length:0),"The source exceeds the 1 MiB editor limit."); return output + } + var at = 0, row = 0, bodies: [(NumberedLine,Int,Int)] = [], seen: Set = [] + while at < units.count { + row += 1; let begin = at + while at < units.count && units[at] != 10 && units[at] != 13 { at += 1 } + let end = at + if at < units.count { let newline = units[at]; at += 1; if newline == 13 && at < units.count && units[at] == 10 { at += 1 } } + var first = begin + while first < end && (units[first] == 32 || units[first] == 9) { first += 1 } + if first == end { continue } + if let invalid = (begin.. 126) }) { + report(row,(source as NSString).rangeOfComposedCharacterSequence(at:invalid),"Use printable ASCII characters (tabs are allowed).") + } + if end-first > 249 { report(row,NSRange(location:first,length:end-first),"BASIC input lines may contain at most 249 characters.") } + guard isDigit(units[first]) else { report(row,NSRange(location:first,length:end-first),"Begin this line with a BASIC line number."); continue } + var after = first; while after < end && isDigit(units[after]) { after += 1 } + let label = NSRange(location:first,length:after-first) + guard let number = Int(String(decoding:units[first.. Int { + var lo=0, hi=sorted.count + while lo Bool { index >= atoms.count || [":","ELSE"].contains(atoms[index].text) } + func unsupported(_ atom: Atom) { report(line.row,atom.range,"Renumber cannot safely interpret this line-number operand; use a literal line number.",.warning) } + func reference(_ index: Int, disableZero: Bool = false) { + let atom = atoms[index] + guard let target = Int(atom.text), target <= 63999 else { report(line.row,atom.range,"Referenced line number is outside 0–63999."); return } + if disableZero && target == 0 { return } // ON ERR/BRK GOTO 0 disables the trap. + if !defined.contains(target) { report(line.row,atom.range,"Referenced line \(target) is not present in this program.",.warning) } + output.references.append(.init(range:atom.range,target:target)) + } + while i < atoms.count { + let atom = atoms[i], word = atom.text + if word == ":" || word == "THEN" || word == "ELSE" { on = false; trap = false } + if word == "ON" { on = true; trap = i+1 < atoms.count && ["ERR","BRK"].contains(atoms[i+1].text) } + if word == "RENUM" { report(line.row,atom.range,"This program renumbers itself with RENUM; automatic editor renumbering is unsafe.",.warning) } + if word == "GO" { + var operand = i+1 + guard operand < atoms.count && ["TO","SUB"].contains(atoms[operand].text) else { unsupported(atom); i += 1; continue } + operand += 1 + var count = 0 + while operand < atoms.count && atoms[operand].numeric { + reference(operand,disableZero:trap); count += 1; operand += 1 + if on && !trap && operand < atoms.count && atoms[operand].text == "," { operand += 1; continue } + break + } + if count == 0 || !boundary(operand) || (operand > 0 && atoms[operand-1].text == ",") { unsupported(atom) } + on = false; trap = false; i = max(i+1,operand); continue + } + if ["THEN","ELSE","RUN","EDIT"].contains(word) { + let operand = i+1 + if operand < atoms.count && atoms[operand].numeric { + reference(operand) + if !boundary(operand+1) { unsupported(atom) } + i = operand+1; continue + } else if word == "EDIT" || (word == "RUN" && !boundary(operand) && atoms[operand].text != "") { unsupported(atom) } + } + if ["LIST","LLIST","DEL"].contains(word) { + var p = i+1, lowerIndex: Int?, upperIndex: Int?, ranged = false + if p < atoms.count && atoms[p].numeric { lowerIndex=p; p += 1 } + if p < atoms.count && atoms[p].text == "-" { + ranged=true; p += 1 + if p < atoms.count && atoms[p].numeric { upperIndex=p; p += 1 } + } + if !boundary(p) { unsupported(atom) } + else if lowerIndex != nil || upperIndex != nil { + let low = lowerIndex.map { Int(atoms[$0].text) ?? 64000 } ?? 0 + let high = upperIndex.map { Int(atoms[$0].text) ?? 64000 } ?? (ranged ? 63999 : low) + if low > 63999 || high > 63999 { report(line.row,atom.range,"Line range is outside 0–63999.") } + else { + // Bounds need not name a real line. Preserve the set + // of included lines, not just exact endpoint matches. + let firstIndex=lowerBound(low), afterLast=lowerBound(high+1) + if firstIndex < afterLast { + let first=sorted[firstIndex], last=sorted[afterLast-1] + if let index=lowerIndex { output.references.append(.init(range:atoms[index].range,target:first)) } + if let index=upperIndex { output.references.append(.init(range:atoms[index].range,target:last)) } + } else { report(line.row,atom.range,"This line range selects no program lines; review it before renumbering.",.warning) } + } + } + i = max(i+1,p); continue + } + i += 1 + } + } + return output + } + static func analyze(_ source: String) -> Analysis { + let result = inspect(source) + return Analysis(lines:result.lines,diagnostics:result.diagnostics) + } + static func lineRange(for number: Int, in source: String) -> NSRange? { + let matches = analyze(source).lines.filter { $0.number == number } + return matches.count == 1 ? matches.first?.range : nil + } + /// Numeric program order determines numbering; physical rows, blank lines, + /// comments, string/data literals and newline style remain unchanged. + static func renumber(_ source: String, start: Int = 10, step: Int = 10) throws -> RenumberResult { + guard (0...63999).contains(start), (1...63999).contains(step) else { + throw AssistanceError(message:"Choose a start from 0 to 63999 and a positive increment up to 63999.") + } + let result = inspect(source) + if let issue = result.diagnostics.first { throw AssistanceError(message:"Row \(issue.row): \(issue.message)") } + let ordered = result.lines.sorted { $0.number < $1.number } + guard ordered.count <= 1 || ordered.count-1 <= (63999-start)/step else { throw AssistanceError(message:"The new line numbers would exceed 63999.") } + let mapping = Dictionary(uniqueKeysWithValues:ordered.enumerated().map { ($0.element.number,start+$0.offset*step) }) + var edits = result.lines.map { ($0.labelRange,String(mapping[$0.number]!)) } + var changed = 0 + for ref in result.references { + guard let target = mapping[ref.target] else { throw AssistanceError(message:"Referenced line \(ref.target) is missing.") } + if (source as NSString).substring(with:ref.range) != String(target) { changed += 1 } + edits.append((ref.range,String(target))) + } + let updated = NSMutableString(string:source) + for (range,text) in edits.sorted(by: { $0.0.location > $1.0.location }) { updated.replaceCharacters(in:range,with:text) } + let newSource = updated as String + // Wider line numbers can make a previously valid line too long. + if let issue=analyze(newSource).diagnostics.first(where: { $0.severity == .error }) { throw AssistanceError(message:"Renumbering would make row \(issue.row) invalid: \(issue.message)") } + return .init(source:newSource,lineCount:ordered.count,changedReferences:changed) + } +} + +// Values are copied from a stopped interpreter. Watches never call BASIC. +struct BASICVariable: Identifiable, Equatable, Sendable { + let name: String + let kind: String + let value: String + let address: Int + let dimensions: [Int] + let elements: [String] + var id: String { name + (dimensions.isEmpty ? "" : "()") } + var title: String { dimensions.isEmpty ? name : name + "(" + dimensions.map { String($0 - 1) }.joined(separator: ",") + ")" } + init?(_ row: [String: Any]) { + guard let name = row["name"] as? String, let kind = row["kind"] as? String, + let value = row["value"] as? String, let address = row["address"] as? Int, + let dimensions = row["dimensions"] as? [Int], let elements = row["elements"] as? [String] else { return nil } + self.name = name; self.kind = kind; self.value = value; self.address = address + self.dimensions = dimensions; self.elements = elements + } + func elementName(_ offset: Int) -> String { + var remainder = offset + let indices = dimensions.map { length -> String in + defer { remainder /= length }; return String(remainder % length) + } + return name + "(" + indices.joined(separator: ",") + ")" + } +} +struct BASICWatch: Equatable, Sendable { + let name: String + let indices: [Int]? + var canonical: String { name + (indices.map { "(" + $0.map(String.init).joined(separator: ",") + ")" } ?? "") } + init?(_ text: String) { + // Deliberately no expressions, functions, assignments or device access. + let compact = text.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() + guard compact.count <= 256, let match = compact.range(of: #"^[A-Z][A-Z0-9]*\$?(\( *[0-9]+ *(, *[0-9]+ *)*\))?$"#, options: .regularExpression) else { return nil } + guard match == compact.startIndex.. String { + guard let variable = variables.first(where: { $0.name == name && $0.dimensions.isEmpty == (indices == nil) }) else { + return indices == nil ? "Not assigned" : "Not dimensioned" + } + guard let indices else { return variable.value } + guard indices.count == variable.dimensions.count else { return "Wrong number of subscripts" } + var offset = 0, stride = 1 + for (index, length) in zip(indices, variable.dimensions) { + guard index >= 0, index < length else { return "Subscript out of range" } + offset += index * stride; stride *= length + } + guard offset < variable.elements.count else { return "Unavailable" } + return variable.elements[offset] + } +} diff --git a/platforms/macos/App/BASICReference.swift b/platforms/macos/App/BASICReference.swift new file mode 100644 index 0000000..b083417 --- /dev/null +++ b/platforms/macos/App/BASICReference.swift @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// The ROM family which supplies a command. Common includes CoCo 3 Super Extended BASIC. +enum BASICReferenceDialect: String, Codable, CaseIterable, Sendable { + case common, disk, rgbdos, sdcdos + + var displayName: String { + switch self { + case .common: return "Common BASIC" + case .disk: return "Disk BASIC" + case .rgbdos: return "RGB-DOS" + case .sdcdos: return "SDC-DOS" + } + } +} + +enum BASICReferenceWork: String, Codable, CaseIterable, Sendable { + case basicGuide, diskGuide, rgbdos, sdcGuide + + var citation: String { + switch self { + case .basicGuide: return "Tandy Corporation. Tandy Color Computer 3 BASIC Quick Reference Guide. 1986." + case .diskGuide: return "Color Computer Disk BASIC Quick Reference Guide. InterTAN Canada Ltd., 1987." + case .rgbdos: return "Krupski, Roger, Joe Scinta, Greg Miller, and Colin J. Stearman. RGB-DOS. Ken-Ton Electronics." + case .sdcGuide: return "Lindner, tim, producer. CoCo SDC User Guide. Fourth version, February 2023. Based on Brian Blake’s original manual." + } + } +} + +struct BASICReferenceEntry: Codable, Identifiable, Sendable { + let id: String + let keyword: String + let title: String + let category: String + let dialect: BASICReferenceDialect + let summary: String + let syntax: [String] + let parameters: [String] + /// A short command fragment, which may need setup or input. Not an executable test. + let sample: String + let exampleID: String? + let related: [String] + let notes: [String] + let source: BASICReferenceWork + let sourcePage: String? + + var citation: String { + guard let location = sourcePage, !location.isEmpty else { return source.citation } + guard location.first?.isNumber == true else { return source.citation + " " + location + "." } + let plural = location.contains("-") || location.contains(",") + return source.citation + (plural ? " pp. " : " p. ") + location.replacingOccurrences(of: "-", with: "–") + "." + } +} + +struct BASICReferenceExample: Codable, Identifiable, Sendable { + let id: String + let title: String + let summary: String + /// Complete, numbered source that is opened in the editor, never implicitly run. + let source: String + let expectedOutput: String + let dialect: BASICReferenceDialect +} + +struct BASICReferenceCatalog: Codable, Sendable { + let entries: [BASICReferenceEntry] + let examples: [BASICReferenceExample] + + enum CatalogError: LocalizedError { + case missingResource + case invalidContent(String) + + var errorDescription: String? { + switch self { + case .missingResource: + return "The BASIC Quick Reference is missing from this app. Reinstall a complete copy of VCC Plus." + case .invalidContent(let detail): + return "The BASIC Quick Reference could not be read: \(detail)" + } + } + } + + static func load(from url: URL) throws -> BASICReferenceCatalog { + let catalog = try JSONDecoder().decode(Self.self, from: Data(contentsOf: url)) + try catalog.validate() + return catalog + } + + /// Preserve failures so the reference window can explain a damaged installation. + static let bundled: Result = Result { + let bundles = [Bundle.main, Bundle(for: BASICReferenceBundleMarker.self)] + guard let url = bundles.compactMap({ $0.url(forResource: "BASICReference", withExtension: "json") }).first else { + throw CatalogError.missingResource + } + return try load(from: url) + } + + private func validate() throws { + guard !entries.isEmpty else { throw CatalogError.invalidContent("there are no reference entries.") } + let entryIDs = Set(entries.map(\.id)) + let exampleIDs = Set(examples.map(\.id)) + guard entryIDs.count == entries.count, exampleIDs.count == examples.count else { + throw CatalogError.invalidContent("an entry or example identifier is duplicated.") + } + for entry in entries { + guard !entry.id.isEmpty, !entry.keyword.isEmpty, !entry.title.isEmpty, + !entry.category.isEmpty, !entry.summary.isEmpty, !entry.syntax.isEmpty, + !entry.syntax.contains(where: \.isEmpty) else { + throw CatalogError.invalidContent("entry \(entry.id) is incomplete.") + } + guard entry.related.allSatisfy(entryIDs.contains), + entry.exampleID.map(exampleIDs.contains) ?? true else { + throw CatalogError.invalidContent("entry \(entry.id) has an unresolved reference.") + } + } + for example in examples { + guard !example.id.isEmpty, !example.title.isEmpty, !example.summary.isEmpty, + !example.source.isEmpty, !example.expectedOutput.isEmpty else { + throw CatalogError.invalidContent("example \(example.id) is incomplete.") + } + } + } +} + +private final class BASICReferenceBundleMarker: NSObject {} diff --git a/platforms/macos/App/BASICReferenceContext.swift b/platforms/macos/App/BASICReferenceContext.swift new file mode 100644 index 0000000..734ecf0 --- /dev/null +++ b/platforms/macos/App/BASICReferenceContext.swift @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// Resolves explicit Quick Help requests without interpreting or changing a +/// program. Offsets use NSTextView's UTF-16 convention, just like editor spans. +enum BASICReferenceContext { + private struct Token { + var keyword: String + var range: NSRange + } + + static func keyword(in source: String, at offset: Int) -> String? { + let text = source as NSString + guard source.utf8.count <= BASICLanguage.maximumSourceBytes, + offset >= 0, offset <= text.length, text.length > 0 else { return nil } + let spans = BASICLanguage.spans(source) + let opaque = spans.filter { [.string, .comment, .data].contains($0.kind) } + // In literals, comments and DATA values, words are data rather than + // commands. An unfinished literal at EOF remains opaque at its end. + for span in opaque { + if NSLocationInRange(offset, span.range) { return nil } + if span.range.length > 0 && offset == text.length && offset == NSMaxRange(span.range) { + if span.kind != .string || text.character(at: text.length - 1) != 34 { return nil } + } + } + let line = text.lineRange(for: NSRange(location: offset, length: 0)) + let units = Array(source.utf16) + func isOpaque(_ at: Int) -> Bool { opaque.contains { NSLocationInRange(at, $0.range) } } + func whitespace(_ at: Int) -> Bool { units[at] == 32 || units[at] == 9 } + var start = line.location, end = NSMaxRange(line) + while end > start && [10, 13].contains(units[end - 1]) { end -= 1 } + guard start < end else { return nil } + for at in start..= start && $0.range.location < end } + .map { Token(keyword: $0.word, range: $0.range) } + // Several public command spellings are composed from shorter ROM + // tokens. Keep their reference entries distinct from their prefixes. + var merged: [Token] = [], index = 0 + let pairs = ["GO TO": "GOTO", "GO SUB": "GOSUB", "LINE INPUT": "LINE INPUT", + "DEF FN": "DEF FN", "ON ERR": "ON ERR", "PRINT USING": "PRINT USING"] + while index < tokens.count { + var token = tokens[index] + if index + 1 < tokens.count { + let next = tokens[index + 1], gap = NSMaxRange(token.range)..= statementStart else { return nil } + if let first = tokens.first(where: { $0.range.location >= statementStart }), first.range.location == statementStart { return first.keyword } + // Assignment statements can omit LET; an argument position within one + // still has a useful help topic. A function name itself wins above. + let prefix = text.substring(with: NSRange(location: statementStart, length: min(offset, end) - statementStart)) + return prefix.contains("=") ? "LET" : nil + } +} diff --git a/platforms/macos/App/BASICReferenceIntegration.swift b/platforms/macos/App/BASICReferenceIntegration.swift new file mode 100644 index 0000000..c63f354 --- /dev/null +++ b/platforms/macos/App/BASICReferenceIntegration.swift @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI + +extension MachineModel { + var basicReferenceDialect: BASICReferenceDialect? { + switch usageProfile { + case .diskBasic: return .disk + case .hardDriveBasic: return .rgbdos + case .cocoSDC: return .sdcdos + default: return nil + } + } +} + +struct BASICReferenceHost: View { + let result: Result + @ObservedObject var machine: MachineModel + let showManualTopic: (BASICReferenceEntry) -> Void + @Environment(\.openWindow) private var openWindow + var body: some View { + switch result { + case .success(let reference): + BASICReferenceView(model: reference, activeDialect: machine.basicReferenceDialect) { entry in + showManualTopic(entry) + openWindow(id: "manual-library") + } openExample: { example in + openWindow(id: "basic-example", value: example.id) + } + case .failure(let error): + ContentUnavailableView { + Label("BASIC Reference Unavailable", systemImage: "book.closed") + } description: { + Text("The bundled reference could not be read. \(error.localizedDescription)") + }.frame(minWidth: 580, minHeight: 400) + } + } +} diff --git a/platforms/macos/App/BASICReferenceView.swift b/platforms/macos/App/BASICReferenceView.swift new file mode 100644 index 0000000..b408077 --- /dev/null +++ b/platforms/macos/App/BASICReferenceView.swift @@ -0,0 +1,263 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import SwiftUI + +/// A deliberate lookup changes the selected topic. The editor never drives this +/// model continuously, so a reference stays put while the user reads and types. +@MainActor +final class BASICReferenceModel: ObservableObject { + let catalog: BASICReferenceCatalog + @Published var selectedID: String? + @Published var search = "" { didSet { reconcileSelection() } } + @Published var category: String? { didSet { reconcileSelection() } } + + init(catalog: BASICReferenceCatalog) { + self.catalog = catalog + selectedID = catalog.entries.first(where: { $0.id == "PRINT" })?.id ?? catalog.entries.first?.id + } + + var categories: [String] { Set(catalog.entries.map(\.category)).sorted() } + var filteredEntries: [BASICReferenceEntry] { + let terms = search.split(whereSeparator: \.isWhitespace).map(String.init) + return catalog.entries.filter { entry in + guard category == nil || category == entry.category else { return false } + let searchable = [entry.title, entry.keyword, entry.summary, entry.category, entry.dialect.displayName].joined(separator: " ") + return terms.allSatisfy { searchable.localizedCaseInsensitiveContains($0) } + }.sorted { + let comparison = $0.title.localizedStandardCompare($1.title) + return comparison == .orderedSame ? $0.id < $1.id : comparison == .orderedAscending + } + } + var selectedEntry: BASICReferenceEntry? { entry(id: selectedID) } + func entry(id: String?) -> BASICReferenceEntry? { + guard let id else { return nil } + return catalog.entries.first { $0.id == id } + } + func example(for entry: BASICReferenceEntry) -> BASICReferenceExample? { + guard let id = entry.exampleID else { return nil } + return catalog.examples.first { $0.id == id } + } + func relatedEntry(_ identifier: String) -> BASICReferenceEntry? { + entry(id: identifier) ?? catalog.entries.first { $0.keyword.caseInsensitiveCompare(identifier) == .orderedSame } + } + func select(_ entry: BASICReferenceEntry) { + search = ""; category = nil; selectedID = entry.id + } + func show(keyword: String, dialect: BASICReferenceDialect? = nil) { + let key = keyword.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() + let candidates = catalog.entries.filter { $0.keyword.uppercased() == key || $0.id.uppercased() == key } + let match = candidates.first { $0.dialect == dialect } + ?? candidates.first { $0.dialect == .common } + ?? candidates.first { $0.dialect == .disk } + ?? candidates.first + if let match { select(match) } + else { category = nil; search = key } + } + func showError(code: String) { + let key = code.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() + if let match = entry(id: "ERROR." + key) { select(match) } + else { show(keyword: key) } + } + private func reconcileSelection() { + let entries = filteredEntries + if !entries.contains(where: { $0.id == selectedID }) { selectedID = entries.first?.id } + } +} + +struct BASICReferenceView: View { + @ObservedObject var model: BASICReferenceModel + let activeDialect: BASICReferenceDialect? + let openManualTopic: (BASICReferenceEntry) -> Void + let openExample: (BASICReferenceExample) -> Void + @FocusState private var searchFocused: Bool + + var body: some View { + VStack(spacing: 0) { + HStack(spacing: 12) { + Image(systemName: "book.closed").font(.largeTitle).foregroundStyle(.tint) + VStack(alignment: .leading, spacing: 3) { + Text("BASIC Quick Reference").font(.title2.bold()) + Text("Commands, examples and help for your CoCo").font(.callout).foregroundStyle(.secondary) + } + Spacer(minLength: 12) + if let activeDialect { + Label(activeDialect.displayName, systemImage: "desktopcomputer") + .font(.caption).foregroundStyle(.secondary) + .accessibilityIdentifier("basic.reference.active-dialect") + } + }.padding(16) + Divider() + HSplitView { + navigation.frame(minWidth: 210, idealWidth: 250, maxWidth: 330) + Group { + if let entry = model.selectedEntry { + ScrollView { + entryDetail(entry).padding(22).frame(maxWidth: .infinity, alignment: .leading) + }.id(entry.id).accessibilityIdentifier("basic.reference.detail") + } else { + ContentUnavailableView { + Label(model.catalog.entries.isEmpty ? "Reference unavailable" : "No matching commands", systemImage: "magnifyingglass") + } description: { + Text(model.catalog.entries.isEmpty ? "The local reference could not be loaded." : "Try a command name or choose a different category.") + } actions: { + if !model.catalog.entries.isEmpty { + Button("Clear Filters") { model.search = ""; model.category = nil } + } + } + } + }.frame(minWidth: 460, maxWidth: .infinity, maxHeight: .infinity) + } + Divider() + HStack(spacing: 6) { + Image(systemName: "internaldrive") + Text("Available offline") + Spacer() + Text("Examples open in the editor. Run them when you’re ready.") + }.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 14).padding(.vertical, 9) + }.frame(minWidth: 780, minHeight: 540) + .background { + Button("Find in BASIC Reference") { searchFocused = true } + .keyboardShortcut("f", modifiers: .command).hidden().accessibilityHidden(true) + } + } + + private var navigation: some View { + VStack(alignment: .leading, spacing: 10) { + HStack(spacing: 6) { + Image(systemName: "magnifyingglass").foregroundStyle(.secondary) + TextField("Find a command", text: $model.search) + .textFieldStyle(.plain).focused($searchFocused) + .accessibilityLabel("Search BASIC reference").accessibilityIdentifier("basic.reference.search") + if !model.search.isEmpty { + Button { model.search = "" } label: { Image(systemName: "xmark.circle.fill") } + .buttonStyle(.plain).foregroundStyle(.secondary).help("Clear reference search").accessibilityLabel("Clear reference search") + } + }.padding(8).background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 7)) + .padding(.horizontal, 12).padding(.top, 12) + Picker("Category", selection: $model.category) { + Text("All Topics").tag(String?.none) + ForEach(model.categories, id: \.self) { Text($0).tag(Optional($0)) } + }.padding(.horizontal, 12).accessibilityIdentifier("basic.reference.category") + List(selection: $model.selectedID) { + ForEach(model.filteredEntries) { entry in + HStack(alignment: .top, spacing: 9) { + Image(systemName: symbol(for: entry)).foregroundStyle(.secondary).frame(width: 18) + VStack(alignment: .leading, spacing: 3) { + Text(entry.title).font(.callout.weight(.medium)) + Text(entry.dialect.displayName).font(.caption).foregroundStyle(.secondary) + } + }.padding(.vertical, 3).tag(entry.id) + .accessibilityIdentifier("basic.reference.topic." + entry.id) + } + }.listStyle(.sidebar).accessibilityIdentifier("basic.reference.list") + Text("\(model.filteredEntries.count) topics").font(.caption).foregroundStyle(.secondary) + .padding(.horizontal, 14).padding(.bottom, 10) + } + } + + private func entryDetail(_ entry: BASICReferenceEntry) -> some View { + VStack(alignment: .leading, spacing: 20) { + VStack(alignment: .leading, spacing: 9) { + HStack(alignment: .firstTextBaseline) { + Text(entry.title).font(.system(.title, design: .monospaced).bold()) + .accessibilityIdentifier("basic.reference.title") + Spacer(minLength: 8) + } + HStack(spacing: 8) { + Label(entry.category, systemImage: symbol(for: entry)) + Text("·") + Text(entry.dialect.displayName) + }.font(.caption).foregroundStyle(.secondary) + Text(entry.summary).textSelection(.enabled) + Button("Read in BASIC Manual", systemImage: "book.pages") { openManualTopic(entry) } + .accessibilityIdentifier("basic.reference.manual") + } + if !entry.syntax.isEmpty { + section("Syntax") { code(entry.syntax.joined(separator: "\n")) } + } + if !entry.parameters.isEmpty { + section("Parameters") { + VStack(alignment: .leading, spacing: 8) { + ForEach(Array(entry.parameters.enumerated()), id: \.offset) { _, parameter in + Text(parameter).font(.callout).textSelection(.enabled) + } + } + } + } + if !entry.sample.isEmpty { + section("Example syntax") { code(entry.sample) } + } + if let example = model.example(for: entry) { + VStack(alignment: .leading, spacing: 10) { + Label(example.title, systemImage: "play.rectangle").font(.headline) + Text(example.summary).font(.callout).textSelection(.enabled) + if !example.expectedOutput.isEmpty { + Text("Expected result: " + example.expectedOutput).font(.callout).foregroundStyle(.secondary) + .textSelection(.enabled) + } + Button { openExample(example) } label: { Label("Open Example", systemImage: "doc.badge.plus") } + .accessibilityIdentifier("basic.reference.example") + Text("Opens a separate program; does not run it.").font(.caption).foregroundStyle(.secondary) + }.padding(14).frame(maxWidth: .infinity, alignment: .leading) + .background(Color.accentColor.opacity(0.07), in: RoundedRectangle(cornerRadius: 9)) + } + if !entry.notes.isEmpty { + section("Good to know") { + VStack(alignment: .leading, spacing: 9) { + ForEach(Array(entry.notes.enumerated()), id: \.offset) { _, note in + Text(note).font(.callout).textSelection(.enabled) + } + } + } + } + let related = entry.related.compactMap(model.relatedEntry) + if !related.isEmpty { + section("Related topics") { + VStack(alignment: .leading, spacing: 8) { + ForEach(related) { relatedEntry in + Button { model.select(relatedEntry) } label: { + Label(relatedEntry.title, systemImage: "arrow.turn.down.right") + }.buttonStyle(.link).accessibilityIdentifier("basic.reference.related." + relatedEntry.id) + } + } + } + } + Divider() + DisclosureGroup { + VStack(alignment: .leading, spacing: 7) { + Text(entry.citation).textSelection(.enabled) + Text("Historical manuals preserved by Color Computer Archive. Explanations and examples written for VCC Plus.") + .foregroundStyle(.secondary) + }.font(.caption).padding(.top, 7) + } label: { + Label("Bibliographic reference", systemImage: "books.vertical").font(.callout) + }.accessibilityIdentifier("basic.reference.attribution") + } + } + + private func section(_ title: String, @ViewBuilder content: () -> Content) -> some View { + VStack(alignment: .leading, spacing: 9) { + Text(title).font(.headline) + content() + }.frame(maxWidth: .infinity, alignment: .leading) + } + private func code(_ text: String) -> some View { + Text(text).font(.system(.body, design: .monospaced)).textSelection(.enabled) + .fixedSize(horizontal: false, vertical: true) + .padding(12).frame(maxWidth: .infinity, alignment: .leading) + .background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 7)) + } + private func symbol(for entry: BASICReferenceEntry) -> String { + let category = entry.category.lowercased() + if entry.id.hasPrefix("ERROR.") || category.contains("error") { return "exclamationmark.circle" } + if category.contains("graphic") || category.contains("display") || category.contains("screen") { return "paintpalette" } + if category.contains("sound") || category.contains("music") { return "speaker.wave.2" } + if category.contains("disk") || category.contains("file") || category.contains("storage") { return "externaldrive" } + if category.contains("cassette") { return "recordingtape" } + if category.contains("string") || category.contains("text") { return "textformat" } + if category.contains("math") || category.contains("number") { return "function" } + if category.contains("flow") || category.contains("control") { return "arrow.triangle.branch" } + if category.contains("memory") { return "memorychip" } + return "terminal" + } +} diff --git a/platforms/macos/App/BinaryFile.swift b/platforms/macos/App/BinaryFile.swift new file mode 100644 index 0000000..db0271d --- /dev/null +++ b/platforms/macos/App/BinaryFile.swift @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +enum BinaryFile { + static let limit = 1024 * 1024 // Matches BinaryImage::maxBytes; structural parsing belongs to the core. + enum Failure: LocalizedError { + case notFile, size + var errorDescription: String? { + switch self { + case .notFile: return "Choose a regular CoCo .bin file." + case .size: return "Choose a nonempty CoCo .bin file, up to 1 MiB." + } + } + } + static func read(_ url: URL) throws -> Data { + let resolved = url.resolvingSymlinksInPath() + guard url.pathExtension.lowercased() == "bin", + try resolved.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw Failure.notFile } + let file = try FileHandle(forReadingFrom: resolved) + defer { try? file.close() } + let data = try file.read(upToCount: limit + 1) ?? Data() + guard !data.isEmpty, data.count <= limit else { throw Failure.size } + return data + } +} diff --git a/platforms/macos/App/CMOCBankedDebug.swift b/platforms/macos/App/CMOCBankedDebug.swift new file mode 100644 index 0000000..9820a7f --- /dev/null +++ b/platforms/macos/App/CMOCBankedDebug.swift @@ -0,0 +1,240 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// A build-produced declaration of unpacked code placement. Hashes bind this +/// declaration to one retained build; object relocation replay and live physical +/// RAM comparisons provide the independent byte checks before debugging. +struct CMOCBankedDebugLayout: Sendable { + struct File: Decodable, Sendable { let path: String; let sha256: String } + struct Page: Decodable, Equatable, Sendable { let logicalPage: Int; let physicalPage: Int } + struct CodeGuard: Equatable, Sendable { let address: UInt16; let bytes: [UInt8] } + struct Framebuffer: Decodable, Equatable, Sendable { + let id: String + let physicalAddress: Int + let mode: String + var canvasBytes: Int? = nil + var workerFields: [String: Any] { + var fields: [String: Any] = ["id": id, "physical_address": physicalAddress, "mode": mode] + if let canvasBytes { fields["canvas_bytes"] = canvasBytes } + return fields + } + } + struct Image: Decodable, Sendable { + let path: String + let logicalAddress: Int + let offset: Int? + let length: Int? + } + struct Module: Sendable { + let id: String + let sections: [String] + let codeSections: [String] + let logicalAddress: Int + let bytes: [UInt8] + let pages: [Page] + let codeGuards: [CodeGuard] + func physicalAddress(_ logical: Int) -> UInt32? { + guard (0..<65536).contains(logical), + let page = pages.first(where: { $0.logicalPage == logical / 8192 }) else { return nil } + return UInt32(page.physicalPage * 8192 + logical % 8192) + } + func isMapped(physicalPages: [Int]) -> Bool { + physicalPages.count == 8 && pages.allSatisfy { physicalPages[$0.logicalPage] == $0.physicalPage } + } + } + private struct ModuleRecord: Decodable { + let id: String; let sections: [String]; let codeSections: [String]; let image: Image?; let pages: [Page] + } + private struct Manifest: Decodable { + let version: Int; let entryPoint: Int + let binary: File; let disk: File?; let linkMap: File + let sources: [String: String]; let artifacts: [String: String] + let modules: [ModuleRecord] + let framebuffers: [Framebuffer]? + } + let entryPoint: UInt16 + let binarySHA256: String + let linkMap: Data + let sourceHashes: [String: String] + let artifactHashes: [String: String] + let modules: [Module] + var framebuffers: [Framebuffer] = [] + func module(forSection name: String) -> Module? { modules.first { $0.sections.contains(name) } } + func module(id: String) -> Module? { modules.first { $0.id == id } } + + static func parse(data: Data, directory: URL, sources: [String: Data], binary: Data, + binaryPath: String, diskPath: String? = nil, allowedOutputs: [String]) throws -> Self { + func fail(_ text: String) -> CMOCSourceMap.Failure { .invalid("banked manifest: " + text) } + guard data.count <= 1024 * 1024 else { throw fail("manifest exceeds 1 MB.") } + // Bound recursive decoding before handing untrusted JSON to Decodable. + var pending: [(Any, Int)] = [(try JSONSerialization.jsonObject(with: data), 0)], nodes = 0 + while let (value, depth) = pending.popLast() { + nodes += 1 + guard depth <= 16, nodes <= 30000 else { throw fail("manifest nesting or record limit exceeded.") } + if let values = value as? [String: Any] { pending += values.values.map { ($0, depth + 1) } } + if let values = value as? [Any] { pending += values.map { ($0, depth + 1) } } + } + let manifest = try JSONDecoder().decode(Manifest.self, from: data) + guard manifest.version == 1, (0..<65536).contains(manifest.entryPoint), + !manifest.modules.isEmpty, manifest.modules.count <= 256, + manifest.artifacts.count <= 8192, sources.count <= 4096 else { throw fail("unsupported version or record count.") } + func path(_ value: String) throws { + guard !value.isEmpty, value.utf8.count <= 4096, !value.hasPrefix("/"), !value.contains("\\"), + !value.contains("\0"), !value.split(separator: "/", omittingEmptySubsequences: false).contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }), + (value as NSString).standardizingPath == value else { throw fail("paths must be canonical project-relative identities.") } + } + func hash(_ value: String) throws { + guard value.count == 64, value.allSatisfy({ $0.isASCII && ($0.isNumber || ("a"..."f").contains(String($0))) }) else { throw fail("invalid SHA-256.") } + } + let root = directory.resolvingSymlinksInPath().standardizedFileURL + let outputs = Set(allowedOutputs) + var loaded: [String: Data] = [:], total = 0 + func read(_ name: String, digest: String) throws -> Data { + try path(name); try hash(digest) + guard outputs.contains(name) else { throw fail("an artifact was not retained as a declared build output.") } + if let data = loaded[name] { + guard CMOCSourceMap.sha256(data) == digest else { throw fail("conflicting artifact hashes.") }; return data + } + let url = root.appendingPathComponent(name) + guard url.resolvingSymlinksInPath().path == url.path else { throw fail("artifact paths must not traverse symbolic links.") } + let info = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) + guard info.isRegularFile == true, info.isSymbolicLink != true, (info.fileSize ?? Int.max) <= 8 * 1024 * 1024 else { throw fail("artifact is not a bounded regular file.") } + let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } + let value = try handle.read(upToCount: 8 * 1024 * 1024 + 1) ?? Data() + total += value.count + guard value.count <= 8 * 1024 * 1024, total <= 128 * 1024 * 1024, + CMOCSourceMap.sha256(value) == digest else { throw fail("artifact changed or exceeds verification limits.") } + loaded[name] = value; return value + } + guard manifest.sources == sources.mapValues(CMOCSourceMap.sha256) else { throw fail("source snapshot differs from the manifest.") } + for (name, digest) in manifest.sources { try path(name); try hash(digest) } + guard manifest.binary.path == binaryPath, CMOCSourceMap.sha256(binary) == manifest.binary.sha256 else { throw fail("delivered executable differs from the manifest.") } + _ = try read(manifest.binary.path, digest: manifest.binary.sha256) + if let disk = manifest.disk { + guard disk.path == diskPath else { throw fail("delivered disk identity differs from the manifest.") } + _ = try read(disk.path, digest: disk.sha256) + } else if diskPath != nil { throw fail("delivered disk is missing from the manifest.") } + let linkMap = try read(manifest.linkMap.path, digest: manifest.linkMap.sha256) + guard let mapText = String(data: linkMap, encoding: .utf8), !mapText.contains("\0") else { throw fail("invalid linker-map encoding.") } + let sectionPattern = try NSRegularExpression(pattern: #"^Section: ([^\s]+) \((.+)\) load at ([0-9A-Fa-f]{4}), length ([0-9A-Fa-f]{4})$"#) + var placements: [(name: String, address: Int, length: Int)] = [] + let rows = mapText.components(separatedBy: .newlines) + guard rows.count <= 100000, rows.allSatisfy({ $0.utf8.count <= 8192 }) else { throw fail("linker map exceeds limits.") } + for row in rows { + let ns = row as NSString + guard let match = sectionPattern.firstMatch(in: row, range: NSRange(location: 0, length: ns.length)) else { + if row.hasPrefix("Section:") { throw fail("unsupported section placement.") }; continue + } + placements.append((ns.substring(with: match.range(at: 1)), + Int(ns.substring(with: match.range(at: 3)), radix: 16)!, Int(ns.substring(with: match.range(at: 4)), radix: 16)!)) + } + for (name, digest) in manifest.artifacts { _ = try read(name, digest: digest) } + var modules: [Module] = [], ids = Set(), sections = Set() + var physical: [UInt32: String] = [:] + for record in manifest.modules { + guard !record.id.isEmpty, record.id.count <= 128, ids.insert(record.id).inserted, + !record.sections.isEmpty, record.sections.count <= 256, + Set(record.codeSections).count == record.codeSections.count, + Set(record.codeSections).isSubset(of: Set(record.sections)), + !record.pages.isEmpty, record.pages.count <= 8 else { throw fail("invalid or repeated module identity.") } + for section in record.sections { + guard !section.isEmpty, section.count <= 256, !section.contains(where: \.isWhitespace), sections.insert(section).inserted else { throw fail("section has ambiguous module ownership.") } + } + guard Set(record.pages.map(\.logicalPage)).count == record.pages.count, + record.pages.allSatisfy({ (0..<8).contains($0.logicalPage) && (0..<1024).contains($0.physicalPage) }) else { + throw fail("module image or page layout is invalid.") + } + let logicalAddress: Int, moduleBytes: [UInt8] + if let declaredImage = record.image { + guard let digest = manifest.artifacts[declaredImage.path] else { throw fail("module image is missing from the artifact evidence.") } + let image = try read(declaredImage.path, digest: digest) + let offset = declaredImage.offset ?? 0 + guard offset >= 0, offset <= image.count else { throw fail("module image range is invalid.") } + let length = declaredImage.length ?? (image.count - offset) + guard length > 0, length <= image.count - offset, + declaredImage.logicalAddress >= 0, declaredImage.logicalAddress < 65536, + length <= 65536 - declaredImage.logicalAddress else { throw fail("module image range is invalid.") } + logicalAddress = declaredImage.logicalAddress + moduleBytes = Array(image[offset..<(offset + length)]) + } else { + guard record.codeSections.isEmpty else { + throw fail("module \(record.id): executable codeSections require a module image.") + } + // Pure BSS owns real physical storage but has no initialized + // bytes. Relocation verification still rejects any initialized + // object section whose bytes are absent from this empty image. + logicalAddress = placements.first { record.sections.contains($0.name) }?.address ?? 0 + moduleBytes = [] + } + var guards: [CodeGuard] = [], occupiedCode = Set() + for section in record.codeSections { + let matching = placements.filter { $0.name == section } + guard !matching.isEmpty else { throw fail("an executable section is missing from the linker map.") } + for placement in matching where placement.length > 0 { + let start = placement.address - logicalAddress + guard start >= 0, start <= moduleBytes.count, placement.length <= moduleBytes.count - start else { throw fail("executable section leaves its module image.") } + for address in placement.address..<(placement.address + placement.length) { + guard occupiedCode.insert(address).inserted else { throw fail("executable section placements overlap inside a module.") } + } + guards.append(CodeGuard(address: UInt16(placement.address), bytes: Array(moduleBytes[start..<(start + placement.length)]))) + } + } + let module = Module(id: record.id, sections: record.sections, codeSections: record.codeSections, + logicalAddress: logicalAddress, bytes: moduleBytes, pages: record.pages, + codeGuards: guards.sorted { $0.address < $1.address }) + var imagePhysical = Set() + for logical in module.logicalAddress..<(module.logicalAddress + moduleBytes.count) { + guard let address = module.physicalAddress(logical), imagePhysical.insert(address).inserted, + physical[address] == nil || physical[address] == module.id else { + throw fail("module images overlap physical RAM or lack a page identity.") + } + physical[address] = module.id + } + // BSS has no image bytes, but its storage must still have one + // physical owner. Initialized non-code data follows the same rule. + for section in record.sections where !record.codeSections.contains(section) { + let matching = placements.filter { $0.name == section } + guard !matching.isEmpty else { throw fail("a data section is missing from the linker map.") } + for placement in matching where placement.length > 0 { + for logical in placement.address..<(placement.address + placement.length) { + guard let address = module.physicalAddress(logical), + physical[address] == nil || physical[address] == module.id else { + throw fail("module storage overlaps another module's physical RAM or lacks a page identity.") + } + physical[address] = module.id + } + } + } + modules.append(module) + } + // A compressed transport can enter through its loader, outside every + // eventual source module. Bind this entry to the delivered DECB trailer. + guard try CMOCSourceMap.decbEntryPoint(binary) == UInt16(manifest.entryPoint) else { throw fail("entry point differs from the delivered executable.") } + let buffers = manifest.framebuffers ?? [] + let modes = Set(["sg4", "pmode0", "pmode1", "pmode2", "pmode3", "pmode4", "hscreen1", "hscreen2", "hscreen3", "hscreen4", "current_gime"]) + guard buffers.count <= 4, Set(buffers.map(\.id)).count == buffers.count, + buffers.allSatisfy({ buffer in + buffer.id != "displayed" && (1...64).contains(buffer.id.utf8.count) && + buffer.id.utf8.allSatisfy({ (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) || $0 == 95 || $0 == 45 }) && + (0..<(8 * 1024 * 1024)).contains(buffer.physicalAddress) && modes.contains(buffer.mode) && { + if buffer.mode == "current_gime" { + guard let size = buffer.canvasBytes, (8192...(8 * 1024 * 1024)).contains(size), + size & (size - 1) == 0, buffer.physicalAddress % size == 0, + buffer.physicalAddress <= 8 * 1024 * 1024 - size else { return false } + return true + } + return buffer.canvasBytes == nil + }() + }) else { throw fail("invalid framebuffer declaration.") } + let canvases = buffers.filter { $0.mode == "current_gime" } + for (index, canvas) in canvases.enumerated() { + let range = canvas.physicalAddress..<(canvas.physicalAddress + canvas.canvasBytes!) + guard canvases.dropFirst(index + 1).allSatisfy({ other in + !range.overlaps(other.physicalAddress..<(other.physicalAddress + other.canvasBytes!)) + }) else { throw fail("overlapping current GIME canvases.") } + } + return Self(entryPoint: UInt16(manifest.entryPoint), binarySHA256: manifest.binary.sha256, + linkMap: linkMap, sourceHashes: manifest.sources, artifactHashes: manifest.artifacts, + modules: modules, framebuffers: buffers) + } +} diff --git a/platforms/macos/App/CMOCBuildHistory.swift b/platforms/macos/App/CMOCBuildHistory.swift new file mode 100644 index 0000000..0ed76ad --- /dev/null +++ b/platforms/macos/App/CMOCBuildHistory.swift @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import Darwin + +/// Completed, owned build snapshots only. Working caches and development disks +/// are deliberately outside this inventory. Cleanup is explicit and recoverable. +final class CMOCBuildHistory: @unchecked Sendable { + struct Entry: Identifiable, Sendable { + let id: UUID + let directory: URL + let createdAt: Date + let configurationName: String + let action: String + let byteCount: Int64 + let hasBinary: Bool + let hasDisk: Bool + let protectionReason: String? + } + struct Removal: Sendable { + var removedIDs: Set = [] + var retained: [UUID: String] = [:] + } + private struct Record: Codable { + let version: Int + let id: UUID + let project: String + let createdAt: Date + let configurationName: String + let action: String + let hasBinary: Bool + let hasDisk: Bool + let byteCount: Int64 + let hashes: [String: String] + } + static let manifestName = ".vccplus-build-history.json" + static let leaseName = ".vccplus-build-history.lock" + private let root: URL + private let lock = NSLock() + private var leases: [UUID: Int32] = [:] + private let trash: @Sendable (URL) throws -> Void + + init(root: URL, trash: @escaping @Sendable (URL) throws -> Void = { url in + try FileManager.default.trashItem(at: url, resultingItemURL: nil) + }) { + self.root = root.standardizedFileURL.resolvingSymlinksInPath() + self.trash = trash + } + deinit { for descriptor in leases.values { close(descriptor) } } + + func record(_ artifact: CMOCBuildArtifact, project: URL) throws { + lock.lock(); defer { lock.unlock() } + let directory = try checkedDirectory(artifact.id) + guard try CMOCProject.physicalURL(artifact.directory) == directory else { throw failure("Build result is outside its owned history folder.") } + let manager = FileManager.default + for name in [Self.manifestName, Self.leaseName] { + guard !manager.fileExists(atPath: directory.appendingPathComponent(name).path) else { + throw failure("The build recipe used a reserved history filename: \(name)") + } + } + let files = try contents(directory) + let descriptor = open(directory.appendingPathComponent(Self.leaseName).path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard descriptor >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + var retained = false + defer { if !retained { close(descriptor); try? manager.removeItem(at: directory.appendingPathComponent(Self.leaseName)) } } + guard flock(descriptor, LOCK_SH | LOCK_NB) == 0 else { throw failure("The new build could not be protected from cleanup.") } + let record = Record(version: 1, id: artifact.id, project: canonicalProject(project), createdAt: Date(), + configurationName: artifact.configurationName, action: artifact.action.rawValue, + hasBinary: artifact.hasBinary, hasDisk: artifact.hasDisk, + byteCount: files.values.reduce(Int64(0)) { $0 + Int64($1.count) }, hashes: files.mapValues(CMOCProject.sha256)) + let temporary = directory.appendingPathComponent(".vccplus-history-" + UUID().uuidString) + defer { try? manager.removeItem(at: temporary) } + try JSONEncoder().encode(record).write(to: temporary, options: .withoutOverwriting) + guard renamex_np(temporary.path, directory.appendingPathComponent(Self.manifestName).path, UInt32(RENAME_EXCL)) == 0 else { + throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) + } + leases[artifact.id] = descriptor; retained = true + } + + func entries(project: URL, protectedIDs: Set = []) throws -> [Entry] { + lock.lock(); defer { lock.unlock() } + guard FileManager.default.fileExists(atPath: root.path) else { return [] } + let canonical = canonicalProject(project) + return try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil).compactMap { url in + guard let id = UUID(uuidString: url.lastPathComponent), let record = try? read(id), record.project == canonical else { return nil } + guard let directory = try? checkedDirectory(id) else { return nil } + let reason: String? + if protectedIDs.contains(id) { reason = "Protected build or assigned media" } + else if let invalid = validationProblem(record, directory: directory) { reason = invalid } + else if leases[id] == nil, !leaseAvailable(directory) { reason = "In use by another app session" } + else { reason = nil } + return Entry(id: id, directory: directory, createdAt: record.createdAt, + configurationName: record.configurationName, action: record.action, byteCount: record.byteCount, + hasBinary: record.hasBinary, hasDisk: record.hasDisk, protectionReason: reason) + }.sorted { $0.createdAt == $1.createdAt ? $0.id.uuidString < $1.id.uuidString : $0.createdAt > $1.createdAt } + } + + func remove(ids: Set, project: URL, protectedIDs: Set) throws -> Removal { + lock.lock(); defer { lock.unlock() } + var result = Removal() + let canonical = canonicalProject(project) + for id in ids { + do { + guard !protectedIDs.contains(id) else { throw failure("Protected build or assigned media") } + let record = try read(id), directory = try checkedDirectory(id) + guard record.project == canonical else { throw failure("This build belongs to a different project.") } + let owned = leases[id] + let descriptor = owned ?? open(directory.appendingPathComponent(Self.leaseName).path, O_RDWR | O_NOFOLLOW | O_CLOEXEC) + guard descriptor >= 0 else { throw failure("Build ownership could not be verified.") } + defer { + if let owned, leases[id] != nil { _ = flock(owned, LOCK_SH) } + if owned == nil { close(descriptor) } + } + guard validLease(descriptor, directory: directory) else { throw failure("Build ownership file changed; kept for recovery") } + guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else { throw failure("In use by another app session") } + if let problem = validationProblem(record, directory: directory) { throw failure(problem) } + // Trash retains a recovery path even if a file was edited in the + // brief interval after validation. Never remove a run disk here. + try trash(directory) + if let owned { leases.removeValue(forKey: id); close(owned) } + result.removedIDs.insert(id) + } catch { result.retained[id] = error.localizedDescription } + } + return result + } + + private func canonicalProject(_ project: URL) -> String { project.standardizedFileURL.resolvingSymlinksInPath().path } + private func failure(_ message: String) -> CMOCBuildError { .message(message) } + private func checkedDirectory(_ id: UUID) throws -> URL { + let rootValues = try root.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) + guard rootValues.isDirectory == true, rootValues.isSymbolicLink != true else { throw failure("Build history folder ownership could not be verified.") } + let canonicalRoot = try CMOCProject.physicalURL(root) + let directory = canonicalRoot.appendingPathComponent(id.uuidString) + let values = try directory.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) + guard values.isDirectory == true, values.isSymbolicLink != true, + try CMOCProject.physicalURL(directory).deletingLastPathComponent() == canonicalRoot else { + throw failure("Build folder ownership could not be verified.") + } + return directory + } + private func read(_ id: UUID) throws -> Record { + let directory = try checkedDirectory(id), url = directory.appendingPathComponent(Self.manifestName) + let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) + guard values.isRegularFile == true, values.isSymbolicLink != true, + let size = values.fileSize, size > 0, size <= 8 * 1024 * 1024 else { throw failure("Build history is missing or invalid.") } + let record = try JSONDecoder().decode(Record.self, from: Data(contentsOf: url)) + guard record.version == 1, record.id == id, record.hashes.count <= 20_000, + record.byteCount >= 0, record.byteCount <= Int64(CMOCProject.maximumProjectBytes), + record.configurationName.count <= 1024, CMOCBuildAction(rawValue: record.action) != nil, + record.project.hasPrefix("/"), record.project.count <= 4096 else { throw failure("Build history is missing or invalid.") } + for path in record.hashes.keys { try CMOCProject.validateRelativePath(path) } + return record + } + private func leaseAvailable(_ directory: URL) -> Bool { + let descriptor = open(directory.appendingPathComponent(Self.leaseName).path, O_RDWR | O_NOFOLLOW | O_CLOEXEC) + guard descriptor >= 0 else { return false } + defer { close(descriptor) } + return validLease(descriptor, directory: directory) && flock(descriptor, LOCK_EX | LOCK_NB) == 0 + } + private func validLease(_ descriptor: Int32, directory: URL) -> Bool { + var held = stat(), current = stat() + guard fstat(descriptor, &held) == 0, + lstat(directory.appendingPathComponent(Self.leaseName).path, ¤t) == 0 else { return false } + return (current.st_mode & S_IFMT) == S_IFREG && current.st_size == 0 && + held.st_dev == current.st_dev && held.st_ino == current.st_ino + } + private func validationProblem(_ record: Record, directory: URL) -> String? { + do { + if let descriptor = leases[record.id], !validLease(descriptor, directory: directory) { + return "Build ownership file changed; kept for recovery" + } + let files = try contents(directory) + guard files.mapValues(CMOCProject.sha256) == record.hashes else { + return "Files changed since this build; kept for recovery" + } + return nil + } catch { return "Files are missing, linked or unreadable; kept for recovery" } + } + /// Unlike project enumeration, this includes hidden/user-added files. Any + /// changed, added or missing file makes a completed snapshot ineligible. + private func contents(_ directory: URL) throws -> [String: Data] { + var enumerationError: Error? + guard let enumerator = FileManager.default.enumerator(at: directory, + includingPropertiesForKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey], + errorHandler: { _, error in enumerationError = error; return false }) else { throw failure("Build files could not be inspected.") } + var files: [String: Data] = [:], total = 0 + while let url = enumerator.nextObject() as? URL { + let relative = String(url.path.dropFirst(directory.path.count + 1)) + if relative == Self.manifestName || relative == Self.leaseName { continue } + try CMOCProject.validateRelativePath(relative) + let values = try url.resourceValues(forKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) + guard values.isSymbolicLink != true else { throw failure("Linked build file") } + if values.isDirectory == true { continue } + // Finder may add this bookkeeping when revealing build products. + // It is not a user source or media change. Links still fail above. + if url.lastPathComponent == ".DS_Store" { continue } + guard values.isRegularFile == true, let size = values.fileSize, size <= CMOCProject.maximumFileBytes, + files.count < 20_000, total + size <= CMOCProject.maximumProjectBytes else { throw failure("Build files exceed inspection limits.") } + let data = try Data(contentsOf: url) + guard data.count <= CMOCProject.maximumFileBytes, total + data.count <= CMOCProject.maximumProjectBytes else { throw failure("Build files changed during inspection.") } + total += data.count; files[relative] = data + } + if let enumerationError { throw enumerationError } + return files + } +} diff --git a/platforms/macos/App/CMOCBuildService.swift b/platforms/macos/App/CMOCBuildService.swift new file mode 100644 index 0000000..9a0af53 --- /dev/null +++ b/platforms/macos/App/CMOCBuildService.swift @@ -0,0 +1,1963 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import CryptoKit +import Darwin + +enum CMOCLaunchMode: String, Codable, CaseIterable, Sendable { case quickload, disk } +enum CMOCDiskBootMode: String, Codable, CaseIterable, Sendable { case none, program, custom } +/// Commands typed at a Disk BASIC prompt after mounting a development disk in FD0. +enum DevelopmentDiskProgram: Sendable { + case basic(String), binary(String) + + var bootCommand: String { + switch self { + case .basic(let name): return "RUN\"\(name)\"" + case .binary(let name): return "LOADM\"\(name)\":EXEC" + } + } + + func instructions(dos: Bool) -> String { + let manual: String + switch self { + case .basic(let name): manual = "type LOAD\"\(name)\", then type RUN on the next line." + case .binary: manual = "type \(bootCommand)." + } + return "Mount the disk in FD0. At the Disk BASIC prompt, " + manual + + (dos ? " You can also type DOS to start the program." : "") + } +} + +enum CMOCBuildAction: String, CaseIterable, Sendable { case build, rebuild, clean, disk, custom } +struct CMOCBuildConfiguration: Codable, Equatable, Sendable { + var name: String + var makeArguments: [String] = [] + init(name: String, makeArguments: [String] = []) { self.name = name; self.makeArguments = makeArguments } + enum CodingKeys: CodingKey { case name, makeArguments } + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + name = try c.decode(String.self, forKey: .name) + makeArguments = try c.decodeIfPresent([String].self, forKey: .makeArguments) ?? [] + } +} + +/// An explicitly configured build recipe, represented as a grouped GNU Make rule. +/// Commands are user-owned Makefile recipes, executed only by Build. +struct CMOCGeneratedResource: Codable, Equatable, Sendable { + var outputs: [String] + var inputs: [String] + var command: String + init(outputs: [String] = [], inputs: [String] = [], command: String = "") { + self.outputs = outputs; self.inputs = inputs; self.command = command + } +} +struct CMOCLibraryProject: Codable, Equatable, Sendable { + var directory: String + var target: String + var archive: String + init(directory: String = "", target: String = "all", archive: String = "") { + self.directory = directory; self.target = target; self.archive = archive + } +} +struct CMOCMakefileSettings: Codable, Equatable, Sendable { + static let marker = "# Generated by VCC Plus — edit Project Settings to regenerate." + var sources: [String] = ["main.c"] + var includePaths: [String] = [] + var libraries: [String] = ["decbfile"] + var libraryPaths: [String] = [] + var defines: [String] = [] + var compilerOptions: [String] = [] + var linkerOptions: [String] = [] + var limit: String? = nil + var libraryProjects: [CMOCLibraryProject] = [] + var generatedResources: [CMOCGeneratedResource] = [] + var executable = "main.bin" + var origin = "2800" + var stackSpace = 2048 + var releaseOptimization = "-O2" + var diskImage: String? = nil + var diskFiles: [String] = [] + var diskBootLoader: String? = nil + var diskBootMode: CMOCDiskBootMode = .none + init() {} + enum CodingKeys: CodingKey { case sources, includePaths, libraries, libraryPaths, defines, compilerOptions, linkerOptions, limit, libraryProjects, generatedResources, executable, origin, stackSpace, releaseOptimization, diskImage, diskFiles, diskBootLoader, diskBootMode } + init(from decoder: Decoder) throws { + self.init(); let c = try decoder.container(keyedBy: CodingKeys.self) + sources = try c.decodeIfPresent([String].self, forKey: .sources) ?? sources + includePaths = try c.decodeIfPresent([String].self, forKey: .includePaths) ?? [] + libraries = try c.decodeIfPresent([String].self, forKey: .libraries) ?? libraries + libraryPaths = try c.decodeIfPresent([String].self, forKey: .libraryPaths) ?? [] + defines = try c.decodeIfPresent([String].self, forKey: .defines) ?? [] + compilerOptions = try c.decodeIfPresent([String].self, forKey: .compilerOptions) ?? [] + linkerOptions = try c.decodeIfPresent([String].self, forKey: .linkerOptions) ?? [] + limit = try c.decodeIfPresent(String.self, forKey: .limit) + libraryProjects = try c.decodeIfPresent([CMOCLibraryProject].self, forKey: .libraryProjects) ?? [] + generatedResources = try c.decodeIfPresent([CMOCGeneratedResource].self, forKey: .generatedResources) ?? [] + executable = try c.decodeIfPresent(String.self, forKey: .executable) ?? executable + origin = try c.decodeIfPresent(String.self, forKey: .origin) ?? origin + stackSpace = try c.decodeIfPresent(Int.self, forKey: .stackSpace) ?? stackSpace + releaseOptimization = try c.decodeIfPresent(String.self, forKey: .releaseOptimization) ?? releaseOptimization + diskImage = try c.decodeIfPresent(String.self, forKey: .diskImage) + diskFiles = try c.decodeIfPresent([String].self, forKey: .diskFiles) ?? [] + diskBootLoader = try c.decodeIfPresent(String.self, forKey: .diskBootLoader) + diskBootMode = try c.decodeIfPresent(CMOCDiskBootMode.self, forKey: .diskBootMode) ?? (diskBootLoader == nil ? .none : .custom) + } + /// Pierre Sarrazin's public-domain autostart.c 0.1.2, copied from + /// third_party/examples/coco-letters/autostart.c. This embedded helper is public + /// domain, separately from the GPL generator. It is emitted only under obj/. + static let dosBootLoaderSource = #""" + // autostart.c - Program to be run by the Disk Basic DOS command. + // By Pierre Sarrazin + // This file is in the public domain. + // + // Reference: Roger Schrag, "A Special Use For The DOS Command", + // The Rainbow, November 1984, p.140. + // + // To compile: cmoc --dos autostart.c + // To install on CoCo disk image: install-coco-boot-loader some-image.dsk autostart.bin + // To run on CoCo: type DOS and to automatically run *.BAS. + // + // Version history: + // 0.1.0 2016-01-16 Use of legacy.h discontinued. + // 0.1.1 2018-04-03 Adapted to CMOC 0.1.51 (const). + // 0.1.2 2018-08-04 Basic line now forced to be uppercase. + + #include + + #define ENDFLG 0x00 // STOP/END FLAG: POSITIVE=STOP, NEG=END + #define CINBFL 0x70 // CONSOLE IN BUFFER FLAG: 00=NOT EMPTY, $FF=EMPTY + #define RVEC4 0x016a // RAM hook: CONSOLE IN + + + byte oldHookInstr; + word oldHookAddr; + const char *basicLineReader; + + + void feedKeyboard() + { + word preservedX; + asm("stx", preservedX); + + * (byte *) CINBFL = 0; // console in buffer now not empty + + char nextBasicByte = (char) toupper(*basicLineReader); + ++basicLineReader; + if (nextBasicByte == 0) // if finished returning Basic line + { + * (byte *) RVEC4 = oldHookInstr; + * (word *) (RVEC4 + 1) = oldHookAddr; + nextBasicByte = '\r'; // return "Enter" to cause execution of Basic line + } + + asm { + lda nextBasicByte + ldx preservedX + tfr u,s // discard stack frame + leas 4,s // discard previous stack frame ptr and return addr + rts // return to caller of CONSOLE IN + } + } + + + int main() + { + * (byte *) ENDFLG = - * (byte *) ENDFLG; // why? + + basicLineReader = + #ifndef COMMAND + "RUN\"*.BAS\"" + #else + COMMAND + #endif + ; + + // Install function feedKeyboard() as CONSOLE IN routine. + // + oldHookInstr = * (byte *) RVEC4; + oldHookAddr = * (word *) (RVEC4 + 1); + + * (byte *) RVEC4 = 0x7e; // JMP instruction + * (void **) (RVEC4 + 1) = (void *) feedKeyboard; + + * (word *) 0x2600 = 0; // overwrite "OS" marker with two null bytes + + asm("jmp", "$ac7c"); // go interpret a Basic line (which is read from console) + + return 0; // avoids compiler error + } + """# + var programBootCommand: String { DevelopmentDiskProgram.binary((executable as NSString).lastPathComponent.uppercased()).bootCommand } + + func generateMakefile(makefileName: String = "Makefile") throws -> String { + // Generated recipes use simple Make-safe project-relative names. Imported + // Makefiles remain free to implement more elaborate escaping and layouts. + func path(_ value: String) throws { + try CMOCProject.validateRelativePath(value) + guard value.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || "_./-".contains($0)) }), !value.hasPrefix("-") else { + throw CMOCBuildError.message("Generated Makefile paths must use letters, numbers, underscores, dots, dashes and slashes: \(value)") + } + } + guard !sources.isEmpty, Set(sources.map { $0.lowercased() }).count == sources.count, sources.allSatisfy({ $0.hasSuffix(".c") }), + ["-O0", "-O1", "-O2"].contains(releaseOptimization), (64...32768).contains(stackSpace), + UInt16(origin.hasPrefix("0x") ? String(origin.dropFirst(2)) : origin, radix: 16) != nil else { + throw CMOCBuildError.message("Choose distinct C sources, a hexadecimal load address, and a supported optimization/stack setting.") + } + func checkedArgument(_ argument: String) throws { + guard !argument.isEmpty, argument.utf8.count <= 8192, !argument.contains("\0"), + !argument.contains("\n"), !argument.contains("\r") else { + throw CMOCBuildError.message("Compiler options and definitions must each occupy one nonempty line.") + } + } + for definition in defines { + try checkedArgument(definition) + let name = definition.prefix(while: { $0 != "=" }) + guard let first = name.first, first.isASCII && (first.isLetter || first == "_"), + name.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "_") }) else { + throw CMOCBuildError.message("Use C macro definitions such as MAX_WORD_LEN=5 or DISPLAY_NAME=\"My Game\".") + } + } + for option in compilerOptions + linkerOptions { + try checkedArgument(option) + guard option.hasPrefix("-"), option != "-", option != "--" else { + throw CMOCBuildError.message("Additional compiler/linker arguments must be options beginning with '-'.") + } + } + if let limit, UInt16(limit.hasPrefix("0x") ? String(limit.dropFirst(2)) : limit, radix: 16) == nil { + throw CMOCBuildError.message("The optional memory limit must be a hexadecimal address, such as 7F80.") + } + func shellArgument(_ token: String) -> String { + // GNU Make define blocks retain # and backslashes. Double dollars for + // Make expansion, then single-quote each argv token for the shell. + "'" + token.replacingOccurrences(of: "$", with: "$$").replacingOccurrences(of: "'", with: "'\"'\"'") + "'" + } + let generatedOutputs = generatedResources.flatMap(\.outputs) + guard Set(generatedOutputs.map { $0.lowercased() }).count == generatedOutputs.count else { throw CMOCBuildError.message("A generated resource may have only one producing recipe.") } + try path(makefileName) + for value in sources + includePaths + libraryPaths + [executable] + [diskImage, diskBootLoader].compactMap({ $0 }) + diskFiles + generatedOutputs + generatedResources.flatMap(\.inputs) { try path(value) } + let reserved = Set([makefileName.lowercased(), CMOCProject.configurationFilename.lowercased()]) + let executableKey = executable.lowercased(), diskKey = diskImage?.lowercased() + let sourcesAndInputs = Set((sources + generatedResources.flatMap(\.inputs)).map { $0.lowercased() }) + guard !reserved.contains(executableKey), !sourcesAndInputs.contains(executableKey), + diskKey != executableKey, + diskKey.map({ !reserved.contains($0) && !sourcesAndInputs.contains($0) }) ?? true, + !sources.contains(where: { $0.lowercased().hasPrefix("obj/") }), + !generatedOutputs.contains(where: { reserved.contains($0.lowercased()) || $0.lowercased() == executableKey || $0.lowercased() == diskKey }) else { + throw CMOCBuildError.message("Build outputs must not replace source files, Makefile, project settings or one another. The obj directory is reserved for compiler products.") + } + if diskImage != nil { + var diskNames = Set() + for file in [executable] + diskFiles { + let name = (file as NSString).lastPathComponent.uppercased() + let parts = name.split(separator: ".", omittingEmptySubsequences: false) + guard (1...2).contains(parts.count), (1...8).contains(parts[0].count), + (parts.count == 1 || (1...3).contains(parts[1].count)), + parts.allSatisfy({ $0.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || "_-".contains($0)) }) }), + diskNames.insert(name).inserted else { + throw CMOCBuildError.message("Disk files need unique 8.3 names (ignoring case), including the executable: \(name)") + } + } + } + for library in libraries { + guard !library.isEmpty, library.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || "_-".contains($0)) }) else { throw CMOCBuildError.message("Invalid library name: \(library)") } + } + for library in libraryProjects { try path(library.directory); try path(library.archive); try path(library.target) } + for recipe in generatedResources { + guard !recipe.outputs.isEmpty, !recipe.command.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + !recipe.command.contains("\0"), recipe.command.utf8.count <= 32768 else { throw CMOCBuildError.message("Each generated resource needs output files and a command.") } + } + let automaticLoader = "obj/vcc-dos-boot/loader.bin" + var loader: String? + switch diskBootMode { + case .none: loader = nil + case .custom: + guard let diskBootLoader else { throw CMOCBuildError.message("Choose a custom DOS bootloader binary, or select None.") } + loader = diskBootLoader + case .program: + guard diskImage != nil, UInt16(origin.hasPrefix("0x") ? String(origin.dropFirst(2)) : origin, radix: 16)! >= 0x2800 else { + throw CMOCBuildError.message("Automatic DOS boot requires a disk image and a program load address of $2800 or higher.") + } + guard !(sources + diskFiles + generatedOutputs + generatedResources.flatMap(\.inputs) + [executable, diskImage!]).contains(where: { + $0.lowercased() == "obj/vcc-dos-boot" || $0.lowercased().hasPrefix("obj/vcc-dos-boot/") + }) else { throw CMOCBuildError.message("obj/vcc-dos-boot is reserved for the automatic DOS bootloader.") } + loader = automaticLoader + } + let objects = sources.map { "obj/" + String($0.dropLast(2)) + ".o" } + let archives = libraryProjects.map(\.archive) + let includeFlags = includePaths.map { "-I" + $0 }.joined(separator: " ") + let libraryFlags = (libraryPaths.map { "-L" + $0 } + libraries.map { "-l" + $0 }).joined(separator: " ") + let compatibility = libraries.contains("vcccompat") ? "export VCC_CMOC_COMPAT = 1\n" : "" + var text = """ + \(Self.marker) + # Ordinary GNU Make; no VCC Plus project parser is required to build it. + CMOC ?= cmoc + PERL ?= perl + WRITECOCOFILE ?= writecocofile + INSTALL_LOADER ?= install-coco-boot-loader + VCC_CONFIGURATION ?= Debug + ifeq ($(VCC_CONFIGURATION),Release) + OPTIM ?= \(releaseOptimization) + else + OPTIM ?= -O0 + DEBUG_FRAME ?= -fno-omit-frame-pointer + endif + define VCC_DEFINES + \(defines.map { shellArgument("-D" + $0) }.joined(separator: " ")) + endef + define VCC_COMPILER_OPTIONS + \(compilerOptions.map(shellArgument).joined(separator: " ")) + endef + define VCC_LINKER_OPTIONS + \(linkerOptions.map(shellArgument).joined(separator: " ")) + endef + \(compatibility)CPPFLAGS += \(includeFlags) $(VCC_DEFINES) + CFLAGS += --coco --intermediate --deps --stack-space=\(stackSpace) $(OPTIM) $(DEBUG_FRAME) $(VCC_COMPILER_OPTIONS) + LDFLAGS += --coco --intermediate --org=\(origin) \(limit.map { "--limit=" + $0 } ?? "") $(VCC_LINKER_OPTIONS) + LDLIBS += \(libraryFlags) + OBJECTS := \(objects.joined(separator: " ")) + .PHONY: all build clean disk libraries + all: build + build: \(executable) + \(executable): $(OBJECTS) \(archives.joined(separator: " ")) \(makefileName) + \t@mkdir -p $(dir $@) + \t"$(CMOC)" $(LDFLAGS) -o $@ $(OBJECTS) \(archives.joined(separator: " ")) $(LDLIBS) + + """ + // Explicit rules preserve directory identity for equal basenames in different folders. + // Generated headers/resources precede compilation on the first build; .d files + // then provide exact per-translation-unit header dependencies. + for (source, object) in zip(sources, objects) { + text += "\(object): \(source) \(makefileName) \(generatedOutputs.joined(separator: " "))\n" + text += "\t@mkdir -p $(dir $@)\n" + text += "\t\"$(CMOC)\" $(CPPFLAGS) $(CFLAGS) --intdir=$(dir $@) -c -o $@ $<\n\n" + } + for recipe in generatedResources { + text += recipe.outputs.joined(separator: " ") + " &: " + recipe.inputs.joined(separator: " ") + " \(makefileName)\n" + let directories = Set(recipe.outputs.map { ($0 as NSString).deletingLastPathComponent }.filter { !$0.isEmpty }).sorted() + if !directories.isEmpty { text += "\t@mkdir -p " + directories.joined(separator: " ") + "\n" } + for line in recipe.command.split(separator: "\n", omittingEmptySubsequences: false) { text += "\t" + line + "\n" } + for output in recipe.outputs { text += "\ttest -f " + output + "\n" } + text += "\n" + } + for (index, library) in libraryProjects.enumerated() { + let refresh = "vcc-library-\(index)" + text += ".PHONY: \(refresh)\n\(refresh):\n" + // Run the submake as the archive recipe so GNU Make restats the + // archive before deciding whether its dependents need relinking. + text += "\(library.archive): \(refresh)\n\t$(MAKE) -C \(library.directory) \(library.target)\n\ttest -f $@\n\n" + } + if diskBootMode == .program { + // No Make-time shell/file evaluation: emit/compile the helper only as + // an ordinary target recipe. Its code must end before the user program. + let define = "-DCOMMAND=\"" + programBootCommand.replacingOccurrences(of: "\"", with: "\\\"") + "\"" + text += "# DOS helper: Pierre Sarrazin, autostart.c 0.1.2, public domain.\n" + text += "\(automaticLoader): \(makefileName)\n\t@mkdir -p $(dir $@)\n" + text += "\t@printf '%s\\n' " + Self.dosBootLoaderSource.components(separatedBy: "\n").map(shellArgument).joined(separator: " ") + " > obj/vcc-dos-boot/loader.c\n" + text += "\t\"$(CMOC)\" --dos -O0 --limit=2800 -o $@ " + shellArgument(define) + " obj/vcc-dos-boot/loader.c\n\n" + } + if let diskImage { + text += "disk: \(diskImage)\n\(diskImage): \(executable) \(diskFiles.joined(separator: " ")) \(loader ?? "") \(makefileName)\n" + text += "\t@mkdir -p $(dir $@)\n" + // Disk BASIC geometry; writecocofile initializes the directory/granule state + // from a blank 0xFF image, as used by the upstream CoCo Letters workflow. + text += "\t$(PERL) -e 'print chr(255) x (35*18*256)' > $@\n" + if let loader { text += "\t$(INSTALL_LOADER) $@ \(loader)\n" } + for file in [executable] + diskFiles { text += "\t$(WRITECOCOFILE) $@ \(file)\n" } + } else { text += "disk:\n\t@echo 'No disk image configured'; exit 1\n" } + text += "\nclean:\n\trm -rf obj\n\trm -f \(executable) \((executable as NSString).deletingPathExtension).map \((executable as NSString).deletingPathExtension).link \(diskImage ?? "") \(generatedOutputs.joined(separator: " "))\n" + for library in libraryProjects { text += "\t$(MAKE) -C \(library.directory) clean\n" } + text += "\n-include $(OBJECTS:.o=.d)\n" + return text + } +} + +/// Portable bindings for libraries supplied by the current app installation. +struct CMOCBundledLibraryBinding: Codable, Equatable, Sendable { + var library = "decbfile" + var minimumVersion = "" + var directoryVariable = "" + var linkVariable = "" + init(library: String = "decbfile", minimumVersion: String = "", directoryVariable: String = "", linkVariable: String = "") { + self.library = library; self.minimumVersion = minimumVersion + self.directoryVariable = directoryVariable; self.linkVariable = linkVariable + } + enum CodingKeys: CodingKey { case library, minimumVersion, directoryVariable, linkVariable } + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + library = try c.decode(String.self, forKey: .library) + minimumVersion = try c.decodeIfPresent(String.self, forKey: .minimumVersion) ?? "" + directoryVariable = try c.decodeIfPresent(String.self, forKey: .directoryVariable) ?? "" + linkVariable = try c.decodeIfPresent(String.self, forKey: .linkVariable) ?? "" + } +} +struct CMOCBundledLibrary: Identifiable, Sendable { + var id: String + var version: String + var license: String + var files: [String: String] + var available: Bool + + static func catalog(at runtime: URL) throws -> [Self] { + guard let record = try JSONSerialization.jsonObject(with: Data(contentsOf: runtime.appendingPathComponent("manifest.json"))) as? [String: Any] else { + throw CMOCBuildError.message("The bundled library manifest is unreadable.") + } + var entries = record["libraries"] as? [String: [String: Any]] ?? [:] + if let disk = record["decbfile"] as? [String: Any] { + entries["decbfile"] = ["version": disk["version"] ?? "", "license": disk["license"] ?? "", "filesSHA256": [ + "share/cmoc/lib/libdecbfile.a": disk["archiveSHA256"] as? String ?? "", + "share/cmoc/include/decbfile.h": disk["headerSHA256"] as? String ?? ""]] + } + let standalone = record["standaloneDisk"] as? [String: Any] + entries["dskcon-standalone"] = ["version": standalone?["cmocVersion"] ?? record["cmoc"] ?? "", "license": "Contains Disk BASIC-derived code; see Licenses & Notices", + "filesSHA256": standalone?["filesSHA256"] ?? [String: String]()] + return entries.keys.sorted().map { name in + let item = entries[name]!, files = item["filesSHA256"] as? [String: String] ?? [:] + let archive = "share/cmoc/lib/lib\(name).a" + return Self(id: name, version: item["version"] as? String ?? "", license: item["license"] as? String ?? "", + files: files, available: files[archive] != nil && FileManager.default.fileExists(atPath: runtime.appendingPathComponent(archive).path)) + } + } + static func version(_ text: String) -> [Int]? { + let pieces = text.split(separator: ".", omittingEmptySubsequences: false) + guard !pieces.isEmpty, pieces.count <= 8, pieces.allSatisfy({ !$0.isEmpty && $0.count <= 8 && $0.allSatisfy({ $0.isASCII && $0.isNumber }) }) else { return nil } + return pieces.compactMap { Int($0) } + } + static func atLeast(_ installed: String, _ required: String) -> Bool { + guard let a = version(installed), let b = version(required) else { return false } + for i in 0.. y } + } + return true + } + static let stagingDirectory = ".vccplus-libraries" + static func validate(_ bindings: [CMOCBundledLibraryBinding], configurations: [CMOCBuildConfiguration]) throws { + guard bindings.count <= 32, Set(bindings.map(\.library)).count == bindings.count else { throw CMOCBuildError.message("Select each bundled library once (up to 32).") } + var directories = Set(), links = Set() + let reserved = Set(["MAKE", "MAKEFLAGS", "MFLAGS", "GNUMAKEFLAGS", "MAKELEVEL", "SHELL", "VCC_TOOLCHAIN"]) + for b in bindings { + guard !b.library.isEmpty, b.library.count <= 80, b.library.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || "_-".contains($0)) }), + b.minimumVersion.isEmpty || version(b.minimumVersion) != nil, + !b.directoryVariable.isEmpty || !b.linkVariable.isEmpty else { throw CMOCBuildError.message("Choose a library, a valid optional minimum version, and a directory or linker variable.") } + for v in [b.directoryVariable, b.linkVariable] where !v.isEmpty { + guard v.count <= 80, let first = v.first, first.isASCII && (first.isLetter || first == "_"), + v.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "_") }), !reserved.contains(v), + !configurations.flatMap(\.makeArguments).contains(where: { $0.prefix(while: { $0 != "=" }) == v }) else { + throw CMOCBuildError.message("Library variables must be ordinary Make names, used only here and not also in configuration arguments: \(v)") + } + } + if !b.directoryVariable.isEmpty, !directories.insert(b.directoryVariable).inserted { throw CMOCBuildError.message("Each library directory needs a distinct Make variable.") } + if !b.linkVariable.isEmpty { links.insert(b.linkVariable) } + } + guard directories.isDisjoint(with: links) else { throw CMOCBuildError.message("A Make variable cannot be both a library directory and linker flags.") } + } + /// Copy verified archives/headers into a space-free isolated workspace. Never + /// point writable Make recipes into the installed application's bundle. + static func stage(_ bindings: [CMOCBundledLibraryBinding], runtime: URL, workspace: URL) throws -> [String: Data] { + let manager = FileManager.default, root = workspace.appendingPathComponent(stagingDirectory) + guard !bindings.isEmpty else { return [:] } + let catalog = try catalog(at: runtime) + var payload: [String: Data] = [:], rules = "# Generated bundled-library bindings; original Makefile is unchanged.\n" + for b in bindings { + guard let library = catalog.first(where: { $0.id == b.library }), library.available else { throw CMOCBuildError.message("Bundled library \(b.library) is not installed in this app.") } + guard b.minimumVersion.isEmpty || atLeast(library.version, b.minimumVersion) else { throw CMOCBuildError.message("\(b.library) requires version \(b.minimumVersion) or newer; this app includes \(library.version).") } + let destination = root.appendingPathComponent(b.library) + for (relative, hash) in library.files { + try CMOCProject.validateRelativePath(relative) + guard relative == "share/cmoc/lib/lib\(b.library).a" || relative.hasPrefix("share/cmoc/include/") || relative.hasPrefix("LICENSES/") else { throw CMOCBuildError.message("Unsupported library manifest path: \(relative)") } + let source = runtime.appendingPathComponent(relative) + guard try source.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink != true else { throw CMOCBuildError.message("Bundled library files must not be links.") } + let data = try Data(contentsOf: source) + guard CMOCProject.sha256(data) == hash else { throw CMOCBuildError.message("Bundled library \(b.library) failed its integrity check. Reinstall the app.") } + let headerPrefix = b.library == "vcccompat" ? "share/cmoc/include/vcc/compat/" : "share/cmoc/include/" + let filename = relative.hasPrefix(headerPrefix) ? String(relative.dropFirst(headerPrefix.count)) : source.lastPathComponent + let path = stagingDirectory + "/" + b.library + "/" + filename + guard payload[path] == nil else { throw CMOCBuildError.message("Duplicate bundled library filename.") } + payload[path] = data + } + if b.library == "vcccompat" { rules += "export VCC_CMOC_COMPAT = 1\n" } + if !b.linkVariable.isEmpty { rules += "override \(b.linkVariable) += -L\(destination.path) -l\(b.library)\n" } + payload[stagingDirectory + "/" + b.library + "/VCC-LIBRARY.txt"] = Data("\(b.library) \(library.version)\n\(library.license)\n".utf8) + } + // Retain bundled third-party notices with the frozen build products. + for (path, bytes) in try CMOCProject.files(in: runtime.appendingPathComponent("LICENSES")) { + payload[stagingDirectory + "/LICENSES/" + path] = bytes + } + payload[stagingDirectory + "/bindings.mk"] = Data(rules.utf8) + for (path, bytes) in payload { + let url = workspace.appendingPathComponent(path) + try manager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + if (try? Data(contentsOf: url)) != bytes { try bytes.write(to: url, options: .atomic) } + } + return payload + } +} + +/// Optional UI metadata. The user's ordinary Makefile remains the build authority. +struct CMOCProjectConfiguration: Codable, Equatable, Sendable { + var entrySource = "main.c" + var makefile = "Makefile" + // An empty override delegates goal selection to Make itself. + var buildTarget = "" + var cleanTarget = "clean" + var diskTarget: String? = nil + var binary: String? = "main.bin" + var diskImage: String? = nil + /// Optional build-produced placement manifest for packed/banked programs. + var debugManifest: String? = nil + /// Additional build-produced floppy images reviewed for owned disk exchange. + /// These are outputs, not source inputs or arbitrary files to mount. + var playtestDisks: [String] = [] + var launchMode: CMOCLaunchMode = .quickload + var launchCommands: [String] = [] + var configurations = [CMOCBuildConfiguration(name: "Debug"), CMOCBuildConfiguration(name: "Release", makeArguments: ["VCC_CONFIGURATION=Release"])] + var jobs = 1 + var bundledLibraries: [CMOCBundledLibraryBinding] = [] + /// Explicit sibling folders needed by a custom Makefile, such as ../tools. + /// They are copied beside the isolated project, never inferred from recipes. + var buildSupportDirectories: [String] = [] + /// Explicit non-source inputs, pre-generated inputs, and disposable output roots. + var resourceInputs: [String] = [] + var generatedInputs: [String] = [] + var outputDirectories: [String] = [] + var makefileSettings: CMOCMakefileSettings? = nil + init() {} + enum CodingKeys: CodingKey { case entrySource, makefile, buildTarget, cleanTarget, diskTarget, binary, diskImage, debugManifest, playtestDisks, launchMode, launchCommands, configurations, jobs, makefileSettings, bundledLibraries, buildSupportDirectories, resourceInputs, generatedInputs, outputDirectories } + init(from decoder: Decoder) throws { + self.init() + let c = try decoder.container(keyedBy: CodingKeys.self) + entrySource = try c.decodeIfPresent(String.self, forKey: .entrySource) ?? entrySource + makefile = try c.decodeIfPresent(String.self, forKey: .makefile) ?? makefile + buildTarget = try c.decodeIfPresent(String.self, forKey: .buildTarget) ?? buildTarget + cleanTarget = try c.decodeIfPresent(String.self, forKey: .cleanTarget) ?? cleanTarget + diskTarget = try c.decodeIfPresent(String.self, forKey: .diskTarget) + if c.contains(.binary) { binary = try c.decodeIfPresent(String.self, forKey: .binary) } + diskImage = try c.decodeIfPresent(String.self, forKey: .diskImage) + debugManifest = try c.decodeIfPresent(String.self, forKey: .debugManifest) + playtestDisks = try c.decodeIfPresent([String].self, forKey: .playtestDisks) ?? [] + launchMode = try c.decodeIfPresent(CMOCLaunchMode.self, forKey: .launchMode) ?? launchMode + launchCommands = try c.decodeIfPresent([String].self, forKey: .launchCommands) ?? [] + configurations = try c.decodeIfPresent([CMOCBuildConfiguration].self, forKey: .configurations) ?? configurations + jobs = try c.decodeIfPresent(Int.self, forKey: .jobs) ?? jobs + makefileSettings = try c.decodeIfPresent(CMOCMakefileSettings.self, forKey: .makefileSettings) + bundledLibraries = try c.decodeIfPresent([CMOCBundledLibraryBinding].self, forKey: .bundledLibraries) ?? [] + buildSupportDirectories = try c.decodeIfPresent([String].self, forKey: .buildSupportDirectories) ?? [] + resourceInputs = try c.decodeIfPresent([String].self, forKey: .resourceInputs) ?? [] + generatedInputs = try c.decodeIfPresent([String].self, forKey: .generatedInputs) ?? [] + outputDirectories = try c.decodeIfPresent([String].self, forKey: .outputDirectories) ?? [] + } + func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(entrySource, forKey: .entrySource); try c.encode(makefile, forKey: .makefile) + try c.encode(buildTarget, forKey: .buildTarget); try c.encode(cleanTarget, forKey: .cleanTarget) + try c.encodeIfPresent(diskTarget, forKey: .diskTarget) + if let binary { try c.encode(binary, forKey: .binary) } else { try c.encodeNil(forKey: .binary) } + try c.encodeIfPresent(diskImage, forKey: .diskImage); try c.encode(launchMode, forKey: .launchMode) + try c.encodeIfPresent(debugManifest, forKey: .debugManifest) + if !playtestDisks.isEmpty { try c.encode(playtestDisks, forKey: .playtestDisks) } + try c.encode(launchCommands, forKey: .launchCommands); try c.encode(configurations, forKey: .configurations) + try c.encode(jobs, forKey: .jobs); try c.encodeIfPresent(makefileSettings, forKey: .makefileSettings) + if !bundledLibraries.isEmpty { try c.encode(bundledLibraries, forKey: .bundledLibraries) } + if !buildSupportDirectories.isEmpty { try c.encode(buildSupportDirectories, forKey: .buildSupportDirectories) } + if !resourceInputs.isEmpty { try c.encode(resourceInputs, forKey: .resourceInputs) } + if !generatedInputs.isEmpty { try c.encode(generatedInputs, forKey: .generatedInputs) } + if !outputDirectories.isEmpty { try c.encode(outputDirectories, forKey: .outputDirectories) } + } + func validated() throws -> Self { + for path in [entrySource, makefile] + [binary, diskImage, debugManifest].compactMap({ $0 }) { try CMOCProject.validateRelativePath(path) } + let declarations = resourceInputs + generatedInputs + outputDirectories + guard declarations.count <= 4096, + Set(declarations.map { $0.lowercased() }).count == declarations.count else { + throw CMOCBuildError.message("Project input/output declarations must have at most 4096 distinct, unambiguous paths.") + } + for path in declarations { + try CMOCProject.validateRelativePath(path) + guard !path.split(separator: "/").contains(where: { [".git", ".hg", ".svn"].contains($0.lowercased()) }) else { + throw CMOCBuildError.message("Version-control internals cannot be declared as project inputs or outputs.") + } + } + guard playtestDisks.count <= 8, + Set(playtestDisks.map { $0.lowercased() }).count == playtestDisks.count else { + throw CMOCBuildError.message("Declare at most eight distinct additional playtest disks.") + } + let otherRoles = [entrySource, makefile, CMOCProject.configurationFilename] + + [binary, diskImage, debugManifest].compactMap { $0 } + resourceInputs + generatedInputs + + (makefileSettings?.sources ?? []) + (makefileSettings?.diskFiles ?? []) + + (makefileSettings?.generatedResources.flatMap(\.inputs) ?? []) + let occupiedRoles = Set(otherRoles.map { $0.lowercased() }) + for path in playtestDisks { + try CMOCProject.validateRelativePath(path) + guard ["dsk", "os9"].contains((path as NSString).pathExtension.lowercased()), + !occupiedRoles.contains(path.lowercased()), + !path.split(separator: "/").contains(where: { [".git", ".hg", ".svn"].contains($0.lowercased()) }) else { + throw CMOCBuildError.message("Additional playtest disks need distinct project-relative .dsk or .os9 output paths, separate from inputs and primary outputs.") + } + } + let concreteOutputs = ([binary, diskImage, debugManifest].compactMap { $0 } + playtestDisks + + (makefileSettings?.generatedResources.flatMap(\.outputs) ?? [])).map { $0.lowercased() } + let ordinaryInputs = [entrySource, makefile, CMOCProject.configurationFilename] + resourceInputs + let explicitInputs = ordinaryInputs + generatedInputs + guard !explicitInputs.contains(where: { concreteOutputs.contains($0.lowercased()) }) else { + throw CMOCBuildError.message("A declared input cannot also be a generated binary, disk, manifest or resource output.") + } + if let debugManifest { + guard !([entrySource, makefile] + [binary, diskImage].compactMap { $0 }).contains(where: { $0.lowercased() == debugManifest.lowercased() }) else { + throw CMOCBuildError.message("The debug manifest needs its own generated output path.") + } + } + if !buildTarget.isEmpty { try Self.validateTarget(buildTarget) } + for target in [cleanTarget] + [diskTarget].compactMap({ $0 }) { try Self.validateTarget(target) } + guard (1...32).contains(jobs), !configurations.isEmpty, configurations.count <= 16, + Set(configurations.map(\.name)).count == configurations.count else { + throw CMOCBuildError.message("Project settings need 1–32 build jobs and uniquely named build configurations.") + } + for config in configurations { + guard !config.name.isEmpty, config.name.count <= 100, config.makeArguments.count <= 64 else { + throw CMOCBuildError.message("Invalid build configuration.") + } + for argument in config.makeArguments { + // Variables are passed as individual argv entries, never shell text. + let name = argument.prefix(while: { $0 != "=" }) + guard argument.contains("="), !name.isEmpty, + name.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "_") }), + !argument.contains("\0"), !argument.contains("\n"), argument.count <= 8192 else { + throw CMOCBuildError.message("Build configuration arguments must be Make variable assignments such as OPTIM=-O0.") + } + } + } + try CMOCBundledLibrary.validate(bundledLibraries, configurations: configurations) + guard buildSupportDirectories.count <= 8, + Set(buildSupportDirectories.map { $0.lowercased() }).count == buildSupportDirectories.count else { + throw CMOCBuildError.message("Choose at most eight distinct sibling build-support folders.") + } + for path in buildSupportDirectories { + let name = String(path.dropFirst(3)) + guard path.hasPrefix("../"), !name.isEmpty, name.utf8.count <= 100, + name.first?.isASCII == true, + name.first!.isLetter || name.first!.isNumber || name.first == "_", + name.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || "_.-".contains($0)) }), + name.lowercased() != "project" else { + throw CMOCBuildError.message("Build-support folders must be named siblings such as ../tools; nested paths and project are not allowed.") + } + } + guard launchCommands.count <= 16, launchCommands.allSatisfy({ !$0.contains("\0") && $0.utf8.count <= 4096 }) else { + throw CMOCBuildError.message("Project launch commands are too large or invalid.") + } + return self + } + static func validateTarget(_ target: String) throws { + guard !target.isEmpty, !target.hasPrefix("-"), !target.contains("="), !target.contains("\0"), + !target.contains("\n"), target.utf8.count <= 512 else { throw CMOCBuildError.message("Choose a valid Make target name.") } + } +} + +struct CMOCProjectFile: Identifiable, Equatable, Sendable { + let relativePath: String + let isEditable: Bool + var id: String { relativePath } +} + +struct CMOCBuildSupportSnapshot: Equatable, Sendable { + let files: [String: Data] + let permissions: [String: Int] + var hashes: [String: String] { + var result = files.mapValues(CMOCProject.sha256) + for (path, mode) in permissions { result["@mode:" + path] = CMOCProject.sha256(Data(String(mode).utf8)) } + return result + } +} + +/// Opening and enumerating an ordinary project never executes its Makefile. +struct CMOCProject: Equatable, Sendable { + static let maximumSourceBytes = 1_048_576 + static let maximumMakefileBytes = 65_536 + static let configurationFilename = "vccplus-project.json" + static let maximumFileBytes = 64 * 1024 * 1024 + static let maximumProjectBytes = 512 * 1024 * 1024 + let directory: URL + var configuration: CMOCProjectConfiguration + init(directory: URL, configuration: CMOCProjectConfiguration = .init()) { + self.directory = URL(fileURLWithPath: directory.standardizedFileURL.path, isDirectory: true) + self.configuration = configuration + } + var sourceURL: URL { directory.appendingPathComponent(configuration.entrySource) } + var makefileURL: URL { directory.appendingPathComponent(configuration.makefile) } + + static let starterSource = DevelopmentStarterSource.planet(withExtension: "c") + ?? "/* Reinstall VCC Plus to restore the Hello World starter. */\n" + + static let starterMakefile = """ + # Ordinary Makefile. VCC Plus supplies CMOC and Make on PATH. + CMOC ?= cmoc + LIBS ?= -ldecbfile + VCC_CONFIGURATION ?= Debug + ifeq ($(VCC_CONFIGURATION),Release) + OPTIM ?= -O2 + else + OPTIM ?= -O0 + DEBUG_FRAME ?= -fno-omit-frame-pointer + endif + .PHONY: build clean + build: main.bin + main.bin: main.c + \t"$(CMOC)" --coco $(OPTIM) $(DEBUG_FRAME) --intermediate -o main.bin main.c $(LIBS) + clean: + \trm -f main.bin main.o main.s main.lst main.map main.link + + """ + + static func create(at directory: URL) throws -> CMOCProject { + let project = CMOCProject(directory: directory.standardizedFileURL) + guard !FileManager.default.fileExists(atPath: project.directory.path) else { + throw CMOCBuildError.message("Choose a new folder for the C project; this folder already exists.") + } + try FileManager.default.createDirectory(at: project.directory, withIntermediateDirectories: false) + do { + try Data(starterSource.utf8).write(to: project.sourceURL, options: .atomic) + try Data(starterMakefile.utf8).write(to: project.makefileURL, options: .atomic) + } catch { try? FileManager.default.removeItem(at: project.directory); throw error } + return project + } + + /// The installed sample is immutable. Each New Project action makes a new, + /// writable source-only copy and never reuses another project's files/media. + static func createHelloDisk(at directory: URL, templateDirectory: URL? = nil) throws -> CMOCProject { + try createTemplate(at: directory, named: "HelloDisk", required: Set(["main.c", "include/hello.h", "src/display.c", "src/disk.c", "assets/words.txt", "tools/build-data.pl", "Makefile", configurationFilename, "README.md", ".gitignore"]), templateDirectory: templateDirectory) + } + + static func createTalkingLander(at directory: URL, templateDirectory: URL? = nil) throws -> CMOCProject { + try createTemplate(at: directory, named: "TalkingPlanetLander", required: ["main.c", "Makefile", configurationFilename, "README.md", ".gitignore"], templateDirectory: templateDirectory) + } + + private static func createTemplate(at directory: URL, named name: String, required: Set, templateDirectory: URL?) throws -> CMOCProject { + guard let template = templateDirectory ?? Bundle.main.resourceURL?.appendingPathComponent("DevelopmentTemplates/" + name) else { + throw CMOCBuildError.message("The project template is unavailable in this build.") + } + let files = try Self.files(in: template) + guard Set(files.keys) == required else { + throw CMOCBuildError.message("The selected template is incomplete or contains unexpected files. Reinstall the app's source-only template.") + } + _ = try CMOCProject.open(at: template) + let manager = FileManager.default + guard !manager.fileExists(atPath: directory.path) else { + throw CMOCBuildError.message("Choose a new folder for the C project; this folder already exists.") + } + try manager.createDirectory(at: directory, withIntermediateDirectories: false) + do { + for (path, data) in files { + let destination = directory.appendingPathComponent(path) + try manager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: destination, options: .atomic) + } + return try CMOCProject.open(at: directory) + } catch { + try? manager.removeItem(at: directory) + throw error + } + } + + static func open(at directory: URL) throws -> CMOCProject { + var project = CMOCProject(directory: directory.standardizedFileURL) + let configURL = project.directory.appendingPathComponent(configurationFilename) + if FileManager.default.fileExists(atPath: configURL.path) { + let text = try readText(configURL, maximumBytes: maximumMakefileBytes) + project.configuration = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: Data(text.utf8)).validated() + } else { + if !FileManager.default.fileExists(atPath: project.makefileURL.path) { + if FileManager.default.fileExists(atPath: project.directory.appendingPathComponent("makefile").path) { project.configuration.makefile = "makefile" } + else if FileManager.default.fileExists(atPath: project.directory.appendingPathComponent("GNUmakefile").path) { project.configuration.makefile = "GNUmakefile" } + } + if !FileManager.default.fileExists(atPath: project.sourceURL.path) { + guard let entry = try project.fileEntries().first(where: { $0.relativePath.hasSuffix(".c") }) else { + throw CMOCBuildError.message("Choose a project folder containing a Makefile and C source, or provide vccplus-project.json with an entry source.") + } + project.configuration.entrySource = entry.relativePath + project.configuration.binary = URL(fileURLWithPath: entry.relativePath).deletingPathExtension().lastPathComponent + ".bin" + } + } + _ = try project.configuration.validated() + _ = try project.readSource() + _ = try readText(project.makefileURL, maximumBytes: maximumMakefileBytes) + return project + } + + static func physicalURL(_ url: URL) throws -> URL { + guard let pointer = realpath(url.path, nil) else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .ENOENT) } + defer { free(pointer) } + return URL(fileURLWithPath: String(cString: pointer), isDirectory: true) + } + + static func validateRelativePath(_ path: String) throws { + let components = path.split(separator: "/", omittingEmptySubsequences: false) + guard !path.isEmpty, !path.hasPrefix("/"), !path.contains("\\"), !path.contains("\0"), !path.contains("\n"), + !components.contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }), path.utf8.count <= 4096 else { + throw CMOCBuildError.message("Project paths must stay inside the project folder: \(path)") + } + } + func fileURL(relativePath: String) throws -> URL { + try Self.validateRelativePath(relativePath) + var url = directory + for component in relativePath.split(separator: "/") { + url.appendPathComponent(String(component)) + if FileManager.default.fileExists(atPath: url.path) { + let values = try url.resourceValues(forKeys: [.isSymbolicLinkKey]) + guard values.isSymbolicLink != true else { throw CMOCBuildError.message("Project files cannot traverse symbolic links: \(relativePath)") } + } + } + return url + } + func fileEntries() throws -> [CMOCProjectFile] { + try CMOCProjectInputManifest.capture(project: self, approvedSupportDirectories: []).files.keys.sorted() + .map { CMOCProjectFile(relativePath: $0, isEditable: Self.isEditable($0)) } + } + + /// Build inputs, excluding conventional compiler products left by an external + /// Make invocation. Prebuilt archives and standalone assembly/data are inputs. + static func filteredInputs(_ files: [String: Data], configuration: CMOCProjectConfiguration) -> [String: Data] { + var excluded = Set() + if let binary = configuration.binary { + excluded.insert(binary.lowercased()) + let stem = (binary as NSString).deletingPathExtension + for ext in ["map", "link"] { excluded.insert((stem + "." + ext).lowercased()) } + } + if let disk = configuration.diskImage { excluded.insert(disk.lowercased()) } + excluded.formUnion(configuration.playtestDisks.map { $0.lowercased() }) + if let manifest = configuration.debugManifest { excluded.insert(manifest.lowercased()) } + if let recipe = configuration.makefileSettings { + for path in recipe.generatedResources.flatMap(\.outputs) { excluded.insert(path.lowercased()) } + for source in recipe.sources { + let stem = "obj/" + (source as NSString).deletingPathExtension + for ext in ["o", "d", "s", "lst"] { excluded.insert((stem + "." + ext).lowercased()) } + } + } + let keys = Set(files.keys.map { $0.lowercased() }) + return files.filter { path, _ in + let key = path.lowercased(), stem = (key as NSString).deletingPathExtension + let ext = (key as NSString).pathExtension + if configuration.makefileSettings != nil && key.hasPrefix("obj/vcc-dos-boot/") { return false } + if excluded.contains(key) || ["o", "d", "lst", "map", "link"].contains(ext) { return false } + if ext == "s" && (keys.contains(stem + ".c") || keys.contains(stem + ".o") || keys.contains(stem + ".lst")) { return false } + if ext == "bin" && (keys.contains(stem + ".c") || keys.contains(stem + ".asm")) { return false } + return true + } + } + + func inputFiles(overlays: [String: String] = [:]) throws -> [String: Data] { + try CMOCProjectInputManifest.capture(project: self, overlays: overlays).files + } + + /// The user must explicitly name these siblings in project settings. Keep + /// their paths outside ordinary project editing and include-file lookup. + func supportSnapshot() throws -> CMOCBuildSupportSnapshot { + _ = try configuration.validated() + let parent = try Self.physicalURL(directory).deletingLastPathComponent() + var files: [String: Data] = [:], permissions: [String: Int] = [:] + var total = 0 + for relative in configuration.buildSupportDirectories { + let name = String(relative.dropFirst(3)) + let root = parent.appendingPathComponent(name, isDirectory: true) + let info = try root.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey]) + guard info.isSymbolicLink != true, info.isDirectory == true, + try Self.physicalURL(root) != Self.physicalURL(directory) else { + throw CMOCBuildError.message("Build-support folders must be separate regular sibling folders: \(relative)") + } + // A support root supplies reviewed files, not another project or + // authority to discover its siblings. Reuse the input classifier + // while ignoring any project configuration stored in that root. + var supportConfiguration = CMOCProjectConfiguration() + supportConfiguration.binary = nil + supportConfiguration.entrySource = "__vcc_support_input__" + supportConfiguration.makefile = "__vcc_support_make__" + let captured = try CMOCProjectInputManifest.capture( + project: CMOCProject(directory: root, configuration: supportConfiguration), + approvedSupportDirectories: [], readConfigurationFile: false, retainHostExecutables: true) + for (path, data) in captured.files { + let key = relative + "/" + path + total += data.count + guard files.count < 20_000, total <= Self.maximumProjectBytes else { + throw CMOCBuildError.message("Build-support folders exceed the 512 MB snapshot limit.") + } + guard let mode = captured.permissions[path] else { + throw CMOCBuildError.message("Build-support file permissions are unavailable: \(key)") + } + files[key] = data; permissions[key] = mode & 0o777 + } + } + return CMOCBuildSupportSnapshot(files: files, permissions: permissions) + } + func supportFiles() throws -> [String: Data] { try supportSnapshot().files } + func supportFileHashes() throws -> [String: String] { try supportSnapshot().hashes } + static func isEditable(_ path: String) -> Bool { + let url = URL(fileURLWithPath: path) + return ["Makefile", "makefile", "GNUmakefile"].contains(url.lastPathComponent) || + ["c", "h", "s", "asm", "lwasm", "mk", "txt", "md", "json", "pl", "py", "sh", "rb", "bas", "cfg", "inc"].contains(url.pathExtension.lowercased()) + } + static func isSource(_ path: String) -> Bool { ["c", "h", "s", "asm", "lwasm", "inc"].contains(URL(fileURLWithPath: path).pathExtension.lowercased()) } + /// Bounded regular-file enumeration. Build snapshots never follow project symlinks. + static func files(in root: URL) throws -> [String: Data] { + let manager = FileManager.default + let canonicalRoot = try physicalURL(root) + var enumerationError: Error? + guard let enumerator = manager.enumerator(at: canonicalRoot, includingPropertiesForKeys: [.isRegularFileKey, .isDirectoryKey, .isSymbolicLinkKey, .fileSizeKey], options: [], errorHandler: { _, error in enumerationError = error; return false }) else { + throw CMOCBuildError.message("The project folder could not be read.") + } + var result: [String: Data] = [:], total = 0 + let excluded = Set([".git", ".svn", ".build", ".vccplus-build", ".DS_Store"]) + while let url = enumerator.nextObject() as? URL { + if excluded.contains(url.lastPathComponent) { enumerator.skipDescendants(); continue } + let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isDirectoryKey, .isSymbolicLinkKey, .fileSizeKey]) + let relative = String(url.path.dropFirst(canonicalRoot.path.count + 1)) + try validateRelativePath(relative) + guard values.isSymbolicLink != true else { throw CMOCBuildError.message("Copy linked resources into the project before building: \(relative)") } + if values.isDirectory == true { continue } + guard values.isRegularFile == true else { throw CMOCBuildError.message("Unsupported project file: \(relative)") } + guard let size = values.fileSize, size <= maximumFileBytes, result.count < 20_000, total + size <= maximumProjectBytes else { + throw CMOCBuildError.message("Project exceeds the 512 MB snapshot or 64 MB per-file limit.") + } + let data = try Data(contentsOf: url) + guard data.count <= maximumFileBytes, total + data.count <= maximumProjectBytes else { throw CMOCBuildError.message("Project changed size while it was being read.") } + total += data.count; result[relative] = data + } + if let enumerationError { throw enumerationError } + return result + } + func currentFileHashes(overlays: [String: String] = [:]) throws -> [String: String] { + let captured = try CMOCProjectInputManifest.capture(project: self, overlays: overlays) + return captured.files.mapValues(Self.sha256).merging(captured.support.hashes) { first, _ in first } + } + func readSource() throws -> String { try readText(relativePath: configuration.entrySource) } + func readText(relativePath: String) throws -> String { + try Self.readText(fileURL(relativePath: relativePath), maximumBytes: Self.maximumSourceBytes) + } + @discardableResult + func saveSource(_ source: String, replacingSHA256 expectedHash: String? = nil) throws -> String { + try saveText(source, relativePath: configuration.entrySource, replacingSHA256: expectedHash) + } + @discardableResult + func saveText(_ source: String, relativePath: String, replacingSHA256 expectedHash: String? = nil) throws -> String { + let url = try fileURL(relativePath: relativePath) + let bytes = try Self.sourceBytes(source) + if let expectedHash { + let disk = try Self.readText(url, maximumBytes: Self.maximumSourceBytes) + guard Self.sha256(Data(disk.utf8)) == expectedHash else { + throw CMOCBuildError.message("\(relativePath) changed outside this window. Reload it before replacing that version.") + } + } + try bytes.write(to: url, options: .atomic) + return Self.sha256(bytes) + } + static func sha256(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() } + static func sourceBytes(_ source: String) throws -> Data { + let data = Data(source.utf8) + guard data.count <= maximumSourceBytes, !source.utf8.contains(0) else { + throw CMOCBuildError.message("Source must be UTF-8 text of at most 1 MB without NUL characters.") + } + return data + } + static func readText(_ url: URL, maximumBytes: Int) throws -> String { + let info = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]) + guard info.isRegularFile == true, info.isSymbolicLink != true else { + throw CMOCBuildError.message("Choose a project containing regular source and Makefile files.") + } + let file = try FileHandle(forReadingFrom: url); defer { try? file.close() } + let data = try file.read(upToCount: maximumBytes + 1) ?? Data() + guard data.count <= maximumBytes, let text = String(data: data, encoding: .utf8), !data.contains(0) else { + throw CMOCBuildError.message("\(url.lastPathComponent) is too large or is not UTF-8 text.") + } + return text + } +} + +/// Original output identity of an explicitly reviewed additional floppy image. +/// Mutable worker copies never overwrite this build receipt. +struct CMOCPlaytestDiskProduct: Codable, Equatable, Sendable { + static let maximumBytes = 512 * 1024 + let relativePath: String + let sha256: String + let byteCount: Int +} + +struct CMOCBuildArtifact: Sendable { + let id: UUID + let directory: URL + let source: String + let sourceData: Data + let sourceSHA256: String + let binaryData: Data + let buildLog: String + let buildOutput: CMOCBuildOutput? + let sources: [String: Data] + let sourceHashes: [String: String] + let fileHashes: [String: String] + let compilationDirectory: URL + let entrySourcePath: String + let binaryRelativePath: String? + let diskRelativePath: String? + /// Digest captured from this build's output bytes, never recomputed from a + /// retained file that may subsequently have changed. + let diskSHA256: String? + let playtestDiskProducts: [CMOCPlaytestDiskProduct] + let debugManifestRelativePath: String? + let outputPaths: [String] + let configurationName: String + let action: CMOCBuildAction + var hasBinary: Bool { binaryRelativePath != nil && !binaryData.isEmpty } + var hasDisk: Bool { diskRelativePath != nil } + var sourceURL: URL { fileURL(entrySourcePath) } + var binaryURL: URL { fileURL(binaryRelativePath ?? "main.bin") } + var diskURL: URL? { diskRelativePath.map(fileURL) } + var listingURL: URL { sourceURL.deletingPathExtension().appendingPathExtension("lst") } + var objectURL: URL { sourceURL.deletingPathExtension().appendingPathExtension("o") } + var mapURL: URL { binaryURL.deletingPathExtension().appendingPathExtension("map") } + var assemblyURL: URL { sourceURL.deletingPathExtension().appendingPathExtension("s") } + var linkScriptURL: URL { binaryURL.deletingPathExtension().appendingPathExtension("link") } + func fileURL(_ path: String) -> URL { directory.appendingPathComponent(path) } + init(id: UUID, directory: URL, source: String, sourceData: Data, sourceSHA256: String, binaryData: Data, buildLog: String, + sources: [String: Data]? = nil, fileHashes: [String: String]? = nil, compilationDirectory: URL? = nil, + entrySourcePath: String = "main.c", binaryRelativePath: String? = "main.bin", diskRelativePath: String? = nil, + outputPaths: [String] = [], configurationName: String = "Debug", action: CMOCBuildAction = .build, + debugManifestRelativePath: String? = nil, diskSHA256: String? = nil, buildOutput: CMOCBuildOutput? = nil, + playtestDiskProducts: [CMOCPlaytestDiskProduct] = []) { + self.id = id; self.directory = directory; self.source = source; self.sourceData = sourceData; self.sourceSHA256 = sourceSHA256 + self.binaryData = binaryData; self.buildLog = buildLog; self.buildOutput = buildOutput; self.sources = sources ?? [entrySourcePath: sourceData] + self.sourceHashes = self.sources.mapValues(CMOCProject.sha256) + self.fileHashes = fileHashes ?? [entrySourcePath: sourceSHA256] + self.compilationDirectory = compilationDirectory ?? directory; self.entrySourcePath = entrySourcePath + self.binaryRelativePath = binaryRelativePath; self.diskRelativePath = diskRelativePath; self.outputPaths = outputPaths + self.debugManifestRelativePath = debugManifestRelativePath + self.diskSHA256 = diskSHA256 + self.playtestDiskProducts = playtestDiskProducts + self.configurationName = configurationName; self.action = action + } + func matches(source: String) -> Bool { sourceSHA256 == CMOCProject.sha256(Data(source.utf8)) } + + /// Only an immutable declared product from this build can supply bytes. + /// Walk from a no-follow directory descriptor, so a replaced parent or leaf + /// cannot redirect the read into another build or an arbitrary host file. + func playtestDiskData(for product: CMOCPlaytestDiskProduct) throws -> Data { + try CMOCProject.validateRelativePath(product.relativePath) + guard playtestDiskProducts.contains(product), outputPaths.contains(product.relativePath), + (1...CMOCPlaytestDiskProduct.maximumBytes).contains(product.byteCount) else { + throw CMOCBuildError.message("The selected playtest disk is not a declared product of this artifact.") + } + return try readPlaytestDisk(relativePath: product.relativePath, sha256: product.sha256, byteCount: product.byteCount) + } + + func playtestPrimaryDiskData() throws -> Data { + guard let relativePath = diskRelativePath, let sha256 = diskSHA256, + outputPaths.contains(relativePath) else { + throw CMOCBuildError.message("The primary playtest disk is not a verified product of this artifact.") + } + return try readPlaytestDisk(relativePath: relativePath, sha256: sha256, byteCount: nil) + } + + private func readPlaytestDisk(relativePath: String, sha256: String, byteCount: Int?) throws -> Data { + try CMOCProject.validateRelativePath(relativePath) + guard sha256.utf8.count == 64, + sha256.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }) else { + throw CMOCBuildError.message("The playtest disk has no valid original build hash.") + } + let path = directory.standardizedFileURL.path + // Only macOS's well-known /var and /tmp aliases are normalized. Other + // links, including a replaced artifact root, fail the descriptor walk. + let root = path == "/var" || path.hasPrefix("/var/") || path == "/tmp" || path.hasPrefix("/tmp/") ? "/private" + path : path + var parent = Darwin.open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW) + guard parent >= 0 else { throw CMOCBuildError.message("The playtest artifact directory is unavailable.") } + defer { Darwin.close(parent) } + let components = root.split(separator: "/").map(String.init) + relativePath.split(separator: "/").map(String.init) + for component in components.dropLast() { + let next = openat(parent, component, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW) + guard next >= 0 else { throw CMOCBuildError.message("The declared playtest disk cannot traverse a replaced or symbolic directory.") } + Darwin.close(parent); parent = next + } + let descriptor = openat(parent, components.last!, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK) + guard descriptor >= 0 else { throw CMOCBuildError.message("The declared playtest disk is unavailable or has been replaced.") } + let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true) + defer { try? handle.close() } + var before = stat() + guard fstat(descriptor, &before) == 0, before.st_mode & S_IFMT == S_IFREG, + before.st_nlink == 1, before.st_size > 0, before.st_size <= off_t(CMOCPlaytestDiskProduct.maximumBytes), + byteCount == nil || before.st_size == off_t(byteCount!) else { + throw CMOCBuildError.message("The declared playtest disk is not the original bounded regular output.") + } + let data = try handle.read(upToCount: CMOCPlaytestDiskProduct.maximumBytes + 1) ?? Data() + var after = stat(), named = stat() + guard fstat(descriptor, &after) == 0, before.st_dev == after.st_dev, before.st_ino == after.st_ino, + before.st_size == after.st_size, before.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec, + before.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec, + fstatat(parent, components.last!, &named, AT_SYMLINK_NOFOLLOW) == 0, + named.st_mode & S_IFMT == S_IFREG, named.st_dev == after.st_dev, named.st_ino == after.st_ino, + data.count == Int(before.st_size), CMOCProject.sha256(data) == sha256 else { + throw CMOCBuildError.message("The declared playtest disk changed after this artifact was built.") + } + return data + } + + func bankedDebugLayout() throws -> CMOCBankedDebugLayout? { + guard let path = debugManifestRelativePath else { return nil } + try CMOCProject.validateRelativePath(path) + guard let binaryRelativePath, outputPaths.contains(path) else { + throw CMOCSourceMap.Failure.invalid("the configured banked debug manifest was not produced by this build.") + } + let url = directory.resolvingSymlinksInPath().standardizedFileURL.appendingPathComponent(path) + guard url.resolvingSymlinksInPath().path == url.standardizedFileURL.path else { + throw CMOCSourceMap.Failure.invalid("banked manifest must not traverse symbolic links.") + } + let info = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) + guard info.isRegularFile == true, info.isSymbolicLink != true, (info.fileSize ?? Int.max) <= 1024 * 1024 else { + throw CMOCSourceMap.Failure.invalid("banked manifest must be a bounded regular file.") + } + let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } + let data = try handle.read(upToCount: 1024 * 1024 + 1) ?? Data() + return try CMOCBankedDebugLayout.parse(data: data, directory: directory, sources: sources, binary: binaryData, + binaryPath: binaryRelativePath, diskPath: diskRelativePath, allowedOutputs: outputPaths) + } +} + +/// A single process's merged output. The runner cannot recover separate stdout +/// and stderr after sending both descriptors to the same pipe. +struct CMOCBuildOutput: Sendable { + let text: String + let byteCount: Int + let truncated: Bool + let workingDirectory: URL + var invocation: [String] = [] + var exitCode: Int32? = nil +} + +private struct CMOCBoundedBuildLog { + static let marker = "\n[Build output truncated; beginning and end retained.]\n" + static func limit(_ text: String, maximumBytes: Int) -> (text: String, truncated: Bool) { + let bytes = Array(text.utf8) + guard bytes.count > maximumBytes else { return (text, false) } + let body = max(0, maximumBytes - marker.utf8.count) + var first = Array(bytes.prefix(body / 2)), last = Array(bytes.suffix(body - body / 2)) + // Input is valid UTF-8; only the two clipping boundaries can split a + // scalar. Remove those fragments rather than adding replacement bytes. + while !first.isEmpty && String(bytes: first, encoding: .utf8) == nil { first.removeLast() } + while !last.isEmpty && String(bytes: last, encoding: .utf8) == nil { last.removeFirst() } + return (String(decoding: first, as: UTF8.self) + marker + String(decoding: last, as: UTF8.self), true) + } +} + +/// Bounded wire formatting shared by native build failures and assistant builds. +/// Parsed source diagnostics may accompany these fields; they never replace the +/// log, since fatal linker/Make lines often have no C source-file diagnostic. +/// Retained per-build evidence. The wire preview and page API share the same +/// redacted bytes; no page reads arbitrary files or reruns a compiler. +struct CMOCBuildReport: Sendable { + struct Diagnostic: Sendable { + let path: String? + let line: Int? + let column: Int? + let severity: String + let stage: String? + let message: String + let raw: String + var fields: [String: Any] { + ["path": path as Any? ?? NSNull(), "line": line as Any? ?? NSNull(), + "column": column as Any? ?? NSNull(), "severity": severity, + "stage": stage as Any? ?? NSNull(), "message": message, "raw": raw] + } + } + let log: String + let exitCode: Int32? + let processOutputBytes: Int? + let processOutputTruncated: Bool + let failureKind: String? + let reason: String? + let invocation: [String] + let diagnostics: [Diagnostic] + let diagnosticsTruncated: Bool + let diagnosticsTotal: Int + let firstError: Diagnostic? + let failureStage: String? + let failingCommand: String? + private static let maximumRetainedLogBytes = 512 * 1024 + + init(error: Error, redacting roots: [URL] = [], visiblePaths: Set? = nil) { + var text = error.localizedDescription, code: Int32?, capture: CMOCBuildOutput? + var kind = "build_error", explanation = error.localizedDescription, stage: String? = "preparation" + if let build = error as? CMOCBuildError { + switch build { + case .failed(let status, let output, let details): + text = output; code = status; capture = details; kind = "process_exit"; stage = "make" + explanation = "Build failed (exit \(status))." + case .timedOut(let output, let details, let status): + text = output; code = status; capture = details; kind = "timeout"; stage = "make" + explanation = "The build exceeded its time limit and was stopped." + case .validation(let message, let output, let details): + text = message + (output.isEmpty ? "" : "\n" + output); capture = details + code = details?.exitCode; kind = "validation"; stage = "validation"; explanation = message + case .message(let message): text = message + } + } + self.init(text: text, capture: capture, code: code, kind: kind, reason: explanation, + fallbackStage: stage, roots: roots, visiblePaths: visiblePaths) + } + init(artifact: CMOCBuildArtifact, redacting roots: [URL] = [], visiblePaths: Set? = nil) { + self.init(text: artifact.buildLog, capture: artifact.buildOutput, code: 0, kind: nil, reason: nil, + fallbackStage: nil, roots: roots + [artifact.compilationDirectory, artifact.directory], visiblePaths: visiblePaths) + } + private init(text: String, capture: CMOCBuildOutput?, code: Int32?, kind: String?, reason: String?, + fallbackStage: String?, roots: [URL], visiblePaths: Set?) { + let allRoots = roots + [capture?.workingDirectory].compactMap { $0 } + let redacted = Self.redact(text, roots: allRoots) + let retained = CMOCBoundedBuildLog.limit(redacted, maximumBytes: Self.maximumRetainedLogBytes) + log = retained.text; exitCode = code; processOutputBytes = capture?.byteCount + processOutputTruncated = capture?.truncated == true || retained.truncated + failureKind = kind; self.reason = reason.map { Self.redact($0, roots: allRoots) } + invocation = (capture?.invocation ?? []).map { Self.redact($0, roots: allRoots) } + let parsed = Self.parseDiagnostics(log, visiblePaths: visiblePaths) + var rows = parsed.items, first = parsed.firstError + var total = parsed.total + if first == nil, let reason = self.reason, ["build_error", "validation", "timeout"].contains(kind ?? "") { + let clipped = CMOCBoundedBuildLog.limit(reason, maximumBytes: 4_096) + let diagnostic = Diagnostic(path: nil, line: nil, column: nil, severity: "error", stage: fallbackStage, + message: clipped.text, raw: clipped.text) + first = diagnostic; total += 1 + if rows.count < 256 { rows.append(diagnostic) } + } + diagnostics = rows; firstError = first; diagnosticsTotal = total + diagnosticsTruncated = parsed.truncated || processOutputTruncated || total != rows.count + failureStage = kind == nil ? nil : first?.stage ?? fallbackStage + // An echoed, recognized compiler command is evidence, but the top-level + // Make invocation is not claimed as a hidden recipe's failing command. + failingCommand = kind == nil ? nil : Self.echoedFailingCommand(log) + } + func fields(maximumLogBytes: Int = 32_000, maximumDiagnostics: Int = 64) -> [String: Any] { + let limit = min(128 * 1024, max(256, maximumLogBytes)) + let bounded = CMOCBoundedBuildLog.limit(log, maximumBytes: limit) + let boundedReason = reason.map { CMOCBoundedBuildLog.limit($0, maximumBytes: 2_048) } + var selected: [[String: Any]] = [], bytes = 0 + for item in diagnostics.prefix(max(0, min(256, maximumDiagnostics))) { + let row = item.fields + guard let encoded = try? JSONSerialization.data(withJSONObject: row), bytes + encoded.count <= 24 * 1024 else { break } + selected.append(row); bytes += encoded.count + } + return ["exit_code": exitCode.map { NSNumber(value: $0) } as Any? ?? NSNull(), + "log": bounded.text, "log_truncated": bounded.truncated || processOutputTruncated, + "log_limit_bytes": limit, "log_retained_bytes": log.utf8.count, + "log_retrievable": true, "process_output_bytes": processOutputBytes as Any? ?? NSNull(), + "process_output_truncated": processOutputTruncated, "output_streams": "combined", "stdout": NSNull(), "stderr": NSNull(), + "failure_kind": failureKind as Any? ?? NSNull(), "reason": boundedReason?.text as Any? ?? NSNull(), + "reason_truncated": boundedReason?.truncated == true, + "failure_stage": failureStage as Any? ?? NSNull(), "invocation": invocation, + "failing_command": failingCommand as Any? ?? NSNull(), + "failing_command_evidence": failingCommand == nil ? "unavailable" : "echoed_before_first_retained_error", + "diagnostics": selected, "diagnostics_total": diagnosticsTotal, + "diagnostics_truncated": diagnosticsTruncated || selected.count != diagnostics.count, + "first_error": firstError?.fields as Any? ?? NSNull(), + "first_error_scope": processOutputTruncated ? "retained_output" : "complete_output"] + } + /// Offsets count UTF-8 bytes in the retained redacted log. A client follows + /// next_offset; a caller-supplied offset inside a scalar is refused. + func logPage(offset: Int, limit: Int = 16_384) throws -> [String: Any] { + let data = Data(log.utf8) + guard offset >= 0, offset <= data.count, (1...32_768).contains(limit), + offset == data.count || data[offset] & 0xc0 != 0x80 else { throw CMOCBuildError.message("invalid_log_page") } + var end = min(data.count, offset + min(limit, data.count - offset)) + while end > offset && end < data.count && data[end] & 0xc0 == 0x80 { end -= 1 } + // At least one Unicode scalar fits, even for an unusually tiny limit. + if end == offset && offset < data.count { + end = offset + 1 + while end < data.count && data[end] & 0xc0 == 0x80 { end += 1 } + } + return ["log": String(decoding: data[offset.. String { + var paths = Set() + for root in roots { + let path = root.standardizedFileURL.path + guard path.count > 1 else { continue } + paths.insert(path) + if path.hasPrefix("/private/var/") || path.hasPrefix("/private/tmp/") { paths.insert(String(path.dropFirst(8))) } + if path.hasPrefix("/var/") || path.hasPrefix("/tmp/") { paths.insert("/private" + path) } + } + var result = text + for path in paths.sorted(by: { $0.count > $1.count }) { + let url = URL(fileURLWithPath: path).absoluteString + for spelling in [url.hasSuffix("/") ? String(url.dropLast()) : url, path] { + result = result.replacingOccurrences(of: spelling, with: "") + } + } + return result + } + private static func stage(for raw: String, file: String?) -> String? { + let lower = raw.lowercased() + if lower.contains("lwlink") || lower.contains("undefined symbol") || lower.contains("undefined reference") || + lower.hasPrefix("external symbol ") || lower.hasPrefix("local symbol ") || lower.hasPrefix("incomplete reference at ") { return "linker" } + if lower.contains("lwasm") { return "assembler" } + if lower.hasPrefix("make:") || lower.hasPrefix("make[") || file.map({ ($0 as NSString).lastPathComponent.lowercased().contains("makefile") }) == true { return "make" } + if let file { + let ext = (file as NSString).pathExtension.lowercased() + if ["s", "asm", "lwasm"].contains(ext) { return "assembler" } + if ["c", "h", "inc"].contains(ext) { return "compiler" } + } + if lower.contains("cmoc:") || lower.contains("cpp:") { return "compiler" } + return nil + } + private static let sourceDiagnostic = try! NSRegularExpression(pattern: #"^(.+?):([0-9]+)(?::([0-9]+))?:\s*(.+)$"#) + private static let assemblerDiagnostic = try! NSRegularExpression(pattern: #"^(.+)\(([0-9]+)\)\s*:\s*(.+)$"#) + private static let diagnosticSeverity = try! NSRegularExpression(pattern: #"^(?:[^:\n]+:\s*)?(fatal(?: error)?|error|warning|note)\s*:"#, options: .caseInsensitive) + private static func severity(_ message: String) -> String? { + let text = message.trimmingCharacters(in: .whitespaces), ns = text as NSString + if let match = diagnosticSeverity.firstMatch(in: text, range: NSRange(location: 0, length: ns.length)) { + let marker = ns.substring(with: match.range(at: 1)).lowercased() + return marker.hasPrefix("fatal") ? "error" : marker + } + let lower = text.lowercased() + if lower.hasPrefix("***") || ((lower.hasPrefix("make:") || lower.hasPrefix("make[")) && lower.contains("***")) || + lower.hasPrefix("undefined symbol") || lower.hasPrefix("undefined reference") || + ((lower.hasPrefix("external symbol ") || lower.hasPrefix("local symbol ")) && lower.contains(" not found")) || + lower.hasPrefix("incomplete reference at ") || lower.hasPrefix("can't open file ") || lower.hasPrefix("cannot open output file ") { return "error" } + return nil + } + private static func parseDiagnostics(_ text: String, visiblePaths: Set?) -> (items: [Diagnostic], firstError: Diagnostic?, total: Int, truncated: Bool) { + var rows: [Diagnostic] = [], firstError: Diagnostic?, total = 0, truncated = false, retainedBytes = 0 + for rawLine in text.components(separatedBy: .newlines) where !rawLine.isEmpty { + // Make echoes these commands before their output. A quoted sample + // such as printf 'main.c:2: error: ...' is not a compiler diagnostic. + let trimmed = rawLine.trimmingCharacters(in: .whitespaces) + if trimmed.hasPrefix("printf ") || trimmed.hasPrefix("echo ") { continue } + let ns = rawLine as NSString + var file: String?, number: Int?, column: Int?, message = rawLine + if let match = sourceDiagnostic.firstMatch(in: rawLine, range: NSRange(location: 0, length: ns.length)) { + file = ns.substring(with: match.range(at: 1)); number = Int(ns.substring(with: match.range(at: 2))) + if match.range(at: 3).location != NSNotFound { column = Int(ns.substring(with: match.range(at: 3))) } + message = ns.substring(with: match.range(at: 4)) + } else if let match = assemblerDiagnostic.firstMatch(in: rawLine, range: NSRange(location: 0, length: ns.length)) { + file = ns.substring(with: match.range(at: 1)); number = Int(ns.substring(with: match.range(at: 2))) + message = ns.substring(with: match.range(at: 3)) + } + guard let severity = severity(message) else { continue } + total += 1 + let resolved: String? + if let file, let visiblePaths { + resolved = visiblePaths.sorted().first { file == $0 || file.hasSuffix("/" + $0) } + } else if let file, !file.hasPrefix("/"), !file.hasPrefix("file:"), !file.hasPrefix("/") { resolved = file.hasPrefix("./") ? String(file.dropFirst(2)) : file } + else { resolved = nil } + let stage = stage(for: rawLine, file: file) + let clippedRaw = CMOCBoundedBuildLog.limit(rawLine, maximumBytes: 4_096) + let clippedMessage = CMOCBoundedBuildLog.limit(message, maximumBytes: 4_096) + let bytes = clippedRaw.text.utf8.count + clippedMessage.text.utf8.count + let diagnostic = Diagnostic(path: resolved, line: number, column: column, severity: severity, stage: stage, + message: clippedMessage.text, raw: clippedRaw.text) + if severity == "error", firstError == nil { firstError = diagnostic } + guard rows.count < 256, retainedBytes + bytes <= 128 * 1024 else { truncated = true; continue } + rows.append(diagnostic) + retainedBytes += bytes; truncated = truncated || clippedRaw.truncated || clippedMessage.truncated + } + return (rows, firstError, total, truncated) + } + private static func echoedFailingCommand(_ text: String) -> String? { + var lastCommand: String? + for line in text.components(separatedBy: .newlines) { + let trimmed = line.trimmingCharacters(in: .whitespaces) + if trimmed.range(of: #"^(?:(?:[^\s]+/)?(?:cmoc|cpp|lwasm|lwlink))\s+"#, options: .regularExpression) != nil { + lastCommand = CMOCBoundedBuildLog.limit(trimmed, maximumBytes: 2_048).text + } + if parseDiagnostics(line, visiblePaths: []).firstError != nil { return lastCommand } + } + return nil + } +} + +enum CMOCBuildFailureReport { + static func fields(for error: Error, redacting roots: [URL] = [], maximumLogBytes: Int = 32_000) -> [String: Any] { + CMOCBuildReport(error: error, redacting: roots).fields(maximumLogBytes: maximumLogBytes) + } +} + +enum CMOCBuildError: LocalizedError { + case message(String) + case failed(status: Int32, log: String, capture: CMOCBuildOutput? = nil) + case timedOut(log: String, capture: CMOCBuildOutput? = nil, exitCode: Int32? = nil) + case validation(message: String, log: String, capture: CMOCBuildOutput? = nil) + var errorDescription: String? { + switch self { + case .message(let value): return value + case .validation(let message, let log, _): return message + (log.isEmpty ? "" : "\n" + log) + case .failed(let status, let log, _): return "Build failed (exit \(status)).\n\(log)" + case .timedOut(let log, _, _): return "The build exceeded its time limit and was stopped.\n\(log)" + } + } +} + +/// All compiler I/O occurs off the main actor. Builds consume an immutable editor +/// snapshot, never mutate the source project, and never load the emulator. +final class CMOCBuildService: @unchecked Sendable { + static let requiredExecutables = ["cmoc", "make", "cpp", "lwasm", "lwlink"] + let toolchain: URL + let buildRoot: URL + private let buildHistory: CMOCBuildHistory + private let lock = NSLock() + private var active: DevelopmentProcessControl? + private let timeout: TimeInterval + private var incrementalRoot: URL? + + init(toolchain: URL, buildRoot: URL = FileManager.default.temporaryDirectory.appendingPathComponent("VCCPlus-OSS-CMOC-Builds"), timeout: TimeInterval = 120) { + self.toolchain = toolchain.standardizedFileURL + self.buildRoot = buildRoot.standardizedFileURL + self.buildHistory = CMOCBuildHistory(root: buildRoot) + self.timeout = timeout + } + + deinit { + if let incrementalRoot { try? FileManager.default.removeItem(at: incrementalRoot) } + } + + /// CMOC dependency files contain unescaped absolute source paths. Keep the + /// compiler's physical working path Make-safe even when a project/results + /// directory contains spaces. Each service owns a separate cache namespace, + /// so concurrent app instances cannot mutate one another's build workspace. + private func incrementalWorkspaceRoot() throws -> URL { + if let incrementalRoot { return incrementalRoot } + let root: URL + if buildRoot.path.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || "_./-".contains($0)) }) { + root = buildRoot.appendingPathComponent(".workspaces").appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) + } else { + var template = Array("/private/tmp/vccplus-cmoc-\(getuid())-XXXXXX".utf8CString) + guard let result = mkdtemp(&template) else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + root = URL(fileURLWithPath: String(cString: result), isDirectory: true) + } + incrementalRoot = root + return root + } + + /// Dependency files are Make programs, not a format we can safely repair. + /// Rebuild this disposable cache when generated dependencies escape its + /// captured inputs. Authored dependency inputs are deliberately excluded. + private static func dependencyCacheInvalidation(files: [String: Data], inputs: Set, allowedRoots: [URL]) -> String? { + var roots = Set() + for root in allowedRoots { + for url in [root.standardizedFileURL, root.resolvingSymlinksInPath().standardizedFileURL] { + let path = url.path + roots.insert(path) + if path.hasPrefix("/private/var/") || path.hasPrefix("/private/tmp/") { roots.insert(String(path.dropFirst(8))) } + if path.hasPrefix("/var/") || path.hasPrefix("/tmp/") { roots.insert("/private" + path) } + } + } + var inspected = 0 + for (path, data) in files where !inputs.contains(path) && (path as NSString).pathExtension.lowercased() == "d" { + inspected += data.count + guard data.count <= 4 * 1024 * 1024, inspected <= 16 * 1024 * 1024, + let text = String(data: data, encoding: .utf8), !text.contains("\0"), + !text.contains("$"), !text.contains("`"), !text.contains("\""), !text.contains("'") else { + return "generated dependency syntax cannot be reused safely" + } + var tokens: [String] = [], token = "", escaped = false, comment = false + for character in text { + if comment { + if character == "\n" { comment = false } + continue + } + if escaped { + // Make continuations join lines; other escapes quote a + // filename character (including whitespace, # and colon). + if character != "\n" && character != "\r" { token.append(character) } + escaped = false + } else if character == "\\" { + escaped = true + } else if character == "#" { + if !token.isEmpty { tokens.append(token); token = "" } + comment = true + } else if character.isWhitespace || character == ":" { + if !token.isEmpty { tokens.append(token); token = "" } + } else { token.append(character) } + } + if escaped { return "generated dependency syntax cannot be reused safely" } + if !token.isEmpty { tokens.append(token) } + for token in tokens where token.hasPrefix("/") { + let dependency = URL(fileURLWithPath: token).standardizedFileURL.path + guard roots.contains(where: { dependency == $0 || dependency.hasPrefix($0 + "/") }) else { + return "generated dependencies refer outside the captured workspace" + } + guard FileManager.default.fileExists(atPath: dependency) else { + return "a generated absolute dependency is no longer available" + } + } + } + return nil + } + + func history(project: URL, protectedIDs: Set = []) throws -> [CMOCBuildHistory.Entry] { + try buildHistory.entries(project: project, protectedIDs: protectedIDs) + } + func removeBuilds(ids: Set, project: URL, protectedIDs: Set) throws -> CMOCBuildHistory.Removal { + lock.lock(); defer { lock.unlock() } + guard active == nil else { throw CMOCBuildError.message("Wait for the current build to finish before cleaning up.") } + return try buildHistory.remove(ids: ids, project: project, protectedIDs: protectedIDs) + } + func cancel() { lock.lock(); let control = active; lock.unlock(); control?.cancel() } + + private func begin(_ control: DevelopmentProcessControl) throws { + lock.lock(); defer { lock.unlock() } + guard active == nil else { throw CMOCBuildError.message("A build is already running.") } + active = control + } + private func end(_ control: DevelopmentProcessControl) { + lock.lock(); defer { lock.unlock() } + if active === control { active = nil } + } + + func build(project: CMOCProject, source: String) async throws -> CMOCBuildArtifact { + let control = DevelopmentProcessControl() + try begin(control) + defer { end(control) } + return try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + DispatchQueue.global(qos: .userInitiated).async { [self] in + do { continuation.resume(returning: try buildSynchronously(project: project, source: source, control: control)) } + catch { continuation.resume(throwing: error) } + } + } + } onCancel: { control.cancel() } + } + + /// Multi-file entry point. Each project/configuration has an incremental cache; + /// each successful invocation returns a separate immutable build snapshot. + func build(project: CMOCProject, overlays: [String: String], action: CMOCBuildAction = .build, + configuration: String? = nil, target: String? = nil) async throws -> CMOCBuildArtifact { + let control = DevelopmentProcessControl() + try begin(control); defer { end(control) } + return try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + DispatchQueue.global(qos: .userInitiated).async { [self] in + do { continuation.resume(returning: try buildProjectSynchronously(project: project, overlays: overlays, action: action, + configurationName: configuration, target: target, control: control)) } + catch { continuation.resume(throwing: error) } + } + } + } onCancel: { control.cancel() } + } + + private func buildProjectSynchronously(project: CMOCProject, overlays: [String: String], action: CMOCBuildAction, + configurationName: String?, target: String?, control: DevelopmentProcessControl) throws -> CMOCBuildArtifact { + try control.checkCancellation() + let manager = FileManager.default + let capturedInputs = try CMOCProjectInputManifest.capture(project: project, overlays: overlays) + let inputs = capturedInputs.files, settings = capturedInputs.configuration + var supportProject = project + supportProject.configuration = settings + let support = capturedInputs.support + guard inputs.count + support.files.count <= 20_000, + inputs.values.reduce(0, { $0 + $1.count }) + support.files.values.reduce(0, { $0 + $1.count }) <= CMOCProject.maximumProjectBytes else { + throw CMOCBuildError.message("Project and build-support files exceed the 512 MB snapshot limit.") + } + guard !inputs.keys.contains(where: { $0 == CMOCBundledLibrary.stagingDirectory || $0.hasPrefix(CMOCBundledLibrary.stagingDirectory + "/") }) else { + throw CMOCBuildError.message(".vccplus-libraries is reserved for isolated bundled-library copies. Move project files outside that directory.") + } + guard let entry = inputs[settings.entrySource], let entryText = String(data: entry, encoding: .utf8), !entry.contains(0), + let makefile = inputs[settings.makefile], let makefileText = String(data: makefile, encoding: .utf8), !makefileText.contains("\0") else { + throw CMOCBuildError.message("The project needs readable UTF-8 entry source and Makefile files.") + } + let name = configurationName ?? settings.configurations[0].name + guard let configuration = settings.configurations.first(where: { $0.name == name }) else { + throw CMOCBuildError.message("Unknown build configuration: \(name)") + } + let chosenTarget: String + switch action { + case .build, .rebuild: chosenTarget = target ?? settings.buildTarget + case .clean: chosenTarget = settings.cleanTarget + case .disk: + guard let diskTarget = target ?? settings.diskTarget else { throw CMOCBuildError.message("Set diskTarget in vccplus-project.json before building a disk.") } + chosenTarget = diskTarget + case .custom: + guard let target else { throw CMOCBuildError.message("Enter a Make target.") } + chosenTarget = target + } + if !chosenTarget.isEmpty || (action != .build && action != .rebuild) { + try CMOCProjectConfiguration.validateTarget(chosenTarget) + } + let bin = toolchain.appendingPathComponent("bin") + for name in Self.requiredExecutables { + guard manager.isExecutableFile(atPath: bin.appendingPathComponent(name).path) else { + throw CMOCBuildError.message("The development toolchain is unavailable (missing \(name)). This build needs the bundled CMOC tools.") + } + } + let manifest = (try? Data(contentsOf: toolchain.appendingPathComponent("manifest.json"))) ?? Data() + let libraryEncoder = JSONEncoder(); libraryEncoder.outputFormatting = [.sortedKeys] + let libraryKey = CMOCProject.sha256(try libraryEncoder.encode(settings.bundledLibraries)) + var supportIdentity = support.hashes + supportIdentity["@directories"] = settings.buildSupportDirectories.joined(separator: "\n") + let supportKey = CMOCProject.sha256(try libraryEncoder.encode(supportIdentity)) + // A newly reviewed media declaration cannot inherit an incidental old + // image from an earlier cache. Empty declarations retain legacy keys. + let playtestMediaKey = settings.playtestDisks.isEmpty ? "" : + "\nplaytest-disks:" + CMOCProject.sha256(try libraryEncoder.encode(settings.playtestDisks)) + let cacheKey = CMOCProject.sha256(Data((project.directory.resolvingSymlinksInPath().path + "\n" + name + "\n" + + configuration.makeArguments.joined(separator: "\n") + "\n" + libraryKey + "\n" + supportKey + "\n" + toolchain.path + "\n" + CMOCProject.sha256(manifest) + playtestMediaKey).utf8)) + let cache = try incrementalWorkspaceRoot().appendingPathComponent(cacheKey) + let workspace = cache.appendingPathComponent("project") + let indexURL = cache.appendingPathComponent("inputs.json") + try manager.createDirectory(at: workspace, withIntermediateDirectories: true) + // Do not preserve a possibly partially written object from a failed/cancelled build. + var succeeded = false + defer { if !succeeded { try? manager.removeItem(at: cache) } } + let decodedInputs = (try? Data(contentsOf: indexURL)).flatMap { try? JSONDecoder().decode([String: String].self, from: $0) } + let recordedInputs = decodedInputs.flatMap { values -> [String: String]? in + guard values.allSatisfy({ path, hash in + (try? CMOCProject.validateRelativePath(path)) != nil && hash.utf8.count == 64 && + hash.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) } + }) else { return nil } + return values + } + var previous = recordedInputs ?? [:] + // Validate the old workspace before discarding anything; a recipe's + // symlink must not redirect input synchronization or cache cleanup. + let cachedFiles = try CMOCProject.files(in: workspace) + var cacheResetReason: String? + if !cachedFiles.isEmpty && (recordedInputs == nil || previous.isEmpty) { + cacheResetReason = "the previous input receipt is missing or invalid" + } else if previous.keys.contains(where: { inputs[$0] == nil }) { + cacheResetReason = "a previously captured input was removed" + } else { + cacheResetReason = Self.dependencyCacheInvalidation(files: cachedFiles, inputs: Set(inputs.keys), allowedRoots: [cache, toolchain]) + } + if cacheResetReason != nil { + // The cache is an app-owned working copy. Never rewrite arbitrary + // Make dependencies or execute a user's clean target to repair it. + try manager.removeItem(at: cache) + try manager.createDirectory(at: workspace, withIntermediateDirectories: true) + previous = [:] + } + for path in previous.keys where inputs[path] == nil { + let url = workspace.appendingPathComponent(path) + if manager.fileExists(atPath: url.path) { try manager.removeItem(at: url) } + } + for (path, data) in inputs { + try control.checkCancellation() + let url = workspace.appendingPathComponent(path) + try manager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + if (try? Data(contentsOf: url)) != data { + try data.write(to: url, options: .atomic) + } + // Shell helpers retain their executable bit; generated products are not copied back. + if let mode = capturedInputs.permissions[path] { + var copiedAttributes: [FileAttributeKey: Any] = [.posixPermissions: mode & 0o777] + // On the initial copy preserve source timestamp ordering for + // custom generated-resource rules. Later content changes always + // receive a fresh mtime so Make cannot miss an edited input. + if previous.isEmpty, !capturedInputs.overlayPaths.contains(path), let date = capturedInputs.modificationDates[path] { + copiedAttributes[.modificationDate] = date + } + try manager.setAttributes(copiedAttributes, ofItemAtPath: url.path) + } + } + // A declared ../tools remains a sibling inside this cache. Never copy + // the project's parent or allow a previous recipe's links to redirect it. + for relative in settings.buildSupportDirectories { + let root = workspace.appendingPathComponent(relative, isDirectory: true).standardizedFileURL + if manager.fileExists(atPath: root.path) { + let info = try root.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey]) + guard info.isSymbolicLink != true, info.isDirectory == true else { + throw CMOCBuildError.message("The isolated build-support folder is invalid: \(relative)") + } + _ = try CMOCProject.files(in: root) + try manager.removeItem(at: root) + } + try manager.createDirectory(at: root, withIntermediateDirectories: true) + } + for (path, data) in support.files { + try control.checkCancellation() + let url = workspace.appendingPathComponent(path).standardizedFileURL + try manager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: url, options: .atomic) + try manager.setAttributes([.posixPermissions: support.permissions[path] ?? 0o644], ofItemAtPath: url.path) + if let date = try manager.attributesOfItem(atPath: project.directory.appendingPathComponent(path).path)[.modificationDate] { + try manager.setAttributes([.modificationDate: date], ofItemAtPath: url.path) + } + } + let libraryPayload = try CMOCBundledLibrary.stage(settings.bundledLibraries, runtime: toolchain, workspace: workspace) + var environment = ProcessInfo.processInfo.environment + environment["PATH"] = bin.path + ":/usr/bin:/bin" + environment["CMOC"] = "cmoc" + environment["VCC_TOOLCHAIN"] = toolchain.path + environment["LC_ALL"] = "C" + for key in ["MAKEFLAGS", "MFLAGS", "MAKELEVEL", "GNUMAKEFLAGS", "PERL5LIB", "PERLLIB", "PERL5OPT"] { environment.removeValue(forKey: key) } + var log = cacheResetReason.map { "Rebuilding isolated cache: \($0).\n" } ?? "" + var combinedOutput: CMOCBuildOutput? + func appendOutput(_ capture: CMOCBuildOutput) { + let retained = CMOCBoundedBuildLog.limit(log + capture.text, maximumBytes: 512 * 1024) + log = retained.text + combinedOutput = CMOCBuildOutput(text: log, byteCount: (combinedOutput?.byteCount ?? 0) + capture.byteCount, + truncated: combinedOutput?.truncated == true || capture.truncated || retained.truncated, + workingDirectory: capture.workingDirectory, invocation: capture.invocation, exitCode: capture.exitCode) + } + func invoke(_ target: String) throws { + try control.checkCancellation(log: log) + let args = ["--no-print-directory", "-f", settings.makefile, "-j\(settings.jobs)", "--output-sync=target"] + + (settings.bundledLibraries.isEmpty ? [] : ["-f", CMOCBundledLibrary.stagingDirectory + "/bindings.mk"]) + + settings.bundledLibraries.filter { !$0.directoryVariable.isEmpty }.map { + // Command-line variables are visible when Make expands prerequisites + // and propagate to recursive Make; a later include is too late. + $0.directoryVariable + "=" + workspace.appendingPathComponent(CMOCBundledLibrary.stagingDirectory).appendingPathComponent($0.library).path + } + configuration.makeArguments + ["MAKE=make", "--"] + (target.isEmpty ? [] : [target]) + let output: (status: Int32, text: String) + do { + output = try control.run(executable: bin.appendingPathComponent("make"), arguments: args, directory: workspace, + environment: environment, timeout: timeout) + } catch CMOCBuildError.timedOut(let text, let capture, let status) { + if let capture { appendOutput(capture) } + else { log = CMOCBoundedBuildLog.limit(log + text, maximumBytes: 512 * 1024).text } + throw CMOCBuildError.timedOut(log: log, capture: combinedOutput, exitCode: status) + } + if let capture = control.capturedOutput { appendOutput(capture) } + else { log = CMOCBoundedBuildLog.limit(log + output.text, maximumBytes: 512 * 1024).text } + guard output.status == 0 else { throw CMOCBuildError.failed(status: output.status, log: log, capture: combinedOutput) } + } + if action == .rebuild { try invoke(settings.cleanTarget) } + try invoke(chosenTarget) + let products = try CMOCProject.files(in: workspace) + let builtSupport = try CMOCProject(directory: workspace, configuration: settings).supportSnapshot() + guard builtSupport == support else { + throw CMOCBuildError.validation(message: "The build modified its build-support files; source and recipe identity no longer match.", log: log, capture: combinedOutput) + } + guard try supportProject.supportSnapshot() == support else { + throw CMOCBuildError.validation(message: "Build-support files changed during the build. Rebuild the current project before running.", log: log, capture: combinedOutput) + } + for (path, bytes) in libraryPayload where products[path] != bytes { + throw CMOCBuildError.validation(message: "The build modified a bundled-library copy: \(path). Bundled libraries are prebuilt; keep library rebuild rules separate.", log: log, capture: combinedOutput) + } + for (path, data) in inputs { + guard products[path] == data else { + throw CMOCBuildError.validation(message: "The build modified \(path); its editor and source locations no longer match. Generate derived files under a separate name.", log: log, capture: combinedOutput) + } + } + // Custom targets can be utilities. Only normal/disk builds promise declared products. + let requiresProducts = action == .build || action == .rebuild || action == .disk + var binaryPath: String?, diskPath: String? + var playtestDiskProducts: [CMOCPlaytestDiskProduct] = [] + if action != .clean && action != .custom { + if let path = settings.binary, let data = products[path], !data.isEmpty { binaryPath = path } + else if requiresProducts && settings.binary != nil { throw CMOCBuildError.validation(message: "Make succeeded but did not produce \(settings.binary!). Set Binary output in Project Settings to the executable created by this Makefile, or leave it empty for a build-only project.", log: log, capture: combinedOutput) } + if let path = settings.diskImage, let data = products[path], !data.isEmpty { diskPath = path } + else if action == .disk || (requiresProducts && settings.launchMode == .disk) { + throw CMOCBuildError.validation(message: "Make succeeded but did not produce the configured disk image.", log: log, capture: combinedOutput) + } + } + if requiresProducts { + for path in settings.playtestDisks { + guard let data = products[path], (1...CMOCPlaytestDiskProduct.maximumBytes).contains(data.count) else { + throw CMOCBuildError.validation(message: "Make succeeded but did not produce the declared playtest disk \(path) as a nonempty output of at most 512 KiB.", log: log, capture: combinedOutput) + } + playtestDiskProducts.append(CMOCPlaytestDiskProduct(relativePath: path, + sha256: CMOCProject.sha256(data), byteCount: data.count)) + } + } + try control.checkCancellation(log: log) + let id = UUID() + let result = buildRoot.appendingPathComponent(id.uuidString) + try manager.createDirectory(at: result, withIntermediateDirectories: true) + var frozen = false + defer { if !frozen { try? manager.removeItem(at: result) } } + for (path, data) in products { + try control.checkCancellation(log: log) + let url = result.appendingPathComponent(path) + try manager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: url, options: .atomic) + } + let projectHashes = inputs.mapValues(CMOCProject.sha256) + let hashes = projectHashes.merging(support.hashes) { first, _ in first } + try JSONEncoder().encode(projectHashes).write(to: indexURL, options: .atomic) + let physicalResult = try CMOCProject.physicalURL(result), physicalWorkspace = try CMOCProject.physicalURL(workspace) + let sources = products.filter { CMOCProject.isSource($0.key) && String(data: $0.value, encoding: .utf8) != nil && !$0.value.contains(0) } + let artifact = CMOCBuildArtifact(id: id, directory: physicalResult, source: entryText, sourceData: entry, + sourceSHA256: CMOCProject.sha256(entry), binaryData: binaryPath.flatMap { products[$0] } ?? Data(), buildLog: log, + sources: sources, fileHashes: hashes, compilationDirectory: physicalWorkspace, entrySourcePath: settings.entrySource, + binaryRelativePath: binaryPath, diskRelativePath: diskPath, outputPaths: products.keys.sorted(), configurationName: name, action: action, + debugManifestRelativePath: settings.debugManifest, + diskSHA256: diskPath.flatMap { products[$0] }.map(CMOCProject.sha256), buildOutput: combinedOutput, + playtestDiskProducts: playtestDiskProducts) + try buildHistory.record(artifact, project: project.directory) + frozen = true; succeeded = true + return artifact + } + + private func buildSynchronously(project: CMOCProject, source: String, control: DevelopmentProcessControl) throws -> CMOCBuildArtifact { + let sourceData = try CMOCProject.sourceBytes(source) + let makefile = try CMOCProject.readText(project.makefileURL, maximumBytes: CMOCProject.maximumMakefileBytes) + let bin = toolchain.appendingPathComponent("bin") + for name in Self.requiredExecutables { + guard FileManager.default.isExecutableFile(atPath: bin.appendingPathComponent(name).path) else { + throw CMOCBuildError.message("The development toolchain is unavailable (missing \(name)). This build needs the bundled CMOC tools.") + } + } + try control.checkCancellation() + let id = UUID() + let directory = buildRoot.appendingPathComponent(id.uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + var succeeded = false + defer { if !succeeded { try? FileManager.default.removeItem(at: directory) } } + try sourceData.write(to: directory.appendingPathComponent("main.c"), options: .atomic) + try Data(makefile.utf8).write(to: directory.appendingPathComponent("Makefile"), options: .atomic) + var environment = ProcessInfo.processInfo.environment + // Deliberately exclude Homebrew and developer-tool paths from runtime lookup. + environment["PATH"] = bin.path + ":/usr/bin:/bin" + environment["CMOC"] = bin.appendingPathComponent("cmoc").path + environment["LC_ALL"] = "C" + environment.removeValue(forKey: "MAKEFLAGS") + environment.removeValue(forKey: "MFLAGS") + environment.removeValue(forKey: "MAKELEVEL") + for key in ["GNUMAKEFLAGS", "PERL5LIB", "PERLLIB", "PERL5OPT"] { environment.removeValue(forKey: key) } + let output = try control.run(executable: bin.appendingPathComponent("make"), arguments: ["--no-print-directory", "-f", "Makefile", "MAKE=make", "--"] + (project.configuration.buildTarget.isEmpty ? [] : [project.configuration.buildTarget]), directory: directory, environment: environment, timeout: timeout) + try control.checkCancellation(log: output.text) + guard output.status == 0 else { throw CMOCBuildError.failed(status: output.status, log: output.text, capture: control.capturedOutput) } + // A successful Makefile must produce all matching artifacts, not reuse an + // old executable. The fresh directory prevents stale-build fallback. + for name in ["main.bin", "main.o", "main.s", "main.lst", "main.map", "main.link"] { + let url = directory.appendingPathComponent(name) + let info = try? url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) + guard info?.isRegularFile == true, info?.isSymbolicLink != true, + let size = info?.fileSize, size > 0, size <= 8 * 1024 * 1024 else { + throw CMOCBuildError.validation(message: "The build did not produce a valid \(name). Keep --intermediate enabled in the Makefile.", log: output.text, capture: control.capturedOutput) + } + } + // Protect mapping from a Makefile which rewrites its input before compiling. + guard try Data(contentsOf: directory.appendingPathComponent("main.c")) == sourceData else { + throw CMOCBuildError.validation(message: "The build modified main.c; its source locations cannot be verified.", log: output.text, capture: control.capturedOutput) + } + let binary = try Data(contentsOf: directory.appendingPathComponent("main.bin")) + // mcpp records the physical working directory (for example /private/tmp, + // not its /tmp symlink). Keep the exact snapshot identity for source maps. + guard let physicalPath = realpath(directory.path, nil) else { + throw CMOCBuildError.validation(message: "The build output folder could not be resolved.", log: output.text, capture: control.capturedOutput) + } + let physicalDirectory = URL(fileURLWithPath: String(cString: physicalPath), isDirectory: true) + free(physicalPath) + let artifact = CMOCBuildArtifact(id: id, directory: physicalDirectory, source: source, + sourceData: sourceData, sourceSHA256: CMOCProject.sha256(sourceData), binaryData: binary, buildLog: output.text, buildOutput: control.capturedOutput) + try control.checkCancellation() + try buildHistory.record(artifact, project: project.directory) + succeeded = true + return artifact + } +} + +/// A separate process group lets cancellation stop make and its compiler children. +/// One pipe merges stdout/stderr; draining continues even after the retained log +/// reaches its cap, so compiler output cannot deadlock a full pipe. +final class DevelopmentProcessControl: @unchecked Sendable { + private let lock = NSLock() + private var pid: pid_t = 0 + private var cancelled = false + private var timedOut = false + private static let maximumOutput = 512 * 1024 + private var lastOutput: CMOCBuildOutput? + var capturedOutput: CMOCBuildOutput? { + lock.lock(); defer { lock.unlock() } + return lastOutput + } + + func cancel(timedOut: Bool = false) { + lock.lock() + if timedOut && pid == 0 { lock.unlock(); return } + cancelled = true; self.timedOut = self.timedOut || timedOut + let current = pid + if current > 0 { Darwin.kill(-current, SIGTERM) } + lock.unlock() + if current > 0 { + DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) { [weak self] in + guard let self else { return } + self.lock.lock(); defer { self.lock.unlock() } + if self.pid == current { Darwin.kill(-current, SIGKILL) } + } + } + } + + func checkCancellation(log: String = "", capture: CMOCBuildOutput? = nil, exitCode: Int32? = nil) throws { + lock.lock(); let stop = cancelled, expired = timedOut; lock.unlock() + if expired { throw CMOCBuildError.timedOut(log: log, capture: capture, exitCode: exitCode) } + if stop { throw CancellationError() } + } + + func run(executable: URL, arguments: [String], directory: URL, environment: [String: String], timeout: TimeInterval) throws -> (status: Int32, text: String) { + try checkCancellation() + var descriptors: [Int32] = [0, 0] + guard pipe(&descriptors) == 0 else { throw POSIXError(.EIO) } + var reader = descriptors[0], writer = descriptors[1] + defer { if reader >= 0 { close(reader) }; if writer >= 0 { close(writer) } } + var actions: posix_spawn_file_actions_t? + var attributes: posix_spawnattr_t? + guard posix_spawn_file_actions_init(&actions) == 0 else { throw POSIXError(.ENOMEM) } + defer { posix_spawn_file_actions_destroy(&actions) } + guard posix_spawnattr_init(&attributes) == 0 else { throw POSIXError(.ENOMEM) } + defer { posix_spawnattr_destroy(&attributes) } + posix_spawn_file_actions_adddup2(&actions, writer, STDOUT_FILENO) + posix_spawn_file_actions_adddup2(&actions, writer, STDERR_FILENO) + posix_spawn_file_actions_addclose(&actions, reader) + posix_spawn_file_actions_addclose(&actions, writer) + posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0) + let changeDirectory: Int32 + if #available(macOS 26.0, *) { + changeDirectory = posix_spawn_file_actions_addchdir(&actions, directory.path) + } else { + changeDirectory = posix_spawn_file_actions_addchdir_np(&actions, directory.path) + } + guard changeDirectory == 0 else { throw POSIXError(POSIXErrorCode(rawValue: changeDirectory) ?? .EINVAL) } + posix_spawnattr_setflags(&attributes, Int16(POSIX_SPAWN_SETPGROUP)) + posix_spawnattr_setpgroup(&attributes, 0) + let argv = ([executable.path] + arguments).map { strdup($0) } + [nil] + let envp = environment.sorted(by: { $0.key < $1.key }).map { strdup($0.key + "=" + $0.value) } + [nil] + defer { argv.forEach { free($0) }; envp.forEach { free($0) } } + var child: pid_t = 0 + lock.lock() + if cancelled { lock.unlock(); try checkCancellation(); throw CancellationError() } + let result = argv.withUnsafeBufferPointer { a in envp.withUnsafeBufferPointer { e in + posix_spawn(&child, executable.path, &actions, &attributes, a.baseAddress!, e.baseAddress!) + } } + if result == 0 { pid = child } + lock.unlock() + guard result == 0 else { throw POSIXError(POSIXErrorCode(rawValue: result) ?? .EIO) } + close(writer); writer = -1 + let deadline = DispatchWorkItem { [weak self] in self?.cancel(timedOut: true) } + DispatchQueue.global().asyncAfter(deadline: .now() + timeout, execute: deadline) + defer { deadline.cancel() } + var beginning = Data(), ending = Data(), total = 0 + let firstLimit = Self.maximumOutput / 2, lastLimit = Self.maximumOutput - firstLimit + var buffer = [UInt8](repeating: 0, count: 8192) + while true { + let count = Darwin.read(reader, &buffer, buffer.count) + if count == 0 { break } + if count < 0 { if errno == EINTR { continue }; break } + total += count + let keep = min(count, max(0, firstLimit - beginning.count)) + if keep > 0 { beginning.append(contentsOf: buffer.prefix(keep)) } + if count > keep { + ending.append(contentsOf: buffer[keep.. lastLimit { ending = Data(ending.suffix(lastLimit)) } + } + } + close(reader); reader = -1 + var status: Int32 = 0 + while waitpid(child, &status, 0) < 0 { if errno != EINTR { break } } + lock.lock(); pid = 0; lock.unlock() + let clipped = total > beginning.count + ending.count + let text: String + if clipped { + text = String(decoding: beginning, as: UTF8.self) + + "\n[Build output truncated at 512 KB; \(total - beginning.count - ending.count) process bytes omitted between beginning and end.]\n" + + String(decoding: ending, as: UTF8.self) + } else { + // The retention split may be in the middle of a UTF-8 scalar. + // Decode contiguous, untruncated output as one byte sequence. + text = String(decoding: beginning + ending, as: UTF8.self) + } + // Invalid process bytes can expand while decoding. Bound the rendered + // UTF-8 as well, and keep the late linker/Make failure visible. + let bounded = CMOCBoundedBuildLog.limit(text, maximumBytes: Self.maximumOutput) + let capture = CMOCBuildOutput(text: bounded.text, byteCount: total, truncated: clipped || bounded.truncated, + workingDirectory: directory, invocation: [executable.path] + arguments, + exitCode: status & 0x7f == 0 ? (status >> 8) & 0xff : 128 + (status & 0x7f)) + lock.lock(); lastOutput = capture; lock.unlock() + // POSIX exit status encoding, including a recognizable signal failure. + let exitStatus = capture.exitCode! + try checkCancellation(log: capture.text, capture: capture, exitCode: exitStatus) + return (exitStatus, capture.text) + } +} diff --git a/platforms/macos/App/CMOCCallStack.swift b/platforms/macos/App/CMOCCallStack.swift new file mode 100644 index 0000000..e062f7e --- /dev/null +++ b/platforms/macos/App/CMOCCallStack.swift @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// Conservative unwinding of CMOC's unoptimized, preserved-U calling convention. +/// Never scans arbitrary stack words for plausible code addresses. An unknown +/// boundary ends the chain instead of silently skipping an intervening frame. +struct CMOCCallStack: Sendable { + struct Frame: Identifiable, Sendable { + let id: Int + let functionName: String + let sourcePath: String + let sourceLine: Int? + /// Current PC for frame zero; the actual calling instruction for callers. + let pc: UInt16 + let u: UInt16 + let localsInspectable: Bool + } + let frames: [Frame] + /// Why the verified chain ended. This is not necessarily the program root. + let termination: String + + static func capture(metadata: CMOCVariableDebug, pc: UInt16, u: UInt16, s: UInt16, + memory: Data, available: Data, maximumFrames: Int = 64) -> Self { + guard memory.count == 65536, available.count == 65536 else { + return Self(frames: [], termination: "A complete paused memory snapshot is required.") + } + guard metadata.sourceMap.verifiesRuntime(memory: memory, available: available) else { + return Self(frames: [], termination: "Executable bytes changed or became unavailable; reconnect the build before inspecting its call stack.") + } + func readable(_ start: Int, _ count: Int) -> Bool { + start >= 0 && count >= 0 && start <= 0xfe00 - count && + available[start..<(start + count)].allSatisfy { $0 != 0 } + } + var verifiedBytes: [Int: UInt8] = [:] + for instruction in metadata.sourceMap.instructions { + let at = Int(instruction.address) + guard readable(at, instruction.bytes.count), + Array(memory[at..<(at + instruction.bytes.count)]) == instruction.bytes else { + return Self(frames: [], termination: "Executable bytes changed or became unavailable; reconnect the build before inspecting its call stack.") + } + for (offset, byte) in instruction.bytes.enumerated() { verifiedBytes[at + offset] = byte } + } + func bytes(_ at: Int, _ expected: [UInt8]) -> Bool { + readable(at, expected.count) && expected.enumerated().allSatisfy { verifiedBytes[at + $0.offset] == $0.element } + } + func word(_ at: Int) -> Int { Int(memory[at]) * 256 + Int(memory[at + 1]) } + func function(at address: Int) -> CMOCVariableDebug.Function? { + let matches = metadata.functions.filter { + let epilogueSize = bytes($0.end, [0x32, 0xc4, 0x35, 0xc0]) ? 4 : + (bytes($0.end, [0x32, 0xc4, 0x35, 0x40, 0x3b]) ? 5 : 0) + return $0.entry <= address && address < $0.end + epilogueSize + } + return matches.count == 1 ? matches[0] : nil + } + func supported(_ function: CMOCVariableDebug.Function) -> Bool { + // CMOC FunctionDef emits PSHS U; LEAU ,S before local allocation, + // then LEAS ,U; PULS U,PC after its metadata end label. ISR epilogues + // use PULS U; RTI and are intentionally not treated as normal calls. + function.frame && bytes(function.entry, [0x34, 0x40, 0x33, 0xe4]) && + bytes(function.end, [0x32, 0xc4, 0x35, 0xc0]) + } + func target(of instruction: CMOCProjectSourceMap.Instruction) -> Int? { + let b = instruction.bytes, next = Int(instruction.address) + b.count + if b.count == 3 && b[0] == 0x17 { // LBSR, signed relative displacement + return (next + Int(Int16(bitPattern: UInt16(b[1]) << 8 | UInt16(b[2])))) & 0xffff + } + if b.count == 2 && b[0] == 0x8d { return (next + Int(Int8(bitPattern: b[1]))) & 0xffff } + if b.count == 3 && b[0] == 0xbd { return Int(b[1]) * 256 + Int(b[2]) } + // JSR n,PCR is statically resolvable; register/indirect calls aren't. + if b.count == 3 && b[0] == 0xad && b[1] == 0x8c { return (next + Int(Int8(bitPattern: b[2]))) & 0xffff } + if b.count == 4 && b[0] == 0xad && b[1] == 0x8d { + return (next + Int(Int16(bitPattern: UInt16(b[2]) << 8 | UInt16(b[3])))) & 0xffff + } + return nil + } + var frames: [Frame] = [], currentPC = Int(pc), frameU = Int(u), visited = Set() + var stackFloor = Int(s) + let limit = min(max(maximumFrames, 1), 128) + while frames.count < limit { + guard let current = function(at: currentPC) else { + return Self(frames: frames, termination: "The next location is outside an unambiguous verified C function; the remaining stack is unavailable.") + } + let location = metadata.sourceMap.location(at: UInt16(currentPC)) + let inBody = current.body <= currentPC && currentPC < current.end && location != nil + let validStorage = readable(frameU, 4) && stackFloor <= frameU && !visited.contains(frameU) + let inspectable = supported(current) && inBody && validStorage + frames.append(Frame(id: frames.count, functionName: current.name, sourcePath: location?.path ?? current.sourcePath, + sourceLine: location?.line, pc: UInt16(currentPC), u: UInt16(frameU), localsInspectable: inspectable)) + guard supported(current) else { + return Self(frames: frames, termination: "This frame uses optimized, interrupt, assembly, or other unsupported stack code. Its locals and remaining callers are unavailable.") + } + guard inBody else { + return Self(frames: frames, termination: "Stopped in a function prologue, epilogue, or unmapped instruction; its frame pointer cannot be assumed valid yet.") + } + guard validStorage else { + return Self(frames: frames, termination: "The frame pointer is outside readable stack memory or repeats an earlier frame; unwinding stopped.") + } + visited.insert(frameU) + let olderU = word(frameU), returnPC = word(frameU + 2) + let calls = metadata.sourceMap.instructions.filter { + Int($0.address) + $0.bytes.count == returnPC && target(of: $0) == current.entry + } + guard calls.count == 1, let call = calls.first, + let caller = function(at: Int(call.address)), caller.body <= Int(call.address), Int(call.address) < caller.end else { + return Self(frames: frames, termination: "The caller is outside verified C code or its call target cannot be proved. Runtime, indirect-call and unknown boundaries stop unwinding here.") + } + guard olderU >= frameU + 4, readable(olderU, 4), !visited.contains(olderU) else { + return Self(frames: frames, termination: "The saved caller frame pointer is invalid, unavailable or non-increasing; unwinding stopped.") + } + stackFloor = frameU + 4 + frameU = olderU + currentPC = Int(call.address) + } + return Self(frames: frames, termination: "The call stack reached its \(limit)-frame inspection limit; additional callers are not shown.") + } +} diff --git a/platforms/macos/App/CMOCCompletion.swift b/platforms/macos/App/CMOCCompletion.swift new file mode 100644 index 0000000..6ea87f8 --- /dev/null +++ b/platforms/macos/App/CMOCCompletion.swift @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// Read-only lexical assistance. Queries never compile, execute Make, evaluate +/// macros, or rebuild the project index. All coordinates are native UTF-16. +enum CMOCCompletion { + struct Candidate: Identifiable, Equatable, Sendable { + var id: String { name } + let name: String + let detail: String + let conditional: Bool + let replacementRange: NSRange + let insertion: String + } + struct ParameterHint: Identifiable, Equatable, Sendable { + var id: String { sourcePath + ":" + signature } + let signature: String + let name: String + let parameters: [String] + let activeParameter: Int + let conditional: Bool + let sourcePath: String + } + private static let keywords = ["asm", "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", "interrupt", "long", "register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while"] + private static let controls: Set = ["if", "for", "while", "switch", "sizeof", "return", "else", "do", "asm", "__asm"] + private static let typeWords: Set = ["void", "char", "short", "int", "long", "float", "double", "unsigned", "signed", "struct", "union", "enum", "typedef"] + + static func suggestions(index: CMOCProjectIndex, path: String, text: String, offset: Int, limit: Int = 80) -> [Candidate] { + guard ["c", "h"].contains((path as NSString).pathExtension.lowercased()), + text.utf8.count <= CMOCProjectIndex.maximumFileBytes else { return [] } + let units = Array(text.utf16) + guard offset >= 0, offset <= units.count, let scan = scan(units, to: offset), !scan.suppressed else { return [] } + var start = offset, end = offset + while start > 0 && identifierPart(units[start - 1]) { start -= 1 } + while end < units.count && identifierPart(units[end]) { end += 1 } + if start < end && !identifierStart(units[start]) { return [] } + let prefix = String(decoding: units[start.. = [], candidates: [Candidate] = [] + let maximum = min(max(1, limit), 200) + for symbol in symbols { + guard seen.insert(symbol.name).inserted else { continue } + let uncertain = symbol.conditional || !revision.safeScopes || (symbol.path == path && revision.changed) + candidates.append(.init(name: symbol.name, + detail: symbol.kind.rawValue + " · " + symbol.signature + " · " + symbol.path, + conditional: uncertain, replacementRange: range, insertion: symbol.name)) + if candidates.count >= maximum { return candidates } + } + for keyword in keywords where keyword.hasPrefix(prefix) && seen.insert(keyword).inserted { + candidates.append(.init(name: keyword, detail: "C keyword", conditional: false, replacementRange: range, insertion: keyword)) + if candidates.count >= maximum { break } + } + return candidates + } + + static func parameterHints(index: CMOCProjectIndex, path: String, text: String, offset: Int) -> [ParameterHint] { + guard ["c", "h"].contains((path as NSString).pathExtension.lowercased()), + text.utf8.count <= CMOCProjectIndex.maximumFileBytes else { return [] } + let units = Array(text.utf16) + guard offset >= 0, offset <= units.count, let scanned = scan(units, to: offset), !scanned.suppressed || scanned.literal else { return [] } + struct Frame { let delimiter: String; let name: String?; let tokenIndex: Int; var argument: Int } + let tokens = scanned.tokens + var stack: [Frame] = [] + for (i, token) in tokens.enumerated() { + switch token.text { + case "(", "[", "{": + guard stack.count < 128 else { return [] } + let previous = i > 0 ? tokens[i - 1] : nil + let member = i > 1 && [".", "->"].contains(tokens[i - 2].text) + let name = token.text == "(" && previous?.identifier == true && !controls.contains(previous!.text) && !member ? previous!.text : nil + stack.append(.init(delimiter: token.text, name: name, tokenIndex: i, argument: 0)) + case ")", "]", "}": + let expected = token.text == ")" ? "(" : token.text == "]" ? "[" : "{" + guard stack.last?.delimiter == expected else { return [] } + stack.removeLast() + case ",": + if stack.last?.name != nil { stack[stack.count - 1].argument += 1 } + default: break + } + } + guard let call = stack.last(where: { $0.name != nil }), let name = call.name else { return [] } + let nameToken = tokens[call.tokenIndex - 1] + let revision = Revision(original: index.documents[path], current: units, offset: nameToken.offset) + // An indexed declaration, or a newly typed obvious declaration, is not + // a call. Function pointers and member calls are deliberately omitted. + if index.symbols.contains(where: { $0.path == path && $0.name == name && $0.offsetUTF16 == revision.offset && $0.kind == .function }) { return [] } + let statementStart = tokens[..<(call.tokenIndex - 1)].lastIndex(where: { [";", "{", "}"].contains($0.text) }).map { $0 + 1 } ?? 0 + let prefix = tokens[statementStart..<(call.tokenIndex - 1)].map(\.text) + if !prefix.contains("="), !prefix.contains(where: { controls.contains($0) }), !prefix.contains("(") { + if prefix.contains(where: { typeWords.contains($0) }) || (!prefix.isEmpty && prefix.allSatisfy { $0 == "*" || $0.utf16.first.map(identifierStart) == true }) { return [] } + } + let matches = index.completionSymbols(from: path, offset: revision.offset, prefix: name, includeLocals: revision.safeScopes) + .filter { $0.name == name && ($0.path != path || revision.keeps($0)) } + // A local object shadows a global function even when its type happens + // to be a function pointer. Do not invent its callable signature. + guard !matches.contains(where: { $0.kind != .function && $0.kind != .macro }) else { return [] } + var seen: Set = [], result: [ParameterHint] = [] + for symbol in matches where symbol.kind == .function || symbol.kind == .macro { + guard let parameters = parameters(in: symbol.signature, name: name), seen.insert(symbol.signature).inserted else { continue } + result.append(.init(signature: symbol.signature, name: name, parameters: parameters, activeParameter: call.argument, + conditional: symbol.conditional || symbol.kind == .macro || !revision.safeScopes || (symbol.path == path && revision.changed), sourcePath: symbol.path)) + if result.count == 8 { break } + } + return result + } + + private struct Revision { + let offset: Int, changed: Bool, safeScopes: Bool + let changedRange: Range + init(original: String?, current: [UInt16], offset: Int) { + guard let original else { self.offset = 0; changed = true; safeScopes = false; changedRange = 0..= current.count - suffix { self.offset = offset + old.count - current.count } + else { self.offset = prefix } + safeScopes = !changed || (old[changedRange].allSatisfy(CMOCCompletion.identifierPart) && current[prefix..<(current.count - suffix)].allSatisfy(CMOCCompletion.identifierPart)) + } + func keeps(_ symbol: CMOCProjectIndex.Symbol) -> Bool { + let token = symbol.offsetUTF16..<(symbol.offsetUTF16 + symbol.lengthUTF16) + return !token.overlaps(changedRange) && !(changedRange.isEmpty && token.contains(changedRange.lowerBound)) + } + } + private struct Token { + let text: String, offset: Int + var identifier: Bool { text.utf16.first.map(CMOCCompletion.identifierStart) == true } + } + private struct Scan { let tokens: [Token]; let suppressed: Bool; var literal = false } + /// Scans only the prefix before the caret, retaining delimiters but treating + /// literals/comments/directives as opaque. Continued lines remain opaque. + private static func scan(_ units: [UInt16], to end: Int) -> Scan? { + var tokens: [Token] = [], i = 0, lineStart = true + while i < end { + if tokens.count >= CMOCProjectIndex.maximumTokens || (i % 1024 == 0 && Task.isCancelled) { return nil } + let c = units[i], next = i + 1 < end ? units[i + 1] : 0 + if c == 10 || c == 13 { lineStart = true; i += 1; continue } + if c == 32 || c == 9 { i += 1; continue } + if (lineStart && c == 35) || (c == 47 && next == 47) { + i += 1 + while i < end { + if units[i] == 10 { + let previous = i > 0 && units[i - 1] == 13 ? i - 2 : i - 1 + if previous < 0 || units[previous] != 92 { break } + } + i += 1 + } + if i == end { return .init(tokens: tokens, suppressed: true) } + continue + } + if c == 47 && next == 42 { + i += 2; var closed = false + while i < end { + if units[i] == 42, i + 1 < end, units[i + 1] == 47 { i += 2; closed = true; break } + if units[i] == 10 { lineStart = true }; i += 1 + } + if !closed { return .init(tokens: tokens, suppressed: true) }; continue + } + lineStart = false + if c == 34 || c == 39 { + let quote = c; i += 1; var closed = false + while i < end { + if units[i] == 92 { i += min(2, end - i); continue } + if units[i] == quote { i += 1; closed = true; break } + i += 1 + } + if !closed { return .init(tokens: tokens, suppressed: true, literal: true) }; continue + } + let start = i; i += 1 + if identifierPart(c) { while i < end && identifierPart(units[i]) { i += 1 } } + else if c == 45 && next == 62 { i += 1 } + tokens.append(.init(text: String(decoding: units[start.. Bool { c == 95 || (65...90).contains(c) || (97...122).contains(c) } + private static func identifierPart(_ c: UInt16) -> Bool { identifierStart(c) || (48...57).contains(c) } + private static func parameters(in signature: String, name: String) -> [String]? { + if signature.hasPrefix("#define ") && !signature.hasPrefix("#define " + name + "(") { return nil } + let declaration = signature.hasPrefix("#define ") ? String(signature.dropFirst(8)) : signature + let units = Array(declaration.utf16) + guard let scan = scan(units, to: units.count), !scan.suppressed else { return nil } + let tokens = scan.tokens + guard let nameIndex = tokens.indices.first(where: { tokens[$0].text == name && $0 + 1 < tokens.count && tokens[$0 + 1].text == "(" }) else { return nil } + var depth = 0, parts: [[String]] = [[]] + for token in tokens[(nameIndex + 2)...] { + if token.text == ")", depth == 0 { + let parameters = parts.map { $0.joined(separator: " ").replacingOccurrences(of: ". . .", with: "...") } + return parameters == [""] || parameters == ["void"] ? [] : parameters + } + if token.text == ",", depth == 0 { parts.append([]); continue } + if ["(", "[", "{"].contains(token.text) { depth += 1 } + if [")", "]", "}"].contains(token.text) { depth -= 1; if depth < 0 { return nil } } + parts[parts.count - 1].append(token.text) + } + return nil // The index bounds display signatures; never guess truncated parameters. + } +} diff --git a/platforms/macos/App/CMOCCompletionEditor.swift b/platforms/macos/App/CMOCCompletionEditor.swift new file mode 100644 index 0000000..fe077a9 --- /dev/null +++ b/platforms/macos/App/CMOCCompletionEditor.swift @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit + +/// AppKit supplies the native completion list and keyboard behavior. Suggestions +/// never provisionally rewrite source: only a final, still-valid choice is an +/// editor operation, preserving the normal document Undo manager. +class CMOCCompletionTextView: NSTextView, SourceFindEditor { + weak var sourceFind: SourceFind? + var completionProvider: ((String, Int) -> [CMOCCompletion.Candidate])? + var completionStatus: ((String) -> Void)? + var parameterHintAction: (() -> Void)? + var assistanceFocusLost: (() -> Void)? + private var completionSource: String? + private var completionRange = NSRange(location: NSNotFound, length: 0) + private var completionOffset = 0 + private var completionCandidates: [CMOCCompletion.Candidate] = [] + + @discardableResult func prepareCompletion() -> Bool { + invalidateCompletion() + guard isEditable else { completionStatus?("Completion is available in editable C sources."); return false } + guard !hasMarkedText() else { completionStatus?("Finish the current text composition before completing an identifier."); return false } + guard selectedRange().length == 0 else { completionStatus?("Place the insertion point inside or after an identifier to complete it."); return false } + guard let completionProvider else { completionStatus?("Source completion is not ready for this editor."); return false } + let source = string, offset = selectedRange().location + let candidates = completionProvider(source, offset) + guard let first = candidates.first, first.replacementRange.location != NSNotFound, + NSMaxRange(first.replacementRange) <= (source as NSString).length else { + completionStatus?("No completion candidates here. Suggestions use the project’s source index.") + return false + } + completionSource = source; completionRange = first.replacementRange; completionOffset = offset + completionCandidates = candidates.filter { $0.replacementRange == first.replacementRange } + let uncertain = completionCandidates.contains { $0.conditional } + completionStatus?("\(completionCandidates.count) source-based suggestions" + (uncertain ? " · Some candidates depend on build settings or scope." : ".")) + return true + } + func invalidateCompletion() { + completionSource = nil; completionRange = NSRange(location: NSNotFound, length: 0) + completionCandidates = [] + } + override func complete(_ sender: Any?) { + guard prepareCompletion() else { return } + super.complete(sender) + } + override var rangeForUserCompletion: NSRange { + completionSource == string ? completionRange : NSRange(location: NSNotFound, length: 0) + } + override func completions(forPartialWordRange charRange: NSRange, indexOfSelectedItem index: UnsafeMutablePointer?) -> [String]? { + guard isEditable, completionSource == string, charRange == completionRange else { return [] } + index?.pointee = -1 + return completionCandidates.map(\.insertion) + } + override func insertCompletion(_ word: String, forPartialWordRange charRange: NSRange, movement: Int, isFinal flag: Bool) { + // The native list asks to preview candidates as the selection moves. + // Keeping these out of the document also keeps them out of draft recovery. + guard flag else { return } + defer { invalidateCompletion() } + guard movement != NSTextMovement.cancel.rawValue, isEditable, !hasMarkedText(), completionSource == string, + selectedRange() == NSRange(location: completionOffset, length: 0), + charRange == completionRange, + completionCandidates.contains(where: { $0.insertion == word }), + completionRange.location != NSNotFound, NSMaxRange(completionRange) <= (string as NSString).length else { return } + breakUndoCoalescing() + insertText(word, replacementRange: completionRange) + breakUndoCoalescing() + undoManager?.setActionName("Complete Identifier") + } + override func cancelOperation(_ sender: Any?) { + invalidateCompletion() + if sourceFind?.cancel(from: self) != true { + _ = nextResponder?.tryToPerform(#selector(NSResponder.cancelOperation(_:)), with: sender) + } + } + override func resignFirstResponder() -> Bool { + let resigned = super.resignFirstResponder() + if resigned { invalidateCompletion(); assistanceFocusLost?() } + return resigned + } + override func performKeyEquivalent(with event: NSEvent) -> Bool { + let modifiers = event.modifierFlags.intersection([.command, .control, .option, .shift]) + if event.keyCode == 49, modifiers == [.control] { complete(nil); return true } + if event.keyCode == 49, modifiers == [.control, .shift] { parameterHintAction?(); return true } + return super.performKeyEquivalent(with: event) + } +} diff --git a/platforms/macos/App/CMOCDevelopmentModel.swift b/platforms/macos/App/CMOCDevelopmentModel.swift new file mode 100644 index 0000000..ec33114 --- /dev/null +++ b/platforms/macos/App/CMOCDevelopmentModel.swift @@ -0,0 +1,1540 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import Combine + +enum CMOCSourceStepMode: Int { case into, over, out } + +struct CMOCEditorDocument: Identifiable { + let id: String + var text: String + var savedText: String + var savedHash: String + var conflict = false + var generated = false + var reference = false + var missing = false + var dirty: Bool { !text.utf8.elementsEqual(savedText.utf8) } +} +struct CMOCSourceBreakpoint: Hashable, Codable { + let file: String + let line: Int +} +struct CMOCBuildDiagnostic: Identifiable { + let id = UUID() + let file: String + let line: Int + let message: String +} + +struct CMOCVariableTreeRow: Identifiable { + enum ID: Hashable { case node(CMOCWatchEvaluator.TreePath), page(CMOCWatchEvaluator.TreePath), limit } + enum Content { + case node(CMOCWatchEvaluator.TreeNode) + case page(CMOCWatchEvaluator.TreePath, offset: Int, total: Int, next: Int?) + case message(String) + } + let id: ID + let depth: Int + let content: Content +} +struct CMOCVariableTreeListing { + let rows: [CMOCVariableTreeRow] + let rootCount: Int + let rootOffset: Int +} + +/// Documents and the exact build snapshot live independently of window lifetime. +/// The existing machine is the only authority for execution and mounted media. +@MainActor +final class CMOCDevelopmentModel: ObservableObject { + private(set) var assistantProjectID = UUID() + private(set) var assistantEditEpoch = 0 + weak var assistantEditor: NSTextView? + weak var assistantEditorPool: CSourceEditor.Coordinator? + var assistantEditorFile = "" + let machine: MachineModel + let service: CMOCBuildService + @Published var source = CMOCProject.starterSource { + didSet { + guard !selecting, let index = documents.firstIndex(where: { $0.id == selectedFile }) else { return } + if source != oldValue { assistantEditEpoch += 1 } + documents[index].text = source + scheduleDraftSave(); scheduleProjectIndex(); scheduleParameterHints() + } + } + @Published private(set) var documents: [CMOCEditorDocument] = [] + @Published private(set) var files: [CMOCProjectFile] = [] + @Published private(set) var selectedFile = "main.c" + @Published private(set) var project: CMOCProject? + @Published private(set) var building = false + @Published private(set) var commanding = false + @Published private(set) var log = "Create or open a C project to begin. Build runs its Makefile; only build projects you trust." + @Published private(set) var message: String? + @Published private(set) var mapping: CMOCSourceMap? + @Published private(set) var projectMapping: CMOCProjectSourceMap? + @Published private(set) var artifact: CMOCBuildArtifact? + @Published private(set) var diagnostics: [CMOCBuildDiagnostic] = [] + @Published var breakpointLine = 9 + @Published private(set) var breakpoints: Set = [] + @Published private(set) var currentLine: Int? + @Published private(set) var currentFile: String? + @Published private(set) var execution = "No development program loaded" + @Published private(set) var pc: UInt16? + @Published var configurationName = "Debug" { didSet { rememberWorkspace(); scheduleProjectIndex() } } + @Published var customTarget = "" + @Published private(set) var navigationLine: Int? + @Published private(set) var navigationRequest = UUID() + private var pausedInputEpoch: UInt64? + @Published private var pausedDebugSnapshot: VCCDebuggerSnapshot? + @Published private(set) var variableMetadata: CMOCVariableDebug? + @Published private(set) var variableStatus = "Build with the bundled compiler to inspect C variables." + @Published private(set) var watches: [String] = [] + @Published var watchExpression = "" + @Published private(set) var sourceStepping = false + @Published private(set) var inspectionRevision = UUID() + @Published private var capturedCallStack: CMOCCallStack? + @Published private(set) var selectedFrameIndex = 0 + private let defaults: UserDefaults + private var selecting = false + private var task: Task? + private var loadedGeneration: UInt64? + private var loadedRevision: UInt64? + private var loadedMapping: UInt64? + private var loadedBuild: UUID? + private var awaitingDiskLoad = false + private var reading = false + private var revision = UUID() + private var checkingFiles = false + private var nextFileCheck = Date.distantPast + private var externalBuildChange = false + private var restorationAttempted = false + @Published private(set) var launchedBuildID: UUID? + private var launchedGeneration: UInt64? + private var launchedRevision: UInt64? + @Published private(set) var latestBuildAttempt = "Not built in this session" + @Published private(set) var buildHistory: [CMOCBuildHistory.Entry] = [] + @Published private(set) var historyBusy = false + @Published private(set) var historyMessage: String? + @Published private(set) var recoveryRecords: [CMOCWorkspaceRecovery.Record] = [] + @Published private(set) var recoveryIssues: [String] = [] + @Published private(set) var recoveryBusy = false + private var historyRemoving = false + private var historyRefreshPending = false + private var recoveryRefreshPending = false + private var recoveryProjectDirectory: URL? + private let recoveryStore: CMOCWorkspaceRecovery + private let recoveryQueue = DispatchQueue(label: "VCCPlus.CMOCRecovery") + private var recoveryDebounce: Task? + + + init(machine: MachineModel, toolchain: URL? = nil, defaults: UserDefaults? = nil, buildRoot: URL? = nil, recoveryRoot: URL? = nil) { + self.machine = machine + self.defaults = defaults ?? machine.developmentDefaults + self.service = CMOCBuildService(toolchain: toolchain ?? Bundle.main.resourceURL!.appendingPathComponent("Toolchain"), + buildRoot: buildRoot ?? machine.developmentRunDirectory.deletingLastPathComponent().appendingPathComponent("Development Builds")) + self.recoveryStore = CMOCWorkspaceRecovery(root: recoveryRoot ?? machine.developmentRunDirectory.deletingLastPathComponent().appendingPathComponent("C Workspace Recovery")) + } + + + struct SourceLocation: Equatable { + let path: String + let line: Int + let column: Int + let length: Int + } + @Published var navigationPane = "Files" + @Published var searchQuery = "" { didSet { scheduleProjectSearch() } } + @Published var searchCaseSensitive = false { didSet { scheduleProjectSearch() } } + @Published private(set) var searchMatches: [CMOCProjectIndex.Match] = [] + @Published private(set) var searchTruncated = false + @Published private(set) var indexing = false + @Published private(set) var indexMessage = "Open a project to browse its source." + @Published private(set) var indexNotes: [String] = [] + @Published private(set) var projectIndex: CMOCProjectIndex? + @Published private(set) var definitionCandidates: [CMOCProjectIndex.Symbol] = [] + @Published private(set) var definitionName = "" + @Published private(set) var navigationColumn: Int? + @Published private(set) var navigationLength = 0 + @Published private(set) var cursorOffset = 0 + @Published private(set) var editorActionRequest = UUID() + private(set) var editorAction: CMOCEditorAction = .indent + func requestEditorAction(_ action: CMOCEditorAction) { + editorAction = action; editorActionRequest = UUID() + } + @Published private(set) var completionRequest = UUID() + @Published private(set) var completionMessage = "Complete identifiers with Control-Space." + @Published private(set) var parameterHints: [CMOCCompletion.ParameterHint] = [] + private var parameterTask: Task? + private var parameterGeneration = UUID() + func requestCompletion() { + completionMessage = "Preparing identifier completion…" + guard project != nil, !selectedFileIsGenerated else { + completionMessage = "Completion is available in editable project C sources."; return + } + guard projectIndex != nil else { + completionMessage = "Reading project declarations; try completion again shortly." + refreshProjectIndex(); return + } + completionRequest = UUID() + } + func reportCompletion(message: String) { completionMessage = message } + func clearParameterHints() { + parameterTask?.cancel(); parameterGeneration = UUID() + if !parameterHints.isEmpty { parameterHints = [] } + } + func refreshParameterHints() { scheduleParameterHints(delay: 0) } + private func scheduleParameterHints(delay: UInt64 = 80_000_000) { + clearParameterHints() + guard let index = projectIndex, let directory = project?.directory else { return } + let path = selectedFile, text = source, offset = cursorOffset, generation = parameterGeneration + parameterTask = Task { [weak self] in + do { + if delay > 0 { try await Task.sleep(nanoseconds: delay) } + try Task.checkCancellation() + let worker = Task.detached(priority: .utility) { + CMOCCompletion.parameterHints(index: index, path: path, text: text, offset: offset) + } + let hints = await withTaskCancellationHandler(operation: { await worker.value }, onCancel: { worker.cancel() }) + guard let self, !Task.isCancelled, parameterGeneration == generation, + project?.directory == directory, selectedFile == path, source == text, + cursorOffset == offset else { return } + parameterHints = hints + } catch { } + } + } + @Published private var backwardLocations: [SourceLocation] = [] + @Published private var forwardLocations: [SourceLocation] = [] + private var cursorOffsets: [String: Int] = [:] + private var indexInputs = CMOCIndexInputs() + private var indexTask: Task? + private var searchTask: Task? + private var indexGeneration = UUID() + private var searchGeneration = UUID() + private var navigationDiskHashes: [String: String] = [:] + var currentOutline: [CMOCProjectIndex.Symbol] { projectIndex?.outline(path: selectedFile) ?? [] } + var canNavigateBack: Bool { !backwardLocations.isEmpty } + var canNavigateForward: Bool { !forwardLocations.isEmpty } + func updateCursor(offset: Int) { + cursorOffset = max(0, min(offset, source.utf16.count)); cursorOffsets[selectedFile] = cursorOffset + scheduleParameterHints() + } + private func location(path: String, text: String, offset: Int, length: Int = 0) -> SourceLocation { + let value = text as NSString, offset = min(max(0, offset), value.length) + let prefix = value.substring(to: offset) as NSString + let lines = prefix.components(separatedBy: "\n") + return .init(path: path, line: lines.count, column: (lines.last?.utf16.count ?? 0) + 1, length: length) + } + private var cursorLocation: SourceLocation { location(path: selectedFile, text: source, offset: cursorOffset) } + private func resetNavigation() { + clearParameterHints(); completionRequest = UUID() + completionMessage = "Complete identifiers with Control-Space." + indexTask?.cancel(); searchTask?.cancel(); indexGeneration = UUID(); searchGeneration = UUID() + projectIndex = nil; indexInputs = .init(); navigationDiskHashes = [:] + searchMatches = []; searchTruncated = false; definitionCandidates = []; definitionName = "" + backwardLocations = []; forwardLocations = []; cursorOffsets = [:]; cursorOffset = 0 + navigationColumn = nil; navigationLength = 0; indexing = false + indexMessage = "Reading project text…"; indexNotes = [] + } + private func scheduleProjectIndex() { startProjectIndex(delay: 350_000_000) } + func refreshProjectIndex() { startProjectIndex(delay: 0) } + private func startProjectIndex(delay: UInt64) { + indexTask?.cancel(); indexGeneration = UUID() + guard let project else { indexing = false; return } + indexing = true + let generation = indexGeneration, inputs = overlays, configuration = configurationName, toolchain = service.toolchain + var generated = artifact?.sources.filter { artifact?.fileHashes[$0.key] == nil } ?? [:] + for document in documents where document.generated && !document.reference && artifact?.fileHashes[document.id] == nil { generated[document.id] = Data(document.text.utf8) } + let snapshots = generated + indexTask = Task { [weak self] in + do { + if delay > 0 { try await Task.sleep(nanoseconds: delay) } + try Task.checkCancellation() + let worker = Task.detached(priority: .utility) { + let collected = try CMOCIndexInputs.load(project: project, toolchain: toolchain, + configurationName: configuration, overlays: inputs, generated: snapshots) + try Task.checkCancellation() + let index = CMOCProjectIndex(documents: collected.documents, defines: collected.defines, + includePaths: collected.includePaths, configurationUncertain: collected.configurationUncertain) + try Task.checkCancellation() + return (collected, index) + } + let (collected, index) = try await withTaskCancellationHandler(operation: { try await worker.value }, onCancel: { worker.cancel() }) + guard let self, !Task.isCancelled, indexGeneration == generation, self.project?.directory == project.directory else { return } + indexInputs = collected; projectIndex = index; indexing = false + let notes = Array(Set(collected.issues + index.issues)).sorted() + indexNotes = notes + indexMessage = "\(index.symbols.count) symbols · Source-based navigation" + scheduleProjectSearch(); scheduleParameterHints() + } catch is CancellationError { } + catch { + guard let self, indexGeneration == generation else { return } + indexing = false; projectIndex = nil; searchMatches = []; definitionCandidates = []; clearParameterHints() + indexMessage = "Navigation unavailable: " + error.localizedDescription + } + } + } + private func scheduleProjectSearch() { + searchTask?.cancel(); searchGeneration = UUID(); searchMatches = []; searchTruncated = false + guard let index = projectIndex, !searchQuery.isEmpty else { return } + let generation = searchGeneration, query = searchQuery, sensitive = searchCaseSensitive + let paths = Set(index.documents.keys).subtracting(indexInputs.referencePaths) + searchTask = Task { [weak self] in + do { + try await Task.sleep(nanoseconds: 150_000_000) + let worker = Task.detached(priority: .utility) { index.search(query: query, caseSensitive: sensitive, limit: 500, paths: paths) } + let results = await withTaskCancellationHandler(operation: { await worker.value }, onCancel: { worker.cancel() }) + guard let self, !Task.isCancelled, searchGeneration == generation else { return } + searchMatches = results.matches; searchTruncated = results.truncated + } catch { } + } + } + func goToDefinition() { + guard !indexing, let index = projectIndex, index.documents[selectedFile] == source else { + indexMessage = "Updating source navigation; try Go to Definition again when indexing finishes." + refreshProjectIndex(); return + } + guard let name = index.token(atUTF16Offset: cursorOffset, in: selectedFile) else { + definitionName = ""; definitionCandidates = []; navigationPane = "Definitions" + indexMessage = "Place the insertion point on a C identifier to find its definition."; return + } + definitionName = name + let position = cursorLocation + definitionCandidates = index.definitions(named: name, from: selectedFile, line: position.line, column: position.column) + if definitionCandidates.count == 1, let target = definitionCandidates.first, !target.conditional { + openSymbol(target) + } else { navigationPane = "Definitions" } + } + func openSymbol(_ symbol: CMOCProjectIndex.Symbol) { + guard projectIndex?.symbols.contains(symbol) == true else { message = "This symbol result is out of date. Refresh navigation and select it again."; return } + openIndexedLocation(.init(path: symbol.path, line: symbol.line, column: symbol.column, length: symbol.lengthUTF16)) + } + func openSearchMatch(_ match: CMOCProjectIndex.Match) { + guard searchMatches.contains(match) else { message = "This search result is out of date. Search again before navigating."; return } + openIndexedLocation(.init(path: match.path, line: match.line, column: match.column, length: match.lengthUTF16)) + } + private func openIndexedLocation(_ target: SourceLocation) { + guard !indexing, let expected = projectIndex?.documents[target.path] else { + message = "Source navigation is updating. Please select the result again when it finishes."; return + } + do { + let current: String? + if let document = documents.first(where: { $0.id == target.path && !$0.reference }) { current = document.text } + else if indexInputs.referencePaths.contains(target.path) { current = indexInputs.documents[target.path] } + else if indexInputs.generatedPaths.contains(target.path) { current = artifact?.sources[target.path].flatMap { String(data: $0, encoding: .utf8) } } + else { current = try project?.readText(relativePath: target.path) } + guard current == expected else { throw CMOCBuildError.message("This result changed since it was indexed. Refresh navigation and select it again.") } + navigate(to: target, recording: true) + } catch { message = error.localizedDescription; refreshProjectIndex() } + } + private func navigate(to target: SourceLocation, recording: Bool) { + let origin = cursorLocation + openFile(target.path, line: target.line) + guard selectedFile == target.path else { return } + if recording && origin != target { + if backwardLocations.last != origin { backwardLocations.append(origin) } + if backwardLocations.count > 100 { backwardLocations.removeFirst(backwardLocations.count - 100) } + forwardLocations = [] + } + navigationColumn = target.column; navigationLength = target.length + let lines = source.components(separatedBy: "\n") + let line = min(max(1, target.line), max(1, lines.count)) + let offset = lines.prefix(line - 1).reduce(0) { $0 + $1.utf16.count + 1 } + min(max(0, target.column - 1), lines[line - 1].utf16.count) + updateCursor(offset: offset); navigationRequest = UUID() + } + func navigateBack() { + guard let target = backwardLocations.last else { return } + let origin = cursorLocation + navigate(to: target, recording: false) + guard selectedFile == target.path else { return } + backwardLocations.removeLast(); forwardLocations.append(origin) + } + func navigateForward() { + guard let target = forwardLocations.last else { return } + let origin = cursorLocation + navigate(to: target, recording: false) + guard selectedFile == target.path else { return } + forwardLocations.removeLast(); backwardLocations.append(origin) + } + + private func buildAttemptKey(_ directory: URL) -> String { + "CMOCBuildAttempt." + CMOCProject.sha256(Data(directory.resolvingSymlinksInPath().path.utf8)) + } + var sourceStatus: String { + guard project != nil else { return "No project open" } + if documents.contains(where: { $0.missing }) { return "Missing files" } + if documents.contains(where: { $0.conflict }) { return "External changes" } + return unsaved ? "Unsaved edits" : "Saved" + } + var buildStatus: String { + guard let artifact else { return latestBuildAttempt } + return "Build \(artifact.id.uuidString.prefix(8)) · \(buildMatchesEditor ? "current" : "out of date")" + } + var programStatus: String { + if awaitingDiskLoad { return "Disk launch pending verification" } + guard let id = launchedBuildID else { return "No verified development launch" } + return "Program \(id.uuidString.prefix(8)) · \(id == artifact?.id ? "latest build" : "earlier or other project")" + } + private func trackLaunch(_ artifact: CMOCBuildArtifact, snapshot: VCCMachineSnapshot) { + launchedBuildID = artifact.id; launchedGeneration = snapshot.generation + launchedRevision = snapshot.debuggerProgramRevision + refreshBuildHistory() + } + private func historyProtection(_ entries: [CMOCBuildHistory.Entry]) -> Set { + var ids = Set([artifact?.id, launchedBuildID].compactMap { $0 }) + if let latest = entries.first(where: { $0.hasBinary || $0.hasDisk }) { ids.insert(latest.id) } + let media = machine.developmentAssignedMediaURLs.map { $0.resolvingSymlinksInPath().standardizedFileURL.path } + for entry in entries { + let path = entry.directory.resolvingSymlinksInPath().standardizedFileURL.path + if media.contains(where: { $0 == path || $0.hasPrefix(path + "/") || path.hasPrefix($0 + "/") }) { ids.insert(entry.id) } + } + return ids + } + func refreshBuildHistory() { + guard let project else { return } + guard !historyBusy else { historyRefreshPending = true; return } + historyBusy = true; historyRefreshPending = false + let service = service + Task { + defer { + historyBusy = false + if historyRefreshPending { refreshBuildHistory() } + } + do { + let entries = try await Task.detached(priority: .utility) { try service.history(project: project.directory) }.value + guard self.project?.directory == project.directory else { return } + let protected = historyProtection(entries) + let checked = try await Task.detached(priority: .utility) { try service.history(project: project.directory, protectedIDs: protected) }.value + guard self.project?.directory == project.directory else { return } + buildHistory = checked + } catch { historyMessage = error.localizedDescription } + } + } + func trashBuilds(_ ids: Set) { + guard !historyBusy, !building, !commanding, !ids.isEmpty, let project else { return } + let alert = NSAlert(); alert.messageText = "Move selected build results to Trash?" + alert.informativeText = "Only verified, unchanged build snapshots can be removed. The latest and loaded builds, assigned media, and your writable Development Runs disks are protected." + alert.addButton(withTitle: "Move to Trash"); alert.addButton(withTitle: "Cancel") + guard alert.runModal() == .alertFirstButtonReturn else { return } + historyBusy = true; historyRemoving = true; historyMessage = nil + let service = service + Task { + do { + let entries = try await Task.detached(priority: .utility) { try service.history(project: project.directory) }.value + let protected = historyProtection(entries) + let result = try await Task.detached(priority: .utility) { try service.removeBuilds(ids: ids, project: project.directory, protectedIDs: protected) }.value + historyMessage = "Moved \(result.removedIDs.count) result(s) to Trash." + (result.retained.isEmpty ? "" : " Kept \(result.retained.count): " + Set(result.retained.values).sorted().joined(separator: "; ")) + } catch { historyMessage = error.localizedDescription } + historyBusy = false; historyRemoving = false; refreshBuildHistory() + } + } + func revealDevelopmentDisks() { + do { + try FileManager.default.createDirectory(at: machine.developmentRunDirectory, withIntermediateDirectories: true) + NSWorkspace.shared.open(machine.developmentRunDirectory) + } catch { historyMessage = error.localizedDescription } + } + private var recoveryDrafts: [CMOCWorkspaceRecovery.Draft] { + documents.filter { !$0.generated && !$0.reference && ($0.dirty || $0.missing || $0.conflict) }.map { + .init(path: $0.id, text: $0.text, savedText: $0.savedText, savedHash: $0.savedHash) + } + } + private func scheduleDraftSave() { + recoveryDebounce?.cancel() + recoveryDebounce = Task { [weak self] in + do { try await Task.sleep(nanoseconds: 500_000_000) } catch { return } + self?.persistDrafts() + } + } + func persistDrafts() { + scheduleProjectIndex() + recoveryDebounce?.cancel(); recoveryDebounce = nil + guard let project else { return } + let drafts = recoveryDrafts, store = recoveryStore + recoveryQueue.async { [weak self] in + do { try store.save(projectDirectory: project.directory, drafts: drafts) } + catch { + let detail = error.localizedDescription + Task { @MainActor [weak self] in + guard self?.project?.directory == project.directory else { return } + self?.message = "Could not save recovery copies: " + detail + } + } + } + } + func flushDraftRecovery(completion: @escaping @MainActor () -> Void) { + persistDrafts() + recoveryQueue.async { Task { @MainActor in completion() } } + } + func refreshRecovery() { + guard let directory = recoveryProjectDirectory else { return } + guard !recoveryBusy else { recoveryRefreshPending = true; return } + recoveryBusy = true; recoveryRefreshPending = false + let store = recoveryStore + recoveryQueue.async { [weak self] in + let result = Result { try store.scan(projectDirectory: directory) } + Task { @MainActor [weak self] in + guard let self else { return }; recoveryBusy = false + guard recoveryProjectDirectory == directory else { refreshRecovery(); return } + switch result { + case .success(let scan): recoveryRecords = scan.records.filter { $0.id != store.sessionID }; recoveryIssues = scan.issues + case .failure(let error): recoveryIssues = [error.localizedDescription] + } + if recoveryRefreshPending { refreshRecovery() } + } + } + } + func restoreRecovery(_ record: CMOCWorkspaceRecovery.Record) { + guard !building, !commanding, !recoveryBusy, !record.isFromRunningSession else { return } + guard let project, project.directory.resolvingSymlinksInPath().path == record.projectPath else { + message = "Open this draft's project to restore into the editor, or export its files to a new folder."; return + } + guard confirmDiscard() else { return } + for draft in record.drafts { + let disk = try? project.readText(relativePath: draft.path) + let conflict = disk.map { CMOCProject.sha256(Data($0.utf8)) != draft.savedHash } ?? true + let doc = CMOCEditorDocument(id: draft.path, text: draft.text, savedText: draft.savedText, + savedHash: draft.savedHash, conflict: conflict, missing: disk == nil) + if let index = documents.firstIndex(where: { $0.id == draft.path }) { documents[index] = doc } + else { documents.append(doc) } + } + if let first = record.drafts.first { selecting = true; selectedFile = first.path; source = first.text; selecting = false } + externalBuildChange = true; rememberWorkspace(); recoveryBusy = true + let store = recoveryStore, drafts = recoveryDrafts + // Publish a new durable copy before removing the prior session's copy. + recoveryQueue.async { [weak self] in + let result = Result { try store.save(projectDirectory: project.directory, drafts: drafts); try store.discard(record) } + Task { @MainActor [weak self] in + guard let self else { return }; recoveryBusy = false + if case .failure(let error) = result { message = error.localizedDescription } + else { message = "Drafts restored into the editor. Project files have not been overwritten." } + refreshRecovery() + } + } + } + func discardRecovery(_ record: CMOCWorkspaceRecovery.Record) { + guard !recoveryBusy, !record.isFromRunningSession else { return } + let alert = NSAlert(); alert.messageText = "Discard this recovery copy?" + alert.informativeText = "This removes only the saved recovery copy of \(record.drafts.count) file(s). Export it first if you may need it. Project files are unchanged." + alert.addButton(withTitle: "Discard Recovery Copy"); alert.addButton(withTitle: "Cancel") + guard alert.runModal() == .alertFirstButtonReturn else { return } + recoveryBusy = true; let store = recoveryStore + recoveryQueue.async { [weak self] in + let result = Result { try store.discard(record) } + Task { @MainActor [weak self] in + guard let self else { return }; recoveryBusy = false + if case .failure(let error) = result { recoveryIssues = [error.localizedDescription] } + refreshRecovery() + } + } + } + func exportRecovery(_ record: CMOCWorkspaceRecovery.Record) { + let panel = NSOpenPanel(); panel.title = "Export Recovered Sources" + panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true + guard panel.runModal() == .OK, let parent = panel.url else { return } + do { + let folder = parent.appendingPathComponent("Recovered Sources-" + UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false) + for draft in record.drafts { + try CMOCProject.validateRelativePath(draft.path) + let target = folder.appendingPathComponent(draft.path) + try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + try CMOCProject.sourceBytes(draft.text).write(to: target, options: .withoutOverwriting) + } + NSWorkspace.shared.open(folder) + } catch { recoveryIssues = [error.localizedDescription] } + } + func saveSelectedCopy() { + guard let doc = documents.first(where: { $0.id == selectedFile }) else { return } + let panel = NSSavePanel(); panel.title = "Save Selected Copy"; panel.nameFieldStringValue = URL(fileURLWithPath: doc.id).lastPathComponent + guard panel.runModal() == .OK, let url = panel.url else { return } + do { + if let original = try project?.fileURL(relativePath: doc.id), original.resolvingSymlinksInPath() == url.resolvingSymlinksInPath() { + throw CMOCBuildError.message("Choose a different filename or folder for this recovery copy. Use Save All to update an unchanged original.") + } + try CMOCProject.sourceBytes(doc.text).write(to: url, options: .atomic) + message = "Saved a copy of \(doc.id). The editor and original file are unchanged." + } catch { message = error.localizedDescription } + } + + var unsaved: Bool { documents.contains(where: \.dirty) } + var overlays: [String:String] { Dictionary(uniqueKeysWithValues: documents.filter { !$0.generated && !$0.reference }.map { ($0.id, $0.text) }) } + var selectedFileIsGenerated: Bool { documents.first(where: { $0.id == selectedFile }).map { $0.generated || $0.reference } == true } + var buildMatchesEditor: Bool { + guard let artifact, !externalBuildChange, !documents.contains(where: { $0.missing || $0.conflict }), artifact.configurationName == configurationName else { return false } + return documents.filter { !$0.reference }.allSatisfy { document in + // Build inputs include Makefile and headers, not just mapped C files. + guard let hash = (document.generated ? artifact.sourceHashes[document.id] : artifact.fileHashes[document.id]) else { return false } + return hash == CMOCProject.sha256(Data(document.text.utf8)) + } + } + var breakpointAddress: UInt16? { buildMatchesEditor ? projectMapping?.addresses(file: selectedFile, line: breakpointLine).first : nil } + var canRun: Bool { !historyRemoving && !building && !commanding && machine.canQuickLoad && !runToBreakpointAddresses.isEmpty && (projectMapping?.bankedLayout == nil || artifact?.hasDisk == true) } + var bundledLibraryCatalog: [CMOCBundledLibrary] { (try? CMOCBundledLibrary.catalog(at: service.toolchain)) ?? [] } + var canLaunch: Bool { !historyRemoving && !building && !commanding && !machine.busy && !machine.diskSaving && buildMatchesEditor && (artifact?.hasBinary == true || artifact?.hasDisk == true) } + var loadedMatchesEditor: Bool { loadedBuild == artifact?.id && loadedBuild != nil && buildMatchesEditor && projectMapping != nil } + var canCommand: Bool { !commanding && !machine.busy && !machine.diskSaving && (machine.state == .running || machine.state == .paused) } + var canStepC: Bool { + canCommand && !building && loadedMatchesEditor && !awaitingDiskLoad && machine.state == .paused && + currentLine != nil && pausedDebugSnapshot != nil && pausedInputEpoch == machine.inputEpoch + } + var canInspectC: Bool { + !building && !commanding && !machine.busy && loadedMatchesEditor && machine.state == .paused && + pausedDebugSnapshot != nil && pausedInputEpoch == machine.inputEpoch && variableMetadata != nil + } + var callStack: CMOCCallStack? { canInspectC ? capturedCallStack : nil } + var inspectionFrame: CMOCCallStack.Frame? { + guard let frames = callStack?.frames, frames.indices.contains(selectedFrameIndex) else { return nil } + return frames[selectedFrameIndex] + } + var inspectingCaller: Bool { inspectionFrame != nil && selectedFrameIndex > 0 } + var inspectionFrameDescription: String? { + guard let frame = inspectionFrame else { return nil } + let location = frame.sourceLine.map { "\(frame.sourcePath):\($0)" } ?? frame.sourcePath + return "Frame \(frame.id) · \(frame.functionName) · \(location)" + } + func selectFrame(_ index: Int) { + guard let frames = callStack?.frames, frames.indices.contains(index) else { return } + selectedFrameIndex = index + let frame = frames[index] + openFile(frame.sourcePath, line: frame.sourceLine) + } + private var evaluator: CMOCWatchEvaluator? { + guard canInspectC, let metadata = variableMetadata, let snapshot = pausedDebugSnapshot, + let u = snapshot.registers["U"] else { return nil } + let frame = inspectionFrame + return CMOCWatchEvaluator(metadata: metadata.projected(physicalPages: Self.physicalPages(snapshot), memory: snapshot.logicalMemory, available: snapshot.logicalMemoryAvailable), context: .init(pc: frame?.pc ?? snapshot.machine.programCounter, + u: frame?.u ?? u.uint16Value, memory: snapshot.logicalMemory, available: snapshot.logicalMemoryAvailable), + frameLocalsAvailable: frame?.localsInspectable == true) + } + var visibleVariables: [CMOCWatchEvaluator.Value] { evaluator?.visibleVariables() ?? [] } + func watchValue(_ expression: String) -> CMOCWatchEvaluator.Value? { evaluator?.evaluate(expression) } + var variableInspectionIdentity: String? { + canInspectC ? "\(inspectionRevision.uuidString):\(selectedFrameIndex)" : nil + } + func variableTree(watches: Bool, expanded: Set, + offsets: [CMOCWatchEvaluator.TreePath: Int], rootOffset: Int) -> CMOCVariableTreeListing { + guard let evaluator else { return .init(rows: [], rootCount: 0, rootOffset: 0) } + let roots = watches ? self.watches.map { CMOCWatchEvaluator.TreePath(root: .watch($0)) } : evaluator.variableRootPaths() + let start = max(0, min(rootOffset, max(0, ((roots.count - 1) / 32) * 32))) + var rows: [CMOCVariableTreeRow] = [] + var limited = false + func append(_ node: CMOCWatchEvaluator.TreeNode, depth: Int) { + guard rows.count < 255 else { limited = true; return } + rows.append(.init(id: .node(node.path), depth: depth, content: .node(node))) + guard node.childCount > 0, expanded.contains(node.path) else { return } + let offset = max(0, min(offsets[node.path] ?? 0, ((node.childCount - 1) / 32) * 32)) + let page = evaluator.children(of: node.path, offset: offset) + for child in page.nodes { append(child, depth: depth + 1) } + if let error = page.error, rows.count < 255 { + rows.append(.init(id: .page(node.path), depth: depth + 1, content: .message(error))) + } else if offset > 0 || page.nextOffset != nil { + if rows.count < 255 { + rows.append(.init(id: .page(node.path), depth: depth + 1, + content: .page(node.path, offset: offset, total: page.totalCount, next: page.nextOffset))) + } else { limited = true } + } + } + for root in roots.dropFirst(start).prefix(32) { append(evaluator.treeNode(at: root), depth: 0) } + if limited { + rows.append(.init(id: .limit, depth: 0, + content: .message("Showing 255 rows. Collapse a branch to inspect more of this page."))) + } + return .init(rows: rows, rootCount: roots.count, rootOffset: start) + } + var inspectionMessage: String { + if variableMetadata == nil { return variableStatus } + if !loadedMatchesEditor { return "Run this build with unchanged sources to inspect C values." } + if machine.state == .running { return "Pause at a verified C location to inspect values." } + if pausedDebugSnapshot == nil { return "No verified C location here. Instruction stepping remains available in Debugger." } + return "Values are read from the paused CoCo. Watches never execute code or change memory." + } + private var watchKey: String? { + project.map { "CMOCWorkspace.watches." + CMOCProject.sha256(Data($0.directory.path.utf8)) } + } + func addWatch() { + let expression = watchExpression.trimmingCharacters(in: .whitespacesAndNewlines) + guard !expression.isEmpty, expression.count <= 256, watches.count < 32 else { return } + if !watches.contains(expression) { watches.append(expression) } + watchExpression = "" + if let watchKey { defaults.set(watches, forKey: watchKey) } + } + func removeWatch(_ expression: String) { + watches.removeAll { $0 == expression } + if let watchKey { defaults.set(watches, forKey: watchKey) } + } + var selectedBreakpoints: Set { Set(breakpoints.filter { $0.file == selectedFile }.map(\.line)) } + var executableLines: [Int] { projectMapping?.executableLines(in: selectedFile) ?? [] } + + func confirmDiscard() -> Bool { + guard unsaved else { return true } + let alert = NSAlert(); alert.messageText = "Save changes to this project?" + alert.informativeText = "\(documents.filter(\.dirty).count) open file(s) contain unsaved changes." + alert.addButton(withTitle: "Save All"); alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard Changes") + switch alert.runModal() { + case .alertFirstButtonReturn: return save() + case .alertThirdButtonReturn: + for i in documents.indices { documents[i].text = documents[i].savedText } + if let selected = documents.first(where: { $0.id == selectedFile }) { selecting = true; source = selected.text; selecting = false } + persistDrafts(); return true + default: return false + } + } + func newProject() { + guard !building, confirmDiscard() else { return } + let choice = NSAlert(); choice.messageText = "Choose a C project template" + choice.informativeText = "Hello Disk demonstrates multiple source files, generated data, disk-file reading and a settings-generated Makefile. Hello World asks you to pick Earth or Mars in a single C file. Talking Planet Lander uses two optional sound cartridges and a joystick. Each template creates an editable copy." + choice.addButton(withTitle: "Hello Disk"); choice.addButton(withTitle: "Hello World"); choice.addButton(withTitle: "Talking Planet Lander"); choice.addButton(withTitle: "Cancel").keyEquivalent = "\u{1b}" + let selection = choice.runModal() + guard [.alertFirstButtonReturn, .alertSecondButtonReturn, .alertThirdButtonReturn].contains(selection) else { return } + let diskTemplate = selection == .alertFirstButtonReturn + let panel = NSSavePanel(); panel.title = "Create C Project Folder"; panel.nameFieldStringValue = diskTemplate ? "HelloDisk" : (selection == .alertThirdButtonReturn ? "TalkingPlanetLander" : "HelloCoCo") + panel.canCreateDirectories = true; panel.prompt = "Create Project" + guard panel.runModal() == .OK, let url = panel.url else { return } + do { + switch selection { + case .alertFirstButtonReturn: try adopt(CMOCProject.createHelloDisk(at: url)) + case .alertThirdButtonReturn: try adopt(CMOCProject.createTalkingLander(at: url)) + default: try adopt(CMOCProject.create(at: url)) + } + } catch { message = error.localizedDescription } + } + func openProject() { + guard !building, confirmDiscard() else { return } + let panel = NSOpenPanel(); panel.title = "Open C Project"; panel.message = "Choose a project folder with a Makefile. Opening does not run its build commands." + panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.allowsMultipleSelection = false + guard panel.runModal() == .OK, let url = panel.url else { return } + recoveryProjectDirectory = url; refreshRecovery() + do { try adopt(CMOCProject.open(at: url)) } catch { message = error.localizedDescription } + } + /// An explicit Library import opens known source without executing its Makefile. + /// Recheck the workspace after asynchronous disk validation and after review. + @discardableResult + func openImportedProject(at directory: URL, expectedProjectID: UUID, + preferredConfiguration: String? = nil, + reviewUnsaved: (() -> Bool)? = nil) async throws -> Bool { + func checkWorkspace() throws { + guard assistantProjectID == expectedProjectID else { + throw CMOCBuildError.message("The C project changed during the download. Your imported source is saved; open its folder when you are ready.") + } + guard !building, !commanding, !historyRemoving else { + throw CMOCBuildError.message("Your imported source is saved. Wait for the current C operation to finish before opening its folder.") + } + } + try checkWorkspace() + let checked = try await Task.detached(priority: .userInitiated) { try CMOCProject.open(at: directory) }.value + if let preferredConfiguration, !checked.configuration.configurations.contains(where: { $0.name == preferredConfiguration }) { + throw CMOCBuildError.message("The source package's requested build configuration is missing. Your current project is kept.") + } + try Task.checkCancellation() + try checkWorkspace() + let accepted: Bool + if let reviewUnsaved { accepted = reviewUnsaved() } + else { accepted = try await reviewImportedProjectSwitch(expectedProjectID: expectedProjectID) } + guard accepted else { return false } + try checkWorkspace() + try adopt(checked) + if let preferredConfiguration { configurationName = preferredConfiguration } + return true + } + private func reviewImportedProjectSwitch(expectedProjectID: UUID) async throws -> Bool { + guard unsaved else { return true } + guard let parent = NSApp.windows.first(where: { $0.identifier?.rawValue == "c-development" && $0.isVisible }) ?? NSApp.keyWindow else { + throw CMOCBuildError.message("Your source copy is saved. Open C Development to review unsaved changes before switching projects.") + } + let alert = NSAlert(); alert.messageText = "Save changes to this project?" + alert.informativeText = "\(documents.filter(\.dirty).count) open file(s) contain unsaved changes. Your downloaded source folder is already saved." + alert.addButton(withTitle: "Save All"); alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard Changes") + parent.makeKeyAndOrderFront(nil) + let response = await LibraryReviewSheet(alert: alert, parent: parent).present() + try Task.checkCancellation() + guard assistantProjectID == expectedProjectID, !building, !commanding, !historyRemoving else { + throw CMOCBuildError.message("The C workspace changed during review. Your imported folder and current project are kept.") + } + switch response { + case .alertFirstButtonReturn: return save() + case .alertThirdButtonReturn: + for i in documents.indices { documents[i].text = documents[i].savedText } + if let selected = documents.first(where: { $0.id == selectedFile }) { selecting = true; source = selected.text; selecting = false } + persistDrafts(); return true + default: return false + } + } + func adopt(_ project: CMOCProject) throws { + guard !building, !commanding, !historyRemoving else { throw CMOCBuildError.message("Wait for the current build or launch to finish before changing projects.") } + persistDrafts() + let entries = try project.fileEntries() + let entry = project.configuration.entrySource + let text = try project.readText(relativePath: entry) + MCPCMOC.shared.closing(self) + assistantProjectID = UUID() + resetNavigation(); self.project = project; files = entries + documents = [.init(id: entry, text: text, savedText: text, savedHash: CMOCProject.sha256(Data(text.utf8)))] + selecting = true; selectedFile = entry; source = text; selecting = false + pausedDebugSnapshot = nil; capturedCallStack = nil; selectedFrameIndex = 0; sourceStepping = false + artifact = nil; mapping = nil; projectMapping = nil; loadedBuild = nil; loadedGeneration = nil; currentLine = nil; currentFile = nil; pc = nil + variableMetadata = nil; variableStatus = "Build with the bundled compiler to inspect C variables." + watches = watchKey.flatMap { defaults.stringArray(forKey: $0) }?.filter { !$0.isEmpty && $0.count <= 256 }.prefix(32).map { $0 } ?? [] + watchExpression = "" + breakpoints = []; externalBuildChange = false + configurationName = project.configuration.configurations.first?.name ?? "Debug" + revision = UUID(); message = nil; execution = "No build from this project loaded" + log = "Opened \(project.directory.lastPathComponent). Build executes this project's Makefile." + diagnostics = [] + let previousAttempt = defaults.string(forKey: buildAttemptKey(project.directory)) + latestBuildAttempt = previousAttempt == "In progress" ? "Previous build did not report completion; rebuild to continue" : "Not built in this session" + rememberWorkspace() + buildHistory = []; historyMessage = nil; recoveryRecords = []; recoveryIssues = [] + recoveryProjectDirectory = project.directory; refreshRecovery(); refreshBuildHistory(); refreshProjectIndex() + } + func restoreWorkspace() { + guard !restorationAttempted else { return }; restorationAttempted = true + guard project == nil, let path = defaults.string(forKey: "CMOCWorkspace.directory") else { return } + recoveryProjectDirectory = URL(fileURLWithPath: path); refreshRecovery() + let tabs = defaults.stringArray(forKey: "CMOCWorkspace.tabs") ?? [] + let selected = defaults.string(forKey: "CMOCWorkspace.selected") + let configuration = defaults.string(forKey: "CMOCWorkspace.configuration") + do { + try adopt(CMOCProject.open(at: URL(fileURLWithPath: path))) + if let configuration, project?.configuration.configurations.contains(where: { $0.name == configuration }) == true { configurationName = configuration } + for tab in tabs where files.contains(where: { $0.relativePath == tab && $0.isEditable }) { openFile(tab) } + if let selected, documents.contains(where: { $0.id == selected }) { openFile(selected) } + } catch { message = "The previous project could not be reopened: \(error.localizedDescription)" } + } + private func rememberWorkspace() { + guard let project else { return } + defaults.set(project.directory.path, forKey: "CMOCWorkspace.directory") + defaults.set(documents.filter { !$0.reference }.map(\.id), forKey: "CMOCWorkspace.tabs") + defaults.set(selectedFile, forKey: "CMOCWorkspace.selected") + defaults.set(configurationName, forKey: "CMOCWorkspace.configuration") + } + func openFile(_ requestedPath: String, line: Int? = nil) { + let path = diagnosticPath(requestedPath) + guard let project else { return } + do { + if indexInputs.referencePaths.contains(path), let text = indexInputs.documents[path] { + let document = CMOCEditorDocument(id: path, text: text, savedText: text, + savedHash: CMOCProject.sha256(Data(text.utf8)), reference: true) + if let i = documents.firstIndex(where: { $0.id == path }) { documents[i] = document } + else { documents.append(document) } + } + if !documents.contains(where: { $0.id == path }) { + let diskText = try? project.readText(relativePath: path) + guard let text = diskText ?? artifact?.sources[path].flatMap({ String(data: $0, encoding: .utf8) }) else { + throw CMOCBuildError.message("This source file is unavailable: " + path) + } + documents.append(.init(id: path, text: text, savedText: text, savedHash: CMOCProject.sha256(Data(text.utf8)), generated: diskText == nil)) + } + guard let document = documents.first(where: { $0.id == path }) else { return } + selecting = true; selectedFile = path; source = document.text; selecting = false + mapping = projectMapping?.map(forFile: path) + if !executableLines.contains(breakpointLine) { breakpointLine = executableLines.first ?? 1 } + navigationLine = line; navigationColumn = nil; navigationLength = 0 + cursorOffset = min(cursorOffsets[path] ?? 0, source.utf16.count) + clearParameterHints(); scheduleParameterHints() + navigationRequest = UUID(); rememberWorkspace() + } catch { message = error.localizedDescription } + } + private func diagnosticPath(_ path: String) -> String { + guard path.hasPrefix("/") else { return path } + if let project, path.hasPrefix(project.directory.path + "/") { return String(path.dropFirst(project.directory.path.count + 1)) } + // Compile diagnostics use the controlled .workspaces//project root. + // Require a known complete project-relative suffix; never match a basename. + if let range = path.range(of: "/project/", options: .backwards), (path.contains("/.workspaces/") || path.hasPrefix("/private/tmp/vccplus-cmoc-")) { + let relative = String(path[range.upperBound...]) + if files.contains(where: { $0.relativePath == relative }) { return relative } + } + return path + } + func closeFile(_ path: String) { + guard let document = documents.first(where: { $0.id == path }) else { return } + if document.dirty { + let alert = NSAlert(); alert.messageText = "Save changes to \(path)?" + alert.addButton(withTitle: "Save"); alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard") + let result = alert.runModal() + if result == .alertSecondButtonReturn { return } + if result == .alertFirstButtonReturn && !saveFile(path) { return } + } + // Keep the final tab visible, but honor the user's Save/Discard decision. + if documents.count == 1 { + if let text = try? project?.readText(relativePath: path) { + documents[0] = .init(id: path, text: text, savedText: text, savedHash: CMOCProject.sha256(Data(text.utf8))) + selecting = true; source = text; selecting = false + } else { + documents[0].text = documents[0].savedText + selecting = true; source = documents[0].text; selecting = false + } + persistDrafts(); return + } + documents.removeAll { $0.id == path } + if selectedFile == path, let first = documents.first { openFile(first.id) } + rememberWorkspace(); persistDrafts() + } + /// Prepare all affected editor drafts before publishing any of them. Files + /// stay on disk until the user explicitly saves through the normal workspace. + func applyAssistantEdits(_ edits: [MCPCMOCEdit], disk: [String: String], projectID: UUID, epoch: Int, undoing: Bool = false) throws { + guard assistantProjectID == projectID, assistantEditEpoch == epoch, !building, !commanding, + assistantEditor?.hasMarkedText() != true else { throw CMOCBuildError.message("stale_revision") } + var updated = documents + for edit in edits { + guard let saved = disk[edit.path] else { throw CMOCBuildError.message("stale_revision") } + if let i = updated.firstIndex(where: { $0.id == edit.path }) { + guard !updated[i].conflict, !updated[i].missing, !updated[i].reference, !updated[i].generated, + updated[i].text.utf8.elementsEqual(edit.before.utf8), updated[i].savedText.utf8.elementsEqual(saved.utf8) + else { throw CMOCBuildError.message("stale_revision") } + updated[i].text = edit.after + } else { + guard saved.utf8.elementsEqual(edit.before.utf8) else { throw CMOCBuildError.message("stale_revision") } + updated.append(.init(id: edit.path, text: edit.after, savedText: saved, savedHash: CMOCProject.sha256(Data(saved.utf8)))) + } + } + assistantEditorPool?.setReviewedBuffers(edits, undoing: undoing) + documents = updated + if let selected = updated.first(where: { $0.id == selectedFile }) { + selecting = true; source = selected.text; selecting = false + } + assistantEditEpoch += 1 + rememberWorkspace(); persistDrafts(); scheduleParameterHints() + } + + /// Adopt an already captured and reviewed disk/configuration snapshot. + /// Clean tabs follow external edits; dirty drafts keep their exact bytes and + /// can only continue when their saved disk base is still unchanged. + func acceptAssistantProjectRefresh(_ updatedProject: CMOCProject, diskFiles: [String: Data], + projectID: UUID, epoch: Int) throws { + guard assistantProjectID == projectID, assistantEditEpoch == epoch, + project?.directory == updatedProject.directory, !building, !commanding, + assistantEditor?.hasMarkedText() != true else { throw CMOCBuildError.message("stale_revision") } + var updated = documents + for index in updated.indices where !updated[index].generated && !updated[index].reference { + let document = updated[index] + let bytes = diskFiles[document.id] + if document.dirty || document.conflict { + guard let bytes, CMOCProject.sha256(bytes) == document.savedHash, !document.conflict else { + throw CMOCBuildError.message("external_file_change: " + document.id + ": Your editor draft is kept; resolve its disk conflict locally before refreshing.") + } + continue + } + guard let bytes, let text = String(data: bytes, encoding: .utf8), !bytes.contains(0) else { + updated[index].missing = true; continue + } + updated[index].text = text; updated[index].savedText = text + updated[index].savedHash = CMOCProject.sha256(bytes) + updated[index].missing = false; updated[index].conflict = false + } + self.project = updatedProject + files = diskFiles.keys.sorted().map { .init(relativePath: $0, isEditable: CMOCProject.isEditable($0)) } + documents = updated + if let selected = updated.first(where: { $0.id == selectedFile }) { + selecting = true; source = selected.text; selecting = false + } + if !updatedProject.configuration.configurations.contains(where: { $0.name == configurationName }) { + configurationName = updatedProject.configuration.configurations.first?.name ?? "Debug" + } + externalBuildChange = true + rememberWorkspace(); persistDrafts(); scheduleProjectIndex() + } + + @discardableResult func saveFile(_ path: String) -> Bool { + guard let project, let index = documents.firstIndex(where: { $0.id == path }) else { return false } + guard !documents[index].generated && !documents[index].reference else { message = "Reference and generated source is read-only. Edit project sources or generator inputs."; return false } + do { + let hash = try project.saveText(documents[index].text, relativePath: path, replacingSHA256: documents[index].savedHash) + documents[index].savedHash = hash; documents[index].savedText = documents[index].text; documents[index].conflict = false + message = nil; persistDrafts(); return true + } catch { message = error.localizedDescription; return false } + } + @discardableResult func save() -> Bool { + guard project != nil else { message = "Create a project before saving."; return false } + for path in documents.filter(\.dirty).map(\.id) { if !saveFile(path) { return false } } + return true + } + func reloadSelected() { + guard let project else { return } + if documents.first(where: { $0.id == selectedFile })?.reference == true { refreshProjectIndex(); return } + if documents.first(where: { $0.id == selectedFile })?.dirty == true { + let alert = NSAlert(); alert.messageText = "Reload \(selectedFile) from disk?" + alert.informativeText = "This discards unsaved edits in this file." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Reload") + guard alert.runModal() == .alertSecondButtonReturn else { return } + } + do { + let text = try project.readText(relativePath: selectedFile) + if let i = documents.firstIndex(where: { $0.id == selectedFile }) { + documents[i] = .init(id: selectedFile, text: text, savedText: text, savedHash: CMOCProject.sha256(Data(text.utf8))) + selecting = true; source = text; selecting = false; message = nil; persistDrafts() + } + } catch { message = error.localizedDescription } + } + func addFile() { + guard !building, !commanding, let project else { return } + let panel = NSSavePanel(); panel.title = "New Project File"; panel.nameFieldStringValue = "module.c"; panel.directoryURL = project.directory + guard panel.runModal() == .OK, let url = panel.url else { return } + let prefix = project.directory.standardizedFileURL.path + "/" + guard url.standardizedFileURL.path.hasPrefix(prefix) else { message = "Choose a location inside this project."; return } + do { + guard !FileManager.default.fileExists(atPath: url.path) else { throw CMOCBuildError.message("Choose a new filename; existing files are kept.") } + let path = String(url.standardizedFileURL.path.dropFirst(prefix.count)) + _ = try project.fileURL(relativePath: path) + try Data().write(to: url, options: .withoutOverwriting) + files = try project.fileEntries(); openFile(path) + } catch { message = error.localizedDescription } + } + func editProjectConfiguration() { + guard let project else { return } + do { + let url = project.directory.appendingPathComponent("vccplus-project.json") + if !FileManager.default.fileExists(atPath: url.path) { + let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + try encoder.encode(project.configuration).write(to: url, options: .withoutOverwriting) + } + files = try project.fileEntries(); openFile("vccplus-project.json") + log = "Project settings are ordinary JSON. Save before building to apply changes; Makefile rules remain authoritative." + } catch { message = error.localizedDescription } + } + func applyProjectSettings(_ configuration: CMOCProjectConfiguration, makefile: String?, expectedMakefileHash: String, expectedConfigHash: String?) throws { + guard let project, !building, !commanding else { return } + let configPath = CMOCProject.configurationFilename + guard !documents.contains(where: { ($0.id == project.configuration.makefile || $0.id == configPath) && $0.dirty }) else { + throw CMOCBuildError.message("Save or reload your edited Makefile and project settings before applying this window.") + } + let validated = try configuration.validated() + let originalMakefile = try project.readText(relativePath: project.configuration.makefile) + guard CMOCProject.sha256(Data(originalMakefile.utf8)) == expectedMakefileHash else { throw CMOCBuildError.message("The Makefile changed while Project Settings was open. Reopen settings to review it.") } + let configURL = try project.fileURL(relativePath: configPath) + let oldConfig = try? Data(contentsOf: configURL) + guard oldConfig.map(CMOCProject.sha256) == expectedConfigHash else { throw CMOCBuildError.message("Project settings changed outside this window. Reopen settings to review them.") } + let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let configData = try encoder.encode(validated) + // Keep the Makefile's previous version recoverable when regenerating. + if let makefile, makefile != originalMakefile { + let backups = project.directory.appendingPathComponent(".vccplus-build/Makefile Backups") + try FileManager.default.createDirectory(at: backups, withIntermediateDirectories: true) + try Data(originalMakefile.utf8).write(to: backups.appendingPathComponent(UUID().uuidString + ".make"), options: .atomic) + _ = try project.saveText(makefile, relativePath: project.configuration.makefile, replacingSHA256: expectedMakefileHash) + } + do { try configData.write(to: configURL, options: .atomic) } + catch { + if makefile != nil { try? Data(originalMakefile.utf8).write(to: project.makefileURL, options: .atomic) } + throw error + } + self.project = CMOCProject(directory: project.directory, configuration: validated) + for path in [configPath, project.configuration.makefile] { + if let i = documents.firstIndex(where: { $0.id == path }), let value = try? self.project?.readText(relativePath: path) { + documents[i] = .init(id: path, text: value, savedText: value, savedHash: CMOCProject.sha256(Data(value.utf8))) + if selectedFile == path { selecting = true; source = value; selecting = false } + } + } + files = try self.project!.fileEntries(); externalBuildChange = true + if !validated.configurations.contains(where: { $0.name == configurationName }) { configurationName = validated.configurations.first!.name } + refreshProjectIndex() + message = nil; log = makefile == nil ? "Project settings saved. The custom Makefile was kept." : "Project settings and Makefile saved. The previous Makefile is retained in .vccplus-build/Makefile Backups." + } + func build() { build(.build) } + func build(_ action: CMOCBuildAction, target: String? = nil) { + guard let project, !building, !commanding, !historyRemoving else { return } + pausedDebugSnapshot = nil; capturedCallStack = nil; selectedFrameIndex = 0; sourceStepping = false + defaults.set("In progress", forKey: buildAttemptKey(project.directory)) + building = true; message = nil; currentLine = nil; currentFile = nil; latestBuildAttempt = "Building \(configurationName)…"; persistDrafts() + revision = UUID() + variableStatus = "Building C debug information…" + log = "Building a project snapshot…"; diagnostics = [] + let inputs = overlays; let configuration = configurationName + task = Task { + defer { + defaults.set(latestBuildAttempt, forKey: buildAttemptKey(project.directory)) + building = false; task = nil; checkExternalFiles(); refreshBuildHistory(); refreshProjectIndex() + } + do { + let built = try await service.build(project: project, overlays: inputs, action: action, configuration: configuration, target: target) + try Task.checkCancellation() + log = built.buildLog + latestBuildAttempt = "\(action == .clean ? "Clean" : "Build") succeeded" + guard built.hasBinary || built.hasDisk else { + execution = "Build action finished; the last runnable build and machine are unchanged" + return + } + var nextMapping: CMOCProjectSourceMap? + var nextVariables: CMOCVariableDebug? + diagnostics = Self.parseDiagnostics(built.buildLog, directory: built.compilationDirectory) + variableStatus = "This build has no verified C variable information." + if built.hasBinary { + do { + let verified = try await Task.detached(priority: .userInitiated) { try CMOCProjectSourceMap.parse(artifact: built) }.value + try Task.checkCancellation() + nextMapping = verified + log += "\nVerified source locations in \(verified.sourcePaths.count) C file(s)." + do { + nextVariables = try await Task.detached(priority: .userInitiated) { + try CMOCVariableDebug.parse(artifact: built, verifiedMap: verified) + }.value + try Task.checkCancellation() + variableStatus = "Compiler types and locations verified." + } catch is CancellationError { throw CancellationError() } + catch { variableStatus = error.localizedDescription } + + } catch is CancellationError { throw CancellationError() } + catch { log += "\nBuild succeeded. Source debugging unavailable: \(error.localizedDescription)" } + } + try Task.checkCancellation() + artifact = built; projectMapping = nextMapping; mapping = nextMapping?.map(forFile: selectedFile); variableMetadata = nextVariables + pausedDebugSnapshot = nil; capturedCallStack = nil + if let data = try? Data(contentsOf: built.fileURL(CMOCProject.configurationFilename)), + let config = try? JSONDecoder().decode(CMOCProjectConfiguration.self, from: data).validated() { + self.project = CMOCProject(directory: project.directory, configuration: config) + } + for i in documents.indices where documents[i].generated { + if let data = built.sources[documents[i].id], let text = String(data: data, encoding: .utf8) { + documents[i].text = text; documents[i].savedText = text; documents[i].savedHash = CMOCProject.sha256(data) + if selectedFile == documents[i].id { selecting = true; source = text; selecting = false } + } + } + if !executableLines.contains(breakpointLine) { breakpointLine = executableLines.first ?? 1 } + execution = "Build finished; the machine has not been changed" + } catch is CancellationError { latestBuildAttempt = "Build cancelled"; variableStatus = "Build cancelled; the last successful result is retained."; log = "Build cancelled. The last successful result and machine are unchanged." } + catch { + message = error.localizedDescription; log = error.localizedDescription + latestBuildAttempt = "Build failed"; variableStatus = "Build failed; the last successful result is retained." + diagnostics = Self.parseDiagnostics(log, directory: nil) + } + } + } + func cancelBuild() { task?.cancel(); service.cancel() } + static func parseDiagnostics(_ text: String, directory: URL?) -> [CMOCBuildDiagnostic] { + guard let regex = try? NSRegularExpression(pattern: #"^(.+?):([0-9]+)(?::[0-9]+)?:\s*(.+)$"#) else { return [] } + return text.components(separatedBy: .newlines).compactMap { line in + let ns = line as NSString + guard let m = regex.firstMatch(in: line, range: NSRange(location: 0, length: ns.length)), let number = Int(ns.substring(with: m.range(at: 2))), number > 0 else { return nil } + var file = ns.substring(with: m.range(at: 1)) + if let directory, file.hasPrefix(directory.path + "/") { file = String(file.dropFirst(directory.path.count + 1)) } + if file.hasPrefix("./") { file = String(file.dropFirst(2)) } + return .init(file: file, line: number, message: ns.substring(with: m.range(at: 3))) + } + } + func toggleBreakpoint(_ line: Int) { + guard !commanding, !building else { return } + guard machine.pasteRemaining == 0 else { message = "Wait for the launch commands to finish before changing source breakpoints."; return } + let point = CMOCSourceBreakpoint(file: selectedFile, line: line) + if breakpoints.contains(point) { breakpoints.remove(point) } + else { breakpoints.insert(point); breakpointLine = line } + updateLiveBreakpoints() + } + private func updateLiveBreakpoints() { + guard loadedMatchesEditor, let artifact, let projectMapping, canCommand else { return } + let points = sourceBreakpointAddresses(includeFallback: false) + let wasRunning = machine.state == .running + let wasSourceStepping = sourceStepping + let wasAwaitingDiskLoad = awaitingDiskLoad + let expectedGeneration = loadedGeneration, expectedRevision = loadedRevision, expectedMapping = loadedMapping + // Discard an older poll already in flight while this command changes the + // breakpoint set. A source edit is still caught by loadedMatchesEditor. + revision = UUID(); let request = revision + commanding = true + let unchanged: (VCCMachineSnapshot) -> Bool = { snapshot in + snapshot.generation == expectedGeneration && snapshot.debuggerProgramRevision == expectedRevision && + (projectMapping.bankedLayout != nil || wasAwaitingDiskLoad || snapshot.debuggerMappingFingerprint == expectedMapping) + } + let invalidate: (String) -> Void = { [weak self] text in + guard let self else { return } + loadedBuild = nil; loadedGeneration = nil; awaitingDiskLoad = false + currentLine = nil; currentFile = nil; pc = nil; execution = text + // Never leave this feature's old addresses armed in a changed MMU + // layout, and never resume a machine that changed during the command. + machine.clearDevelopmentBreakpoints { [weak self] in self?.commanding = false } + } + let finish = { [weak self] in + guard let self else { return } + if wasRunning && !wasSourceStepping { machine.debuggerContinue { [weak self] in self?.commanding = false; self?.refresh() } } + else { commanding = false; refresh() } + } + machine.debuggerPause { [weak self] in + guard let self else { return } + machine.readDebugger(address: 0, followPC: true, memoryAddress: 0) { [weak self] detail in + guard let self else { return } + guard revision == request, loadedMatchesEditor, let detail, unchanged(detail.machine), detail.machine.errorMessage == nil else { + invalidate("Machine or project changed; run the build again before updating source breakpoints"); return + } + if points.isEmpty, projectMapping.bankedLayout != nil { + // Removing the last stop does not discard verified bank + // evidence needed by Pause, source steps and watches. + machine.armDevelopmentBreakpoints([], sourceMap: projectMapping, pointModules: [:]) { [weak self] snapshot in + guard let self else { return } + guard revision == request, loadedMatchesEditor, let snapshot, snapshot.errorMessage == nil, unchanged(snapshot) else { + invalidate(snapshot?.errorMessage ?? "Machine changed while updating source breakpoints"); return + } + attach(artifact, snapshot: snapshot); awaitingDiskLoad = wasAwaitingDiskLoad + finish() + } + } else if points.isEmpty { + machine.clearDevelopmentBreakpoints { [weak self] in + guard let self else { return } + if wasAwaitingDiskLoad { + loadedBuild = nil; loadedGeneration = nil; currentLine = nil; currentFile = nil; pc = nil + execution = "Source breakpoints cleared before the disk program was verified" + } + awaitingDiskLoad = false; finish() + } + } else { + machine.armDevelopmentBreakpoints(points, sourceMap: projectMapping, pointModules: sourceBreakpointModules(includeFallback: false)) { [weak self] snapshot in + guard let self else { return } + guard revision == request, loadedMatchesEditor, let snapshot, snapshot.errorMessage == nil, unchanged(snapshot) else { + invalidate(snapshot?.errorMessage ?? "Machine changed while updating source breakpoints; run the build again"); return + } + // Rearming doesn't replace code. Retain a previously + // verified paused source connection so instruction steps + // keep updating even before another breakpoint is hit. + // An unverified disk launch, however, must keep waiting. + attach(artifact, snapshot: snapshot) + awaitingDiskLoad = wasAwaitingDiskLoad + finish() + } + } + } + } + } + /// Every compiled instance of a C line owns its own module-qualified stop. + /// Ordinary flat programs retain their first mapped address per line. + private func sourceBreakpointSelection(includeFallback: Bool) -> [(UInt16, String?)] { + guard let projectMapping else { return [] } + func selection(_ point: CMOCSourceBreakpoint) -> [(UInt16, String?)] { + let code = projectMapping.instructions.filter { $0.sourcePath == point.file && $0.sourceLine == point.line } + if projectMapping.bankedLayout == nil { return code.first.map { [($0.address, nil)] } ?? [] } + return Dictionary(grouping: code, by: { $0.moduleID ?? "" }).values.compactMap { group in + group.min(by: { $0.address < $1.address }).map { ($0.address, $0.moduleID) } + } + } + let configured = breakpoints.flatMap(selection) + if configured.isEmpty && includeFallback { + return selection(CMOCSourceBreakpoint(file: selectedFile, line: breakpointLine)) + } + return configured + } + private func sourceBreakpointAddresses(includeFallback: Bool) -> [UInt16] { + Array(Set(sourceBreakpointSelection(includeFallback: includeFallback).map { $0.0 })).sorted() + } + private func sourceBreakpointModules(includeFallback: Bool) -> [UInt16: Set] { + var result: [UInt16: Set] = [:] + for (address, module) in sourceBreakpointSelection(includeFallback: includeFallback) { + if let module { result[address, default: []].insert(module) } + } + return result + } + /// Normal launches use only breakpoints the user explicitly added. + var resolvedBreakpointAddresses: [UInt16] { buildMatchesEditor ? sourceBreakpointAddresses(includeFallback: false) : [] } + /// The selected-line fallback belongs only to the explicit Run to Breakpoint action. + var runToBreakpointAddresses: [UInt16] { buildMatchesEditor ? sourceBreakpointAddresses(includeFallback: true) : [] } + func confirmRun() { + guard canRun else { return } + if projectMapping?.bankedLayout != nil { confirmDiskLaunch(toBreakpoint: true); return } + let alert = NSAlert(); alert.messageText = "Run C program in this CoCo?" + alert.informativeText = "This replaces program memory without restarting or changing mounted media, then runs to a verified source breakpoint. Use a booted Disk BASIC machine. Save any BASIC program you want to keep first." + alert.addButton(withTitle: "Run to Breakpoint"); alert.addButton(withTitle: "Cancel") + if alert.runModal() == .alertFirstButtonReturn { run() } + } + func run() { + checkExternalFiles() + guard canRun, let artifact else { return } + if projectMapping?.bankedLayout != nil { launchDisk(commands: project?.configuration.launchCommands ?? [], toBreakpoint: true); return } + let addresses = runToBreakpointAddresses + guard !addresses.isEmpty else { return } + commanding = true; message = nil; currentLine = nil; revision = UUID() + machine.prepareToQuit { [weak self] in + guard let self else { return } + guard !machine.unsavedMedia else { commanding = false; message = "Save or export pending media before running. The machine is paused."; return } + guard buildMatchesEditor, self.artifact?.id == artifact.id else { commanding = false; message = "Project changed. Build again before running."; return } + machine.debuggerLoadDevelopmentBinary(artifact.binaryData, breakpoints: addresses) { [weak self] snapshot in + guard let self else { return }; commanding = false + guard let snapshot else { message = "The machine became unavailable."; return } + if let error = snapshot.errorMessage { message = error; return } + attach(artifact, snapshot: snapshot); execution = "Running to source breakpoint"; refresh() + } + } + } + private func attach(_ artifact: CMOCBuildArtifact, snapshot: VCCMachineSnapshot) { + trackLaunch(artifact, snapshot: snapshot) + loadedBuild = artifact.id; loadedGeneration = snapshot.generation + loadedRevision = snapshot.debuggerProgramRevision; loadedMapping = snapshot.debuggerMappingFingerprint + } + func launch() { + checkExternalFiles() + guard canLaunch, let project, let artifact else { return } + if project.configuration.launchMode == .disk || (!artifact.hasBinary && artifact.hasDisk) { confirmDiskLaunch(); return } + if !resolvedBreakpointAddresses.isEmpty { + guard canRun else { message = "Banked source debugging needs a declared disk image. Clear source breakpoints to run this binary without source debugging."; return } + confirmRun(); return + } + let alert = NSAlert(); alert.messageText = "Load and run the built program?" + alert.informativeText = "This replaces CoCo program memory and runs without a source breakpoint. Mounted media and machine settings are kept." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Run") + guard alert.runModal() == .alertSecondButtonReturn else { return } + launchQuickload() + } + /// Confirmation-free execution shared with regression tests; the UI confirms first. + func launchQuickload() { + checkExternalFiles() + guard canLaunch, let artifact, artifact.hasBinary else { return } + commanding = true; revision = UUID() + machine.prepareToQuit { [weak self] in + guard let self else { return } + guard !machine.unsavedMedia, buildMatchesEditor, self.artifact?.id == artifact.id else { commanding = false; message = "Save pending media and rebuild changed sources before running."; return } + machine.runDevelopmentBinary(artifact.binaryData) { [weak self] snapshot in + guard let self else { return } + commanding = false + guard let snapshot, snapshot.errorMessage == nil else { message = snapshot?.errorMessage ?? "Program launch failed."; return } + loadedBuild = nil; loadedGeneration = nil; awaitingDiskLoad = false + pausedDebugSnapshot = nil; currentLine = nil; currentFile = nil; pc = nil + trackLaunch(artifact, snapshot: snapshot) + execution = "Program running without source breakpoints" + } + } + } + func confirmDiskLaunch(toBreakpoint: Bool = false) { + guard canLaunch, let artifact, artifact.hasDisk, let project else { message = "Build a disk target first."; return } + guard machine.diskEnabled else { message = "Select a machine profile with its floppy controller enabled before launching this disk."; return } + let commands = project.configuration.launchCommands + let alert = NSAlert(); alert.messageText = "Mount the development disk in FD0?" + alert.informativeText = "This replaces the current FD0 assignment with a separate working copy of the build disk. Pending media must be saved first. Machine settings are kept.\n\n" + (commands.isEmpty ? "No commands will be typed. Load or boot the program yourself." : "At the BASIC prompt, these commands will be typed:\n" + commands.joined(separator: "\n")) + alert.addButton(withTitle: "Mount and Launch"); alert.addButton(withTitle: "Cancel") + guard alert.runModal() == .alertFirstButtonReturn else { return } + launchDisk(commands: commands, toBreakpoint: toBreakpoint) + } + func launchDisk(commands: [String], toBreakpoint: Bool = false) { + checkExternalFiles() + guard let artifact, let diskPath = artifact.diskRelativePath, canLaunch else { return } + commanding = true; message = nil; revision = UUID() + machine.prepareToQuit { [weak self] in + guard let self else { return } + guard !machine.unsavedMedia, buildMatchesEditor, self.artifact?.id == artifact.id else { commanding = false; message = "Save pending media and rebuild changed sources before mounting the development disk."; return } + do { + let copyFolder = machine.developmentRunDirectory.appendingPathComponent("Run-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: copyFolder, withIntermediateDirectories: true) + let copy = copyFolder.appendingPathComponent(URL(fileURLWithPath: diskPath).lastPathComponent) + try FileManager.default.copyItem(at: artifact.fileURL(diskPath), to: copy) + machine.mountDevelopmentDisk(copy) { [weak self] snapshot in + guard let self else { return } + guard let snapshot, snapshot.errorMessage == nil else { commanding = false; message = snapshot?.errorMessage ?? "Disk mounting failed."; return } + trackLaunch(artifact, snapshot: snapshot) + armDiskAndResume(artifact: artifact, commands: commands, toBreakpoint: toBreakpoint) + } + } catch { commanding = false; message = error.localizedDescription } + } + } + private func armDiskAndResume(artifact: CMOCBuildArtifact, commands: [String], toBreakpoint: Bool = false) { + let addresses = toBreakpoint ? runToBreakpointAddresses : resolvedBreakpointAddresses + let finish = { [weak self] in + guard let self else { return } + machine.debuggerContinue { [weak self] in + guard let self else { return }; commanding = false + do { if !commands.isEmpty { machine.startPaste(try CocoPaste(commands.joined(separator: "\n") + "\n", mode: .text)) } } + catch { message = error.localizedDescription } + } + } + guard let projectMapping, !addresses.isEmpty else { + // A prior debugging run may still own temporary source breakpoints. + // Clear only that set before booting; retain the assembly debugger's breakpoints. + loadedBuild = nil; loadedGeneration = nil; awaitingDiskLoad = false + pausedDebugSnapshot = nil; currentLine = nil; currentFile = nil; pc = nil + execution = "Development disk mounted; running without source breakpoints" + machine.clearDevelopmentBreakpoints(completion: finish) + return + } + machine.armDevelopmentBreakpoints(addresses, sourceMap: projectMapping, pointModules: sourceBreakpointModules(includeFallback: toBreakpoint)) { [weak self] snapshot in + guard let self else { return } + guard let snapshot, snapshot.errorMessage == nil else { commanding = false; message = snapshot?.errorMessage ?? "Cannot arm disk breakpoints."; return } + attach(artifact, snapshot: snapshot); awaitingDiskLoad = true + execution = "Waiting for the disk loader to reach verified program code"; finish() + } + } + func revealBuild() { if let artifact { NSWorkspace.shared.open(artifact.directory) } } + func toggleExecution() { + guard canCommand else { return }; commanding = true + pausedDebugSnapshot = nil; revision = UUID() + let complete = { [weak self] in self?.commanding = false; self?.refresh() } + if machine.state == .running { machine.debuggerPause(completion: complete) } + else { machine.debuggerContinue(completion: complete) } + } + func stepInstruction() { + guard canCommand, machine.state == .paused else { return }; commanding = true + pausedDebugSnapshot = nil; revision = UUID() + machine.debuggerStep { [weak self] in self?.commanding = false; self?.refresh() } + } + func stepSource(_ mode: CMOCSourceStepMode) { + checkExternalFiles() + guard canStepC, let projectMapping, let snapshot = pausedDebugSnapshot else { return } + var identities: [String: UInt32] = [:] + let instructions = projectMapping.instructions + let locations = instructions.map { instruction -> NSNumber in + let key = "\(instruction.moduleID ?? ""):\(instruction.sourcePath):\(instruction.sourceLine)" + if identities[key] == nil { identities[key] = UInt32(identities.count + 1) } + return NSNumber(value: identities[key]!) + } + commanding = true; sourceStepping = true; message = nil; revision = UUID() + pausedDebugSnapshot = nil; currentLine = nil; currentFile = nil + machine.debuggerStepSource(mode: mode.rawValue, addresses: instructions.map { NSNumber(value: $0.address) }, + locations: locations, bytes: instructions.map { Data($0.bytes) }, expected: snapshot.machine, + moduleIdentifiers: projectMapping.bankedLayout == nil ? nil : instructions.map { $0.moduleID ?? "" }) { [weak self] in + guard let self else { return } + commanding = false + if let error = machine.fileError { message = error } + refresh() + } + } + func checkExternalFiles() { + guard !building, let project else { return } + do { + let entries = try project.fileEntries() + if entries.map(\.relativePath) != files.map(\.relativePath) { files = entries } + for index in documents.indices where !documents[index].generated && !documents[index].reference { + guard let disk = try? project.readText(relativePath: documents[index].id) else { + documents[index].missing = true; externalBuildChange = true + message = "\(documents[index].id) is missing or unreadable. Its editor contents are kept; use Save Selected Copy to recover them." + scheduleDraftSave(); continue + } + documents[index].missing = false + let hash = CMOCProject.sha256(Data(disk.utf8)) + guard hash != documents[index].savedHash else { continue } + if documents[index].dirty || documents[index].conflict { + if !documents[index].conflict { documents[index].conflict = true; message = "\(documents[index].id) changed outside VCC Plus. Your edits are kept; use Reload File to accept the disk version." } + } else { + documents[index].text = disk; documents[index].savedText = disk; documents[index].savedHash = hash + if selectedFile == documents[index].id { selecting = true; source = disk; selecting = false } + } + } + if let artifact { + let hashes = try project.currentFileHashes(overlays: overlays) + let changed = hashes != artifact.fileHashes + if externalBuildChange != changed { externalBuildChange = changed } + } + } catch { if message != error.localizedDescription { message = error.localizedDescription }; externalBuildChange = true } + } + private func scheduleExternalCheck() { + guard !building, !checkingFiles, let project else { return } + checkingFiles = true + let saved = Dictionary(uniqueKeysWithValues: documents.map { ($0.id, $0.savedHash) }) + let request = revision + Task { + defer { checkingFiles = false } + do { + let filesOnDisk = try await Task.detached(priority: .utility) { try project.inputFiles() }.value + let hashes = await Task.detached(priority: .utility) { filesOnDisk.mapValues(CMOCProject.sha256) }.value + let supportHashes = try await Task.detached(priority: .utility) { + var captured = project + if let bytes = filesOnDisk[CMOCProject.configurationFilename] { + captured.configuration = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: bytes).validated() + } + return try captured.supportFileHashes() + }.value + guard !building, revision == request, self.project?.directory == project.directory, + saved == Dictionary(uniqueKeysWithValues: documents.map { ($0.id, $0.savedHash) }) else { return } + let entries = filesOnDisk.keys.sorted().map { CMOCProjectFile(relativePath: $0, isEditable: CMOCProject.isEditable($0)) } + if entries != files { files = entries } + for index in documents.indices where !documents[index].generated && !documents[index].reference { + guard let bytes = filesOnDisk[documents[index].id], let disk = String(data: bytes, encoding: .utf8), let hash = hashes[documents[index].id] else { + if !documents[index].missing { + documents[index].missing = true + message = "\(documents[index].id) is missing or unreadable. Its editor contents are kept; use Save Selected Copy to recover them." + scheduleDraftSave() + } + continue + } + documents[index].missing = false + guard hash != documents[index].savedHash else { continue } + if documents[index].dirty || documents[index].conflict { + if !documents[index].conflict { + documents[index].conflict = true + message = "\(documents[index].id) changed outside VCC Plus. Your edits are kept; reload the file to accept the disk version." + } + } else { + documents[index].text = disk; documents[index].savedText = disk; documents[index].savedHash = hash + if selectedFile == documents[index].id { selecting = true; source = disk; selecting = false } + } + } + let textHashes = hashes.filter { CMOCProject.isEditable($0.key) } + if textHashes != navigationDiskHashes { + navigationDiskHashes = textHashes; scheduleProjectIndex() + } + if let artifact { + var current = hashes.merging(supportHashes) { first, _ in first } + for (path, text) in overlays { current[path] = CMOCProject.sha256(Data(text.utf8)) } + let changed = current != artifact.fileHashes + if changed != externalBuildChange { externalBuildChange = changed } + } + } catch { + guard self.project?.directory == project.directory else { return } + if message != error.localizedDescription { message = error.localizedDescription } + externalBuildChange = true + } + } + } + static func physicalPages(_ snapshot: VCCDebuggerSnapshot) -> [Int: Int] { + Dictionary(uniqueKeysWithValues: snapshot.mmu.effective.enumerated().filter { $0.element.source == 0 }.map { + ($0.offset, Int($0.element.sourceAddress) / 8192) + }) + } + func refresh() { + if Date() >= nextFileCheck { nextFileCheck = Date().addingTimeInterval(3); scheduleExternalCheck() } + guard (loadedBuild != nil || launchedBuildID != nil), !building, !reading, !commanding else { return } + reading = true; let request = revision; let epoch = machine.inputEpoch + machine.readDebugger(address: 0, followPC: true, memoryAddress: 0) { [weak self] snapshot in + guard let self else { return }; reading = false + guard revision == request, machine.inputEpoch == epoch, let snapshot else { return } + if launchedGeneration != snapshot.machine.generation || launchedRevision != snapshot.machine.debuggerProgramRevision { + launchedBuildID = nil; launchedGeneration = nil; launchedRevision = nil + } + guard loadedBuild != nil else { return } + let previousSnapshot = pausedDebugSnapshot + let previousEpoch = pausedInputEpoch + pausedDebugSnapshot = nil + sourceStepping = snapshot.machine.debuggerSourceStepping + if loadedGeneration != snapshot.machine.generation || loadedRevision != snapshot.machine.debuggerProgramRevision || (!awaitingDiskLoad && projectMapping?.bankedLayout == nil && loadedMapping != snapshot.machine.debuggerMappingFingerprint) { + loadedBuild = nil; loadedGeneration = nil; currentLine = nil; currentFile = nil; pc = nil + execution = "Machine changed; run the build again to reconnect source locations"; return + } + guard loadedMatchesEditor else { publishStop(nil, file: nil, line: nil, text: "Project changed; build again before using source locations"); return } + if awaitingDiskLoad { + guard snapshot.machine.debuggerDevelopmentAttached else { return } + awaitingDiskLoad = false; loadedMapping = snapshot.machine.debuggerMappingFingerprint + } + if snapshot.machine.state == .running { publishStop(nil, file: nil, line: nil, text: sourceStepping ? "Stepping through C — Pause to stop" : "Running"); return } + let address = snapshot.machine.programCounter + let activeMap = projectMapping?.projected(physicalPages: Self.physicalPages(snapshot), memory: snapshot.logicalMemory, available: snapshot.logicalMemoryAvailable) + guard let instruction = activeMap?.instruction(at: address), let live = snapshot.instructions.first, + live.address == instruction.address, Array(live.bytes) == instruction.bytes else { + publishStop(address, file: nil, line: nil, text: "Paused at \(String(format: "$%04X", address)) — no verified C line here; use Debugger for assembly"); return + } + // Variable locations are valid only while all mapped code still matches. + // Inspection reads the same immutable snapshot as PC and registers. + let memory = snapshot.logicalMemory, available = snapshot.logicalMemoryAvailable + let codeMatches = (projectMapping?.bankedLayout == nil || snapshot.machine.debuggerDevelopmentAttached) && + activeMap?.verifiesRuntime(memory: memory, available: available) == true + if codeMatches { + pausedDebugSnapshot = snapshot; pausedInputEpoch = epoch + let sameStop = previousEpoch == epoch && previousSnapshot?.machine.programCounter == address && + previousSnapshot?.machine.debuggerMappingFingerprint == snapshot.machine.debuggerMappingFingerprint && + previousSnapshot?.registers["U"] == snapshot.registers["U"] && + previousSnapshot?.registers["S"] == snapshot.registers["S"] && + previousSnapshot?.logicalMemory == snapshot.logicalMemory && + previousSnapshot?.logicalMemoryAvailable == snapshot.logicalMemoryAvailable + if !sameStop { + inspectionRevision = UUID() + selectedFrameIndex = 0 + capturedCallStack = variableMetadata.flatMap { metadata in + guard let u = snapshot.registers["U"], let s = snapshot.registers["S"] else { return nil } + return CMOCCallStack.capture(metadata: metadata.projected(physicalPages: Self.physicalPages(snapshot), memory: snapshot.logicalMemory, available: snapshot.logicalMemoryAvailable), pc: address, u: u.uint16Value, s: s.uint16Value, + memory: memory, available: available) + } + } + } + else { + publishStop(address, file: nil, line: nil, text: "Program bytes changed; run the build again before C debugging") + return + } + let changedLocation = currentFile != instruction.sourcePath || currentLine != instruction.sourceLine || pc != address + publishStop(address, file: instruction.sourcePath, line: instruction.sourceLine, text: "Paused at \(instruction.sourcePath):\(instruction.sourceLine) · \(String(format: "$%04X", address)) · \(snapshot.stopReason)") + if changedLocation { openFile(instruction.sourcePath, line: instruction.sourceLine) } + } + } + private func publishStop(_ address: UInt16?, file: String?, line: Int?, text: String) { + if pc != address { pc = address }; if currentFile != file { currentFile = file } + if currentLine != line { currentLine = line }; if execution != text { execution = text } + } +} diff --git a/platforms/macos/App/CMOCDevelopmentView.swift b/platforms/macos/App/CMOCDevelopmentView.swift new file mode 100644 index 0000000..eefa821 --- /dev/null +++ b/platforms/macos/App/CMOCDevelopmentView.swift @@ -0,0 +1,1439 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit + +struct CMOCDevelopmentView: View { + @ObservedObject var model: CMOCDevelopmentModel + @StateObject private var finder = SourceFind() + @ObservedObject private var menu: MachineMenuState + @Environment(\.openWindow) private var openWindow + @State private var showSettings = false + @State private var showHistory = false + @State private var showRecovery = false + @State private var selectedHintID = "" + @State private var outputTab = "Build Log" + @State private var expandedVariables: Set = [] + @State private var variableOffsets: [CMOCWatchEvaluator.TreePath: Int] = [:] + @State private var variableRootOffset = 0 + @FocusState private var searchFocused: Bool + init(model: CMOCDevelopmentModel) { self.model = model; self.menu = model.machine.menuState } + var body: some View { + VStack(alignment: .leading, spacing: 0) { + header.padding(16) + Divider() + toolbar.padding(.horizontal, 16).padding(.vertical, 10) + workspaceStatus + Divider() + if let message = model.message { + HStack(alignment: .top) { + Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.orange) + Text(message).textSelection(.enabled).lineLimit(4).accessibilityIdentifier("cmoc.error") + }.font(.callout).padding(10).frame(maxWidth: .infinity, alignment: .leading).background(.orange.opacity(0.08)) + } + HSplitView { + navigator.frame(minWidth: 190, idealWidth: 240, maxWidth: 340) + VStack(spacing: 0) { + navigationBar + tabs + sourceAssistanceBar + if model.inspectingCaller { + HStack { + Label(model.inspectionFrameDescription ?? "Caller", systemImage: "square.stack.3d.up") + .lineLimit(2).accessibilityIdentifier("cmoc.frame.context") + Spacer(minLength: 4) + Button("Show Current Frame") { model.selectFrame(0) } + .accessibilityIdentifier("cmoc.frame.current") + }.font(.caption).padding(8).background(Color.accentColor.opacity(0.08)) + } + SourceFindBar(finder: finder, source: model.source, readOnly: model.selectedFileIsGenerated) + VSplitView { + CSourceEditor(finder: finder, text: $model.source, + currentLine: model.loadedMatchesEditor && model.currentFile == model.selectedFile ? model.currentLine : nil, + file: model.selectedFile, readOnly: model.selectedFileIsGenerated, breakpoints: model.selectedBreakpoints, + breakpointControlsEnabled: model.project != nil && !model.building && !model.commanding && !menu.values.pasting, + navigationLine: model.navigationLine, navigationColumn: model.navigationColumn, + navigationLength: model.navigationLength, navigationRequest: model.navigationRequest, + toggleBreakpoint: model.toggleBreakpoint, cursorChanged: model.updateCursor, + goToDefinition: model.goToDefinition, + completionIndex: model.projectIndex, completionRequest: model.completionRequest, + completionStatus: model.reportCompletion, parameterHints: model.refreshParameterHints, + clearParameterHints: model.clearParameterHints, + editorAction: model.editorAction, editorActionRequest: model.editorActionRequest, attach: { path, editor, pool in + model.assistantEditorFile = path; model.assistantEditor = editor; model.assistantEditorPool = pool + }) + .id(model.project?.directory.path ?? "empty") + .frame(minHeight: showsVariableInspector ? 120 : 160).accessibilityIdentifier("cmoc.editor") + output.frame(minHeight: showsVariableInspector ? 220 : 90, + idealHeight: showsVariableInspector ? 280 : 180, maxHeight: 310) + } + }.frame(minWidth: 565) + } + Divider() + debugBar.padding(.horizontal, 14).padding(.vertical, 9) + HStack { + Image(systemName: model.currentLine == nil ? "info.circle" : "stop.circle.fill") + Text(model.execution).lineLimit(2).textSelection(.enabled).accessibilityIdentifier("cmoc.execution") + Spacer(minLength: 0) + if model.artifact != nil && !model.buildMatchesEditor { + Label("Build out of date", systemImage: "exclamationmark.triangle").foregroundStyle(.orange) + } + }.font(.caption).padding(.horizontal, 14).padding(.bottom, 10) + }.frame(minWidth: 900, minHeight: 650) + .focusedSceneValue(\.sourceFind, finder) + .focusedSceneValue(\.projectSearch, { model.navigationPane = "Search"; searchFocused = true }) + .onChange(of: model.variableInspectionIdentity) { _, _ in + expandedVariables.removeAll(); variableOffsets.removeAll(); variableRootOffset = 0 + } + .onChange(of: outputTab) { _, _ in variableRootOffset = 0 } + .onChange(of: model.navigationPane) { _, pane in + if pane == "Search" { searchFocused = true } + } + .sheet(isPresented: $showSettings) { CMOCProjectSettingsView(model: model) } + .sheet(isPresented: $showHistory) { CMOCBuildHistoryView(model: model) } + .sheet(isPresented: $showRecovery) { CMOCRecoveryView(model: model) } + .onDisappear { model.persistDrafts(); MCPCMOC.shared.closing(model) } + .task { + model.restoreWorkspace() + while !Task.isCancelled { + model.refresh() + try? await Task.sleep(nanoseconds: 200_000_000) + } + } + } + private var showsVariableInspector: Bool { outputTab == "Variables" || outputTab == "Watches" } + private var header: some View { + HStack(spacing: 12) { + Image(systemName: "curlybraces.square").font(.largeTitle).foregroundStyle(.tint) + VStack(alignment: .leading, spacing: 3) { + Text(model.project?.directory.lastPathComponent ?? "C Development").font(.title2.bold()).lineLimit(1).truncationMode(.middle) + Text("CMOC · Project workspace").foregroundStyle(.secondary).font(.callout) + } + Spacer(minLength: 8) + Button("Assistant…", systemImage: "link") { MCPCMOC.shared.showAccess(model) }.disabled(model.project == nil) + Button { showHistory = true } label: { Label("Build History", systemImage: "clock.arrow.circlepath") } + .accessibilityIdentifier("cmoc.history") + Button { showRecovery = true } label: { Label(model.recoveryRecords.isEmpty ? "Recovery" : "Recovery (\(model.recoveryRecords.count))", systemImage: "doc.badge.clock") } + .accessibilityIdentifier("cmoc.recovery") + .help("Review saved recovery copies of unsaved editor text") + Button { showSettings = true } label: { Label("Project Settings", systemImage: "slider.horizontal.3") } + .disabled(model.project == nil || model.building).accessibilityIdentifier("cmoc.settings") + Button { openWindow(id: "debugger") } label: { Label("Debugger", systemImage: "ladybug") } + } + } + private var workspaceStatus: some View { + HStack(alignment: .top, spacing: 12) { + statusItem("Source", text: model.sourceStatus, symbol: "doc.text", identifier: "source") + statusItem("Build", text: model.buildStatus, symbol: "hammer", identifier: "build", detail: model.artifact == nil ? nil : model.latestBuildAttempt) + statusItem("CoCo", text: model.programStatus, symbol: "desktopcomputer", identifier: "program") + }.padding(.horizontal, 16).padding(.bottom, 9) + } + private func statusItem(_ title: String, text: String, symbol: String, identifier: String, detail: String? = nil) -> some View { + VStack(alignment: .leading, spacing: 2) { + Label(title, systemImage: symbol).font(.caption.weight(.medium)).foregroundStyle(.secondary) + Text(text).font(.caption).lineLimit(2).fixedSize(horizontal: false, vertical: true) + if let detail { Text(detail).font(.caption).foregroundStyle(.secondary).lineLimit(1) } + }.frame(maxWidth: .infinity, alignment: .leading) + .help(text).accessibilityElement(children: .combine).accessibilityIdentifier("cmoc.status." + identifier) + } + private var toolbar: some View { + HStack(spacing: 8) { + Button { model.newProject() } label: { Label("New", systemImage: "doc.badge.plus") } + Button { model.openProject() } label: { Label("Open", systemImage: "folder") } + Button { model.save() } label: { Label("Save All", systemImage: "square.and.arrow.down") } + .disabled(model.project == nil || !model.unsaved).keyboardShortcut("s", modifiers: [.command]) + Divider().frame(height: 22) + Picker("Configuration", selection: $model.configurationName) { + ForEach(model.project?.configuration.configurations ?? [], id: \.name) { Text($0.name).tag($0.name) } + }.labelsHidden().frame(width: 100).disabled(model.building).accessibilityLabel("Build configuration") + Button { model.build() } label: { Label("Build", systemImage: "hammer") } + .disabled(model.project == nil || model.building).accessibilityIdentifier("cmoc.build") + Menu { + Button("Rebuild", systemImage: "arrow.clockwise") { model.build(.rebuild) } + Button("Clean", systemImage: "trash") { model.build(.clean) } + Button("Build Disk", systemImage: "externaldrive") { model.build(.disk) } + .disabled(model.project?.configuration.diskTarget == nil) + Divider() + Button("Show Build Products", systemImage: "folder") { model.revealBuild() }.disabled(model.artifact == nil) + Button("Edit Makefile", systemImage: "doc.text") { if let project = model.project { model.openFile(project.configuration.makefile) } } + Button("Reload File from Disk", systemImage: "arrow.clockwise") { model.reloadSelected() } + Button("Save Selected Copy…", systemImage: "square.and.arrow.up") { model.saveSelectedCopy() } + .disabled(model.documents.isEmpty).accessibilityIdentifier("cmoc.saveCopy") + } label: { Image(systemName: "ellipsis.circle") }.menuStyle(.borderlessButton).frame(width: 28) + .disabled(model.project == nil || model.building).help("Show build and file actions").accessibilityLabel("Build and file actions") + if model.building { ProgressView().controlSize(.small); Button { model.cancelBuild() } label: { Image(systemName: "xmark.circle.fill") }.help("Cancel Build").accessibilityLabel("Cancel Build") } + Spacer(minLength: 0) + Button { model.launch() } label: { Label(model.project?.configuration.launchMode == .disk ? "Launch Disk" : "Run", systemImage: "play.fill") } + .disabled(!model.canLaunch).accessibilityIdentifier("cmoc.launch") + }.controlSize(.regular).disabled(model.commanding) + } + private var navigator: some View { + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 4) { + navigationMode("Files", symbol: "folder") + Button { + model.navigationPane = "Search"; searchFocused = true + } label: { Image(systemName: "magnifyingglass").frame(maxWidth: .infinity).contentShape(Rectangle()) } + .buttonStyle(.plain).padding(.vertical, 7) + .background(model.navigationPane == "Search" ? Color.accentColor.opacity(0.16) : .clear, in: RoundedRectangle(cornerRadius: 5)) + .help("Find in Project (⇧⌘F)").accessibilityLabel("Find in Project").accessibilityIdentifier("cmoc.navigation.search") + navigationMode("Outline", symbol: "list.bullet.indent") + navigationMode("Definitions", symbol: "arrow.turn.down.right") + }.padding(.horizontal, 8).padding(.vertical, 5) + Divider() + switch model.navigationPane { + case "Search": projectSearch + case "Outline": symbolOutline + case "Definitions": definitionResults + default: projectFiles + } + }.background(.background) + } + private func navigationMode(_ title: String, symbol: String) -> some View { + let lowercasedTitle: String = title.lowercased() + let highlight: Color = model.navigationPane == title ? Color.accentColor.opacity(0.16) : Color.clear + let helpText: String = "Show " + lowercasedTitle + " in the project navigator" + let accessibilityTitle: String = title + " navigator" + let identifier: String = "cmoc.navigation." + lowercasedTitle + return Button { model.navigationPane = title } label: { Image(systemName: symbol).frame(maxWidth: .infinity).contentShape(Rectangle()) } + .buttonStyle(.plain).padding(.vertical, 7) + .background(highlight, in: RoundedRectangle(cornerRadius: 5)) + .help(helpText).accessibilityLabel(accessibilityTitle) + .accessibilityIdentifier(identifier) + } + private var navigationBar: some View { + HStack(spacing: 8) { + SourceFindButton(finder: finder) + Button { model.navigateBack() } label: { Image(systemName: "chevron.left") } + .disabled(!model.canNavigateBack).keyboardShortcut("[", modifiers: .command) + .help("Back (⌘[)").accessibilityLabel("Back to Previous Location").accessibilityIdentifier("cmoc.navigation.back") + Button { model.navigateForward() } label: { Image(systemName: "chevron.right") } + .disabled(!model.canNavigateForward).keyboardShortcut("]", modifiers: .command) + .help("Forward (⌘])").accessibilityLabel("Forward to Next Location").accessibilityIdentifier("cmoc.navigation.forward") + Button { model.goToDefinition() } label: { Label("Go to Definition", systemImage: "arrow.turn.down.right") } + .disabled(model.project == nil).keyboardShortcut("j", modifiers: [.command, .control]) + .help("Find definitions or declarations for the identifier at the insertion point (⌃⌘J). Ambiguous matches are listed for review.") + .accessibilityIdentifier("cmoc.navigation.definition") + Button { model.requestCompletion() } label: { Label("Complete", systemImage: "text.cursor") } + .disabled(model.project == nil || model.selectedFileIsGenerated || model.projectIndex == nil) + .help("Complete a C identifier (Control-Space). Inserts a name only; arrows select, Return accepts and Escape dismisses.") + .accessibilityIdentifier("cmoc.completion.request") + Menu { + ForEach(CMOCEditorAction.allCases, id: \.self) { action in + Button(action.rawValue) { model.requestEditorAction(action) } + .disabled(action != .match && model.selectedFileIsGenerated) + .accessibilityIdentifier("cmoc.edit." + action.rawValue) + } + } label: { Label("Edit", systemImage: "text.alignleft") } + .disabled(!["c", "h"].contains((model.selectedFile as NSString).pathExtension.lowercased())) + .help("Indent: Control-]; Outdent: Control-[; Comment: Command-/; Matching bracket: Control-M") + .accessibilityIdentifier("cmoc.edit.menu") + if model.selectedFileIsGenerated { + Image(systemName: "lock").foregroundStyle(.secondary) + .help("Read-only header or generated build source").accessibilityLabel("Read-only source") + } + Spacer(minLength: 4) + if model.indexing { ProgressView().controlSize(.mini).accessibilityLabel("Indexing project") } + Text(model.indexMessage).font(.caption).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle) + .help(model.indexMessage).accessibilityIdentifier("cmoc.navigation.status") + if !model.indexNotes.isEmpty { + Menu { + ForEach(model.indexNotes, id: \.self) { Text($0) } + } label: { Image(systemName: "info.circle") } + .menuStyle(.borderlessButton).fixedSize() + .help("Show source navigation notes") + .accessibilityLabel("Source navigation notes") + .accessibilityIdentifier("cmoc.navigation.notes") + } + Button { model.refreshProjectIndex() } label: { Image(systemName: "arrow.clockwise") } + .disabled(model.project == nil || model.indexing).help("Refresh Project Index") + .accessibilityLabel("Refresh Project Index").accessibilityIdentifier("cmoc.navigation.refresh") + }.controlSize(.small).padding(.horizontal, 10).padding(.vertical, 6).background(.bar) + } + private var sourceAssistanceBar: some View { + HStack(alignment: .top, spacing: 8) { + Button { model.refreshParameterHints() } label: { Image(systemName: "function") } + .buttonStyle(.plain).help("Show parameter hints for the call at the insertion point (Control-Shift-Space)") + .accessibilityLabel("Show Parameter Hints").accessibilityIdentifier("cmoc.parameters.request") + if let hint = model.parameterHints.first(where: { $0.id == selectedHintID }) ?? model.parameterHints.first { + VStack(alignment: .leading, spacing: 3) { + Text(hint.signature).font(.system(.caption, design: .monospaced)).lineLimit(1).truncationMode(.middle) + .textSelection(.enabled).help(hint.signature + "\n" + hint.sourcePath) + .accessibilityIdentifier("cmoc.parameters.signature") + Text(parameterDescription(hint)).font(.caption.weight(.medium)).foregroundStyle(.tint) + .lineLimit(1).help(parameterDescription(hint)).accessibilityIdentifier("cmoc.parameters.active") + } + Spacer(minLength: 2) + if hint.conditional { Image(systemName: "questionmark.circle").foregroundStyle(.secondary).help("Source-based candidate; declaration or build settings may be uncertain.") } + if model.parameterHints.count > 1 { + Menu { + ForEach(model.parameterHints) { candidate in + Button(candidate.signature + " — " + candidate.sourcePath) { selectedHintID = candidate.id } + } + } label: { Text("\(model.parameterHints.count) candidates") } + .fixedSize().accessibilityLabel("Parameter hint candidates").accessibilityIdentifier("cmoc.parameters.candidates") + } + } else { + Text(model.completionMessage.isEmpty ? "Parameter hints appear inside function calls. Complete inserts identifier names." : model.completionMessage) + .font(.caption).foregroundStyle(.secondary).lineLimit(2) + .accessibilityIdentifier("cmoc.completion.status") + Spacer(minLength: 2) + } + }.frame(height: 34, alignment: .top).padding(.horizontal, 10).padding(.vertical, 6).background(.bar) + } + private func parameterDescription(_ hint: CMOCCompletion.ParameterHint) -> String { + guard !hint.parameters.isEmpty else { return "No parameters" } + let active = hint.activeParameter + if hint.parameters.indices.contains(active) { return "Argument \(active + 1): \(hint.parameters[active])" } + if hint.parameters.last == "..." { return "Argument \(active + 1): variadic value (…)" } + return "Argument \(active + 1): beyond this declaration’s parameter list" + } + private var projectSearch: some View { + VStack(alignment: .leading, spacing: 0) { + TextField("Find in Project", text: $model.searchQuery) + .textFieldStyle(.roundedBorder).focused($searchFocused) + .accessibilityIdentifier("cmoc.search.query").padding(.horizontal, 9).padding(.top, 9) + Toggle("Match case", isOn: $model.searchCaseSensitive) + .toggleStyle(.checkbox).font(.caption).padding(9).accessibilityIdentifier("cmoc.search.case") + if !model.searchQuery.isEmpty { + Text("\(model.searchMatches.count) match\(model.searchMatches.count == 1 ? "" : "es")\(model.searchTruncated ? " · showing first results" : "")") + .font(.caption).foregroundStyle(.secondary).padding(.horizontal, 10).padding(.bottom, 6) + } + if model.searchQuery.isEmpty { + navigationEmpty("Search project text", detail: "Includes unsaved editor changes. Search is literal; regular expressions are not used.", symbol: "magnifyingglass") + } else if model.searchMatches.isEmpty && !model.indexing { + navigationEmpty("No matches", detail: "Try another word or turn off Match case.", symbol: "magnifyingglass") + } else { + List(model.searchMatches) { match in + Button { model.openSearchMatch(match) } label: { + VStack(alignment: .leading, spacing: 3) { + Text("\(match.path):\(match.line)").font(.caption.weight(.medium)).lineLimit(2).truncationMode(.middle) + Text(match.preview).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary).lineLimit(2) + }.padding(.vertical, 3).frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()) + }.buttonStyle(.plain).help("\(match.path):\(match.line):\(match.column)") + .accessibilityLabel("Search match in \(match.path), line \(match.line), \(match.preview)") + .accessibilityIdentifier("cmoc.search.result.\(match.id)") + }.listStyle(.sidebar).accessibilityLabel("Project search results") + } + } + } + private var symbolOutline: some View { + VStack(alignment: .leading, spacing: 0) { + Text(URL(fileURLWithPath: model.selectedFile).lastPathComponent).font(.caption.weight(.semibold)) + .lineLimit(1).truncationMode(.middle).padding(10).help(model.selectedFile) + if model.currentOutline.isEmpty { + navigationEmpty("No C symbols", detail: "Functions, global declarations, types and macros appear here for the current C source or header.", symbol: "list.bullet.indent") + } else { + List(model.currentOutline) { symbol in navigationSymbol(symbol, showPath: false) } + .listStyle(.sidebar).accessibilityLabel("Current file symbols") + } + } + } + private var definitionResults: some View { + VStack(alignment: .leading, spacing: 0) { + Text(model.definitionName.isEmpty ? "DEFINITIONS" : model.definitionName) + .font(.caption.weight(.semibold)).lineLimit(2).padding(10) + Text("Source-based candidates, not compiler-verified bindings. Conditional or duplicate declarations may need your choice.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, 10).padding(.bottom, 8) + if model.definitionCandidates.isEmpty { + navigationEmpty(model.definitionName.isEmpty ? "Choose an identifier" : "No definition found", detail: model.definitionName.isEmpty ? "Place the insertion point on a C identifier and choose Go to Definition." : "No candidate is available in the indexed source. Macros and custom build settings can limit source-based lookup.", symbol: "arrow.turn.down.right") + } else { + List(model.definitionCandidates) { symbol in navigationSymbol(symbol, showPath: true) } + .listStyle(.sidebar).accessibilityLabel("Definition candidates") + } + } + } + private func navigationEmpty(_ title: String, detail: String, symbol: String) -> some View { + VStack(alignment: .leading, spacing: 7) { + Label(title, systemImage: symbol).font(.callout.weight(.medium)) + Text(detail).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 0) + }.padding(12).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + } + private func navigationSymbol(_ symbol: CMOCProjectIndex.Symbol, showPath: Bool) -> some View { + Button { model.openSymbol(symbol) } label: { + VStack(alignment: .leading, spacing: 3) { + HStack(alignment: .firstTextBaseline, spacing: 6) { + Image(systemName: symbolIcon(symbol.kind.rawValue)).foregroundStyle(.secondary) + Text(symbol.name).font(.system(.callout, design: .monospaced)).lineLimit(1).truncationMode(.middle) + Spacer(minLength: 0) + Text("\(symbol.line)").font(.caption.monospacedDigit()).foregroundStyle(.secondary) + } + Text(showPath ? symbol.path : symbol.kind.rawValue.capitalized) + .font(.caption).foregroundStyle(.secondary).lineLimit(2).truncationMode(.middle) + if symbol.conditional { Label("Conditional candidate", systemImage: "questionmark.circle").font(.caption2).foregroundStyle(.secondary) } + if !symbol.isDefinition { Text("Declaration").font(.caption2).foregroundStyle(.secondary) } + }.padding(.vertical, 3).frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()) + }.buttonStyle(.plain).help(symbol.signature + "\n\(symbol.path):\(symbol.line):\(symbol.column)") + .accessibilityLabel("\(symbol.name), \(symbol.kind.rawValue), \(symbol.path), line \(symbol.line)" + (symbol.conditional ? ", conditional" : "")) + .accessibilityIdentifier("cmoc.symbol.\(symbol.id)") + } + private func symbolIcon(_ kind: String) -> String { + switch kind.lowercased() { + case "function": return "function" + case "macro": return "number" + case "struct", "union", "type", "typedef": return "square.stack.3d.up" + case "enum", "enumerator": return "list.number" + default: return "shippingbox" + } + } + private var projectFiles: some View { + VStack(alignment: .leading, spacing: 0) { + HStack { Text("PROJECT").font(.caption.bold()).foregroundStyle(.secondary); Spacer(); Button { model.addFile() } label: { Image(systemName: "doc.badge.plus") }.buttonStyle(.plain).help("New Project File").accessibilityLabel("New Project File").disabled(model.project == nil || model.commanding || model.building) }.padding(12) + List { + OutlineGroup(CMOCNavigatorNode.tree(model.files), children: \.children) { node in + if let file = node.file { + Button { + if file.isEditable { model.openFile(file.relativePath) } + } label: { + HStack(spacing: 7) { + Image(systemName: symbol(file.relativePath)).foregroundStyle(.secondary).frame(width: 16) + Text(node.name).lineLimit(1).truncationMode(.middle) + Spacer(minLength: 0) + if model.documents.first(where: { $0.id == file.relativePath })?.dirty == true { Circle().fill(.secondary).frame(width: 6, height: 6).accessibilityLabel("Unsaved changes") } + }.padding(.vertical, 3).contentShape(Rectangle()) + }.buttonStyle(.plain).disabled(!file.isEditable) + .listRowBackground(model.selectedFile == file.relativePath ? Color.accentColor.opacity(0.14) : Color.clear) + .accessibilityLabel("Open " + file.relativePath).help(file.relativePath) + } else { + Label(node.name, systemImage: "folder").foregroundStyle(.secondary).help(node.id) + } + } + }.listStyle(.sidebar).accessibilityLabel("Project files") + if !model.breakpoints.isEmpty { + Divider() + Text("BREAKPOINTS").font(.caption.bold()).foregroundStyle(.secondary).padding(12) + ScrollView { + VStack(alignment: .leading, spacing: 8) { + ForEach(model.breakpoints.sorted { ($0.file, $0.line) < ($1.file, $1.line) }, id: \.self) { point in + Button { model.openFile(point.file, line: point.line); model.breakpointLine = point.line } label: { + Label("\(point.file):\(point.line)", systemImage: "stop.circle.fill").lineLimit(1) + }.buttonStyle(.plain).foregroundStyle(model.projectMapping?.addresses(file: point.file, line: point.line).isEmpty == false ? Color.accentColor : Color.secondary) + } + }.padding(.horizontal, 12).padding(.bottom, 12) + }.frame(maxHeight: 130) + } + }.background(.background) + } + private func symbol(_ path: String) -> String { + switch URL(fileURLWithPath: path).pathExtension.lowercased() { + case "c", "h": return "curlybraces" + case "dsk": return "externaldrive" + case "png", "jpg": return "photo" + default: return path.hasSuffix("Makefile") ? "hammer" : "doc.text" + } + } + private var tabs: some View { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 0) { + ForEach(model.documents) { doc in + HStack(spacing: 8) { + Button { model.openFile(doc.id) } label: { + HStack(spacing: 5) { + if doc.missing || doc.conflict { + Image(systemName: doc.missing ? "doc.badge.ellipsis" : "exclamationmark.triangle") + .foregroundStyle(.orange).accessibilityLabel(doc.missing ? "File missing" : "Changed outside the editor") + } + Text(URL(fileURLWithPath: doc.id).lastPathComponent + (doc.dirty ? " •" : "")).lineLimit(1) + } + }.buttonStyle(.plain).help(doc.id) + Button { model.closeFile(doc.id) } label: { Image(systemName: "xmark").font(.caption2) }.buttonStyle(.plain).help("Close " + doc.id).accessibilityLabel("Close " + doc.id) + }.padding(.horizontal, 12).padding(.vertical, 9) + .background(model.selectedFile == doc.id ? Color.accentColor.opacity(0.1) : Color.clear) + Divider().frame(height: 22) + } + } + }.background(.bar) + } + private var output: some View { + VStack(alignment: .leading, spacing: 0) { + HStack { + Picker("Development inspector", selection: $outputTab) { + Text("Build Log").tag("Build Log") + Text("Issues (\(model.diagnostics.count))").tag("Issues") + Text("Call Stack").tag("Call Stack") + Text("Variables").tag("Variables") + Text("Watches").tag("Watches") + }.pickerStyle(.segmented).labelsHidden().frame(maxWidth: 540).accessibilityIdentifier("cmoc.inspector") + Spacer() + }.padding(7) + if outputTab == "Build Log" { + HStack { + Spacer() + TextField("Make target…", text: $model.customTarget).frame(width: 140).accessibilityLabel("Custom Make target") + Button("Build Target") { model.build(.custom, target: model.customTarget) }.disabled(model.customTarget.isEmpty || model.project == nil || model.building || model.commanding) + }.padding(.horizontal, 7).padding(.bottom, 7) + } + Divider() + if outputTab == "Variables" || outputTab == "Watches" { + if let stack = model.callStack, !stack.frames.isEmpty { + HStack { + Picker("Inspect frame", selection: Binding(get: { model.selectedFrameIndex }, set: model.selectFrame)) { + ForEach(stack.frames) { frame in + Text("\(frame.id): \(frame.functionName)").tag(frame.id) + } + }.accessibilityIdentifier("cmoc.frame.picker") + if model.inspectingCaller { Text("Caller values").foregroundStyle(.secondary) } + }.font(.caption).padding(.horizontal, 10).padding(.top, 6) + } + } + if outputTab == "Watches" { + HStack { + TextField("Expression, e.g. score or player.x", text: $model.watchExpression) + .textFieldStyle(.roundedBorder).onSubmit { model.addWatch() }.accessibilityIdentifier("cmoc.watch.expression") + .help("Read-only names, fields, array indexes and pointers. Arithmetic uses checked 64-bit watch integers, not target C overflow rules. Stored floating-point values can be inspected; floating-point arithmetic, calls, assignments and casts are unavailable.") + Button { model.addWatch() } label: { Label("Add Watch", systemImage: "plus") } + .disabled(model.watchExpression.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || model.watches.count >= 32) + .accessibilityIdentifier("cmoc.watch.add") + }.padding(.horizontal, 10).padding(.vertical, 6) + } + ScrollView { + if outputTab == "Call Stack" { + callStackInspector + } else if outputTab == "Variables" || outputTab == "Watches" { + variableInspector + } else if outputTab == "Issues" { + LazyVStack(alignment: .leading, spacing: 6) { + ForEach(model.diagnostics) { issue in + Button { model.openFile(issue.file, line: issue.line) } label: { + Label("\(issue.file):\(issue.line): \(issue.message)", systemImage: "exclamationmark.circle").multilineTextAlignment(.leading).frame(maxWidth: .infinity, alignment: .leading) + }.buttonStyle(.plain).padding(.vertical, 3) + } + if model.diagnostics.isEmpty { Text("No compiler issues.").foregroundStyle(.secondary) } + }.padding(10) + } else { + Text(model.log).font(.system(.caption, design: .monospaced)).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).padding(10) + } + } + }.background(.background) + } + private var callStackInspector: some View { + VStack(alignment: .leading, spacing: 8) { + if let stack = model.callStack { + Text("Select a frame to view its source, then use Variables or Watches to inspect it. Stepping always controls frame 0.") + .font(.caption).foregroundStyle(.secondary) + ForEach(stack.frames) { frame in + Button { model.selectFrame(frame.id) } label: { + HStack(spacing: 10) { + Text("\(frame.id)").monospacedDigit().foregroundStyle(.secondary).frame(width: 22) + Image(systemName: frame.id == 0 ? "pause.circle" : "arrow.turn.up.left").foregroundStyle(.secondary) + Text(frame.functionName).fontWeight(.medium) + Spacer(minLength: 4) + Text(frame.sourcePath + (frame.sourceLine.map { ":\($0)" } ?? "")) + .foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle) + Image(systemName: frame.id == model.selectedFrameIndex ? "checkmark.circle.fill" : "circle") + .foregroundStyle(frame.id == model.selectedFrameIndex ? Color.accentColor : Color.secondary) + }.padding(7).contentShape(Rectangle()) + .background(frame.id == model.selectedFrameIndex ? Color.accentColor.opacity(0.1) : Color.clear) + .clipShape(RoundedRectangle(cornerRadius: 5)) + }.buttonStyle(.plain).accessibilityIdentifier("cmoc.frame.\(frame.id)") + .accessibilityLabel("Frame \(frame.id), \(frame.functionName), \(frame.sourcePath), line \(frame.sourceLine ?? 0)") + .accessibilityValue(frame.id == model.selectedFrameIndex ? "Selected" : "") + } + Text(stack.termination).font(.caption).foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("cmoc.stack.boundary") + } else { + Text(model.inspectionMessage).font(.caption).foregroundStyle(.secondary) + } + }.padding(10).frame(maxWidth: .infinity, alignment: .leading) + } + private var variableInspector: some View { + let listing = model.variableTree(watches: outputTab == "Watches", expanded: expandedVariables, + offsets: variableOffsets, rootOffset: variableRootOffset) + return VStack(alignment: .leading, spacing: 8) { + HStack(alignment: .top) { + Text(model.inspectionMessage).font(.caption).foregroundStyle(.secondary) + .accessibilityIdentifier("cmoc.variables.status") + Spacer(minLength: 4) + if !expandedVariables.isEmpty { + Button("Collapse All", systemImage: "chevron.up.chevron.down") { expandedVariables.removeAll() } + .buttonStyle(.borderless).accessibilityIdentifier("cmoc.tree.collapse") + } + } + if listing.rootCount > 32 { + HStack { + Button("Previous Variables", systemImage: "chevron.left") { changeRootPage(max(0, listing.rootOffset - 32)) } + .disabled(listing.rootOffset == 0) + Text("\(listing.rootOffset + 1)–\(min(listing.rootOffset + 32, listing.rootCount)) of \(listing.rootCount)") + Button("Next Variables", systemImage: "chevron.right") { changeRootPage(listing.rootOffset + 32) } + .disabled(listing.rootOffset + 32 >= listing.rootCount) + }.buttonStyle(.borderless) + } + ForEach(listing.rows) { row in treeRow(row) } + if model.canInspectC && listing.rootCount == 0 { + Text(outputTab == "Watches" ? "Add a read-only C expression to follow it between stops." : "No C variables in this scope.") + .foregroundStyle(.secondary) + } + if !model.canInspectC && outputTab == "Watches" { + ForEach(model.watches, id: \.self) { expression in + HStack { + variableRow(name: expression, type: "", value: "Unavailable", error: nil) + removeWatchButton(expression) + } + } + } + }.font(.system(.caption, design: .monospaced)).padding(10).frame(maxWidth: .infinity, alignment: .leading) + } + private func changeRootPage(_ offset: Int) { + variableRootOffset = offset; expandedVariables.removeAll(); variableOffsets.removeAll() + } + @ViewBuilder private func treeRow(_ row: CMOCVariableTreeRow) -> some View { + switch row.content { + case .node(let node): + HStack(alignment: .top, spacing: 5) { + if node.childCount > 0 { + let action = (expandedVariables.contains(node.path) ? "Collapse " : "Expand ") + treePathLabel(node.path) + Button { + if expandedVariables.contains(node.path) { expandedVariables.remove(node.path) } + else { expandedVariables.insert(node.path) } + } label: { + Image(systemName: expandedVariables.contains(node.path) ? "chevron.down" : "chevron.right") + .frame(width: 16, height: 18).contentShape(Rectangle()) + }.buttonStyle(.plain) + .help(action).accessibilityLabel(action) + .accessibilityIdentifier("cmoc.tree.expand." + treePathLabel(node.path)) + .accessibilityValue(expandedVariables.contains(node.path) ? "Expanded" : "Collapsed") + } else { Color.clear.frame(width: 16, height: 1).accessibilityHidden(true) } + variableRow(name: node.name, type: node.typeName, value: node.value, error: node.error) + .help(node.address.map { String(format: "Storage: $%04X", $0) } ?? "") + if node.path.components.isEmpty, case .watch(let expression) = node.path.root { + removeWatchButton(expression) + } + }.padding(.leading, CGFloat(min(row.depth, 6)) * 12) + case .page(let path, let offset, let total, let next): + HStack { + Button("Previous", systemImage: "chevron.left") { variableOffsets[path] = max(0, offset - 32) } + .disabled(offset == 0).accessibilityLabel("Previous children of " + treePathLabel(path)) + Text("\(offset + 1)–\(min(offset + 32, total)) of \(total)").foregroundStyle(.secondary) + Button("Next", systemImage: "chevron.right") { if let next { variableOffsets[path] = next } } + .disabled(next == nil).accessibilityLabel("Next children of " + treePathLabel(path)) + .accessibilityIdentifier("cmoc.tree.next." + treePathLabel(path)) + }.buttonStyle(.borderless).padding(.leading, CGFloat(min(row.depth, 6)) * 12 + 21) + case .message(let text): + Text(text).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + .padding(.leading, CGFloat(min(row.depth, 6)) * 12) + } + } + private func removeWatchButton(_ expression: String) -> some View { + Button { + model.removeWatch(expression) + expandedVariables = expandedVariables.filter { $0.root != .watch(expression) } + variableOffsets = variableOffsets.filter { $0.key.root != .watch(expression) } + } label: { Image(systemName: "minus.circle") } + .buttonStyle(.plain).help("Remove watch " + expression).accessibilityLabel("Remove watch " + expression) + } + private func treePathLabel(_ path: CMOCWatchEvaluator.TreePath) -> String { + let root: String + switch path.root { case .variable(let name), .watch(let name): root = name } + return root + path.components.map { + switch $0 { case .index(let index): return "[\(index)]"; case .member(let name): return "." + name; case .pointee: return ".Pointee" } + }.joined() + } + private func variableRow(name: String, type: String, value: String, error: String?) -> some View { + VStack(alignment: .leading, spacing: 3) { + HStack(alignment: .firstTextBaseline, spacing: 12) { + Text(name).fontWeight(.medium).frame(minWidth: 90, alignment: .leading) + Text(type).foregroundStyle(.secondary) + Spacer(minLength: 4) + Text(value).foregroundStyle(error == nil ? Color.primary : Color.secondary) + }.textSelection(.enabled) + if let error { Text(error).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) } + }.accessibilityElement(children: .combine) + } + private var breakpointAction: String { + let verb = model.selectedBreakpoints.contains(model.breakpointLine) ? "Remove" : "Set" + return "\(verb) breakpoint on line \(model.breakpointLine)" + } + private var debugBar: some View { + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 8) { + Picker("Source breakpoint", selection: $model.breakpointLine) { + if model.executableLines.isEmpty { Text("Build for source lines").tag(model.breakpointLine) } + else { ForEach(model.executableLines, id: \.self) { Text("Line \($0)").tag($0) } } + }.frame(width: 220).disabled(!model.buildMatchesEditor || model.executableLines.isEmpty).accessibilityIdentifier("cmoc.breakpoint") + Button { model.toggleBreakpoint(model.breakpointLine) } label: { Image(systemName: model.selectedBreakpoints.contains(model.breakpointLine) ? "minus.circle" : "plus.circle") }.disabled(model.project == nil).help(breakpointAction).accessibilityLabel(breakpointAction) + Button { model.confirmRun() } label: { Label("Run to Breakpoint", systemImage: "play.fill") }.disabled(!model.canRun).accessibilityIdentifier("cmoc.run") + Spacer(minLength: 0) + Button { model.toggleExecution() } label: { Label(model.machine.state == .running ? "Pause" : "Continue", systemImage: model.machine.state == .running ? "pause.fill" : "play") }.disabled(!model.canCommand) + } + HStack(spacing: 10) { + Label("C Step", systemImage: "curlybraces").foregroundStyle(.secondary) + Button { model.stepSource(.over) } label: { Label("Over", systemImage: "arrow.turn.down.right") } + .help("Execute the current C line in frame 0, stepping over called functions. Selecting a caller does not change execution.").accessibilityIdentifier("cmoc.step.over") + .disabled(!model.canStepC) + Button { model.stepSource(.into) } label: { Label("Into", systemImage: "arrow.down.to.line") } + .help("Stop at the next mapped C line, entering a called function when source is available.").accessibilityIdentifier("cmoc.step.into") + .disabled(!model.canStepC) + Button { model.stepSource(.out) } label: { Label("Out", systemImage: "arrow.up.to.line") } + .help("Finish this function and stop at its return address. Unmapped callers remain available in the assembly debugger.").accessibilityIdentifier("cmoc.step.out") + .disabled(!model.canStepC) + Spacer(minLength: 0) + Button { model.stepInstruction() } label: { Label("Instruction", systemImage: "arrow.right.to.line") } + .disabled(!model.canCommand || model.machine.state != .paused).help("Execute one CPU instruction.") + } + }.controlSize(.small) + } +} + +private struct CMOCBuildHistoryView: View { + @ObservedObject var model: CMOCDevelopmentModel + @Environment(\.dismiss) private var dismiss + @State private var selected: Set = [] + private var eligible: Set { Set(model.buildHistory.filter { $0.protectionReason == nil }.map(\.id)) } + var body: some View { + VStack(alignment: .leading, spacing: 0) { + HStack { + Label("Build History", systemImage: "clock.arrow.circlepath").font(.title2.bold()) + Spacer() + if model.historyBusy { ProgressView().controlSize(.small).accessibilityLabel("Reading build history") } + Button("Refresh", systemImage: "arrow.clockwise") { model.refreshBuildHistory() } + .disabled(model.historyBusy).accessibilityIdentifier("cmoc.history.refresh") + }.padding(18) + Text("Completed builds for this project. The latest result, loaded programs and changed files are protected. Removing a build moves it to the Trash; development disks stay in their own folder.") + .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, 18).padding(.bottom, 12) + if let message = model.historyMessage { + Text(message).font(.callout).foregroundStyle(.orange).textSelection(.enabled) + .padding(.horizontal, 18).padding(.bottom, 10).accessibilityIdentifier("cmoc.history.message") + } + Divider() + ScrollView { + if model.buildHistory.isEmpty { + VStack(spacing: 8) { + Image(systemName: "hammer").font(.largeTitle).foregroundStyle(.secondary) + Text(model.project == nil ? "Open a project to review its builds" : "No completed builds recorded yet").font(.headline) + Text("Builds made before history was added remain untouched.").foregroundStyle(.secondary) + }.frame(maxWidth: .infinity).padding(35) + } else { + LazyVStack(alignment: .leading, spacing: 0) { + ForEach(model.buildHistory) { entry in + historyRow(entry) + Divider().padding(.leading, 38) + } + }.padding(.horizontal, 18) + } + }.frame(maxWidth: .infinity, maxHeight: .infinity) + Divider() + HStack(spacing: 10) { + Button("Development Disks", systemImage: "externaldrive") { model.revealDevelopmentDisks() } + .accessibilityIdentifier("cmoc.history.disks") + Spacer() + Button("Move Selected to Trash…", systemImage: "trash") { + model.trashBuilds(selected.intersection(eligible)); selected.removeAll() + }.disabled(selected.intersection(eligible).isEmpty || model.historyBusy || model.building || model.commanding) + .accessibilityIdentifier("cmoc.history.trash") + Button("Done") { dismiss() }.keyboardShortcut(.defaultAction) + }.padding(18) + }.frame(width: 690, height: 470) + .onAppear { model.refreshBuildHistory() } + .onChange(of: model.buildHistory.map(\.id)) { _, _ in selected.formIntersection(eligible) } + } + private func historyRow(_ entry: CMOCBuildHistory.Entry) -> some View { + let latestID = model.artifact?.id ?? model.buildHistory.first(where: { $0.hasBinary || $0.hasDisk })?.id + let isLatest = entry.id == latestID + let isLaunched = entry.id == model.launchedBuildID + return HStack(alignment: .top, spacing: 10) { + Toggle("Build from " + entry.createdAt.formatted(date: .abbreviated, time: .shortened), isOn: Binding( + get: { selected.contains(entry.id) }, + set: { if $0 { selected.insert(entry.id) } else { selected.remove(entry.id) } })) + .toggleStyle(.checkbox).labelsHidden().disabled(entry.protectionReason != nil || model.historyBusy) + .help(entry.protectionReason ?? (selected.contains(entry.id) ? "Deselect this build for cleanup" : "Select this build for cleanup")) + .accessibilityIdentifier("cmoc.history.select.\(entry.id)") + VStack(alignment: .leading, spacing: 5) { + HStack { + Text(entry.createdAt.formatted(date: .abbreviated, time: .shortened)).fontWeight(.medium) + Spacer() + Text(ByteCountFormatter.string(fromByteCount: entry.byteCount, countStyle: .file)).foregroundStyle(.secondary) + } + HStack(spacing: 10) { + Text(entry.configurationName + " · " + entry.action.capitalized) + Text(entry.id.uuidString.prefix(8)).font(.system(.caption, design: .monospaced)) + if entry.hasBinary { Label("Program", systemImage: "curlybraces") } + if entry.hasDisk { Label("Disk", systemImage: "externaldrive") } + }.font(.caption).foregroundStyle(.secondary) + if isLatest || isLaunched { + HStack(spacing: 10) { + if isLatest { Label("Latest build", systemImage: "checkmark.seal") } + if isLaunched { Label("Launched in CoCo", systemImage: "desktopcomputer") } + }.font(.caption).foregroundStyle(.tint) + } + if let reason = entry.protectionReason, + reason != "Protected build or assigned media" || (!isLatest && !isLaunched) { + Label(reason, systemImage: "lock").font(.caption).foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + Button { NSWorkspace.shared.activateFileViewerSelecting([entry.directory]) } label: { Image(systemName: "folder") } + .buttonStyle(.borderless).help("Show Build in Finder").accessibilityLabel("Show build from " + entry.createdAt.formatted(date: .abbreviated, time: .shortened) + " in Finder") + }.padding(.vertical, 12) + } +} + +private struct CMOCRecoveryView: View { + @ObservedObject var model: CMOCDevelopmentModel + @Environment(\.dismiss) private var dismiss + var body: some View { + VStack(alignment: .leading, spacing: 0) { + HStack { + Label("Editor Recovery", systemImage: "doc.badge.clock").font(.title2.bold()) + Spacer() + if model.recoveryBusy { ProgressView().controlSize(.small).accessibilityLabel("Reading recovery copies") } + Button("Refresh", systemImage: "arrow.clockwise") { model.refreshRecovery() } + .disabled(model.recoveryBusy).accessibilityIdentifier("cmoc.recovery.refresh") + }.padding(18) + Text("Unsaved editor text is kept separately from project files. Restore a copy into the editor, or export it to a folder for safekeeping. Files on disk are never silently replaced.") + .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, 18).padding(.bottom, 12) + if let message = model.message { + Label(message, systemImage: "info.circle").font(.callout).textSelection(.enabled).lineLimit(3) + .padding(.horizontal, 18).padding(.bottom, 10).accessibilityIdentifier("cmoc.recovery.message") + } + Divider() + ScrollView { + VStack(alignment: .leading, spacing: 12) { + ForEach(Array(model.recoveryIssues.enumerated()), id: \.offset) { _, issue in + Label(issue, systemImage: "exclamationmark.triangle").foregroundStyle(.orange).font(.callout) + .textSelection(.enabled).fixedSize(horizontal: false, vertical: true) + } + if model.recoveryRecords.isEmpty { + VStack(spacing: 8) { + Image(systemName: "checkmark.shield").font(.largeTitle).foregroundStyle(.secondary) + Text("No recovery copies to review").font(.headline) + Text("Current edits are saved automatically. Copies from earlier sessions appear here.").foregroundStyle(.secondary) + }.frame(maxWidth: .infinity).padding(.vertical, 25) + } + ForEach(model.recoveryRecords) { record in + recoveryRow(record) + Divider() + } + }.padding(18) + }.frame(maxWidth: .infinity, maxHeight: .infinity) + Divider() + HStack { + Text("Copies from another running app can be exported; close that app before restoring or discarding them.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 20) + Button("Done") { dismiss() }.keyboardShortcut(.defaultAction) + }.padding(18) + }.frame(width: 690, height: 470) + .onAppear { model.persistDrafts(); model.refreshRecovery() } + } + private func recoveryRow(_ record: CMOCWorkspaceRecovery.Record) -> some View { + VStack(alignment: .leading, spacing: 7) { + HStack { + Text(record.modifiedAt.formatted(date: .abbreviated, time: .shortened)).fontWeight(.medium) + Spacer() + Text("\(record.drafts.count) file\(record.drafts.count == 1 ? "" : "s")").foregroundStyle(.secondary) + } + Text(record.drafts.prefix(4).map(\.path).joined(separator: ", ") + (record.drafts.count > 4 ? "…" : "")) + .font(.caption).foregroundStyle(.secondary).lineLimit(2).textSelection(.enabled) + HStack(spacing: 10) { + if record.isFromRunningSession { + Label("Open in another app session", systemImage: "lock").font(.caption).foregroundStyle(.secondary) + } + Spacer(minLength: 0) + Button("Export…", systemImage: "square.and.arrow.up") { model.exportRecovery(record) } + .disabled(model.recoveryBusy).accessibilityIdentifier("cmoc.recovery.export.\(record.id)") + Button("Restore", systemImage: "arrow.uturn.backward") { model.restoreRecovery(record) } + .disabled(record.isFromRunningSession || model.recoveryBusy || model.building || model.commanding) + .accessibilityIdentifier("cmoc.recovery.restore.\(record.id)") + Button { model.discardRecovery(record) } label: { Image(systemName: "trash") } + .disabled(record.isFromRunningSession || model.recoveryBusy) + .help("Discard Recovery Copy").accessibilityLabel("Discard recovery copy from " + record.modifiedAt.formatted(date: .abbreviated, time: .shortened)) + }.controlSize(.small) + }.padding(.vertical, 4) + } +} + +/// A stable native text view; machine polling never replaces its contents, +/// selection, undo stack or first responder. Highlighting changes attributes only. +struct CSourceEditor: NSViewRepresentable { + var finder: SourceFind? = nil + @Binding var text: String + let currentLine: Int? + var file = "main.c" + var readOnly = false + var breakpoints: Set = [] + var breakpointControlsEnabled = true + var navigationLine: Int? = nil + var navigationColumn: Int? = nil + var navigationLength = 0 + var navigationRequest = UUID() + var toggleBreakpoint: (Int) -> Void = { _ in } + var cursorChanged: (Int) -> Void = { _ in } + var goToDefinition: () -> Void = {} + var completionIndex: CMOCProjectIndex? + var completionRequest = UUID() + var completionStatus: (String) -> Void = { _ in } + var parameterHints: () -> Void = {} + var clearParameterHints: () -> Void = {} + var editorAction: CMOCEditorAction = .indent + var editorActionRequest = UUID() + var attach: (String, NSTextView, Coordinator) -> Void = { _, _, _ in } + func makeCoordinator() -> Coordinator { Coordinator(self) } + func makeNSView(context: Context) -> NSScrollView { + let scroll = NSScrollView(); scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = true; scroll.borderType = .bezelBorder + let editor = context.coordinator.makeEditor(file: file, text: text) + scroll.documentView = editor + scroll.verticalRulerView = CLineRuler(scrollView: scroll, orientation: .verticalRuler) + scroll.hasVerticalRuler = true; scroll.rulersVisible = true + context.coordinator.activeFile = file + context.coordinator.highlight(editor, line: currentLine) + updateNSView(scroll, context: context) + return scroll + } + static func dismantleNSView(_ scroll: NSScrollView, coordinator: Coordinator) { + for editor in coordinator.editors.values { (editor as? CMOCCompletionTextView)?.invalidateCompletion() } + } + func updateNSView(_ scroll: NSScrollView, context: Context) { + context.coordinator.parent = self + let coordinator = context.coordinator + let changedFile = coordinator.activeFile != file + if changedFile { + (scroll.documentView as? CMOCCompletionTextView)?.invalidateCompletion() + let hadFocus = (scroll.window?.firstResponder as? NSTextView) === scroll.documentView + let editor = coordinator.editors[file] ?? coordinator.makeEditor(file: file, text: text) + scroll.documentView = editor + scroll.verticalRulerView?.clientView = editor + coordinator.activeFile = file + coordinator.line = nil + if hadFocus { scroll.window?.makeFirstResponder(editor) } + } + guard let editor = scroll.documentView as? NSTextView else { return } + finder?.editor = editor + attach(file, editor, coordinator) + editor.setAccessibilityLabel("C source editor, " + file) + if readOnly { (editor as? CMOCCompletionTextView)?.invalidateCompletion() } + editor.isEditable = !readOnly + (editor as? CMOCEditingTextView)?.sourceEditingEnabled = ["c", "h"].contains((file as NSString).pathExtension.lowercased()) + if !editor.string.utf8.elementsEqual(text.utf8) { + (editor as? CMOCCompletionTextView)?.invalidateCompletion() + editor.string = text; editor.undoManager?.removeAllActions() + coordinator.highlight(editor, line: currentLine) + } else if coordinator.line != currentLine { coordinator.highlight(editor, line: currentLine) } + if let ruler = scroll.verticalRulerView as? CLineRuler { + ruler.points = breakpoints; ruler.active = breakpointControlsEnabled; ruler.onClick = toggleBreakpoint + if changedFile { ruler.invalidateMarkers() } + } + if coordinator.navigationRequest != navigationRequest { + coordinator.navigationRequest = navigationRequest + if let navigationLine { coordinator.navigate(editor, to: navigationLine, column: navigationColumn ?? 1, length: navigationLength) } + } + if coordinator.completionRequest != completionRequest { + coordinator.completionRequest = completionRequest + let request = completionRequest, requestedFile = file + Task { @MainActor [weak editor, weak coordinator] in + guard let editor, let coordinator, coordinator.parent.completionRequest == request, + coordinator.activeFile == requestedFile, editor === coordinator.editors[requestedFile], editor.isEditable else { return } + editor.window?.makeFirstResponder(editor) + coordinator.parent.completionStatus("Finding completions…") + editor.complete(nil) + } + } + if coordinator.editorActionRequest != editorActionRequest { + coordinator.editorActionRequest = editorActionRequest + let request = editorActionRequest, requestedFile = file, action = editorAction + Task { @MainActor [weak editor, weak coordinator] in + guard let editor = editor as? CMOCEditingTextView, let coordinator, + coordinator.parent.editorActionRequest == request, coordinator.activeFile == requestedFile, + editor === coordinator.editors[requestedFile] else { return } + editor.window?.makeFirstResponder(editor); editor.performSourceAction(action) + } + } + if changedFile { coordinator.reportCursor(editor) } + } + @MainActor final class Coordinator: NSObject, NSTextViewDelegate { + var parent: CSourceEditor + var line: Int? + var activeFile = "" + var editors: [String: NSTextView] = [:] + var undoManagers: [ObjectIdentifier: UndoManager] = [:] + private var suspendedUndo: [String: (UndoManager, NSRange)] = [:] + private var updatingReviewedBuffers = false + /// Per-tab typing history belongs to the preceding text. Keep it while + /// the panel owns grouped Undo, then reattach it only on exact rollback. + func setReviewedBuffers(_ changes: [MCPCMOCEdit], undoing: Bool) { + if !undoing { suspendedUndo.removeAll() } + updatingReviewedBuffers = true + defer { updatingReviewedBuffers = false } + for change in changes { + guard let editor = editors[change.path], editor.string.utf8.elementsEqual(change.before.utf8) else { continue } + let key = ObjectIdentifier(editor) + editor.breakUndoCoalescing() + if !undoing, let manager = undoManagers[key] { + suspendedUndo[change.path] = (manager, editor.selectedRange()) + } + undoManagers[key] = UndoManager() + (editor as? CMOCCompletionTextView)?.invalidateCompletion() + editor.string = change.after + highlight(editor, line: nil) + if undoing, let (manager, selection) = suspendedUndo.removeValue(forKey: change.path) { + undoManagers[key] = manager + editor.setSelectedRange(selection) + } + } + } + func undoManager(for view: NSTextView) -> UndoManager? { undoManagers[ObjectIdentifier(view)] } + var navigationRequest: UUID? + var completionRequest: UUID + var editorActionRequest: UUID + init(_ parent: CSourceEditor) { + self.parent = parent; completionRequest = parent.completionRequest; editorActionRequest = parent.editorActionRequest + } + func makeEditor(file: String, text: String) -> NSTextView { + let editor = CNavigationTextView(frame: .zero) + editor.definitionAction = { [weak self, weak editor] in + guard let self, let editor, self.activeFile == file else { return } + self.parent.cursorChanged(editor.selectedRange().location) + self.parent.goToDefinition() + } + editor.completionProvider = { [weak self, weak editor] text, offset in + guard let self, let editor, self.activeFile == file, self.parent.file == file, + editor === self.editors[file], !self.parent.readOnly, let index = self.parent.completionIndex else { return [] } + return CMOCCompletion.suggestions(index: index, path: file, text: text, offset: offset) + } + editor.completionStatus = { [weak self] message in self?.parent.completionStatus(message) } + editor.assistanceFocusLost = { [weak self, weak editor] in + Task { @MainActor [weak self, weak editor] in + guard let self, let editor, self.activeFile == file, + editor.window?.firstResponder !== editor else { return } + self.parent.clearParameterHints() + } + } + editor.parameterHintAction = { [weak self, weak editor] in + guard let self, let editor, self.activeFile == file else { return } + self.parent.cursorChanged(editor.selectedRange().location); self.parent.parameterHints() + } + undoManagers[ObjectIdentifier(editor)] = UndoManager() + editor.isRichText = false; editor.allowsUndo = true; editor.isAutomaticQuoteSubstitutionEnabled = false + editor.isAutomaticDashSubstitutionEnabled = false; editor.isAutomaticTextReplacementEnabled = false + editor.isAutomaticSpellingCorrectionEnabled = false; editor.isContinuousSpellCheckingEnabled = false + editor.font = .monospacedSystemFont(ofSize: 13, weight: .regular) + editor.textContainerInset = NSSize(width: 12, height: 10) + editor.isVerticallyResizable = true; editor.isHorizontallyResizable = true + editor.minSize = NSSize(width: 0, height: 0); editor.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) + editor.textContainer?.containerSize = editor.maxSize; editor.textContainer?.widthTracksTextView = false + editor.autoresizingMask = [.width]; editor.string = text; editor.delegate = self + editor.setAccessibilityLabel("C source editor, " + file); editor.setAccessibilityIdentifier("cmoc.source") + editors[file] = editor + highlight(editor, line: nil) + return editor + } + func navigate(_ editor: NSTextView, to line: Int, column: Int, length: Int) { + (editor as? CMOCCompletionTextView)?.invalidateCompletion() + let lines = (editor.string as NSString).components(separatedBy: "\n") + guard line > 0, line <= lines.count else { return } + let lineLength = (lines[line - 1] as NSString).length + let within = min(max(0, column - 1), lineLength) + let offset = lines.prefix(line - 1).reduce(0) { $0 + ($1 as NSString).length + 1 } + within + let range = NSRange(location: offset, length: min(max(0, length), lineLength - within)) + editor.setSelectedRange(range) + // Include the start of the line so short declarations do not open + // with their return type hidden by horizontal scrolling. + editor.scrollRangeToVisible(NSRange(location: offset - within, length: within + range.length)) + editor.scrollRangeToVisible(range) + editor.window?.makeFirstResponder(editor) + } + func textViewDidChangeSelection(_ notification: Notification) { + guard let editor = notification.object as? NSTextView, editor === editors[activeFile] else { return } + (editor as? CMOCEditingTextView)?.refreshBracketHighlight() + reportCursor(editor) + } + func reportCursor(_ editor: NSTextView) { + let file = activeFile, offset = editor.selectedRange().location + // NSTextView can notify while SwiftUI is updating its view. Publish + // after that update, and discard callbacks from a tab left behind. + Task { @MainActor [weak self, weak editor] in + guard let self, let editor, self.activeFile == file, self.parent.file == file, + editor === self.editors[file], editor.selectedRange().location == offset else { return } + if editor.hasMarkedText() || editor.selectedRange().length > 0 { self.parent.clearParameterHints() } + else { self.parent.cursorChanged(offset) } + } + } + func textDidChange(_ notification: Notification) { + guard !updatingReviewedBuffers, let editor = notification.object as? NSTextView, editor === editors[activeFile] else { return } + (editor as? CMOCCompletionTextView)?.invalidateCompletion() + parent.text = editor.string; highlight(editor, line: nil) + (editor as? CMOCEditingTextView)?.refreshBracketHighlight() + } + func highlight(_ editor: NSTextView, line: Int?) { + self.line = line + guard let storage = editor.textStorage else { return } + let full = NSRange(location: 0, length: storage.length) + storage.beginEditing() + storage.addAttributes([.foregroundColor: NSColor.textColor, .font: NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)], range: full) + storage.removeAttribute(.backgroundColor, range: full) + let patterns: [(String, NSColor)] = [ + (#"\b(?:int|char|void|unsigned|signed|long|short|const|volatile|struct|enum|typedef|return|if|else|while|for|do|switch|case|break|continue|sizeof|asm|__asm)\b"#, .systemPurple), + (#"(?m)^\s*#.*$"#, .systemOrange), + (#"\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'"#, .systemRed), + (#"(?m)//[^\n]*|/\*[\s\S]*?\*/"#, .secondaryLabelColor) + ] + for (pattern, color) in patterns { + guard let regex = try? NSRegularExpression(pattern: pattern) else { continue } + for match in regex.matches(in: editor.string, range: full) { storage.addAttribute(.foregroundColor, value: color, range: match.range) } + } + if let line, line > 0 { + let lines = (editor.string as NSString).components(separatedBy: "\n") + if line <= lines.count { + let start = lines.prefix(line - 1).reduce(0) { $0 + ($1 as NSString).length + 1 } + let range = NSRange(location: start, length: (lines[line - 1] as NSString).length) + storage.addAttribute(.backgroundColor, value: NSColor.systemYellow.withAlphaComponent(0.25), range: range) + if !editor.hasMarkedText() { editor.scrollRangeToVisible(range) } + } + } + storage.endEditing() + (editor.enclosingScrollView?.verticalRulerView as? CLineRuler)?.invalidateMarkers() + } + } +} + +/// The definition command uses the clicked C identifier and leaves AppKit's +/// standard editing actions intact. It is navigation only, including in headers. +private final class CNavigationTextView: CMOCEditingTextView { + var definitionAction: (() -> Void)? + @objc private func findDefinition(_ sender: Any?) { definitionAction?() } + @objc private func showParameterHints(_ sender: Any?) { parameterHintAction?() } + @objc private func completeIdentifier(_ sender: Any?) { + let selected = selectedRange() + if selected.length > 0 { setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) } + complete(sender) + } + override func performKeyEquivalent(with event: NSEvent) -> Bool { + let modifiers = event.modifierFlags.intersection([.command, .control, .option, .shift]) + if modifiers == [.command, .control], event.charactersIgnoringModifiers?.lowercased() == "j" { + definitionAction?(); return true + } + return super.performKeyEquivalent(with: event) + } + override func menu(for event: NSEvent) -> NSMenu? { + let location = characterIndexForInsertion(at: convert(event.locationInWindow, from: nil)) + let current = selectedRange() + if current.length == 0 || !NSLocationInRange(location, current) { + let text = string as NSString + func identifier(_ index: Int) -> Bool { + guard index >= 0, index < text.length else { return false } + let character = text.character(at: index) + return character == 95 || (65...90).contains(character) || (97...122).contains(character) || (48...57).contains(character) + } + var start = min(location, text.length), end = min(location, text.length) + if !identifier(start), identifier(start - 1) { start -= 1; end = start } + while identifier(start - 1) { start -= 1 } + while identifier(end) { end += 1 } + setSelectedRange(NSRange(location: start, length: end - start)) + } + let menu = super.menu(for: event) ?? NSMenu() + let identifier = NSUserInterfaceItemIdentifier("cmoc.editor.goToDefinition") + if let existing = menu.items.first(where: { $0.identifier == identifier }) { + existing.target = self; return menu + } + let item = NSMenuItem(title: "Go to Definition", action: #selector(findDefinition(_:)), keyEquivalent: "j") + item.target = self; item.identifier = identifier; item.keyEquivalentModifierMask = [.command, .control] + let completion = NSMenuItem(title: "Complete Identifier", action: #selector(completeIdentifier(_:)), keyEquivalent: " ") + completion.target = self; completion.keyEquivalentModifierMask = [.control]; completion.isEnabled = isEditable + let hints = NSMenuItem(title: "Show Parameter Hints", action: #selector(showParameterHints(_:)), keyEquivalent: " ") + hints.target = self; hints.keyEquivalentModifierMask = [.control, .shift] + let actions: [(String, Selector)] = [ + ("Indent", #selector(indentSource(_:))), ("Outdent", #selector(outdentSource(_:))), + ("Toggle Line Comment", #selector(toggleSourceComment(_:))), ("Go to Matching Bracket", #selector(matchSourceBracket(_:))) + ] + for (title, selector) in actions.reversed() { + let action = NSMenuItem(title: title, action: selector, keyEquivalent: "") + action.target = self; action.isEnabled = sourceEditingEnabled && (selector == #selector(matchSourceBracket(_:)) || isEditable) + menu.insertItem(action, at: 0) + } + menu.insertItem(.separator(), at: 0); menu.insertItem(hints, at: 0); menu.insertItem(completion, at: 0); menu.insertItem(item, at: 0) + return menu + } +} + +/// A focused project builder, not a graphical editor for every GNU Make feature. +private struct CMOCProjectSettingsView: View { + @ObservedObject var model: CMOCDevelopmentModel + @Environment(\.dismiss) private var dismiss + @State private var configuration = CMOCProjectConfiguration() + @State private var recipe = CMOCMakefileSettings() + @State private var managed = false + @State private var section = "Build" + @State private var error: String? + @State private var originalMakefile = "" + @State private var configHash: String? + private let sections = ["Build", "Sources", "Libraries", "Resources", "Disk & Run", "Preview"] + var body: some View { + VStack(spacing: 0) { + HStack { + Image(systemName: "slider.horizontal.3").font(.title2).foregroundStyle(.tint) + VStack(alignment: .leading) { Text("Project Settings").font(.title2.bold()); Text(model.project?.directory.lastPathComponent ?? "").foregroundStyle(.secondary) } + Spacer() + }.padding(20) + Picker("Settings section", selection: $section) { ForEach(sections, id: \.self) { Text($0).tag($0) } }.pickerStyle(.segmented).labelsHidden().padding(.horizontal, 20).padding(.bottom, 12) + Divider() + ScrollView { + VStack(alignment: .leading, spacing: 18) { + switch section { + case "Build": buildSettings + case "Sources": sourceSettings + case "Libraries": librarySettings + case "Resources": resourceSettings + case "Disk & Run": diskSettings + default: preview + } + }.padding(20).frame(maxWidth: .infinity, alignment: .leading) + } + if let error { Text(error).foregroundStyle(.red).textSelection(.enabled).padding(.horizontal, 20).padding(.vertical, 8) } + Divider() + HStack { + Text(managed ? "Generate an ordinary Makefile from these settings." : "Use your existing Makefile and configure its targets.").font(.caption).foregroundStyle(.secondary) + Spacer(); Button("Cancel", role: .cancel) { dismiss() } + Button(managed ? "Save & Generate" : "Save Settings") { apply() }.keyboardShortcut(.defaultAction) + }.padding(16) + }.frame(width: 760, height: 640) + .onAppear { + guard let project = model.project else { return } + configuration = project.configuration + recipe = configuration.makefileSettings ?? CMOCMakefileSettings() + if configuration.makefileSettings == nil { + recipe.sources = model.files.filter { $0.relativePath.hasSuffix(".c") }.map(\.relativePath) + recipe.executable = configuration.binary ?? "program.bin" + recipe.diskImage = configuration.diskImage + } + managed = configuration.makefileSettings != nil + originalMakefile = (try? project.readText(relativePath: configuration.makefile)) ?? "" + if let data = try? Data(contentsOf: project.directory.appendingPathComponent(CMOCProject.configurationFilename)) { configHash = CMOCProject.sha256(data) } + } + } + private var buildSettings: some View { + VStack(alignment: .leading, spacing: 16) { + Picker("Makefile management", selection: $managed) { Text("Generate from settings").tag(true); Text("Custom Makefile").tag(false) }.pickerStyle(.radioGroup) + Text("Generated projects cover C modules, libraries, generated resources and Disk BASIC disks. Custom Makefiles remain fully editable; VCC Plus does not attempt to interpret their rules.").font(.callout).foregroundStyle(.secondary) + Divider() + if managed { + LabeledContent("Executable") { TextField("program.bin", text: $recipe.executable) } + LabeledContent("Load address (hex)") { TextField("2800", text: $recipe.origin).frame(width: 140) } + LabeledContent("Highest load address (hex)") { TextField("Optional, e.g. 7F80", text: optional($recipe.limit)).frame(width: 180) } + LabeledContent("Stack bytes") { TextField("2048", value: $recipe.stackSpace, format: .number).frame(width: 140) } + Picker("Release optimization", selection: $recipe.releaseOptimization) { Text("None (−O0)").tag("-O0"); Text("Level 1").tag("-O1"); Text("Level 2").tag("-O2") } + Text("Debug builds disable optimization and retain intermediate files for verified source breakpoints.").font(.caption).foregroundStyle(.secondary) + } else { + LabeledContent("Build target") { TextField("Makefile default", text: $configuration.buildTarget) } + Text("Leave blank to let Make choose its default goal, including .DEFAULT_GOAL and included Makefiles. Set a target only to override it.").font(.caption).foregroundStyle(.secondary) + LabeledContent("Clean target") { TextField("clean", text: $configuration.cleanTarget) } + LabeledContent("Binary output") { TextField("program.bin", text: optional($configuration.binary)) } + } + Text("Build-support folders").font(.headline) + Text("Optional sibling folders copied beside the project for builds, one per line. For example ../tools. Include only folders this Makefile needs.").font(.caption).foregroundStyle(.secondary) + paths($configuration.buildSupportDirectories).frame(height: 65).accessibilityLabel("Build-support folders") + CMOCPlaytestMediaSettings(paths: $configuration.playtestDisks) + Stepper("Parallel jobs: \(configuration.jobs)", value: $configuration.jobs, in: 1...32) + Text("Project files stay portable. Builds run from an isolated copy, and opening settings never runs a command.").font(.caption).foregroundStyle(.secondary) + }.textFieldStyle(.roundedBorder) + } + private var sourceSettings: some View { + VStack(alignment: .leading, spacing: 12) { + Text("C source files").font(.headline) + Text("One project-relative path per line. Headers are tracked through compiler dependencies. Generated C files can be listed before they exist.").foregroundStyle(.secondary).font(.callout) + paths($recipe.sources).frame(height: 170).disabled(!managed) + Text("Include directories").font(.headline) + paths($recipe.includePaths).frame(height: 90).disabled(!managed) + LabeledContent("Initially opened file") { TextField("main.c", text: $configuration.entrySource) } + Text("Preprocessor definitions").font(.headline) + Text("One NAME or NAME=value per line. For example MAX_WORD_LEN=5 or DISPLAY_NAME=\"My Game\".").font(.caption).foregroundStyle(.secondary) + paths($recipe.defines).frame(height: 85).disabled(!managed) + DisclosureGroup("Additional compiler and linker options") { + VStack(alignment: .leading, spacing: 8) { + Text("Compiler options (one argument per line)").font(.caption) + paths($recipe.compilerOptions).frame(height: 70) + Text("Linker options (one argument per line)").font(.caption) + paths($recipe.linkerOptions).frame(height: 70) + } + }.disabled(!managed) + } + } + private var librarySettings: some View { + VStack(alignment: .leading, spacing: 14) { + if managed { generatedLibrarySettings; Divider() } + Group { + HStack { + Text("Bundled libraries").font(.headline) + Spacer() + Button("Add Library", systemImage: "plus") { + if let library = model.bundledLibraryCatalog.first(where: { item in !configuration.bundledLibraries.contains(where: { $0.library == item.id }) && item.available }) { + configuration.bundledLibraries.append(.init(library: library.id)) + } + }.accessibilityIdentifier("cmoc.library.add") + } + Text("Use selected libraries from this app without editing the Makefile. Map its library-directory variables, or append a library to its linker-flags variable. Copies stay in the isolated build folder.").font(.callout).foregroundStyle(.secondary) + ForEach(configuration.bundledLibraries.indices, id: \.self) { index in + VStack(alignment: .leading, spacing: 8) { + HStack { + Picker("Library", selection: $configuration.bundledLibraries[index].library) { + ForEach(model.bundledLibraryCatalog) { library in + Text("\(library.id) · \(library.version)\(library.available ? "" : " — unavailable")").tag(library.id) + } + if !model.bundledLibraryCatalog.contains(where: { $0.id == configuration.bundledLibraries[index].library }) { + Text(configuration.bundledLibraries[index].library + " — unavailable").tag(configuration.bundledLibraries[index].library) + } + } + Button { configuration.bundledLibraries.remove(at: index) } label: { Image(systemName: "minus.circle") } + .help("Remove library " + configuration.bundledLibraries[index].library).accessibilityLabel("Remove library " + configuration.bundledLibraries[index].library) + } + LabeledContent("Minimum version") { TextField("Optional", text: $configuration.bundledLibraries[index].minimumVersion).accessibilityLabel("Minimum version for " + configuration.bundledLibraries[index].library) } + LabeledContent("Directory variable") { TextField("For example: DECBFILE_LIB_DIR", text: $configuration.bundledLibraries[index].directoryVariable).accessibilityLabel("Directory variable for " + configuration.bundledLibraries[index].library) } + LabeledContent("Append to linker variable") { TextField("For example: LIBS (optional)", text: $configuration.bundledLibraries[index].linkVariable).accessibilityLabel("Linker variable for " + configuration.bundledLibraries[index].library) } + if let library = model.bundledLibraryCatalog.first(where: { $0.id == configuration.bundledLibraries[index].library }) { + Text(library.license).font(.caption).foregroundStyle(.secondary) + } + }.padding(12).background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 8)) + } + if configuration.bundledLibraries.isEmpty { Text("No bundled-library overrides. The Makefile controls its own dependencies.").foregroundStyle(.secondary) } + Text("Directory bindings provide headers and prebuilt archives, not a library Makefile. Linker additions preserve the Makefile’s existing flags and follow the order above. Leave either variable blank when it is not needed. Missing libraries and incompatible versions stop the build.").font(.caption).foregroundStyle(.secondary) + } + }.textFieldStyle(.roundedBorder) + } + private var generatedLibrarySettings: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Linked libraries").font(.headline) + Text("Names without the lib prefix or .a suffix; for example decbfile, bgraph, bsound or bcontrol. Use sdc to browse a CoCo SDC card or mount a disk image, bank for reserved CoCo 3 RAM, gime for double-buffered graphics, ssc for Speech/Sound, and orch90 for stereo. For joystick presses and releases, add input followed by bcontrol. Use vcccompat for TP-10 printer output and sequential cassette text files. For disk streams add decbfile after vcccompat, or add wydealloc after vcccompat for bounded allocation. Add dskcon-standalone after decbfile to use the optional standalone disk driver when included in your toolchain. It requires explicit initialization and interrupt handling; see its header and Licenses & Notices. Library order is preserved.").font(.callout).foregroundStyle(.secondary) + paths($recipe.libraries).frame(height: 80) + Text("Additional library directories").font(.headline) + paths($recipe.libraryPaths).frame(height: 60) + HStack { Text("Library subprojects").font(.headline); Spacer(); Button("Add", systemImage: "plus") { recipe.libraryProjects.append(.init()) } } + ForEach(recipe.libraryProjects.indices, id: \.self) { index in + VStack(alignment: .leading, spacing: 5) { + HStack { + TextField("Directory", text: $recipe.libraryProjects[index].directory) + TextField("Make target", text: $recipe.libraryProjects[index].target) + let directory = recipe.libraryProjects[index].directory + let action = directory.isEmpty ? "Remove library project" : "Remove library project " + directory + Button { recipe.libraryProjects.remove(at: index) } label: { Image(systemName: "minus.circle") } + .help(action).accessibilityLabel(action) + } + TextField("Archive path from project root", text: $recipe.libraryProjects[index].archive) + }.padding(8).background(.quaternary, in: RoundedRectangle(cornerRadius: 6)) + } + }.disabled(!managed).textFieldStyle(.roundedBorder) + } + private var resourceSettings: some View { + VStack(alignment: .leading, spacing: 14) { + HStack { Text("Generated resources").font(.headline); Spacer(); Button("Add Rule", systemImage: "plus") { recipe.generatedResources.append(.init()) } } + Text("Use a rule for dictionary data, fonts or generated C. Declare all inputs and outputs so Make can rebuild only when needed. Commands are shell recipes and execute only when you build.").font(.callout).foregroundStyle(.secondary) + ForEach(recipe.generatedResources.indices, id: \.self) { index in + VStack(alignment: .leading, spacing: 8) { + HStack { Text("Rule \(index + 1)").font(.headline); Spacer(); Button("Remove", systemImage: "minus.circle") { recipe.generatedResources.remove(at: index) } } + Text("Input files (one per line)").font(.caption); paths($recipe.generatedResources[index].inputs).frame(height: 55) + Text("Output files (one per line)").font(.caption); paths($recipe.generatedResources[index].outputs).frame(height: 55) + Text("Commands").font(.caption); TextEditor(text: $recipe.generatedResources[index].command).font(.system(.body, design: .monospaced)).frame(height: 85).border(.quaternary) + }.padding(10).background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 8)) + } + if recipe.generatedResources.isEmpty { Text("No generated resources configured.").foregroundStyle(.secondary) } + }.disabled(!managed) + } + private var diskSettings: some View { + VStack(alignment: .leading, spacing: 12) { + if managed { + LabeledContent("Disk image output") { TextField("game.dsk (optional)", text: optional($recipe.diskImage)) } + Text("Disk contents").font(.headline) + Text("The executable is added automatically. List other files here, one per line. Disk BASIC filenames must fit its 8.3 naming rules.").font(.callout).foregroundStyle(.secondary) + paths($recipe.diskFiles).frame(height: 100) + Picker("DOS boot", selection: $recipe.diskBootMode) { + Text("None").tag(CMOCDiskBootMode.none) + Text("Run this program").tag(CMOCDiskBootMode.program) + Text("Custom bootloader").tag(CMOCDiskBootMode.custom) + }.accessibilityIdentifier("cmoc.disk-boot-mode") + if recipe.diskBootMode == .custom { + LabeledContent("Bootloader binary") { TextField("autostart.bin", text: optional($recipe.diskBootLoader)) } + Text("Type DOS to start the custom bootloader.").font(.caption).foregroundStyle(.secondary) + } + let program = DevelopmentDiskProgram.binary((recipe.executable as NSString).lastPathComponent.uppercased()) + Text(program.instructions(dos: recipe.diskBootMode == .program)) + .font(.caption).foregroundStyle(.secondary) + } else { + LabeledContent("Disk target") { TextField("disk", text: optional($configuration.diskTarget)) } + LabeledContent("Disk image output") { TextField("game.dsk", text: optional($configuration.diskImage)) } + } + Divider() + Picker("Launch method", selection: $configuration.launchMode) { Text("Quickload executable").tag(CMOCLaunchMode.quickload); Text("Mount disk in FD0").tag(CMOCLaunchMode.disk) } + Text("Commands after mounting").font(.headline) + paths($configuration.launchCommands).frame(height: 90) + if managed && recipe.diskBootMode == .program && configuration.launchCommands != ["DOS"] { + Button("Use DOS after mounting", systemImage: "terminal") { configuration.launchCommands = ["DOS"] } + .help("Changes only the saved launch commands; nothing runs until you choose Launch Disk.") + } + Text("For example: LOADM\"GAME\":EXEC, or DOS for a bootable disk. Launch asks first; commands require the CoCo to be waiting at BASIC. Machine profiles and RAM are not changed automatically.").font(.caption).foregroundStyle(.secondary) + }.textFieldStyle(.roundedBorder) + } + private var preview: some View { + VStack(alignment: .leading, spacing: 12) { + Text(managed ? "Generated Makefile Preview" : "Current Makefile").font(.headline) + Text(managed ? ((try? recipe.generateMakefile(makefileName: configuration.makefile)) ?? "Complete the settings to preview the Makefile.") : originalMakefile) + .font(.system(.caption, design: .monospaced)).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) + } + } + private func optional(_ value: Binding) -> Binding { Binding(get: { value.wrappedValue ?? "" }, set: { value.wrappedValue = $0.isEmpty ? nil : $0 }) } + private func paths(_ value: Binding<[String]>) -> some View { + TextEditor(text: Binding(get: { value.wrappedValue.joined(separator: "\n") }, set: { value.wrappedValue = $0.components(separatedBy: "\n") })) + .font(.system(.body, design: .monospaced)).border(.quaternary) + } + private func apply() { + do { + func clean(_ list: [String]) -> [String] { list.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } } + recipe.sources = clean(recipe.sources); recipe.includePaths = clean(recipe.includePaths); recipe.libraries = clean(recipe.libraries) + recipe.libraryPaths = clean(recipe.libraryPaths); recipe.diskFiles = clean(recipe.diskFiles) + recipe.defines = clean(recipe.defines); recipe.compilerOptions = clean(recipe.compilerOptions); recipe.linkerOptions = clean(recipe.linkerOptions) + for i in recipe.generatedResources.indices { recipe.generatedResources[i].inputs = clean(recipe.generatedResources[i].inputs); recipe.generatedResources[i].outputs = clean(recipe.generatedResources[i].outputs) } + configuration.launchCommands = clean(configuration.launchCommands) + configuration.buildSupportDirectories = clean(configuration.buildSupportDirectories) + configuration.playtestDisks = clean(configuration.playtestDisks) + var makefile: String? + if managed { + makefile = try recipe.generateMakefile(makefileName: configuration.makefile) + configuration.makefileSettings = recipe; configuration.binary = recipe.executable + configuration.diskImage = recipe.diskImage; configuration.diskTarget = recipe.diskImage == nil ? nil : "disk" + configuration.buildTarget = recipe.diskImage == nil ? "build" : "disk"; configuration.cleanTarget = "clean" + configuration.configurations = [.init(name: "Debug"), .init(name: "Release", makeArguments: ["VCC_CONFIGURATION=Release"])] + if makefile != originalMakefile { + let alert = NSAlert(); alert.messageText = "Replace the project's Makefile?" + alert.informativeText = "The Preview tab shows the generated rules. Any custom rules in the current Makefile will be replaced; a backup is kept in the project’s .vccplus-build folder." + alert.addButton(withTitle: "Replace Makefile"); alert.addButton(withTitle: "Cancel") + guard alert.runModal() == .alertFirstButtonReturn else { return } + } + } else { configuration.makefileSettings = nil } + try model.applyProjectSettings(configuration, makefile: makefile, expectedMakefileHash: CMOCProject.sha256(Data(originalMakefile.utf8)), expectedConfigHash: configHash) + dismiss() + } catch { self.error = error.localizedDescription } + } +} + +private struct CMOCNavigatorNode: Identifiable { + let id: String + let name: String + let file: CMOCProjectFile? + let children: [CMOCNavigatorNode]? + static func tree(_ files: [CMOCProjectFile], prefix: String = "") -> [Self] { + let direct = files.filter { $0.relativePath.hasPrefix(prefix) } + let names = Set(direct.map { String($0.relativePath.dropFirst(prefix.count).split(separator: "/").first ?? "") }).sorted() + return names.compactMap { name in + guard !name.isEmpty else { return nil } + let path = prefix + name + if let file = direct.first(where: { $0.relativePath == path }) { return Self(id: path, name: name, file: file, children: nil) } + return Self(id: path, name: name, file: nil, children: tree(direct, prefix: path + "/")) + } + } +} + + +/// Shared by the native project form and its unshown layout regression fixture. +struct CMOCPlaytestMediaSettings: View { + @Binding var paths: [String] + var body: some View { + VStack(alignment: .leading, spacing: 8) { + Text("Additional playtest disk outputs").font(.headline) + Text("Optional project-relative .dsk or .os9 products, one per line (up to eight, 512 KB each). The Make recipe must build them. Reviewed assistant playtests can exchange private copies in FD0 while paused; the primary boot disk is listed separately.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + TextEditor(text: Binding(get: { paths.joined(separator: "\n") }, + set: { paths = $0.components(separatedBy: "\n") })) + .font(.system(.body, design: .monospaced)).frame(height: 65).border(.quaternary) + .accessibilityLabel("Additional playtest disk outputs") + } + } +} diff --git a/platforms/macos/App/CMOCEditing.swift b/platforms/macos/App/CMOCEditing.swift new file mode 100644 index 0000000..5c3ed79 --- /dev/null +++ b/platforms/macos/App/CMOCEditing.swift @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit + +enum CMOCEditorAction: String, CaseIterable { + case indent = "Indent", outdent = "Outdent", comment = "Toggle Line Comment", match = "Go to Matching Bracket" +} + +/// Small source edits, not a formatter. Coordinates and selections use UTF-16. +enum CMOCEditing { + struct Edit { let range: NSRange; let text: String; let selection: NSRange } + static func lineEdit(_ text: String, selection: NSRange, action: CMOCEditorAction) -> Edit? { + let source = text as NSString + guard selection.location <= source.length, selection.length <= source.length - selection.location, + text.utf8.count <= 1_048_576, action != .match else { return nil } + let first = source.lineRange(for: NSRange(location: selection.location, length: 0)).location + let last = selection.length == 0 ? selection.location : NSMaxRange(selection) - 1 + let end = NSMaxRange(source.lineRange(for: NSRange(location: last, length: 0))) + let range = NSRange(location: first, length: end - first) + let original = source.substring(with: range) as NSString + var lines: [(offset: Int, text: String)] = [], cursor = 0 + repeat { + let line = original.lineRange(for: NSRange(location: cursor, length: 0)) + lines.append((cursor, original.substring(with: line))) + cursor = NSMaxRange(line) + } while cursor < original.length + let uncomment = action == .comment && lines.filter { !$0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } + .allSatisfy { $0.text.trimmingCharacters(in: .whitespaces).hasPrefix("//") } + var output = "", caret = selection.location - first + for line in lines { + let units = Array(line.text.utf16) + let leading = units.prefix { $0 == 32 || $0 == 9 }.count + let blank = line.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + var at = 0, remove = 0, insert = "" + switch action { + case .indent: insert = " " + case .outdent: remove = units.first == 9 ? 1 : units.prefix { $0 == 32 }.prefix(4).count + case .comment: + if !blank { at = leading; if uncomment { + remove = 2 + ((leading + 2 < units.count && units[leading + 2] == 32) ? 1 : 0) + } else { insert = "// " } } + case .match: break + } + if selection.length == 0, line.offset + at <= selection.location - first { + caret += insert.utf16.count - min(remove, max(0, selection.location - first - line.offset - at)) + } + output += (line.text as NSString).replacingCharacters(in: NSRange(location: at, length: remove), with: insert) + } + guard output != original as String else { return nil } + let selected = selection.length == 0 ? NSRange(location: first + caret, length: 0) : NSRange(location: first, length: output.utf16.count) + return .init(range: range, text: output, selection: selected) + } + /// Pair only C code delimiters; literals, comments and directives are opaque. + static func bracketPairs(_ text: String) -> [Int: Int] { + guard text.utf8.count <= 1_048_576 else { return [:] } + let u = Array(text.utf16); var i = 0, stack: [(UInt16, Int)] = [], pairs: [Int: Int] = [:], lineStart = true + while i < u.count { + let c = u[i], next: UInt16 = i + 1 < u.count ? u[i + 1] : 0 + if c == 10 || c == 13 { lineStart = true; i += 1; continue } + if c == 32 || c == 9 { i += 1; continue } + if (lineStart && c == 35) || (c == 47 && next == 47) { + while i < u.count { + if u[i] == 10 { + let previous = i > 0 && u[i - 1] == 13 ? i - 2 : i - 1 + if previous < 0 || u[previous] != 92 { break } + } + i += 1 + }; continue + } + if c == 47 && next == 42 { + i += 2 + while i < u.count { + if u[i] == 42 && i + 1 < u.count && u[i + 1] == 47 { i += 2; break } + if u[i] == 10 { lineStart = true }; i += 1 + }; continue + } + lineStart = false + if c == 34 || c == 39 { + let quote = c; i += 1 + while i < u.count { + if u[i] == 92 { i += min(2, u.count - i); continue } + if u[i] == quote { i += 1; break }; i += 1 + }; continue + } + if [UInt16(40), 91, 123].contains(c) { + guard stack.count < 512 else { return [:] }; stack.append((c, i)) + } else if [UInt16(41), 93, 125].contains(c) { + let expected: UInt16 = c == 41 ? 40 : c == 93 ? 91 : 123 + if let top = stack.last, top.0 == expected { pairs[top.1] = i; pairs[i] = top.1; stack.removeLast() } + else { stack.removeAll() } + } + i += 1 + } + return pairs + } + static func newline(_ text: String, selection: NSRange) -> String { + let s = text as NSString + guard selection.location <= s.length else { return "\n" } + let range = s.lineRange(for: NSRange(location: selection.location, length: 0)) + let before = s.substring(with: NSRange(location: range.location, length: selection.location - range.location)) + let indent = String(before.prefix { $0 == " " || $0 == "\t" }) + let trimmed = before.trimmingCharacters(in: .whitespaces) + // A temporary closing brace lets the same lexer recognize an unmatched + // opening brace without mistaking a brace in a literal/comment for code. + let prefix = s.substring(to: selection.location).trimmingCharacters(in: .whitespaces) + let opensBlock = trimmed.hasSuffix("{") && bracketPairs(prefix + "}")[prefix.utf16.count] == prefix.utf16.count - 1 + let ending = text.contains("\r\n") ? "\r\n" : "\n" + return ending + indent + (opensBlock ? (indent.contains("\t") ? "\t" : " ") : "") + } +} + +class CMOCEditingTextView: CMOCCompletionTextView { + var sourceEditingEnabled = true + private var pairedText: String? + private var pairs: [Int: Int] = [:] + private var highlighted: [Int] = [] + func refreshBracketHighlight() { + guard let layoutManager else { return } + // Edits can shift old temporary ranges; clear this editor's bracket + // overlay before painting the new pair. Execution-line color lives in + // text storage and is unaffected. + layoutManager.removeTemporaryAttribute(.backgroundColor, forCharacterRange: NSRange(location: 0, length: (string as NSString).length)) + highlighted = [] + guard sourceEditingEnabled, !hasMarkedText(), selectedRange().length == 0 else { return } + if pairedText != string { pairedText = string; pairs = CMOCEditing.bracketPairs(string) } + let caret = selectedRange().location + guard let origin = pairs[caret] != nil ? caret : (caret > 0 && pairs[caret - 1] != nil ? caret - 1 : nil), let mate = pairs[origin] else { return } + highlighted = [origin, mate] + for offset in highlighted { + layoutManager.addTemporaryAttribute(.backgroundColor, value: NSColor.controlAccentColor.withAlphaComponent(0.3), forCharacterRange: NSRange(location: offset, length: 1)) + } + } + @objc func indentSource(_ sender: Any?) { performSourceAction(.indent) } + @objc func outdentSource(_ sender: Any?) { performSourceAction(.outdent) } + @objc func toggleSourceComment(_ sender: Any?) { performSourceAction(.comment) } + @objc func matchSourceBracket(_ sender: Any?) { performSourceAction(.match) } + func performSourceAction(_ action: CMOCEditorAction) { + guard sourceEditingEnabled, !hasMarkedText(), selectedRanges.count == 1 else { return } + invalidateCompletion() + if action == .match { + refreshBracketHighlight() + if highlighted.count == 2 { + let target = highlighted[1] + setSelectedRange(NSRange(location: target, length: 0)); scrollRangeToVisible(NSRange(location: target, length: 1)) + } else { completionStatus?("Place the insertion point beside a matched code bracket: ( ), [ ] or { }.") } + return + } + guard isEditable, let edit = CMOCEditing.lineEdit(string, selection: selectedRange(), action: action) else { return } + breakUndoCoalescing(); insertText(edit.text, replacementRange: edit.range) + setSelectedRange(edit.selection); breakUndoCoalescing(); undoManager?.setActionName(action.rawValue) + refreshBracketHighlight() + } + override func insertTab(_ sender: Any?) { + guard sourceEditingEnabled, isEditable, !hasMarkedText() else { super.insertTab(sender); return } + if selectedRange().length > 0 { performSourceAction(.indent) } + else { insertText(" ", replacementRange: selectedRange()) } + } + override func insertBacktab(_ sender: Any?) { + if sourceEditingEnabled { performSourceAction(.outdent) } else { super.insertBacktab(sender) } + } + override func insertNewline(_ sender: Any?) { + guard sourceEditingEnabled, isEditable, !hasMarkedText() else { super.insertNewline(sender); return } + let value = CMOCEditing.newline(string, selection: selectedRange()) + breakUndoCoalescing(); insertText(value, replacementRange: selectedRange()); breakUndoCoalescing() + } + override func performKeyEquivalent(with event: NSEvent) -> Bool { + guard sourceEditingEnabled else { return super.performKeyEquivalent(with: event) } + let flags = event.modifierFlags.intersection([.command, .control, .shift, .option]) + let key = event.charactersIgnoringModifiers + if flags == [.command], key == "/" { performSourceAction(.comment); return true } + if flags == [.control], key == "]" { performSourceAction(.indent); return true } + if flags == [.control], key == "[" { performSourceAction(.outdent); return true } + if flags == [.control], key?.lowercased() == "m" { performSourceAction(.match); return true } + return super.performKeyEquivalent(with: event) + } +} diff --git a/platforms/macos/App/CMOCIndexInputs.swift b/platforms/macos/App/CMOCIndexInputs.swift new file mode 100644 index 0000000..0b2e940 --- /dev/null +++ b/platforms/macos/App/CMOCIndexInputs.swift @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// Read-only inputs for browsing. Never invokes Make or a compiler to discover +/// flags, and never follows project links into unrelated folders. +struct CMOCIndexInputs: Sendable { + static let libraryPrefix = "@toolchain/include/" + static let maximumBytes = 16 * 1024 * 1024 + static let maximumFiles = 1024 + var documents: [String: String] = [:] + var referencePaths: Set = [] + var generatedPaths: Set = [] + var issues: [String] = [] + var defines: [String] = [] + var includePaths: [String] = [] + var configurationUncertain = true + + static func load(project: CMOCProject, toolchain: URL, configurationName: String, + overlays: [String: String], generated: [String: Data]) throws -> Self { + var result = Self(), total = 0 + func issue(_ message: String) { if result.issues.count < 16 { result.issues.append(message) } } + func accept(_ text: String, path: String) { + guard !text.contains("\0"), text.utf8.count <= CMOCProject.maximumSourceBytes else { + issue("Skipped oversized or non-text file: \(path)"); return + } + let oldSize = result.documents[path]?.utf8.count ?? 0 + guard (result.documents[path] != nil || result.documents.count < maximumFiles), + total - oldSize + text.utf8.count <= maximumBytes else { + issue("Index limited to \(maximumFiles) files and 16 MB of text."); return + } + total += text.utf8.count - oldSize; result.documents[path] = text + } + // An edited configuration is a browsing hint only, never a build command. + var configuration = project.configuration + if let text = overlays[CMOCProject.configurationFilename] ?? (try? project.readText(relativePath: CMOCProject.configurationFilename)) { + do { configuration = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: Data(text.utf8)).validated() } + catch { issue("Project settings contain errors; using the last accepted browsing settings.") } + } + let generatedOutputs = Set(configuration.makefileSettings?.generatedResources.flatMap(\.outputs) ?? []) + let root = try CMOCProject.physicalURL(project.directory) + var readError: Error? + let keys: Set = [.isRegularFileKey, .isSymbolicLinkKey, .isDirectoryKey, .fileSizeKey] + let excluded: Set = [".git", ".svn", ".build", ".vccplus-build", ".DS_Store"] + guard let enumerator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: Array(keys), + errorHandler: { _, error in readError = error; return false }) else { + throw CMOCBuildError.message("The project could not be read for navigation.") + } + var urls: [(String, URL)] = [] + var visited = 0 + while let url = enumerator.nextObject() as? URL { + try Task.checkCancellation(); visited += 1 + guard visited <= 20_000 else { issue("Project navigation stopped after 20,000 entries."); break } + if excluded.contains(url.lastPathComponent) { enumerator.skipDescendants(); continue } + let path = String(url.path.dropFirst(root.path.count + 1)) + if path.hasPrefix(libraryPrefix) { enumerator.skipDescendants(); issue("Reserved library-reference path omitted from project: \(path)"); continue } + let values = try url.resourceValues(forKeys: keys) + if values.isSymbolicLink == true { enumerator.skipDescendants(); issue("Linked file or folder omitted: \(path)"); continue } + if values.isDirectory == true { continue } + guard values.isRegularFile == true, CMOCProject.isEditable(path), !generatedOutputs.contains(path) else { continue } + guard let size = values.fileSize, size <= CMOCProject.maximumSourceBytes else { issue("Oversized text file omitted: \(path)"); continue } + urls.append((path, url)) + } + if let readError { issue("Some project files could not be read: " + readError.localizedDescription) } + for (path, _) in urls.sorted(by: { $0.0 < $1.0 }) { + try Task.checkCancellation() + if let overlay = overlays[path] { accept(overlay, path: path); continue } + do { accept(try project.readText(relativePath: path), path: path) } + catch { issue("Unreadable text file omitted: \(path)") } + if result.documents.count >= maximumFiles || total >= maximumBytes { issue("Project text limit reached; some files are not indexed."); break } + } + for (path, text) in overlays.sorted(by: { $0.key < $1.key }) { + try Task.checkCancellation() + guard !path.hasPrefix(libraryPrefix), CMOCProject.isEditable(path) else { continue } + _ = try project.fileURL(relativePath: path) + accept(text, path: path) + } + for (path, data) in generated.sorted(by: { $0.key < $1.key }) where result.documents[path] == nil && ["c", "h"].contains((path as NSString).pathExtension.lowercased()) { + try Task.checkCancellation() + try CMOCProject.validateRelativePath(path) + guard data.count <= CMOCProject.maximumSourceBytes, let text = String(data: data, encoding: .utf8) else { continue } + accept(text, path: path); if result.documents[path] != nil { result.generatedPaths.insert(path) } + } + if !result.generatedPaths.isEmpty { issue("Generated sources are read-only snapshots from the last successful build.") } + + if let recipe = configuration.makefileSettings { + result.includePaths = recipe.includePaths + result.defines = recipe.defines + // Trust flags only when the current Makefile exactly matches the + // generated recipe, and selected Make assignments cannot alter it. + let expected = try? recipe.generateMakefile(makefileName: configuration.makefile) + let current = result.documents[configuration.makefile] + let assignments = configuration.configurations.first(where: { $0.name == configurationName })?.makeArguments ?? [] + result.configurationUncertain = expected == nil || current != expected || assignments.contains { !$0.hasPrefix("VCC_CONFIGURATION=") } + var coco = true, unsignedChar = false, noRelocate = false + var floatingPointMacro: String? + var undefined: Set = [] + for option in recipe.compilerOptions { + if option.hasPrefix("-D"), option.count > 2 { result.defines.append(String(option.dropFirst(2))) } + else if option.hasPrefix("-I"), option.count > 2 { + let path = String(option.dropFirst(2)) + if (try? project.fileURL(relativePath: path)) != nil { result.includePaths.append(path) } + else { issue("External include path is not browsed: \(path)"); result.configurationUncertain = true } + } else if option == "-funsigned-char" { unsignedChar = true } + else if option == "-fsigned-char" { unsignedChar = false } + else if option == "--native-float" { floatingPointMacro = "_CMOC_NATIVE_FLOAT_=1" } + else if option == "--mc6839" { floatingPointMacro = "_CMOC_MC6839_=1" } + else if option == "--no-relocate" { noRelocate = true } + else if option.hasPrefix("-U"), option.count > 2 { undefined.insert(String(option.dropFirst(2))); result.configurationUncertain = true } + else if option == "--coco" { coco = true } + else if ["--os9", "--vectrex", "--dragon", "--usim", "--thommo", "--void-target"].contains(option) { coco = false; result.configurationUncertain = true } + else if !["-O0", "-O1", "-O2", "-fno-omit-frame-pointer", "--intermediate", "--deps"].contains(option) { result.configurationUncertain = true } + } + // CMOC resolves mode switches in argument order, then emits its + // builtin definitions before all user -D arguments. Preserve that + // order so explicit user values can override a builtin value. + var builtins: [String] = [] + if coco { builtins.append("_COCO_BASIC_=1") } + if unsignedChar { builtins.append("_CMOC_unsigned_char_=1") } + if noRelocate { builtins.append("_CMOC_NO_RELOCATE_=1") } + if let floatingPointMacro { builtins.append(floatingPointMacro) } + result.defines.insert(contentsOf: builtins, at: 0) + result.defines.removeAll { undefined.contains(String($0.prefix { $0 != "=" })) } + } + if result.configurationUncertain { issue("Custom Make flags are not evaluated; conditional definitions are browsing candidates, not compiler-verified bindings.") } + if let data = try? Data(contentsOf: toolchain.appendingPathComponent("manifest.json")), + let manifest = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let version = manifest["cmoc"] as? String { + let components = version.split(separator: ".").compactMap { Int($0) } + if components.count == 3 { result.defines.insert("_CMOC_VERSION_=\(components[0] * 1000000 + components[1] * 1000 + components[2])", at: 0) } + } + let undefined = Set((configuration.makefileSettings?.compilerOptions ?? []).filter { $0.hasPrefix("-U") && $0.count > 2 }.map { String($0.dropFirst(2)) }) + result.defines.removeAll { undefined.contains(String($0.prefix { $0 != "=" })) } + let requestedHeaders = toolchain.appendingPathComponent("share/cmoc/include") + if (try? requestedHeaders.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) == true { + issue("Linked library include folder is not browsed."); return result + } + guard let headers = try? CMOCProject.physicalURL(requestedHeaders) else { + issue("Bundled library headers are unavailable; project navigation remains available."); return result + } + let compatibility = configuration.makefileSettings?.libraries.contains("vcccompat") == true || + configuration.bundledLibraries.contains { $0.library == "vcccompat" } + if compatibility { result.includePaths.append("@toolchain/include/vcc/compat") } + result.includePaths.append("@toolchain/include") + if let libraryFiles = FileManager.default.enumerator(at: headers, includingPropertiesForKeys: Array(keys), errorHandler: { _, _ in false }) { + var count = 0 + while let url = libraryFiles.nextObject() as? URL { + try Task.checkCancellation(); count += 1 + guard count <= 4096 else { issue("Library header scan reached its limit."); break } + let values = try url.resourceValues(forKeys: keys) + if values.isSymbolicLink == true { libraryFiles.skipDescendants(); continue } + if !compatibility, url == headers.appendingPathComponent("vcc/compat", isDirectory: true) { + libraryFiles.skipDescendants(); continue + } + guard values.isRegularFile == true, url.pathExtension.lowercased() == "h" else { continue } + let path = libraryPrefix + String(url.path.dropFirst(headers.path.count + 1)) + guard (values.fileSize ?? Int.max) <= CMOCProject.maximumSourceBytes, + let text = try? CMOCProject.readText(url, maximumBytes: CMOCProject.maximumSourceBytes) else { issue("Library header omitted: \(path)"); continue } + accept(text, path: path) + if result.documents[path] != nil { result.referencePaths.insert(path) } + } + } else { issue("Bundled library headers are unavailable; project navigation remains available.") } + return result + } +} diff --git a/platforms/macos/App/CMOCOwnedCallContext.swift b/platforms/macos/App/CMOCOwnedCallContext.swift new file mode 100644 index 0000000..4019c3b --- /dev/null +++ b/platforms/macos/App/CMOCOwnedCallContext.swift @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// Read-only evidence from an owned, paused run. This deliberately has no caller +/// supplied memory address: the only newly disclosed storage is [S, S + 64). +enum CMOCOwnedCallContext { + static func capture(map: CMOCProjectSourceMap, metadata: CMOCVariableDebug?, + pc: UInt16, s: UInt16, u: UInt16, memory: Data, available: Data, + physicalPages: [Int: Int], sharedPaths: Set) -> [String: Any] { + func unavailable(_ reason: String) -> [String: Any] { + ["status": "unavailable", "reason": reason] + } + guard memory.count == 65536, available.count == 65536 else { + return unavailable("A complete immutable memory and availability snapshot is required.") + } + let start = Int(s), limit = start + 64 + guard limit <= 0xfe00 else { return unavailable("The actual S window crosses protected memory or wraps.") } + func ram(_ address: Int, _ count: Int) -> Bool { + guard address >= 0, count > 0, address <= 0xfe00 - count else { return false } + return (address / 8192...(address + count - 1) / 8192).allSatisfy { + physicalPages[$0].map { (0..<1024).contains($0) } == true + } + } + func readable(_ address: Int, _ count: Int) -> Bool { + ram(address, count) && available[address..<(address + count)].allSatisfy { $0 != 0 } + } + guard readable(start, 64) else { + return unavailable("Every byte of the actual S window must be available RAM with a physical mapping.") + } + let selected = map.projected(physicalPages: physicalPages, memory: memory, available: available) + guard selected.verifiesRuntime(memory: memory, available: available), readable(Int(pc), 1) else { + return unavailable("The current executable bytes or RAM mapping could not be verified.") + } + // Metadata must identify this same retained build. Use the supplied map's + // current bank projection, never a metadata object's stale projection. + let debug: CMOCVariableDebug? + if let metadata, + metadata.sourceMap.binarySHA256 == map.binarySHA256, + metadata.sourceMap.linkMapSHA256 == map.linkMapSHA256, + metadata.sourceMap.sourceHashes == map.sourceHashes, + metadata.sourceMap.objectHashes == map.objectHashes, + metadata.sourceMap.listingHashes == map.listingHashes { + debug = CMOCVariableDebug(functions: metadata.functions, variables: metadata.variables, + sourceMap: map).projected(physicalPages: physicalPages, memory: memory, available: available) + } else { debug = nil } + let function = debug?.entryFunction(containing: pc) + let instruction = selected.instruction(at: pc) + let mappedSource = instruction.map { + sharedPaths.contains($0.sourcePath) && !$0.bytes.isEmpty && readable(Int(pc), $0.bytes.count) && + Array(memory[Int(pc)..<(Int(pc) + $0.bytes.count)]) == $0.bytes + } == true + let functionSource = function.map { sharedPaths.contains($0.sourcePath) } == true + let executableSource = selected.executableLocation(at: pc, memory: memory, available: available, sharedPaths: sharedPaths) != nil + guard mappedSource || functionSource || executableSource else { + return unavailable("The current PC has no verified executable identity in shared source.") + } + + var spans: [[String: Any]] = [], cursor = start + while cursor < limit { + let end = min(limit, (cursor / 8192 + 1) * 8192) + spans.append(["logical_address": cursor, "physical_address": physicalPages[cursor / 8192]! * 8192 + cursor % 8192, + "count": end - cursor]) + cursor = end + } + let words = stride(from: 0, to: 64, by: 2).map { offset -> [String: Any] in + ["offset": offset, "address": start + offset, + "value": Int(memory[start + offset]) * 256 + Int(memory[start + offset + 1])] + } + var result: [String: Any] = [ + "status": "available", + "stack_window": ["address": start, "count": 64, "bytes": Array(memory[start.. Bool { + guard readable(address, bytes.count) else { return false } + let guards: [(Int, [UInt8])] + if let layout = selected.bankedLayout { + guard let moduleID, selected.activeModuleIDs?.contains(moduleID) == true, + let module = layout.module(id: moduleID) else { return false } + guards = module.codeGuards.map { (Int($0.address), $0.bytes) } + } else { + guard moduleID == nil else { return false } + guards = selected.flatCodeGuards.map { (Int($0.address), $0.bytes) } + } + return bytes.enumerated().allSatisfy { offset, byte in + let location = address + offset + return memory[location] == byte && guards.contains { begin, data in + location >= begin && location - begin < data.count && data[location - begin] == byte + } + } + } + func normal(_ f: CMOCVariableDebug.Function) -> Bool { + f.frame && f.entry >= 0 && f.body >= f.entry + 4 && f.body < f.end && f.end <= 0xfe00 - 4 && + guarded(f.entry, [0x34, 0x40, 0x33, 0xe4], moduleID: f.moduleID) && + guarded(f.end, [0x32, 0xc4, 0x35, 0xc0], moduleID: f.moduleID) + } + guard normal(function) else { return result } + let frameBase: Int, returnAddress: Int, phase: String + if Int(pc) == function.entry { + frameBase = start - 2 // U after the proven, as-yet unexecuted PSHS U. + returnAddress = start; phase = "function_entry" + } else if Int(pc) >= function.body, Int(pc) < function.end, mappedSource, + Int(u) >= start, Int(u) <= limit - 4 { + frameBase = Int(u); returnAddress = frameBase + 2; phase = "mapped_body" + } else { return result } + // Only these two bytes, already inside the raw window, identify a + // potential caller. Never search other stack words for return addresses. + let returnPC = Int(memory[returnAddress]) * 256 + Int(memory[returnAddress + 1]) + func target(_ i: CMOCProjectSourceMap.Instruction) -> Int? { + let b = i.bytes, address = Int(i.address) + switch b.count { + case 2 where b[0] == 0x8d: return (address + 2 + Int(Int8(bitPattern: b[1]))) & 0xffff + case 3 where b[0] == 0x17: + return (address + 3 + Int(Int16(bitPattern: UInt16(b[1]) << 8 | UInt16(b[2])))) & 0xffff + case 3 where b[0] == 0xbd: return Int(b[1]) * 256 + Int(b[2]) + case 3 where b[0] == 0xad && b[1] == 0x8c: + return (address + 3 + Int(Int8(bitPattern: b[2]))) & 0xffff + case 4 where b[0] == 0xad && b[1] == 0x8d: + return (address + 4 + Int(Int16(bitPattern: UInt16(b[2]) << 8 | UInt16(b[3])))) & 0xffff + default: return nil // Indirect, tail, interrupt and guessed calls are unsupported. + } + } + let calls = selected.instructions.filter { + Int($0.address) + $0.bytes.count == returnPC && target($0) == function.entry + } + guard calls.count == 1, let call = calls.first, sharedPaths.contains(call.sourcePath), + guarded(Int(call.address), call.bytes, moduleID: call.moduleID), + let caller = debug.entryFunction(containing: call.address), normal(caller), + sharedPaths.contains(caller.sourcePath), caller.moduleID == call.moduleID, + caller.name.utf8.count <= 1024, caller.sourcePath.utf8.count <= 4096, + Int(call.address) >= caller.body else { return result } + result["caller"] = ["status": "available", "function": caller.name, "source_path": caller.sourcePath, + "source_line": call.sourceLine, "call_address": Int(call.address), "return_address": returnPC, + "evidence": "unique_verified_direct_call", "callee_phase": phase] + + let parameters = debug.variables.filter { + $0.sourcePath == function.sourcePath && sharedPaths.contains($0.sourcePath) && + $0.moduleID == function.moduleID && ($0.scopeModuleID == nil || $0.scopeModuleID == function.moduleID) && + !$0.isStatic && $0.address == nil && $0.scope == (function.body..= 4 + }.sorted { ($0.offset ?? 0) < ($1.offset ?? 0) } + var items: [[String: Any]] = [], occupied = Set(), names = Set() + for (index, parameter) in parameters.prefix(32).enumerated() { + guard let offset = parameter.offset, offset <= 32767, + !parameter.name.isEmpty, parameter.name.utf8.count <= 1024, + parameters.filter({ $0.name == parameter.name }).count == 1, + names.insert(parameter.name).inserted else { continue } + let address = frameBase + offset, type = parameter.type + guard type.kind == "integer", [1, 2, 4].contains(type.size), type.name.utf8.count <= 1024, let signed = type.signed, + address >= start, address <= limit - type.size, + !parameters.enumerated().contains(where: { otherIndex, other in + guard otherIndex != index, let otherOffset = other.offset, + otherOffset <= 32767, other.type.size > 0, other.type.size <= 65536 else { return false } + return offset < otherOffset + other.type.size && otherOffset < offset + type.size + }), + (address..<(address + type.size)).allSatisfy({ !occupied.contains($0) }) else { continue } + var value: Int64 = 0 + for byte in memory[address..<(address + type.size)] { value = value * 256 + Int64(byte) } + if signed && memory[address] & 0x80 != 0 { value -= Int64(1) << (type.size * 8) } + occupied.formUnion(address..<(address + type.size)) + items.append(["name": parameter.name, "type": type.name, "address": address, "frame_offset": offset, + "byte_count": type.size, "value": value, "evidence": "compiler_location_and_normal_cmoc_abi"]) + } + result["arguments"] = ["status": items.isEmpty ? "unavailable" : "available", "items": items, + "reason": "Only compiler-located integer parameters wholly inside the actual S window are interpreted; other values remain unavailable.", + "all_recorded_parameters_available": !parameters.isEmpty && items.count == parameters.count, + "recorded_parameter_count": parameters.count] + return result + } +} diff --git a/platforms/macos/App/CMOCProjectIndex.swift b/platforms/macos/App/CMOCProjectIndex.swift new file mode 100644 index 0000000..8254302 --- /dev/null +++ b/platforms/macos/App/CMOCProjectIndex.swift @@ -0,0 +1,577 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// A bounded, non-executing lexical index. This is navigation assistance, not a +/// compiler AST: macro expansion, arbitrary Make recipes and expression types +/// are deliberately not guessed. Conditional candidates remain visibly marked. +struct CMOCProjectIndex: Sendable { + enum Kind: String, Sendable { case function = "Function", variable = "Variable", type = "Type", macro = "Macro", parameter = "Parameter", member = "Member", enumerator = "Enumerator" } + struct Symbol: Identifiable, Hashable, Sendable { + var id: String { "\(path):\(offsetUTF16):\(kind.rawValue)" } + let path: String + let name: String + let line: Int + let column: Int + let kind: Kind + let signature: String + let isDefinition: Bool + let isStatic: Bool + let conditional: Bool + let scope: String? + let offsetUTF16: Int + let lengthUTF16: Int + fileprivate let scopeStart: Int + fileprivate let scopeEnd: Int + } + struct Match: Identifiable, Hashable, Sendable { + var id: String { "\(path):\(offsetUTF16):\(lengthUTF16)" } + let path: String + let line: Int + let column: Int + let lengthUTF16: Int + let preview: String + let offsetUTF16: Int + } + struct SearchResults: Sendable { let matches: [Match]; let truncated: Bool } + static let maximumFiles = 1024 + static let maximumFileBytes = 1_048_576 + static let maximumTotalBytes = 16 * 1_048_576 + static let maximumTokens = 150_000 + static let maximumSymbols = 20_000 + let documents: [String: String] + let symbols: [Symbol] + let issues: [String] + private let tokens: [String: [Token]] + private struct Include: Sendable { let name: String; let quoted: Bool } + private enum Directive: Sendable { + case include(Include), define(String), undef(String) + } + private struct Step: Sendable { + let directive: Directive + let offset: Int + let conditional: Bool + } + private let steps: [String: [Step]] + private let guarded: Set + private let undefinedNames: Set + private let includePaths: [String] + + init(documents input: [String: String], defines: [String] = [], includePaths: [String] = [], configurationUncertain: Bool = false) { + var accepted: [String: String] = [:], notes: [String] = [], total = 0 + for path in input.keys.sorted() { + if Task.isCancelled { notes.append("Index cancelled."); break } + guard let text = input[path] else { continue } + let size = text.utf8.count + guard accepted.count < Self.maximumFiles, size <= Self.maximumFileBytes, + total + size <= Self.maximumTotalBytes, !text.contains("\0") else { + notes.append("Index omitted \(path): file/count/size limit or non-text contents."); continue + } + accepted[path] = text; total += size + } + var parsed: [String: [Token]] = [:], all: [Symbol] = [], links: [String: [Step]] = [:] + var guards: [String: String] = [:], undefinedNames: Set = [] + for path in accepted.keys.sorted() where ["c", "h"].contains((path as NSString).pathExtension.lowercased()) { + if Task.isCancelled { notes.append("Index cancelled."); break } + let source = accepted[path]! + let preparation = Self.prepare(source, path: path, defines: defines, uncertain: configurationUncertain) + let lexed = Self.lex(preparation.text, conditionalLines: preparation.conditionalLines) + parsed[path] = lexed.tokens + links[path] = preparation.steps + guards[path] = preparation.guardName + for step in preparation.steps { + if case .undef(let name) = step.directive { undefinedNames.insert(name) } + } + if lexed.truncated { notes.append("Symbol scan stopped at \(Self.maximumTokens) tokens in \(path).") } + var parser = Parser(path: path, source: source, tokens: lexed.tokens) + parser.parse() + if parser.limited { notes.append("Declaration scan reached its nesting or symbol limit in \(path).") } + let additions = preparation.macros + parser.symbols + let remaining = max(0, Self.maximumSymbols - all.count) + all += additions.prefix(remaining) + if additions.count > remaining { notes.append("Symbol limit reached; some declarations in \(path) were omitted.") } + } + if configurationUncertain { notes.append("Custom build flags are not evaluated. Definitions are lexical candidates; conditional branches may differ from the compiled program.") } + self.documents = accepted; self.symbols = all.sorted { ($0.path, $0.offsetUTF16) < ($1.path, $1.offsetUTF16) } + self.issues = Array(notes.prefix(32)); self.tokens = parsed; self.steps = links + self.guarded = Set(guards.compactMap { undefinedNames.contains($0.value) ? nil : $0.key }) + self.undefinedNames = undefinedNames; self.includePaths = Array(includePaths.prefix(128)) + } + func outline(path: String) -> [Symbol] { symbols.filter { $0.path == path && $0.scope == nil && $0.kind != .parameter && $0.kind != .member } } + func token(atUTF16Offset offset: Int, in path: String) -> String? { + guard let values = tokens[path], let token = values.first(where: { $0.identifier && $0.offset <= offset && offset < $0.offset + $0.text.utf16.count }) ?? values.last(where: { $0.identifier && $0.offset + $0.text.utf16.count == offset }) else { return nil } + return token.text + } + /// Locals are visible only after their declaration and inside their lexical + /// block. Member access has no inferred C type: return member candidates, + /// never accidentally substitute a same-named global. + func definitions(named name: String, from path: String, line: Int, column: Int) -> [Symbol] { + guard !name.isEmpty, name.utf8.count <= 256 else { return [] } + let offset = Self.offset(line: line, column: column, text: documents[path] ?? "") + let fileTokens = tokens[path] ?? [] + let targetIndex = fileTokens.firstIndex { $0.text == name && $0.offset <= offset && offset < $0.offset + $0.text.utf16.count } + ?? fileTokens.lastIndex { $0.text == name && $0.offset + $0.text.utf16.count == offset } + let preceding = targetIndex.flatMap { $0 > 0 ? fileTokens[$0 - 1] : nil } + ?? fileTokens.last { $0.offset < offset && $0.offset + $0.text.utf16.count <= offset } + let member = preceding?.text == "." || preceding?.text == "->" + let matches = symbols.filter { $0.name == name } + if member { return matches.filter { $0.kind == .member }.map { $0.withConditional() } } + let local = matches.filter { $0.path == path && $0.scope != nil && $0.kind != .member && $0.offsetUTF16 <= offset && $0.scopeStart <= offset && offset <= $0.scopeEnd } + if let narrowest = local.map(\.scopeStart).max() { return local.filter { $0.scopeStart == narrowest }.sorted { $0.offsetUTF16 > $1.offsetUTF16 } } + let visible = visibleFiles(from: path) + let overrides = macroOverrides(from: path, offset: offset, names: [name]) + let globals = matches.filter { overrides.keeps($0) }.filter { $0.scope == nil && (!$0.isStatic || $0.path == path || visible.contains($0.path)) } + let sameFile = globals.filter { $0.path == path && $0.isDefinition } + if overrides.uncertain.contains(name) { + return globals.filter { visible.contains($0.path) }.sorted { $0.kind != .macro && $1.kind == .macro }.map { $0.withConditional() } + } + if !sameFile.isEmpty { return sameFile } + let visibleDefinitions = globals.filter { visible.contains($0.path) && $0.isDefinition } + if !visibleDefinitions.isEmpty { return visibleDefinitions } + // External definitions may reside in a different translation unit. Keep + // duplicate external definitions visible instead of choosing by filename. + let definitions = globals.filter { $0.isDefinition && !$0.isStatic && ($0.kind == .function || $0.kind == .variable) } + if !definitions.isEmpty { return definitions } + let declarations = globals.filter { visible.contains($0.path) || $0.path == path } + return declarations.isEmpty ? globals.map { $0.withConditional() } : declarations + } + /// Completion is intentionally narrower than definition navigation: only + /// declarations in this source and literal included headers participate. + func completionSymbols(from path: String, offset: Int, prefix: String, includeLocals: Bool = true) -> [Symbol] { + let visible = visibleFiles(from: path) + var result = symbols.filter { symbol in + guard symbol.name.hasPrefix(prefix), visible.contains(symbol.path), symbol.kind != .member else { return false } + if symbol.path == path && symbol.offsetUTF16 > offset { return false } + if symbol.scope != nil { + return includeLocals && symbol.path == path && symbol.scopeStart <= offset && offset <= symbol.scopeEnd + } + return true + } + let overrides = macroOverrides(from: path, offset: offset, names: Set(result.lazy.filter { $0.kind == .macro }.map(\.name))) + result = result.filter { overrides.keeps($0) }.map { overrides.uncertain.contains($0.name) ? $0.withConditional() : $0 } + let locals = Dictionary(grouping: result.filter { $0.scope != nil }, by: \.name) + result.removeAll { symbol in + guard let scoped = locals[symbol.name], let innermost = scoped.map(\.scopeStart).max() else { return false } + return symbol.scope == nil || symbol.scopeStart != innermost + } + return result.sorted { + let a = ($0.scope == nil ? 1 : 0, $0.kind == .macro && overrides.uncertain.contains($0.name) ? 1 : 0, $0.path == path ? 0 : 1, $0.name, $0.path, $0.offsetUTF16) + let b = ($1.scope == nil ? 1 : 0, $1.kind == .macro && overrides.uncertain.contains($1.name) ? 1 : 0, $1.path == path ? 0 : 1, $1.name, $1.path, $1.offsetUTF16) + return a < b + } + } + func search(query: String, caseSensitive: Bool = false, limit: Int = 500, paths: Set? = nil) -> SearchResults { + let limit = max(1, min(2000, limit)) + guard !query.isEmpty, query.utf16.count <= 1024 else { return .init(matches: [], truncated: false) } + var found: [Match] = [] + for path in documents.keys.sorted() where paths == nil || paths!.contains(path) { + if Task.isCancelled { return .init(matches: found, truncated: true) } + let text = documents[path]! as NSString + var start = 0 + while start < text.length { + if Task.isCancelled { return .init(matches: found, truncated: true) } + let range = text.range(of: query, options: caseSensitive ? [.literal] : [.literal, .caseInsensitive], range: NSRange(location: start, length: text.length - start)) + guard range.location != NSNotFound, range.length > 0 else { break } + if found.count >= limit { return .init(matches: found, truncated: true) } + let before = text.substring(to: range.location) as NSString + let lineRange = text.lineRange(for: NSRange(location: range.location, length: 0)) + let preview = (text.substring(with: lineRange) as NSString).substring(to: min(240, lineRange.length)).trimmingCharacters(in: .newlines) + found.append(.init(path: path, line: before.components(separatedBy: "\n").count, + column: range.location - lineRange.location + 1, lengthUTF16: range.length, preview: preview, offsetUTF16: range.location)) + start = range.location + range.length + } + } + return .init(matches: found, truncated: false) + } + private func visibleFiles(from path: String) -> Set { + var visible: Set = [path], pending = [path] + while let file = pending.popLast(), visible.count <= Self.maximumFiles { + for step in steps[file] ?? [] { + if case .include(let include) = step.directive, let target = resolve(include, in: file), + visible.insert(target).inserted { pending.append(target) } + } + } + return visible + } + private func resolve(_ include: Include, in file: String) -> String? { + let parent = (file as NSString).deletingLastPathComponent + let local = parent.isEmpty ? include.name : parent + "/" + include.name + let names = (include.quoted ? [local] : []) + includePaths.map { $0.isEmpty ? include.name : $0 + "/" + include.name } + return names.lazy.map { ($0 as NSString).standardizingPath }.first { documents[$0] != nil } + } + + private struct MacroOverrides { + var live: [String: Set] = [:] + var undefined: Set = [] + var uncertain: Set = [] + func keeps(_ symbol: Symbol) -> Bool { + guard undefined.contains(symbol.name) else { return true } + let macros = live[symbol.name] ?? [] + if symbol.kind == .macro { return macros.contains(symbol.id) } + return symbol.kind != .function || macros.isEmpty || uncertain.contains(symbol.name) + } + } + /// Resolve only names with an explicit #undef. Replay literal directives in + /// include order up to the caret; unknown branches keep alternative candidates. + private func macroOverrides(from path: String, offset: Int, names: Set) -> MacroOverrides { + let relevant = names.intersection(undefinedNames) + guard !relevant.isEmpty else { return MacroOverrides() } + var state = MacroOverrides(), confirmed: Set = [], ancestors: Set = [] + var budget = Self.maximumTokens + func scan(_ file: String, through limit: Int, certain: Bool) { + guard budget > 0, !confirmed.contains(file), !ancestors.contains(file) else { return } + guard ancestors.count < 64, !Task.isCancelled else { budget = 0; return } + ancestors.insert(file) + defer { ancestors.remove(file) } + if guarded.contains(file), certain { confirmed.insert(file) } + for step in steps[file] ?? [] { + guard step.offset <= limit, budget > 0 else { break } + budget -= 1 + let definite = certain && !step.conditional + switch step.directive { + case .include(let include): + if let nested = resolve(include, in: file) { scan(nested, through: Int.max, certain: definite) } + case .define(let name) where relevant.contains(name): + let id = "\(file):\(step.offset):\(Kind.macro.rawValue)" + if definite { + state.live[name] = [id] + state.uncertain.remove(name) + } else { + state.live[name, default: []].insert(id) + if state.undefined.contains(name) { state.uncertain.insert(name) } + } + case .undef(let name) where relevant.contains(name): + state.undefined.insert(name) + if definite { + state.live[name] = [] + state.uncertain.remove(name) + } else if state.live[name]?.isEmpty == false { state.uncertain.insert(name) } + default: break + } + } + } + scan(path, through: offset, certain: true) + return budget > 0 ? state : MacroOverrides() + } + private static func offset(line: Int, column: Int, text: String) -> Int { + let lines = text.components(separatedBy: "\n") + guard line > 0, line <= lines.count else { return 0 } + return lines.prefix(line - 1).reduce(0) { $0 + $1.utf16.count + 1 } + max(0, min(column - 1, lines[line - 1].utf16.count)) + } + private struct Token: Sendable { + let text: String, offset: Int, line: Int, column: Int, conditional: Bool + var identifier: Bool { guard let first = text.utf8.first else { return false }; return Self.identifierStart(first) } + static func identifierStart(_ c: UInt8) -> Bool { c == 95 || (65...90).contains(c) || (97...122).contains(c) } + } + private static func lex(_ text: String, conditionalLines: Set) -> (tokens: [Token], truncated: Bool) { + let bytes = Array(text.utf16); var result: [Token] = [], i = 0, line = 1, column = 1 + func idStart(_ c: UInt16) -> Bool { c == 95 || (65...90).contains(c) || (97...122).contains(c) } + func advance() { if bytes[i] == 10 { line += 1; column = 1 } else { column += 1 }; i += 1 } + while i < bytes.count { + if result.count >= maximumTokens || (i % 1024 == 0 && Task.isCancelled) { return (result, true) } + let c = bytes[i] + if c == 32 || c == 9 || c == 13 || c == 10 { advance(); continue } + if c == 34 || c == 39 { + let quote = c; advance() + while i < bytes.count { if bytes[i] == 92 { advance(); if i < bytes.count { advance() }; continue }; if bytes[i] == quote { advance(); break }; advance() } + continue + } + let start = i, startLine = line, startColumn = column + if idStart(c) || (48...57).contains(c) { + advance(); while i < bytes.count && (idStart(bytes[i]) || (48...57).contains(bytes[i])) { advance() } + } else { + advance() + if i < bytes.count && ((c == 45 && bytes[i] == 62) || (c == 38 && bytes[i] == 38) || (c == 124 && bytes[i] == 124) || (c == 61 && bytes[i] == 61) || (c == 33 && bytes[i] == 61)) { advance() } + } + result.append(.init(text: String(decoding: bytes[start.. Self { self == .no || other == .no ? .no : self == .yes && other == .yes ? .yes : .unknown } + func or(_ other: Self) -> Self { self == .yes || other == .yes ? .yes : self == .no && other == .no ? .no : .unknown } + } + private struct Preparation { var text: String; var conditionalLines: Set; var macros: [Symbol]; var steps: [Step]; var guardName: String? } + private static func prepare(_ text: String, path: String, defines: [String], uncertain: Bool) -> Preparation { + // Blank comments while retaining all UTF-16 coordinates and quoted text. + var units = Array(text.utf16), i = 0, quote: UInt16?, block = false, lineComment = false + var currentLine = 1, literalContinuationLines: Set = [], lineCommentEscape = false + while i < units.count { + let c = units[i], next = i + 1 < units.count ? units[i + 1] : 0 + if c == 10 { currentLine += 1; if quote != nil { literalContinuationLines.insert(currentLine) } } + if block { + if c == 42 && next == 47 { units[i] = 32; units[i + 1] = 32; i += 2; block = false; continue } + if c != 10 && c != 13 { units[i] = 32 }; i += 1; continue + } + if lineComment { + if c == 10 { lineComment = lineCommentEscape; lineCommentEscape = false } + else if c != 13 { lineCommentEscape = c == 92; units[i] = 32 } + i += 1; continue + } + if let q = quote { if c == 92 { + if next == 10 { currentLine += 1; literalContinuationLines.insert(currentLine) } + i += min(2, units.count - i); continue + }; if c == q { quote = nil }; i += 1; continue } + if c == 34 || c == 39 { quote = c; i += 1; continue } + if c == 47 && next == 42 { units[i] = 32; units[i+1] = 32; i += 2; block = true; continue } + if c == 47 && next == 47 { units[i] = 32; units[i+1] = 32; i += 2; lineComment = true; continue } + i += 1 + } + let clean = String(decoding: units, as: UTF16.self).components(separatedBy: "\n") + // A conventional outer include guard makes a second literal include inert. + let nonempty = clean.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty } + let guardName = nonempty.first.flatMap { $0.hasPrefix("#ifndef ") ? String($0.dropFirst(8)) : nil } + var guarded = guardName.map { nonempty.dropFirst().first == "#define " + $0 && nonempty.last == "#endif" } ?? false + let lastContent = clean.lastIndex { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } + var macros: [String: String] = [:] + for define in defines.prefix(256) { let pieces = define.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false); if let name = pieces.first { macros[String(name)] = pieces.count > 1 ? String(pieces[1]) : "1" } } + var conditional: Set = [], symbols: [Symbol] = [], steps: [Step] = [], output: [String] = [], offset = 0 + var active = Truth.yes, stack: [(parent: Truth, taken: Truth)] = [], unknownMacros: Set = [], included = false, continuing = false + func condition(_ expression: String) -> Truth { + evaluateCondition(expression, macros: macros, unknownMacros: unknownMacros, unknownAbsent: uncertain || included) + } + for (number, line) in clean.enumerated() { + if Task.isCancelled { break } + let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines) + let blank = String(repeating: " ", count: line.utf16.count) + defer { offset += line.utf16.count + 1 } + if continuing { continuing = trimmed.hasSuffix("\\"); output.append(blank); continue } + guard trimmed.hasPrefix("#"), !literalContinuationLines.contains(number + 1) else { + output.append(active == .no ? blank : line) + if active == .unknown { conditional.insert(number + 1) }; continue + } + continuing = trimmed.hasSuffix("\\") + output.append(blank) + let directive = trimmed.dropFirst().trimmingCharacters(in: .whitespaces) + let command = String(directive.prefix { $0.isLetter }), argument = String(directive.dropFirst(directive.prefix { $0.isLetter }.count)).trimmingCharacters(in: .whitespaces) + if stack.count == 1, command == "elif" || command == "else" || (command == "endif" && number != lastContent) { + guarded = false + } + switch command { + case "if", "ifdef", "ifndef": + let test = command == "if" ? condition(argument) : condition("defined(\(argument))") + let value = command == "ifndef" ? test.inverted : test + stack.append((active, value)); active = active.and(value) + case "elif": + if let frame = stack.popLast() { let test = condition(argument); active = frame.parent.and(frame.taken.inverted).and(test); stack.append((frame.parent, frame.taken.or(test))) } + case "else": if let frame = stack.last { active = frame.parent.and(frame.taken.inverted); stack[stack.count - 1].taken = .yes } + case "endif": if let frame = stack.popLast() { active = frame.parent } + case "include" where active != .no: + if let first = argument.first, first == "\"" || first == "<", let end = argument.dropFirst().firstIndex(of: first == "\"" ? "\"" : ">") { steps.append(.init(directive: .include(.init(name: String(argument[argument.index(after: argument.startIndex).., unknownAbsent: Bool, depth: Int = 0) -> Truth { + guard depth < 32, expression.utf16.count <= 8192 else { return .unknown } + let expr = expression.trimmingCharacters(in: .whitespaces) + if expr.hasPrefix("(") && expr.hasSuffix(")") { + var depth = 0, wraps = true + for (i, c) in expr.enumerated() { if c == "(" { depth += 1 }; if c == ")" { depth -= 1 }; if depth == 0 && i < expr.count - 1 { wraps = false } } + if wraps { return evaluateCondition(String(expr.dropFirst().dropLast()), macros: macros, unknownMacros: unknownMacros, unknownAbsent: unknownAbsent, depth: depth + 1) } + } + for op in ["||", "&&"] { + let chars = Array(expr), operatorChars = Array(op); var depth = 0 + if chars.count >= 2 { for i in 0..<(chars.count - 1) { if chars[i] == "(" { depth += 1 }; if chars[i] == ")" { depth -= 1 }; if depth == 0 && chars[i] == operatorChars[0] && chars[i+1] == operatorChars[1] { + let left = evaluateCondition(String(chars[.. = ["void", "char", "short", "int", "long", "float", "double", "signed", "unsigned", "byte", "word", "size_t", "ptrdiff_t"] + private let qualifiers: Set = ["const", "volatile", "extern", "static", "register", "auto", "typedef", "inline", "interrupt", "__interrupt", "__norts__", "__norts", "__asm__", "asm", "__asm"] + private let controls: Set = ["return", "if", "else", "while", "do", "for", "switch", "case", "break", "continue", "goto", "sizeof"] + mutating func parse() { parseRange(0.. Int? { + let pairs = ["(": ")", "[": "]", "{": "}"] + guard let close = pairs[tokens[index].text] else { return nil } + var level = 0 + for i in index.. [[Token]] { + var result: [[Token]] = [], current: [Token] = [], parens = 0, brackets = 0, braces = 0 + for token in values { + if token.text == separator && parens == 0 && brackets == 0 && braces == 0 { result.append(current); current = []; continue } + current.append(token) + switch token.text { case "(": parens += 1; case ")": parens -= 1; case "[": brackets += 1; case "]": brackets -= 1; case "{": braces += 1; case "}": braces -= 1; default: break } + } + if !current.isEmpty { result.append(current) }; return result + } + private func declaratorStart(_ declaration: [Token]) -> Int? { + guard let first = declaration.first, first.identifier, !controls.contains(first.text) else { return nil } + var i = 0, consumed = false + while i < declaration.count { + let name = declaration[i].text + if qualifiers.contains(name) || types.contains(name) { consumed = true; i += 1; continue } + if ["struct", "union", "enum"].contains(name) { + consumed = true; i += 1 + if i < declaration.count && declaration[i].identifier { i += 1 } + continue + } + if !consumed && declaration[i].identifier && i + 1 < declaration.count && (declaration[i+1].identifier || declaration[i+1].text == "*") { + // A named type from another header is plausible, but it is + // only a lexical declaration, never semantic type resolution. + consumed = true; i += 1; continue + } + break + } + return consumed && i < declaration.count ? i : nil + } + private func declarator(_ values: [Token]) -> (name: Token, function: Bool, parameters: [Token])? { + guard let nameIndex = values.firstIndex(where: { $0.identifier && !qualifiers.contains($0.text) }) else { return nil } + let name = values[nameIndex] + if nameIndex + 1 < values.count, values[nameIndex+1].text == "(" { + var depth = 0 + for i in (nameIndex+1).. begin, tokens[i-1].text == "for", let scope, + let separator = tokens[(i+1).. Self { + .init(path: path, name: name, line: line, column: column, kind: kind, signature: signature, + isDefinition: isDefinition, isStatic: isStatic, conditional: true, scope: scope, + offsetUTF16: offsetUTF16, lengthUTF16: lengthUTF16, scopeStart: scopeStart, scopeEnd: scopeEnd) + } +} diff --git a/platforms/macos/App/CMOCProjectInputs.swift b/platforms/macos/App/CMOCProjectInputs.swift new file mode 100644 index 0000000..06d1ad2 --- /dev/null +++ b/platforms/macos/App/CMOCProjectInputs.swift @@ -0,0 +1,240 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// One bounded, content-based description of project inputs. Excluded directory +/// rows explain an entire subtree without reading or hashing its generated data. +struct CMOCProjectInputManifest: Equatable, Sendable { + struct Entry: Codable, Equatable, Sendable { + let path: String + let role: String + let reason: String + let included: Bool + let affectsRevision: Bool + let affectsBuild: Bool + let sha256: String? + let executable: Bool + var permissions: Int? = nil + var publicFields: [String: Any] { + ["path": path, "role": role, "reason": reason, "included": included, + "affects_revision": affectsRevision, "affects_build": affectsBuild, + "sha256": sha256 as Any? ?? NSNull(), "executable": executable, + "permissions": permissions as Any? ?? NSNull()] + } + var control: Bool { ["recipe", "project_settings", "generator", "support", "pending_support_root", "executable"].contains(role) } + } + struct Change: Equatable, Sendable { + let path: String + let previous: Entry? + let current: Entry? + var requiresReview: Bool { + guard let previous, let current else { return true } + return previous.included != current.included || previous.role != current.role || + previous.executable != current.executable || previous.control || current.control + } + var publicFields: [String: Any] { + ["path": path, "previous": previous?.publicFields as Any? ?? NSNull(), + "current": current?.publicFields as Any? ?? NSNull(), "requires_review": requiresReview] + } + } + let configuration: CMOCProjectConfiguration + let files: [String: Data] + let permissions: [String: Int] + let modificationDates: [String: Date] + let overlayPaths: Set + let support: CMOCBuildSupportSnapshot + let entries: [Entry] + var sharedPaths: [String] { files.keys.filter(CMOCProject.isEditable).sorted() } + var identity: String { + let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys] + let rows = entries.filter(\.included) + // Configuration is a value already validated at capture. Encoding these + // Codable values cannot depend on disk timestamps or dictionary order. + let data = (try? encoder.encode(rows)) ?? Data() + let config = (try? encoder.encode(configuration)) ?? Data() + return CMOCProject.sha256(data + config) + } + static func == (lhs: Self, rhs: Self) -> Bool { lhs.identity == rhs.identity } + /// Restricted assistant recipes use only reviewed C/header inputs (or the + /// fixed Hello Disk set), not the user's arbitrary Make resources/helpers. + func restricting(to paths: Set) -> Self { + Self(configuration: configuration, files: files.filter { paths.contains($0.key) }, + permissions: permissions.filter { paths.contains($0.key) }, + modificationDates: modificationDates.filter { paths.contains($0.key) }, + overlayPaths: overlayPaths.intersection(paths), support: .init(files: [:], permissions: [:]), + entries: entries.map { entry in + guard entry.included, !paths.contains(entry.path) else { return entry } + return Entry(path: entry.path, role: "excluded_scope", reason: "Not used by the approved restricted recipe.", + included: false, affectsRevision: false, affectsBuild: false, sha256: nil, executable: false) + }) + } + func changes(from old: Self) -> [Change] { + let before = Dictionary(uniqueKeysWithValues: old.entries.map { ($0.path, $0) }) + let after = Dictionary(uniqueKeysWithValues: entries.map { ($0.path, $0) }) + return Set(before.keys).union(after.keys).sorted().compactMap { path in + let lhs = before[path], rhs = after[path] + guard lhs?.included == true || rhs?.included == true, lhs != rhs else { return nil } + return Change(path: path, previous: lhs, current: rhs) + } + } + + static func capture(project: CMOCProject, overlays: [String: String] = [:], + approvedSupportDirectories: [String]? = nil, + readConfigurationFile: Bool = true, retainHostExecutables: Bool = false) throws -> Self { + let fm = FileManager.default + let root = try CMOCProject.physicalURL(project.directory) + var configuration = project.configuration + let settingsURL = try project.fileURL(relativePath: CMOCProject.configurationFilename) + if readConfigurationFile, let text = overlays[CMOCProject.configurationFilename] { + configuration = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: Data(text.utf8)) + } else if readConfigurationFile, fm.fileExists(atPath: settingsURL.path) { + let attributes = try fm.attributesOfItem(atPath: settingsURL.path) + guard ((attributes[.size] as? NSNumber)?.intValue ?? Int.max) <= CMOCProject.maximumFileBytes else { + throw CMOCBuildError.message("Project settings exceed the input limit.") + } + configuration = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: Data(contentsOf: settingsURL)) + } + configuration = try configuration.validated() + let effective = CMOCProject(directory: project.directory, configuration: configuration) + let recipe = configuration.makefileSettings + let generatedOutputs = Set(recipe?.generatedResources.flatMap(\.outputs) ?? []) + var products = generatedOutputs.union(configuration.playtestDisks) + for path in [configuration.binary, configuration.diskImage, configuration.debugManifest].compactMap({ $0 }) { + products.insert(path) + } + if let binary = configuration.binary { + let stem = (binary as NSString).deletingPathExtension + for ext in ["map", "link"] { products.insert(stem + "." + ext) } + } + let explicitSources = Set((recipe?.sources ?? []) + [configuration.entrySource]) + let explicitResources = Set(configuration.resourceInputs + (recipe?.generatedResources.flatMap(\.inputs) ?? []) + (recipe?.diskFiles ?? [])) + .subtracting(products) + let explicitGenerated = Set(configuration.generatedInputs) + let explicit = explicitSources.union(explicitResources).union(explicitGenerated) + .union([configuration.makefile, CMOCProject.configurationFilename]) + let includeDirectories = recipe?.includePaths ?? [] + let hard = Set([".git", ".svn", ".hg", ".ds_store"]) + let incidental = Set(["captures", "screenshots", "evidence", "receipts", "logs", "test-results", "tmp", "temp", ".cache", ".build", ".vccplus-build"]) + func within(_ path: String, _ directory: String) -> Bool { path == directory || path.hasPrefix(directory + "/") } + func explicitlyNeeded(_ path: String, directory: Bool) -> Bool { + explicit.contains(path) || (directory && explicit.contains(where: { $0.hasPrefix(path + "/") })) || + includeDirectories.contains(where: { within(path, $0) || (directory && within($0, path)) }) + } + var enumerationError: Error? + guard let enumerator = fm.enumerator(at: root, + includingPropertiesForKeys: [.isRegularFileKey, .isDirectoryKey, .isSymbolicLinkKey, .fileSizeKey], + options: [], errorHandler: { _, error in enumerationError = error; return false }) else { + throw CMOCBuildError.message("The project folder could not be read.") + } + var candidates: [String: URL] = [:], excluded: [Entry] = [], names = Set() + func exclusion(_ path: String, _ role: String, _ reason: String) { + excluded.append(Entry(path: path, role: role, reason: reason, included: false, + affectsRevision: false, affectsBuild: false, sha256: nil, executable: false)) + } + while let url = enumerator.nextObject() as? URL { + let path = String(url.path.dropFirst(root.path.count + 1)) + try CMOCProject.validateRelativePath(path) + guard names.insert(path.lowercased()).inserted, names.count <= 20_000 else { + throw CMOCBuildError.message("Project input names are ambiguous or exceed the 20,000-entry limit.") + } + let value = try url.resourceValues(forKeys: [.isRegularFileKey, .isDirectoryKey, .isSymbolicLinkKey]) + if hard.contains(url.lastPathComponent.lowercased()) { + enumerator.skipDescendants(); exclusion(path, "excluded", "Version-control or platform metadata; subtree excluded."); continue + } + guard value.isSymbolicLink != true else { + throw CMOCBuildError.message("Project inputs cannot traverse symbolic links: \(path)") + } + let directory = value.isDirectory == true + let soft = path.split(separator: "/").contains(where: { incidental.contains($0.lowercased()) }) || + configuration.outputDirectories.contains(where: { within(path, $0) }) + if soft && !explicitlyNeeded(path, directory: directory) { + enumerator.skipDescendants(); exclusion(path, "excluded_output", "Incidental or declared output directory; subtree excluded."); continue + } + if directory { continue } + guard value.isRegularFile == true else { throw CMOCBuildError.message("Unsupported project input: \(path)") } + candidates[path] = url + } + if let enumerationError { throw enumerationError } + for path in explicitResources.union(explicitGenerated) { + guard candidates[path] != nil else { throw CMOCBuildError.message("Missing declared project input: \(path)") } + } + var files: [String: Data] = [:], permissions: [String: Int] = [:], dates: [String: Date] = [:] + var entries = excluded, total = 0 + let keys = Set(candidates.keys.map { $0.lowercased() }) + for path in candidates.keys.sorted() { + let key = path.lowercased(), ext = (key as NSString).pathExtension + let stem = (key as NSString).deletingPathExtension + let declared = explicit.contains(path) || includeDirectories.contains(where: { within(path, $0) }) + if products.contains(path) { + exclusion(path, "generated_output", "Declared build output; captured in the resulting artifact, not the input revision."); continue + } + if !declared && (["o", "d", "lst", "map", "link", "log"].contains(ext) || + (ext == "s" && (keys.contains(stem + ".c") || keys.contains(stem + ".o") || keys.contains(stem + ".lst"))) || + (ext == "bin" && (keys.contains(stem + ".c") || keys.contains(stem + ".asm"))) || + key.hasSuffix("-receipt.json") || key.hasSuffix(".receipt.json") || + (recipe != nil && key.hasPrefix("obj/vcc-dos-boot/"))) { + exclusion(path, "compiler_output", "Conventional compiler product, log or receipt; declare it explicitly if it is an input."); continue + } + let url = candidates[path]! + let attributes = try fm.attributesOfItem(atPath: url.path) + let mode = (attributes[.posixPermissions] as? NSNumber)?.intValue ?? 0o644 + let originalSize = (attributes[.size] as? NSNumber)?.intValue ?? Int.max + guard originalSize <= CMOCProject.maximumFileBytes else { throw CMOCBuildError.message("Project input exceeds the 64 MB file limit: \(path)") } + let data = try overlays[path].map(CMOCProject.sourceBytes) ?? Data(contentsOf: url) + // A locally compiled host executable is an output, unless explicitly + // retained as a reviewed tool/resource. CoCo binaries are unaffected. + let magic = Array(data.prefix(4)) + let hostExecutable = [[0x7f,0x45,0x4c,0x46], [0xcf,0xfa,0xed,0xfe], [0xce,0xfa,0xed,0xfe], + [0xfe,0xed,0xfa,0xcf], [0xfe,0xed,0xfa,0xce], [0xca,0xfe,0xba,0xbe]].contains(magic.map(Int.init)) + if hostExecutable && !declared && !retainHostExecutables { + exclusion(path, "host_build_output", "Compiled host executable; declare it explicitly to retain it as a build input."); continue + } + total += data.count + guard data.count <= CMOCProject.maximumFileBytes, total <= CMOCProject.maximumProjectBytes else { + throw CMOCBuildError.message("Project inputs exceed the 512 MB snapshot limit.") + } + files[path] = data; permissions[path] = mode & 0o777 + dates[path] = attributes[.modificationDate] as? Date + let role: String + if path == CMOCProject.configurationFilename { role = "project_settings" } + else if path == configuration.makefile || ["makefile", "gnumakefile"].contains((key as NSString).lastPathComponent) || ext == "mk" { role = "recipe" } + else if ["pl", "py", "sh", "rb"].contains(ext) { role = "generator" } + else if mode & 0o111 != 0 { role = "executable" } + else if explicitGenerated.contains(path) { role = "generated_input" } + else if ["h", "inc"].contains(ext) { role = "header" } + else if CMOCProject.isSource(path) { role = "source" } + else { role = "resource" } + entries.append(Entry(path: path, role: role, + reason: declared ? "Explicitly declared source, include, resource or generated input." : "Project input inside the approved root.", + included: true, affectsRevision: true, affectsBuild: true, sha256: CMOCProject.sha256(data), executable: mode & 0o111 != 0, + permissions: ["recipe", "project_settings", "generator", "executable"].contains(role) ? mode & 0o777 : nil)) + } + // Exclusions collected during file classification were appended after + // the traversal rows. Include them without duplicating existing rows. + let seen = Set(entries.map(\.path)) + entries += excluded.filter { !seen.contains($0.path) } + var supportProject = effective + if let approvedSupportDirectories { + let approved = Set(approvedSupportDirectories) + supportProject.configuration.buildSupportDirectories = configuration.buildSupportDirectories.filter(approved.contains) + for path in configuration.buildSupportDirectories where !approved.contains(path) { + // New sibling roots require native approval BEFORE enumeration, + // hashing or copying. Only their already-declared names are public. + entries.append(Entry(path: path, role: "pending_support_root", + reason: "New build-support root; contents remain unread until native approval authorizes the whole root.", + included: true, affectsRevision: true, affectsBuild: true, sha256: nil, executable: false)) + } + } + let support = try supportProject.supportSnapshot() + guard files.count + support.files.count <= 20_000, + total + support.files.values.reduce(0, { $0 + $1.count }) <= CMOCProject.maximumProjectBytes else { + throw CMOCBuildError.message("Project and approved support inputs exceed snapshot limits.") + } + for (path, data) in support.files { + entries.append(Entry(path: path, role: "support", reason: "Explicitly approved build-support root.", included: true, + affectsRevision: true, affectsBuild: true, sha256: CMOCProject.sha256(data), executable: (support.permissions[path] ?? 0) & 0o111 != 0, + permissions: (support.permissions[path] ?? 0) & 0o777)) + } + return Self(configuration: configuration, files: files, permissions: permissions, modificationDates: dates, + overlayPaths: Set(overlays.keys).intersection(files.keys), support: support, entries: entries.sorted { $0.path < $1.path }) + } +} diff --git a/platforms/macos/App/CMOCSourceMap.swift b/platforms/macos/App/CMOCSourceMap.swift new file mode 100644 index 0000000..6f6c311 --- /dev/null +++ b/platforms/macos/App/CMOCSourceMap.swift @@ -0,0 +1,1047 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import CryptoKit + +/// Verified mapping for one CMOC C translation unit, not a general C debugger. +/// LWASM object offsets are relocated using the matching LWLINK map. Every +/// initialized byte in the user object, including relocation operands, must +/// match the final DECB executable before any source breakpoint is exposed. +struct CMOCSourceMap: Sendable { + /// Bound public catalog arrays by their actual encoded JSON size, including + /// escaping. Private verified selectors retain every entry. + static func boundedJSONCatalog(_ values: [T], maximumBytes: Int = 32 * 1024) -> (items: [T], total: Int, truncated: Bool) { + var items: [T] = [], bytes = 2 // array brackets + for value in values { + guard let encoded = try? JSONSerialization.data(withJSONObject: [value]) else { break } + let addition = encoded.count - 2 + (items.isEmpty ? 0 : 1) + guard bytes + addition <= maximumBytes else { break } + items.append(value); bytes += addition + } + return (items, values.count, items.count != values.count) + } + + struct Instruction: Equatable, Sendable { + let sourceLine: Int // one-based C source line + let address: UInt16 + let bytes: [UInt8] // final linked bytes, never unresolved listing bytes + let assembly: String + var moduleID: String? = nil + var physicalAddress: UInt32? = nil + } + struct Provenance: Equatable, Sendable { + let sourceSHA256: String + let binarySHA256: String + let objectSHA256: String + let listingSHA256: String + let linkMapSHA256: String + } + enum Failure: LocalizedError { + case invalid(String) + var errorDescription: String? { + switch self { case .invalid(let message): return "Cannot verify CMOC source mapping: " + message } + } + } + let sourceName: String + let entryPoint: UInt16 + let provenance: Provenance + let instructions: [Instruction] + var executableLines: [Int] { Array(Set(instructions.map(\.sourceLine))).sorted() } + func addresses(forLine line: Int) -> [UInt16] { instructions.filter { $0.sourceLine == line }.map(\.address) } + func line(at address: UInt16) -> Int? { instructions.first { $0.address == address }?.sourceLine } + func matches(source: Data, binary: Data) -> Bool { + Self.sha256(source) == provenance.sourceSHA256 && Self.sha256(binary) == provenance.binarySHA256 + } + static func sha256(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() } + static func decbEntryPoint(_ data: Data) throws -> UInt16 { try BinaryImage(data).entry } + + /// The caller must build all artifacts together from an immutable source + /// snapshot in a fresh directory. C-source hashes are not present in LWOBJ. + static func parse(source: Data, sourceName: String, listing: Data, object: Data, + objectName: String, linkMap: Data, binary: Data, + sourceAliases: [String] = [], objectAliases: [String] = [], + strictIdentities: Bool = false, allowEmpty: Bool = false, + bankedLayout: CMOCBankedDebugLayout? = nil) throws -> Self { + for data in [source, listing, object, linkMap, binary] { + guard data.count <= 8 * 1024 * 1024 else { throw Failure.invalid("an artifact exceeds 8 MB.") } + } + guard let sourceText = String(data: source, encoding: .utf8), !sourceText.contains("\0"), + !sourceName.isEmpty, !objectName.isEmpty else { throw Failure.invalid("invalid source identity or encoding.") } + let verified = try verifiedSections(object: object, objectName: objectName, linkMap: linkMap, binary: binary, + objectAliases: objectAliases, strictIdentities: strictIdentities, bankedLayout: bankedLayout) + let sourceLines = sourceText.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n").components(separatedBy: "\n").count + let listingLines = try textLines(listing) + let rowPattern = try NSRegularExpression(pattern: #"^\((.{0,17})\):([0-9]{5,}) (.*)$"#) + let sectionPattern = try NSRegularExpression(pattern: #"^\s*SECTION\s+([^\s,]+)(?:\s|,|$)"#, options: .caseInsensitive) + let linePattern = try NSRegularExpression(pattern: #"^\* Line (.+):([0-9]+)(?::.*)?$"#) + let functionPattern = try NSRegularExpression(pattern: #"^\* FUNCTION .+: defined at (.+):([0-9]+)$"#) + var sectionName: String?, sourceLine: Int?, instructions: [Instruction] = [] + var seenAddresses = Set() + for text in listingLines { + let octets = Array(text.utf8) + guard octets.count >= 22, octets[21] == 32 else { continue } + let metadata = String(decoding: octets.dropFirst(22), as: UTF8.self) + guard let row = groups(rowPattern, metadata) else { continue } + let assembly = row[3], trimmed = assembly.trimmingCharacters(in: .whitespaces) + if let groups = groups(sectionPattern, assembly) { + guard sectionName == nil, verified.sections[groups[1]] != nil else { throw Failure.invalid("unknown or nested listing section.") } + sectionName = groups[1]; sourceLine = nil; continue + } + if trimmed.uppercased() == "ENDSECTION" { sectionName = nil; sourceLine = nil; continue } + if trimmed.hasPrefix("* END FUNCTION") { sourceLine = nil; continue } + if let location = groups(linePattern, trimmed) ?? groups(functionPattern, trimmed) { + sourceLine = nil + if ([sourceName] + sourceAliases).contains(where: { strictIdentities ? normalized(location[1]) == normalized($0) : matchesSource(location[1], $0) }), !trimmed.contains(": inline assembly") { + guard let number = Int(location[2]), number > 0, number <= sourceLines else { + throw Failure.invalid("a C source line is outside the source snapshot.") + } + sourceLine = number + } + continue + } + guard let sectionName, (bankedLayout != nil || sectionName == "code"), let sourceLine else { continue } + let digits = String(decoding: octets[5..<21], as: UTF8.self).trimmingCharacters(in: .whitespaces) + guard octets[4] == 32, !digits.isEmpty, + octets.prefix(4).allSatisfy({ (48...57).contains($0) || (65...70).contains($0) || (97...102).contains($0) }) else { continue } + guard digits.count % 2 == 0, digits.allSatisfy({ $0.isASCII && $0.isHexDigit }), + let offset = Int(String(decoding: octets.prefix(4), as: UTF8.self), radix: 16), + let section = verified.sections[sectionName], let final = section.final else { throw Failure.invalid("unsupported addressed listing row.") } + let chars = Array(digits) + let originalBytes = stride(from: 0, to: chars.count, by: 2).map { UInt8(String(chars[$0...($0 + 1)]), radix: 16)! } + guard offset + originalBytes.count <= final.count, + Array(section.original[offset..<(offset + originalBytes.count)]) == originalBytes else { + throw Failure.invalid("listing bytes do not match the object file.") + } + let opcode = trimmed.split(whereSeparator: \.isWhitespace).first?.uppercased() ?? "" + // Data in inline assembly is not an executable breakpoint location. + if ["FCB", "FDB", "FCC", "FCS", "FILL", "ZMB", "RMB", "RMD", "RMDQ", "FCQ"].contains(opcode) { continue } + if let bankedLayout { + guard bankedLayout.module(forSection: sectionName)?.codeSections.contains(sectionName) == true else { + throw Failure.invalid("a C instruction is outside the declared executable sections.") + } + } + let address = UInt16(section.base + offset) + let identity = bankedLayout?.module(forSection: sectionName)?.physicalAddress(Int(address)) ?? UInt32(address) + guard seenAddresses.insert(identity).inserted else { throw Failure.invalid("duplicate instruction addresses in the listing.") } + instructions.append(Instruction(sourceLine: sourceLine, address: address, + bytes: Array(final[offset..<(offset + originalBytes.count)]), assembly: trimmed, + moduleID: bankedLayout?.module(forSection: sectionName)?.id, + physicalAddress: bankedLayout?.module(forSection: sectionName)?.physicalAddress(Int(address)))) + } + guard sectionName == nil, allowEmpty || !instructions.isEmpty else { throw Failure.invalid("no verified C instruction locations were found.") } + return Self(sourceName: sourceName, entryPoint: verified.entry, + provenance: Provenance(sourceSHA256: sha256(source), binarySHA256: sha256(binary), objectSHA256: sha256(object), + listingSHA256: sha256(listing), linkMapSHA256: sha256(linkMap)), instructions: instructions) + } + + /// Resolve compiler debug labels from the object symbol table itself. The + /// map's section placements have been verified against the executable; + /// unused map symbols alone are not proof of a variable/scope address. + static func resolvedObjectSymbols(object: Data, objectName: String, objectAliases: [String] = [], + linkMap: Data) throws -> [String: Int] { + let objects = try ObjectSection.parse(object), map = try LinkMap(linkMap) + let names = Set(([objectName] + objectAliases).map(normalized)) + let identities = Set(map.sections.filter { names.contains(normalized($0.object)) }.map(\.object)) + guard identities.count == 1, let identity = identities.first else { + throw Failure.invalid("debug object identity is missing or ambiguous.") + } + let placements = map.sections.filter { $0.object == identity } + guard Set(placements.map(\.name)).count == placements.count, + Set(placements.map(\.name)) == Set(objects.map(\.name)) else { + throw Failure.invalid("debug object sections do not match the linker map.") + } + var result: [String: Int] = [:] + for section in objects { + guard let placement = placements.first(where: { $0.name == section.name }), + placement.length == section.length, placement.address + placement.length <= 65536 else { + throw Failure.invalid("debug object section has an invalid placement.") + } + for (name, offset) in section.locals { + let address = offset + (section.constant ? 0 : placement.address) + guard result[name] == nil, address < 65536 else { + throw Failure.invalid("debug object symbol is ambiguous or outside logical memory.") + } + result[name] = address + } + } + return result + } + + /// Symbol ownership comes from the object's section table, never an address + /// guess: two overlay sections can legitimately have the same logical PC. + static func resolvedObjectSymbolModules(object: Data, layout: CMOCBankedDebugLayout) throws -> [String: String] { + var result: [String: String] = [:] + for section in try ObjectSection.parse(object) where !section.constant { + // Assemblers may retain empty default data/BSS sections. They own + // neither storage nor debug labels and need no bank declaration. + if section.length == 0 && section.locals.isEmpty { continue } + guard let module = layout.module(forSection: section.name) else { + throw Failure.invalid("debug symbol section has no banked module identity.") + } + for name in section.locals.keys { + guard result[name] == nil else { throw Failure.invalid("debug symbol has ambiguous module ownership.") } + result[name] = module.id + } + } + return result + } + + /// A raw linker symbol is executable only when its own retained object + /// defines it inside initialized, declared executable bytes. A map label, + /// BSS address or another object's section boundary is not enough proof. + static func executableObjectSymbols(object: Data, objectName: String, objectAliases: [String] = [], + linkMap: Data, binary: Data, layout: CMOCBankedDebugLayout, sourcePaths: [String] = []) throws -> [CMOCProjectSourceMap.ExecutableSymbol] { + let verified = try verifiedSections(object: object, objectName: objectName, linkMap: linkMap, binary: binary, + objectAliases: objectAliases, strictIdentities: true, bankedLayout: layout) + let sections = try ObjectSection.parse(object), map = try LinkMap(linkMap) + let accepted = Set(([objectName] + objectAliases).map(normalized)) + let identities = Set(map.sections.filter { accepted.contains(normalized($0.object)) }.map(\.object)) + guard identities.count == 1, let identity = identities.first else { throw Failure.invalid("executable symbol object is missing or ambiguous.") } + let mappedSymbols = Dictionary(grouping: map.symbolRecords.filter { $0.object == identity }, by: \.name) + func entryLike(_ name: String, exported: Bool) -> Bool { + if exported { return true } + // CMOC's function-size EQU values can coincidentally fall inside + // code, and function-end labels are boundaries rather than entries. + // Retain deliberate assembly exports even with these spellings. + guard !name.hasPrefix("funcend_"), !name.hasPrefix("funcsize_"), + !name.hasPrefix(".vcc.debug.") else { return false } + let bytes = Array(name.utf8) + guard let first = bytes.first, (65...90).contains(first) || (97...122).contains(first) || first == 95, + bytes.allSatisfy({ (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) || [95, 46, 36, 64].contains($0) }) else { return false } + // Compiler instruction/debug labels are not a function catalog. + // An explicitly exported assembly label remains selectable. + return !(first == 76 && bytes.count > 1 && bytes.dropFirst().allSatisfy { (48...57).contains($0) }) + } + var result: [CMOCProjectSourceMap.ExecutableSymbol] = [] + for section in sections where !section.bss && !section.constant && section.length > 0 { + guard let module = layout.module(forSection: section.name), module.codeSections.contains(section.name), + let placed = verified.sections[section.name], let linked = placed.final, + placed.base >= 0, placed.base + linked.count <= 0xfe00 else { continue } + // Match the guards to independently relocated object bytes, not + // merely to a self-declared symbol address or image hash. + for (offset, byte) in linked.enumerated() { + let address = placed.base + offset + guard let guardRange = module.codeGuards.first(where: { + address >= Int($0.address) && address - Int($0.address) < $0.bytes.count + }), guardRange.bytes[address - Int(guardRange.address)] == byte else { + throw Failure.invalid("executable object section is not covered by matching code guards.") + } + } + for (name, offset) in section.locals where offset < section.length && entryLike(name, exported: section.exportedNames.contains(name)) { + let address = placed.base + offset + let matches = mappedSymbols[name] ?? [] + guard matches.count == 1, matches[0].address == address, let physical = module.physicalAddress(address), + !name.isEmpty, name.utf8.count <= 1024 else { continue } + result.append(.init(name: name, objectPath: objectName, sectionName: section.name, + address: UInt16(address), moduleID: module.id, physicalAddress: physical, sourcePaths: sourcePaths)) + } + } + return result + } + + struct VerifiedSection { + let base: Int + let original: [UInt8] + let final: [UInt8]? + } + + /// Apply every supported object relocation and compare the result with the + /// actual linked DECB bytes before interpreting either C or assembly lines. + static func verifiedSections(object: Data, objectName: String, linkMap: Data, binary: Data, + objectAliases: [String] = [], strictIdentities: Bool = true, + bankedLayout: CMOCBankedDebugLayout? = nil) throws + -> (entry: UInt16, sections: [String: VerifiedSection]) { + let image = try bankedLayout == nil ? BinaryImage(binary) : nil + let objects = try ObjectSection.parse(object) + let map = try LinkMap(linkMap) + let acceptedObjects = Set(([objectName] + objectAliases).map(normalized)) + let exactObjects = Set(map.sections.filter { acceptedObjects.contains(normalized($0.object)) }.map(\.object)) + let matchingObjects = !exactObjects.isEmpty || strictIdentities ? exactObjects : Set(map.sections.filter { + URL(fileURLWithPath: $0.object).lastPathComponent == URL(fileURLWithPath: objectName).lastPathComponent + }.map(\.object)) + guard matchingObjects.count == 1, let mappedObject = matchingObjects.first else { + throw Failure.invalid("the object filename is missing or ambiguous in the linker map.") + } + let placements = map.sections.filter { $0.object == mappedObject } + guard Set(placements.map(\.name)).count == placements.count, + Set(placements.map(\.name)) == Set(objects.map(\.name)) else { + throw Failure.invalid("object sections do not uniquely match the linker map.") + } + var bases: [String: Int] = [:] + for section in objects { + guard let placement = placements.first(where: { $0.name == section.name }), + placement.length == section.length, placement.address + placement.length <= 65536 else { + throw Failure.invalid("section size or address differs from the linker map.") + } + bases[section.name] = placement.address + if let bankedLayout, !section.constant, section.length > 0 { + guard let module = bankedLayout.module(forSection: section.name), + (placement.address / 8192...((placement.address + placement.length - 1) / 8192)).allSatisfy({ page in + module.pages.contains { $0.logicalPage == page } + }) else { + throw Failure.invalid("object section has no complete physical placement.") + } + } + } + func local(_ name: String, in section: ObjectSection) throws -> Int { + if let offset = section.locals[name] { return offset + (section.constant ? 0 : bases[section.name]!) } + let matches = objects.filter { $0.locals[name] != nil } + guard matches.count == 1, let target = matches.first, let offset = target.locals[name] else { + throw Failure.invalid("a local relocation symbol is missing or ambiguous.") + } + return offset + (target.constant ? 0 : bases[target.name]!) + } + var linkedSections: [String: [UInt8]] = [:] + for section in objects { + guard !section.bss && !section.constant else { continue } + var linked = section.bytes + var touched = Set() + for relocation in section.relocations { + let width = relocation.width + // Zero-width references express linker dependencies only. + if width == 0 { continue } + guard relocation.offset + width <= linked.count else { throw Failure.invalid("relocation leaves its section.") } + let value = try relocation.evaluate(base: bases[section.name]!, local: { try local($0, in: section) }, external: { symbol in + let values = map.symbols[symbol] ?? [] + guard values.count == 1, let value = values.first else { + throw Failure.invalid("an external relocation symbol is missing or ambiguous.") + } + return value + }) + for index in 0..> (8 * (width - 1 - index))) + } + } + for (offset, byte) in linked.enumerated() { + let address = bases[section.name]! + offset + let actual: UInt8? + if let bankedLayout { + guard let module = bankedLayout.module(forSection: section.name) else { throw Failure.invalid("section has no banked module identity.") } + let index = address - module.logicalAddress + actual = module.bytes.indices.contains(index) ? module.bytes[index] : nil + } else { actual = image?.bytes[address] } + guard actual == byte else { + throw Failure.invalid("object/linker-map bytes do not match the executable. Rebuild before debugging.") + } + } + linkedSections[section.name] = linked + } + var sections: [String: VerifiedSection] = [:] + for section in objects { + sections[section.name] = VerifiedSection(base: bases[section.name]!, original: section.bytes, + final: linkedSections[section.name]) + } + return (bankedLayout?.entryPoint ?? image!.entry, sections) + } + + private static func matchesSource(_ candidate: String, _ expected: String) -> Bool { + let candidate = normalized(candidate), expected = normalized(expected) + if candidate == expected { return true } + // The caller knows the immutable build snapshot path. Some bundled + // preprocessors emit it absolutely, others retain the bare input name. + return expected.hasPrefix("/") && candidate == URL(fileURLWithPath: expected).lastPathComponent + } + private static func normalized(_ name: String) -> String { + var value = name + while value.hasPrefix("./") { value.removeFirst(2) } + return value + } + private static func textLines(_ data: Data) throws -> [String] { + guard let text = String(data: data, encoding: .utf8), !text.contains("\0") else { throw Failure.invalid("invalid text encoding.") } + let lines = text.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n") + guard lines.count <= 100_000, lines.allSatisfy({ $0.utf8.count <= 8192 }) else { throw Failure.invalid("text exceeds mapping limits.") } + return lines + } + private static func groups(_ regex: NSRegularExpression, _ text: String) -> [String]? { + let ns = text as NSString + guard let match = regex.firstMatch(in: text, range: NSRange(location: 0, length: ns.length)) else { return nil } + return (0.. UInt8 { + guard offset < bytes.count else { throw Failure.invalid("truncated binary artifact.") } + defer { offset += 1 }; return bytes[offset] + } + mutating func word() throws -> Int { Int(try byte()) * 256 + Int(try byte()) } + mutating func string() throws -> String { + var result: [UInt8] = [] + while true { + let next = try byte(); if next == 0 { break }; result.append(next) + guard result.count <= 4096 else { throw Failure.invalid("oversized object symbol.") } + } + guard let value = String(bytes: result, encoding: .utf8) else { throw Failure.invalid("invalid object symbol encoding.") } + return value + } + } + private struct Relocation { + enum Term { case integer(Int), external(String), local(String), base, operation(UInt8) } + let offset: Int, width: Int + let terms: [Term] + func evaluate(base: Int, local: (String) throws -> Int, external: (String) throws -> Int) throws -> Int { + var stack: [Int] = [] + for term in terms { + switch term { + case .integer(let n): stack.append(n) + case .external(let name): stack.append(try external(name)) + case .local(let name): stack.append(try local(name)) + case .base: stack.append(base) + case .operation(let operation): + guard let rhs = stack.popLast() else { throw Failure.invalid("invalid relocation expression.") } + if [12, 13, 14].contains(operation) { + stack.append(operation == 12 ? -rhs : operation == 13 ? ~rhs : (~rhs & 255)); continue + } + guard let lhs = stack.popLast() else { throw Failure.invalid("invalid relocation expression.") } + let result: Int + switch operation { + case 1: result = lhs + rhs + case 2: result = lhs - rhs + case 3: result = lhs * rhs + case 4, 6: guard rhs != 0 else { throw Failure.invalid("division by zero in relocation.") }; result = lhs / rhs + case 5: guard rhs != 0 else { throw Failure.invalid("division by zero in relocation.") }; result = lhs % rhs + case 7: result = lhs & rhs + case 8: result = lhs | rhs + case 9: result = lhs ^ rhs + case 10: result = lhs != 0 && rhs != 0 ? 1 : 0 + case 11: result = lhs != 0 || rhs != 0 ? 1 : 0 + case 15: result = lhs == rhs ? 1 : 0 + case 16: result = lhs != rhs ? 1 : 0 + case 17: result = lhs < rhs ? 1 : 0 + case 18: result = lhs <= rhs ? 1 : 0 + case 19: result = lhs > rhs ? 1 : 0 + case 20: result = lhs >= rhs ? 1 : 0 + default: throw Failure.invalid("unsupported relocation operator.") + } + // Bound malicious expressions before Swift arithmetic can overflow. + guard (-0x7fff_ffff...0x7fff_ffff).contains(result) else { throw Failure.invalid("relocation arithmetic overflow.") } + stack.append(result) + } + } + guard stack.count == 1, let result = stack.first else { throw Failure.invalid("unresolved relocation expression.") } + return result + } + } + private struct ObjectSection { + let name: String, flags: Set, length: Int, bytes: [UInt8] + let locals: [String: Int] + let exportedNames: Set + let relocations: [Relocation] + var bss: Bool { flags.contains(1) } + var constant: Bool { flags.contains(2) } + static func parse(_ data: Data) throws -> [Self] { + var reader = Reader(data) + for expected in Array("LWOBJ16".utf8) + [0] { guard try reader.byte() == expected else { throw Failure.invalid("unsupported LWASM object format.") } } + var sections: [Self] = [] + while !reader.finished { + let name = try reader.string() + if name.isEmpty { guard reader.finished else { throw Failure.invalid("trailing object bytes.") }; break } + guard !sections.contains(where: { $0.name == name }), sections.count < 256 else { throw Failure.invalid("duplicate or excessive object sections.") } + var flags = Set() + while true { let flag = try reader.byte(); if flag == 0 { break }; guard [1, 2].contains(flag) else { throw Failure.invalid("unsupported section flags.") }; flags.insert(flag) } + var locals: [String: Int] = [:], exportedNames = Set() + for table in 0..<2 { + while true { + let symbol = try reader.string(); if symbol.isEmpty { break } + let value = try reader.word() + if table == 0 { guard locals[symbol] == nil else { throw Failure.invalid("duplicate local symbol.") }; locals[symbol] = value } + else { exportedNames.insert(symbol) } + } + } + var relocations: [Relocation] = [] + while true { + var type = try reader.byte(); if type == 0 { break } + var terms: [Relocation.Term] = [], width = 2 + while type != 0 { + switch type { + case 255: + guard terms.isEmpty else { throw Failure.invalid("relocation flags follow expression terms.") } + switch try reader.byte() { case 1: width = 1; case 2: width = 0; default: throw Failure.invalid("unsupported relocation flags.") } + case 1: terms.append(.integer(Int(Int16(bitPattern: UInt16(try reader.word()))))) + case 2: terms.append(.external(try reader.string())) + case 3: terms.append(.local(try reader.string())) + case 4: terms.append(.operation(try reader.byte())) + case 5: terms.append(.base) + default: throw Failure.invalid("unsupported relocation term.") + } + guard terms.count <= 4096 else { throw Failure.invalid("oversized relocation expression.") } + type = try reader.byte() + } + relocations.append(Relocation(offset: try reader.word(), width: width, terms: terms)) + } + let length = try reader.word() + var bytes: [UInt8] = [] + if !flags.contains(1) { for _ in 0.. + } + struct Location: Equatable, Hashable, Sendable { + let path: String + let line: Int + } + let entryPoint: UInt16 + let binarySHA256: String + let sourceHashes: [String: String] + let instructions: [Instruction] + let objectHashes: [String: String] + let listingHashes: [String: String] + let linkMapSHA256: String + var bankedLayout: CMOCBankedDebugLayout? = nil + var activeModuleIDs: Set? = nil + var executableSymbols: [ExecutableSymbol] = [] + /// Complete relocated executable sections for ordinary flat programs. The + /// worker binds these logical bytes to its actual runtime mapping through + /// the native flat debugger path; no stock physical pages are assumed. + var flatCodeGuards: [CodeGuard] = [] + + var sourcePaths: [String] { Array(Set(instructions.map(\.sourcePath))).sorted() } + + private static func cSymbolAlias(_ name: String) -> String? { + guard name.hasPrefix("_"), name.utf8.count > 1 else { return nil } + let alias = String(name.dropFirst()) + guard let first = alias.utf8.first, (65...90).contains(first) || (97...122).contains(first) || first == 95, + alias.utf8.allSatisfy({ (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) || $0 == 95 }) else { return nil } + return alias + } + + /// Symbol selection names one proven executable address, not a C function + /// range, source line or frame layout. Raw names and unique C aliases work. + func executableSymbol(named name: String) -> ExecutableSymbol? { + let matches = executableSymbols.filter { $0.name == name || Self.cSymbolAlias($0.name) == name } + return matches.count == 1 ? matches.first : nil + } + + var executableSymbolNames: [String] { + var counts: [String: Int] = [:] + for symbol in executableSymbols { + for name in Set([symbol.name] + [Self.cSymbolAlias(symbol.name)].compactMap { $0 }) { + counts[name, default: 0] += 1 + } + } + return counts.filter { $0.value == 1 }.map(\.key).sorted() + } + + /// Runtime identity for code without C statements or typed function ranges. + /// Requires a bank projection and rechecks all code against this snapshot. + func executableLocation(at address: UInt16, memory: Data, available: Data, sharedPaths: Set? = nil) -> ExecutableLocation? { + guard address < 0xfe00, let layout = bankedLayout, let active = activeModuleIDs, + verifiesRuntime(memory: memory, available: available) else { return nil } + let permitted = sharedPaths.map { sharedExecutableModuleIDs(paths: $0) } ?? active + let matches: [ExecutableLocation] = layout.modules.filter { active.contains($0.id) && permitted.contains($0.id) }.flatMap { module in + module.codeGuards.compactMap { code in + let start = Int(code.address), end = start + code.bytes.count + guard Int(address) >= start, Int(address) < end, end <= 0xfe00, + let physical = module.physicalAddress(Int(address)) else { return nil } + return .init(address: address, moduleID: module.id, physicalAddress: physical, codeRange: start..) -> Set { + let mapped = instructions.filter { paths.contains($0.sourcePath) }.compactMap(\.moduleID) + let symbols = executableSymbols.filter { !paths.isDisjoint(with: $0.sourcePaths) }.map(\.moduleID) + return Set(mapped + symbols).intersection(activeModuleIDs ?? []) + } + + func executableCodeRanges(sharedPaths: Set) -> [Range] { + guard let layout = bankedLayout else { return [] } + let permitted = sharedExecutableModuleIDs(paths: sharedPaths) + return layout.modules.filter { permitted.contains($0.id) }.flatMap { module in + module.codeGuards.compactMap { code in + let start = Int(code.address), end = start + code.bytes.count + return !code.bytes.isEmpty && end <= 0xfe00 ? start..] { + guard let layout = bankedLayout, let active = activeModuleIDs else { return [] } + return layout.modules.filter { active.contains($0.id) }.flatMap { module in + module.codeGuards.compactMap { code in + let start = Int(code.address), end = start + code.bytes.count + return !code.bytes.isEmpty && end <= 0xfe00 ? start.. Bool { + guard memory.count == 65536, available.count == 65536 else { return false } + func matches(_ address: UInt16, _ bytes: [UInt8]) -> Bool { + let start = Int(address), end = start + bytes.count + return end <= memory.count && available[start.. [Int] { + Array(Set(instructions.filter { $0.sourcePath == path }.map(\.sourceLine))).sorted() + } + func addresses(forLine line: Int, in path: String) -> [UInt16] { + instructions.filter { $0.sourcePath == path && $0.sourceLine == line }.map(\.address) + } + func location(at address: UInt16) -> Location? { + let matches = instructions.filter { $0.address == address } + return matches.count == 1 ? matches.first.map { Location(path: $0.sourcePath, line: $0.sourceLine) } : nil + } + func matches(sources: [String: Data], binary: Data) -> Bool { + sources.mapValues(CMOCSourceMap.sha256) == sourceHashes && CMOCSourceMap.sha256(binary) == binarySHA256 + } + + static func parse(sources: [String: Data], compilationDirectory: URL, + units: [TranslationUnit], linkMap: Data, binary: Data, + bankedLayout: CMOCBankedDebugLayout? = nil) throws -> Self { + guard !units.isEmpty, units.count <= 1024, !sources.isEmpty, sources.count <= 4096 else { + throw CMOCSourceMap.Failure.invalid("no supported compilation units or too many project sources.") + } + if let bankedLayout { + guard bankedLayout.binarySHA256 == CMOCSourceMap.sha256(binary), + bankedLayout.sourceHashes == sources.mapValues(CMOCSourceMap.sha256), + bankedLayout.linkMap == linkMap else { throw CMOCSourceMap.Failure.invalid("banked build identities disagree.") } + } + let paths = sources.keys.sorted() + for path in paths { + guard !path.isEmpty, !path.hasPrefix("/"), !path.split(separator: "/").contains(".."), + (path as NSString).standardizingPath == path else { + throw CMOCSourceMap.Failure.invalid("source identities must be canonical project-relative paths.") + } + } + var instructions: [Instruction] = [], addresses = Set(), occupied = Set() + var entry: UInt16?, objectHashes: [String: String] = [:], listingHashes: [String: String] = [:] + var executableSymbols: [ExecutableSymbol] = [], flatCodeGuards: [CodeGuard] = [] + let marker = try NSRegularExpression(pattern: #"\* (?:Line (.+):([0-9]+)(?::.*)?|FUNCTION .+: defined at (.+):([0-9]+))$"#) + func normalize(_ value: String) -> String { + var value = value + while value.hasPrefix("./") { value.removeFirst(2) } + return (value as NSString).standardizingPath + } + for unit in units { + guard sources[unit.sourcePath] != nil, objectHashes[unit.objectName] == nil else { + throw CMOCSourceMap.Failure.invalid("a translation unit is missing its source or repeats an object identity.") + } + if let bankedLayout { + let listingPath = String(unit.objectName.dropLast(2)) + ".lst" + guard bankedLayout.artifactHashes[unit.objectName] == CMOCSourceMap.sha256(unit.object), + unit.listing.isEmpty || bankedLayout.artifactHashes[listingPath] == CMOCSourceMap.sha256(unit.listing) else { + throw CMOCSourceMap.Failure.invalid("object/listing is absent from the banked build manifest.") + } + } + guard let listingText = String(data: unit.listing, encoding: .utf8) else { + throw CMOCSourceMap.Failure.invalid("invalid listing encoding.") + } + var mentioned = Set() + for line in listingText.components(separatedBy: .newlines) { + let ns = line as NSString + guard let match = marker.firstMatch(in: line, range: NSRange(location: 0, length: ns.length)) else { continue } + let index = match.range(at: 1).location == NSNotFound ? 3 : 1 + mentioned.insert(normalize(ns.substring(with: match.range(at: index)))) + } + let candidates = paths.filter { path in + let absolute = compilationDirectory.appendingPathComponent(path).path + return mentioned.contains(normalize(path)) || mentioned.contains(normalize(absolute)) || + (path == unit.sourcePath && mentioned.contains(normalize(unit.sourceName))) + } + // Even an assembly-only/optimized-away C unit must have its object + // bytes checked. It simply contributes no source breakpoint locations. + for path in candidates.isEmpty ? [unit.sourcePath] : candidates { + let absolute = compilationDirectory.appendingPathComponent(path).path + let sourceName = path == unit.sourcePath ? unit.sourceName : absolute + let map = try CMOCSourceMap.parse(source: sources[path]!, sourceName: sourceName, + listing: unit.listing, object: unit.object, objectName: unit.objectName, + linkMap: linkMap, binary: binary, sourceAliases: [path, absolute], + objectAliases: [compilationDirectory.appendingPathComponent(unit.objectName).path], + strictIdentities: true, allowEmpty: true, bankedLayout: bankedLayout) + if let entry, entry != map.entryPoint { throw CMOCSourceMap.Failure.invalid("inconsistent entry points.") } + entry = map.entryPoint + for item in map.instructions { + guard addresses.insert(item.physicalAddress ?? UInt32(item.address)).inserted else { + throw CMOCSourceMap.Failure.invalid("two source locations claim the same instruction address.") + } + for index in item.bytes.indices { + let address = Int(item.address) + index + let identity = item.moduleID.flatMap { bankedLayout?.module(id: $0)?.physicalAddress(address) } ?? UInt32(address) + guard address < 65536, occupied.insert(identity).inserted else { + throw CMOCSourceMap.Failure.invalid("overlapping source instruction ranges.") + } + } + instructions.append(Instruction(sourcePath: path, sourceLine: item.sourceLine, + address: item.address, bytes: item.bytes, assembly: item.assembly, + moduleID: item.moduleID, physicalAddress: item.physicalAddress)) + } + } + if let bankedLayout { + executableSymbols += try CMOCSourceMap.executableObjectSymbols(object: unit.object, objectName: unit.objectName, + objectAliases: [compilationDirectory.appendingPathComponent(unit.objectName).path], linkMap: linkMap, + binary: binary, layout: bankedLayout, sourcePaths: candidates) + guard executableSymbols.count <= 8192 else { throw CMOCSourceMap.Failure.invalid("executable symbol catalog exceeds its limit.") } + } else { + let verified = try CMOCSourceMap.verifiedSections(object: unit.object, objectName: unit.objectName, + linkMap: linkMap, binary: binary, + objectAliases: [compilationDirectory.appendingPathComponent(unit.objectName).path], strictIdentities: true) + if let code = verified.sections["code"], let bytes = code.final, !bytes.isEmpty { + guard code.base >= 0, code.base + bytes.count <= 0xfe00 else { + throw CMOCSourceMap.Failure.invalid("flat executable code is outside supported RAM.") + } + flatCodeGuards.append(.init(address: UInt16(code.base), bytes: bytes)) + } + } + objectHashes[unit.objectName] = CMOCSourceMap.sha256(unit.object) + if !unit.listing.isEmpty { listingHashes[unit.objectName] = CMOCSourceMap.sha256(unit.listing) } + } + guard let entry, !instructions.isEmpty || !executableSymbols.isEmpty || !flatCodeGuards.isEmpty else { throw CMOCSourceMap.Failure.invalid("no verified C locations or executable evidence were found.") } + var guarded = IndexSet() + for guardRange in flatCodeGuards { + let range = Int(guardRange.address)..<(Int(guardRange.address) + guardRange.bytes.count) + guard !guarded.intersects(integersIn: range) else { throw CMOCSourceMap.Failure.invalid("flat executable sections overlap.") } + guarded.insert(integersIn: range) + } + return Self(entryPoint: entry, binarySHA256: CMOCSourceMap.sha256(binary), + sourceHashes: sources.mapValues(CMOCSourceMap.sha256), instructions: instructions.sorted { $0.address < $1.address }, + objectHashes: objectHashes, listingHashes: listingHashes, linkMapSHA256: CMOCSourceMap.sha256(linkMap), bankedLayout: bankedLayout, + executableSymbols: executableSymbols.sorted { ($0.name, $0.objectPath, $0.address) < ($1.name, $1.objectPath, $1.address) }, + flatCodeGuards: flatCodeGuards.sorted { $0.address < $1.address }) + } +} + +extension CMOCProjectSourceMap { + func addresses(file: String, line: Int) -> [UInt16] { addresses(forLine: line, in: file) } + func instruction(at address: UInt16) -> Instruction? { + let matches = instructions.filter { $0.address == address } + return matches.count == 1 ? matches.first : nil + } + + /// Select only modules whose complete page contract matches the current + /// snapshot. The caller must additionally verify live bytes before using it. + func projected(physicalPages: [Int: Int]) -> Self { + guard let bankedLayout else { return self } + let active = Set(bankedLayout.modules.filter { module in + module.pages.allSatisfy { physicalPages[$0.logicalPage] == $0.physicalPage } + }.map(\.id)) + return projected(activeModuleIDs: active) + } + + /// Mapped code can still belong to a loader or an overlay not installed + /// yet. Such modules contribute no source or variable identities until all + /// their executable bytes match this same immutable memory snapshot. + func projected(physicalPages: [Int: Int], memory: Data, available: Data) -> Self { + guard let bankedLayout else { return self } + guard memory.count == 65536, available.count == 65536 else { return projected(activeModuleIDs: []) } + let active = Set(bankedLayout.modules.filter { module in + module.pages.allSatisfy { physicalPages[$0.logicalPage] == $0.physicalPage } && + module.codeGuards.allSatisfy { guardRange in + let start = Int(guardRange.address), end = start + guardRange.bytes.count + return end <= memory.count && available[start..) -> Self { + return Self(entryPoint: entryPoint, binarySHA256: binarySHA256, sourceHashes: sourceHashes, + instructions: instructions.filter { $0.moduleID.map(active.contains) == true }, + objectHashes: objectHashes, listingHashes: listingHashes, linkMapSHA256: linkMapSHA256, + bankedLayout: bankedLayout, activeModuleIDs: active, + executableSymbols: executableSymbols.filter { active.contains($0.moduleID) }) + } + + /// Compatibility projection for the existing editor. Object/listing hashes + /// identify the complete contributing project set, not a single object file. + func map(forFile path: String) -> CMOCSourceMap? { + let selected = instructions.filter { $0.sourcePath == path } + guard let hash = sourceHashes[path], !selected.isEmpty else { return nil } + func aggregate(_ values: [String: String]) -> String { + CMOCSourceMap.sha256(Data(values.keys.sorted().map { $0 + "\0" + values[$0]! }.joined(separator: "\n").utf8)) + } + return CMOCSourceMap(sourceName: path, entryPoint: entryPoint, + provenance: .init(sourceSHA256: hash, binarySHA256: binarySHA256, + objectSHA256: aggregate(objectHashes), listingSHA256: aggregate(listingHashes), linkMapSHA256: linkMapSHA256), + instructions: selected.map { .init(sourceLine: $0.sourceLine, address: $0.address, bytes: $0.bytes, assembly: $0.assembly, + moduleID: $0.moduleID, physicalAddress: $0.physicalAddress) }) + } + + static func parse(artifact: CMOCBuildArtifact, bankedLayout: CMOCBankedDebugLayout? = nil) throws -> Self { + guard artifact.hasBinary else { throw CMOCSourceMap.Failure.invalid("this target did not produce an executable binary.") } + let retainedBinary = try Data(contentsOf: artifact.binaryURL) + guard retainedBinary == artifact.binaryData else { + throw CMOCSourceMap.Failure.invalid("retained executable bytes differ from this build's binary identity.") + } + let bankedLayout = try bankedLayout ?? artifact.bankedDebugLayout() + let linkMap = try bankedLayout?.linkMap ?? Data(contentsOf: artifact.mapURL) + guard let mapText = String(data: linkMap, encoding: .utf8) else { throw CMOCSourceMap.Failure.invalid("invalid linker-map encoding.") } + let objectPattern = try NSRegularExpression(pattern: #"^Section: [^\s]+ \((.+)\) load at [0-9A-Fa-f]{4}, length [0-9A-Fa-f]{4}$"#) + var linked = Set() + for row in mapText.components(separatedBy: .newlines) { + let ns = row as NSString + if let match = objectPattern.firstMatch(in: row, range: NSRange(location: 0, length: ns.length)) { + var path = ns.substring(with: match.range(at: 1)) + while path.hasPrefix("./") { path.removeFirst(2) } + let prefix = artifact.compilationDirectory.path + "/" + if path.hasPrefix(prefix) { path.removeFirst(prefix.count) } + linked.insert(path) + } + } + let marker = try NSRegularExpression(pattern: #"\* (?:Line (.+):[0-9]+(?::.*)?|FUNCTION .+: defined at (.+):[0-9]+)$"#) + var aliases: [String: String] = [:] + for path in artifact.sources.keys { + aliases[path] = path + aliases[artifact.compilationDirectory.appendingPathComponent(path).path] = path + } + var units: [TranslationUnit] = [] + let outputs = Set(artifact.outputPaths.isEmpty ? [artifact.entrySourcePath.replacingOccurrences(of: ".c", with: ".o"), artifact.entrySourcePath.replacingOccurrences(of: ".c", with: ".lst")] : artifact.outputPaths) + for path in outputs.sorted() where path.hasSuffix(".o") && linked.contains(path) { + let listingPath = String(path.dropLast(2)) + ".lst" + guard outputs.contains(listingPath) || bankedLayout != nil else { continue } + // Assembly-only objects still replay every relocation even when + // their recipe did not request a source listing. + let listing = try outputs.contains(listingPath) ? Data(contentsOf: artifact.fileURL(listingPath)) : Data() + guard let text = String(data: listing, encoding: .utf8) else { throw CMOCSourceMap.Failure.invalid("invalid listing encoding.") } + var referenced: [String] = [] + for row in text.components(separatedBy: .newlines) { + let ns = row as NSString + guard let match = marker.firstMatch(in: row, range: NSRange(location: 0, length: ns.length)) else { continue } + let index = match.range(at: 1).location == NSNotFound ? 2 : 1 + var name = ns.substring(with: match.range(at: index)) + while name.hasPrefix("./") { name.removeFirst(2) } + if let source = aliases[name], !referenced.contains(source) { referenced.append(source) } + } + guard let source = referenced.first(where: { $0.hasSuffix(".c") }) ?? referenced.first ?? (bankedLayout == nil ? nil : artifact.entrySourcePath) else { continue } + units.append(TranslationUnit(sourcePath: source, + sourceName: artifact.compilationDirectory.appendingPathComponent(source).path, + objectName: path, listing: listing, object: try Data(contentsOf: artifact.fileURL(path)))) + } + return try parse(sources: artifact.sources, compilationDirectory: artifact.compilationDirectory, + units: units, linkMap: linkMap, binary: artifact.binaryData, bankedLayout: bankedLayout) + } +} + +/// The same verified source/type evidence serves build receipts and stopped +/// observations. Catalogs contain only shared declarations and bounded metadata; +/// they confer no permission to read arbitrary guest addresses. +struct CMOCPublicDebugEvidence { + static func fields(artifact: CMOCBuildArtifact, sharedPaths: Set) -> [String: Any] { + do { + let map = try CMOCProjectSourceMap.parse(artifact: artifact) + do { + return fields(map: map, metadata: try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map), + variableError: nil, sharedPaths: sharedPaths) + } catch { + return fields(map: map, metadata: nil, variableError: reason(error, artifact: artifact), sharedPaths: sharedPaths) + } + } catch { + return ["status": "unavailable", "source_map": "unavailable", "variables": "unavailable", + "reason": reason(error, artifact: artifact), "reason_code": "debug_evidence_not_verified", + "binary_sha256": CMOCSourceMap.sha256(artifact.binaryData), + "requirements": "Retain the matching executable, linker map, linked project objects and listings. Packed/banked builds also need the declared debug manifest."] + } + } + + private static func reason(_ error: Error, artifact: CMOCBuildArtifact) -> String { + var text = error.localizedDescription + for root in [artifact.directory.path, artifact.compilationDirectory.path].sorted(by: { $0.count > $1.count }) { + text = text.replacingOccurrences(of: root, with: "") + } + return String(text.prefix(2000)) + } + + static func fields(map: CMOCProjectSourceMap, metadata: CMOCVariableDebug?, variableError: String?, + sharedPaths: Set) -> [String: Any] { + var fields: [String: Any] = ["status": metadata == nil ? "source_only" : "verified", + "source_map": "verified", "variables": metadata == nil ? "unavailable" : "verified", + "banked": map.bankedLayout != nil, "binary_sha256": map.binarySHA256, + "entry_point": Int(map.entryPoint), "link_map_sha256": map.linkMapSHA256, + "c_frame_locals": "unavailable", "c_frame_locals_reason": "Owned entry/instruction stops do not establish a C frame; optimized-out or unknown layouts are not guessed.", + "owned_stop_evidence": map.bankedLayout != nil ? "declared_banked_modules" : map.flatCodeGuards.isEmpty ? "unavailable" : "verified_flat_code"] + if let variableError { fields["reason"] = variableError; fields["reason_code"] = "typed_metadata_unavailable" } + func catalog(_ name: String, _ rows: [Any]) { + let result = CMOCSourceMap.boundedJSONCatalog(rows, maximumBytes: 16 * 1024) + fields[name] = result.items; fields[name + "_total"] = result.total; fields[name + "_truncated"] = result.truncated + } + let instructions = map.instructions.filter { sharedPaths.contains($0.sourcePath) } + catalog("c_line_stops", instructions.map { point in + ["path": point.sourcePath, "line": point.sourceLine, "address": Int(point.address), + "module_id": point.moduleID as Any? ?? NSNull(), + "physical_address": point.physicalAddress as Any? ?? NSNull()] as [String: Any] + }) + let functions = metadata?.functions.filter { sharedPaths.contains($0.sourcePath) } ?? [] + let functionNames = (metadata?.breakpointFunctionNames ?? []).filter { name in functions.contains { $0.name == name } } + let symbols = map.executableSymbolNames.filter { name in + map.executableSymbol(named: name).map { !sharedPaths.isDisjoint(with: $0.sourcePaths) } == true + } + let entries = Set((metadata?.functionEntryNames ?? []).filter { name in functions.contains { $0.name == name } } + symbols).sorted() + catalog("functions", functionNames) + catalog("function_entries", entries) + catalog("executable_symbols", symbols) + catalog("function_details", functions.map { function in + var row: [String: Any] = ["name": function.name, "path": function.sourcePath, + "entry_address": function.entry, "module_id": function.moduleID as Any? ?? NSNull(), + "function_entry_available": metadata?.entryFunction(named: function.name) != nil] + if let point = metadata?.breakpointInstruction(named: function.name) { + row["c_line_stop"] = ["path": point.sourcePath, "line": point.sourceLine, "address": Int(point.address)] + } else { row["c_line_unavailable"] = "No unique compiler-mapped C statement in this function's verified body." } + if let line = function.sourceLine { row["declaration_line"] = line } + return row + }) + catalog("globals", globalDeclarations(metadata: metadata, sharedPaths: sharedPaths)) + catalog("modules", map.bankedLayout?.modules.map(\.id) ?? []) + catalog("module_details", map.bankedLayout?.modules.map { module in + ["id": module.id, "pages": module.pages.map { ["logical_page": $0.logicalPage, "physical_page": $0.physicalPage] }] as [String: Any] + } ?? []) + catalog("framebuffers", map.bankedLayout?.framebuffers.map(\.workerFields) ?? []) + fields["function_metadata_count"] = functions.count + return fields + } + + static func globalDeclarations(metadata: CMOCVariableDebug?, sharedPaths: Set) -> [[String: Any]] { + (metadata?.variables ?? []).filter { $0.scope == nil && $0.offset == nil && sharedPaths.contains($0.sourcePath) } + .sorted { ($0.sourcePath, $0.line, $0.name) < ($1.sourcePath, $1.line, $1.name) }.map { variable in + var row: [String: Any] = ["name": variable.name, "path": variable.sourcePath, "line": variable.line, + "type": variable.type.name, "byte_count": variable.type.size, + "module_id": variable.moduleID as Any? ?? NSNull(), "is_static": variable.isStatic, + "status": "runtime_required"] + if let address = variable.address, address >= 0, variable.type.size > 0, address + variable.type.size <= 0xfe00 { + row["address"] = address + } else { row["status"] = "unavailable"; row["unavailable"] = "No supported verified RAM storage for this declaration." } + if variable.type.kind == "unsupported" { + row["status"] = "unavailable"; row["unavailable"] = "The compiler emitted an unsupported or optimized-out type/storage layout." + } + return row + } + } + + /// Values come from the same frozen safe-memory capture as registers and + /// permitted ranges. Each declaration is resolved independently so a local + /// shadow cannot cause a global's address/value to be mislabeled. + static func globals(metadata: CMOCVariableDebug?, sharedPaths: Set, context: CMOCWatchEvaluator.Context, + permittedRanges: [Range], physicalPages: [Int: Int]) -> (items: [[String: Any]], total: Int, truncated: Bool) { + let definitions = (metadata?.variables ?? []).filter { $0.scope == nil && $0.offset == nil && sharedPaths.contains($0.sourcePath) } + .sorted { ($0.sourcePath, $0.line, $0.name) < ($1.sourcePath, $1.line, $1.name) } + var rows = globalDeclarations(metadata: metadata, sharedPaths: sharedPaths) + // Bound evaluation work independently of the encoded catalog size. + rows = Array(rows.prefix(128)) + for index in rows.indices { + let variable = definitions[index] + guard let metadata, let address = variable.address, + permittedRanges.contains(where: { $0.contains(address) && address + variable.type.size <= $0.upperBound }), + variable.type.size > 0 else { + rows[index]["status"] = "unavailable"; rows[index]["unavailable"] = "Storage is not readable in this verified stopped mapping."; continue + } + let selected = CMOCVariableDebug(functions: metadata.functions, variables: [variable], sourceMap: metadata.sourceMap) + let value = CMOCWatchEvaluator(metadata: selected, context: context, frameLocalsAvailable: false).evaluate(variable.name) + if let error = value.error { rows[index]["status"] = "unavailable"; rows[index]["unavailable"] = error } + else { rows[index]["status"] = "available"; rows[index]["value"] = value.value } + if let page = physicalPages[address / 8192] { rows[index]["physical_address"] = page * 8192 + address % 8192 } + } + let catalog = CMOCSourceMap.boundedJSONCatalog(rows, maximumBytes: 32 * 1024) + return (catalog.items, definitions.count, catalog.truncated || catalog.items.count != definitions.count) + } +} diff --git a/platforms/macos/App/CMOCVariableDebug.swift b/platforms/macos/App/CMOCVariableDebug.swift new file mode 100644 index 0000000..401ad50 --- /dev/null +++ b/platforms/macos/App/CMOCVariableDebug.swift @@ -0,0 +1,359 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// Types and storage locations emitted by the compiler, bound to the exact +/// source/object/listing/link-map/executable set already verified by the IDE. +struct CMOCVariableDebug: Sendable { + final class CType: Decodable, Sendable { + struct Member: Decodable, Sendable { + let name: String + let offset: Int + let type: CType + } + let name: String + let kind: String + let size: Int + let signed: Bool? + let count: Int? + let element: CType? + let members: [Member]? + let floatingFormat: String? + init(name: String, kind: String, size: Int, signed: Bool? = nil, + count: Int? = nil, element: CType? = nil, members: [Member]? = nil, floatingFormat: String? = nil) { + self.name = name; self.kind = kind; self.size = size; self.signed = signed + self.count = count; self.element = element; self.members = members + self.floatingFormat = floatingFormat + } + static var integer: CType { CType(name: "int", kind: "integer", size: 2, signed: true) } + } + struct Function: Sendable { + let name: String + let sourcePath: String + let entry: Int + let body: Int + let end: Int + let frame: Bool + var moduleID: String? = nil + var sourceLine: Int? = nil + } + struct Variable: Sendable { + let name: String + let sourcePath: String + let line: Int + let type: CType + let address: Int? + let offset: Int? + let scope: Range? + let isStatic: Bool + var moduleID: String? = nil + var scopeModuleID: String? = nil + } + let functions: [Function] + let variables: [Variable] + let sourceMap: CMOCProjectSourceMap + + /// A compiler function record alone is not a C breakpoint location: pure + /// assembly functions can have type metadata without any mapped C statement. + /// Keep the advertised names and the actual stop selection on one path. + func breakpointInstruction(named name: String) -> CMOCProjectSourceMap.Instruction? { + let matches = functions.filter { $0.name == name } + guard matches.count == 1, let function = matches.first else { return nil } + return sourceMap.instructions.lazy.filter { + $0.moduleID == function.moduleID && Int($0.address) >= function.body && Int($0.address) < function.end + }.min { $0.address < $1.address } + } + + var breakpointFunctionNames: [String] { + Set(functions.map(\.name)).filter { breakpointInstruction(named: $0) != nil }.sorted() + } + + /// Function-entry stops describe a verified executable symbol, including + /// assembly functions and C prologues. They never imply a mapped C line. + func entryFunction(named name: String) -> Function? { + let matches = functions.filter { $0.name == name } + guard matches.count == 1, let function = matches.first, verifiesEntry(function) else { return nil } + return function + } + + var functionEntryNames: [String] { + Set(functions.map(\.name)).filter { entryFunction(named: $0) != nil }.sorted() + } + + /// A live containing-function claim requires an explicit bank projection. + /// PC may be in a verified prologue before the first mapped C statement. + func entryFunction(containing address: UInt16) -> Function? { + guard sourceMap.activeModuleIDs != nil || (sourceMap.bankedLayout == nil && !sourceMap.flatCodeGuards.isEmpty) else { return nil } + let matches = functions.filter { + Int(address) >= $0.entry && Int(address) < $0.end && verifiesEntry($0) + } + return matches.count == 1 ? matches.first : nil + } + + private func verifiesEntry(_ function: Function) -> Bool { + guard !function.name.isEmpty, !function.sourcePath.isEmpty, + function.entry >= 0, function.end > function.entry, function.end <= 0xfe00 else { return false } + if sourceMap.bankedLayout == nil { + guard function.moduleID == nil else { return false } + var covered = function.entry + for code in sourceMap.flatCodeGuards.sorted(by: { $0.address < $1.address }) { + let begin = Int(code.address), end = begin + code.bytes.count + if end <= covered { continue } + guard begin <= covered else { return false } + covered = end + if covered >= function.end { return true } + } + return false + } + guard + let identity = function.moduleID, let module = sourceMap.bankedLayout?.module(id: identity), + !module.codeSections.isEmpty, + !module.pages.isEmpty, module.pages.count <= 8, + Set(module.pages.map(\.logicalPage)).count == module.pages.count, + module.pages.allSatisfy({ (0..<8).contains($0.logicalPage) && (0..<1024).contains($0.physicalPage) }) else { return false } + if let active = sourceMap.activeModuleIDs, !active.contains(identity) { return false } + for page in function.entry / 8192...(function.end - 1) / 8192 { + guard module.pages.contains(where: { $0.logicalPage == page }) else { return false } + } + var covered = function.entry + for code in module.codeGuards.sorted(by: { $0.address < $1.address }) { + let begin = Int(code.address), end = begin + code.bytes.count + if end <= covered { continue } + guard begin <= covered else { return false } + covered = end + if covered >= function.end { return true } + } + return false + } + + func projected(physicalPages: [Int: Int]) -> Self { + projected(sourceMap: sourceMap.projected(physicalPages: physicalPages)) + } + + func projected(physicalPages: [Int: Int], memory: Data, available: Data) -> Self { + projected(sourceMap: sourceMap.projected(physicalPages: physicalPages, memory: memory, available: available)) + } + + private func projected(sourceMap selected: CMOCProjectSourceMap) -> Self { + guard let active = selected.activeModuleIDs else { return self } + return Self(functions: functions.filter { $0.moduleID.map(active.contains) == true }, + variables: variables.filter { variable in + variable.moduleID.map(active.contains) == true && + (variable.scopeModuleID == nil || variable.scopeModuleID.map(active.contains) == true) + }, sourceMap: selected) + } + + enum Failure: LocalizedError { + case invalid(String) + var errorDescription: String? { if case .invalid(let text) = self { return "C variables unavailable: " + text }; return nil } + } + private struct Record: Decodable { + let kind: String + let name: String + let location: String + let type: CType? + let symbol: String? + let begin: String + let end: String + let frame: Bool? + let offset: Int? + let `static`: Bool? + } + static func parse(artifact: CMOCBuildArtifact, verifiedMap: CMOCProjectSourceMap) throws -> Self { + func fail(_ message: String) -> Failure { .invalid(message) } + guard verifiedMap.matches(sources: artifact.sources, binary: artifact.binaryData) else { + throw fail("source or executable changed since verification. Rebuild before debugging.") + } + let linkData = try verifiedMap.bankedLayout?.linkMap ?? Data(contentsOf: artifact.mapURL) + guard CMOCSourceMap.sha256(linkData) == verifiedMap.linkMapSHA256, + let linkText = String(data: linkData, encoding: .utf8) else { throw fail("linker map changed since verification.") } + func canonical(_ name: String) -> String { + // NSString standardization can collapse /private/var to /var only + // while the path exists. Strip the frozen physical build prefix + // first, so keeping/reusing/deleting the incremental cache cannot + // change the identity of the same retained compiler location. + let physicalPrefix = artifact.compilationDirectory.path + "/" + var name = name + if name.hasPrefix(physicalPrefix) { + name.removeFirst(physicalPrefix.count) + } else { + name = (name as NSString).standardizingPath + let aliasPrefix = (artifact.compilationDirectory.path as NSString).standardizingPath + "/" + if name.hasPrefix(aliasPrefix) { name.removeFirst(aliasPrefix.count) } + } + while name.hasPrefix("./") { name.removeFirst(2) } + return name + } + let symbolPattern = try NSRegularExpression(pattern: #"^Symbol: (.+) \((.+)\) = ([0-9A-Fa-f]{4})$"#) + var symbols: [String: [String: Int]] = [:] + for line in linkText.components(separatedBy: .newlines) { + let ns = line as NSString + guard let match = symbolPattern.firstMatch(in: line, range: NSRange(location: 0, length: ns.length)) else { continue } + let name = ns.substring(with: match.range(at: 1)), object = canonical(ns.substring(with: match.range(at: 2))) + guard let address = Int(ns.substring(with: match.range(at: 3)), radix: 16), symbols[object]?[name] == nil else { + throw fail("duplicate or malformed linker symbol.") + } + symbols[object, default: [:]][name] = address + } + func location(_ raw: String) throws -> (String, Int) { + guard let colon = raw.lastIndex(of: ":"), let line = Int(raw[raw.index(after: colon)...]), line > 0 else { + throw fail("invalid compiler source location.") + } + let path = canonical(String(raw[..= 0, member.offset <= type.size, + member.type.size <= type.size - member.offset else { throw fail("member leaves its aggregate.") } + } + case "floating": + guard (type.floatingFormat?.count ?? 0) <= 128 else { throw fail("invalid floating-point format metadata.") } + // Unknown or legacy formats remain individually unavailable. + // Known tags must agree with the declared storage layout. + if let format = type.floatingFormat, + let size = ["coco-basic-40": 5, "ieee754-binary32-be": 4][format], size != type.size { + throw fail("floating-point format disagrees with its storage size.") + } + case "unsupported": break + default: throw fail("unknown type metadata version.") + } + } + var functions: [Function] = [], variables: [Variable] = [] + for object in verifiedMap.objectHashes.keys.sorted() { + guard let listingHash = verifiedMap.listingHashes[object], + listingHash != CMOCSourceMap.sha256(Data()) else { continue } + let listingPath = String(object.dropLast(2)) + ".lst" + let listing = try Data(contentsOf: artifact.fileURL(listingPath)) + let bytes = try Data(contentsOf: artifact.fileURL(object)) + guard CMOCSourceMap.sha256(listing) == verifiedMap.listingHashes[object], + CMOCSourceMap.sha256(bytes) == verifiedMap.objectHashes[object], + let text = String(data: listing, encoding: .utf8) else { throw fail("compiler artifacts changed since verification.") } + // LWASM retains at most 2,048 input bytes per line. Large compiler + // type records therefore lose their tail in the listing. Recover + // only from the immutable, source-hashed assembly from this build, + // and bind every recovered record to the corresponding listing row. + func metadataRows(_ text: String) -> [(payload: String, prefixBytes: Int)] { + text.components(separatedBy: .newlines).compactMap { row in + guard let marker = row.range(of: "* VCCDBG1 ") else { return nil } + return (String(row[marker.upperBound...]), row[.. listed.payload.utf8.count && + complete.payload.hasPrefix(listed.payload) + guard exact || truncated else { + throw fail("\(assemblyPath): compiler metadata record differs from the verified listing.") + } + } + payloads = completeRows.map(\.payload) + } + let objectSymbols = try CMOCSourceMap.resolvedObjectSymbols(object: bytes, objectName: object, + objectAliases: [artifact.compilationDirectory.appendingPathComponent(object).path], linkMap: linkData) + let symbolModules = try verifiedMap.bankedLayout.map { try CMOCSourceMap.resolvedObjectSymbolModules(object: bytes, layout: $0) } ?? [:] + func module(_ symbol: String) throws -> String? { + guard verifiedMap.bankedLayout != nil else { return nil } + guard let id = symbolModules[symbol] else { throw fail("compiler storage label has no verified banked placement.") } + return id + } + func visible(_ id: String?) -> Bool { + guard let active = verifiedMap.activeModuleIDs else { return true } + return id.map(active.contains) == true + } + func address(_ name: String) throws -> Int { + guard let result = symbols[canonical(object)]?[name], objectSymbols[name] == result else { + throw fail("compiler storage label disagrees with its object symbol table.") + } + return result + } + for (recordIndex, payload) in payloads.enumerated() { + guard payload.utf8.count < 512 * 1024, functions.count + variables.count < 20000 else { throw fail("debug metadata exceeds its limits.") } + let payloadData = Data(payload.utf8) + // Bound nesting before recursive Decodable type construction. + let decodedJSON: Any + do { decodedJSON = try JSONSerialization.jsonObject(with: payloadData) } + catch { + throw fail("\(listingPath), metadata record \(recordIndex + 1): invalid or truncated JSON; retain hash-verified compiler assembly for complete type records.") + } + var pending: [(Any, Int)] = [(decodedJSON, 0)] + var nodes = 0 + while let (node, depth) = pending.popLast() { + nodes += 1 + guard depth <= 24, nodes <= 10000 else { throw fail("debug type nesting exceeds its limits.") } + if let dictionary = node as? [String: Any] { pending += dictionary.values.map { ($0, depth + 1) } } + else if let array = node as? [Any] { pending += array.map { ($0, depth + 1) } } + } + let record: Record + do { record = try JSONDecoder().decode(Record.self, from: payloadData) } + catch { + throw fail("\(listingPath), metadata record \(recordIndex + 1): unsupported compiler metadata format (\(String(describing: error))).") + } + let (path, line) = try location(record.location) + guard !record.name.isEmpty, record.name.count < 1024 else { throw fail("invalid variable or function name.") } + if record.kind == "function" { + guard let symbol = record.symbol else { throw fail("function has no entry symbol.") } + let entry = try address(symbol), body = try address(record.begin), end = try address(record.end) + guard entry <= body, body <= end else { throw fail("invalid function range.") } + let identity = try module(symbol) + guard try module(record.begin) == identity, try module(record.end) == identity else { throw fail("function spans incompatible module placements.") } + if visible(identity) { + functions.append(Function(name: record.name, sourcePath: path, entry: entry, body: body, end: end, frame: record.frame == true, moduleID: identity, sourceLine: line)) + } + } else if record.kind == "variable" { + guard let type = record.type, (record.offset == nil) != (record.symbol == nil) else { throw fail("variable has ambiguous storage.") } + try validate(type) + let storage = try record.symbol.map(address) + if let storage, storage + type.size > 65536 { throw fail("variable leaves logical memory.") } + if let offset = record.offset, !(-32768...32767).contains(offset) { throw fail("invalid stack offset.") } + var scope: Range? + let identity = try record.symbol.map(module) ?? (record.begin.isEmpty ? nil : module(record.begin)) + var scopeIdentity: String? + if !record.begin.isEmpty || !record.end.isEmpty { + let begin = try address(record.begin), end = try address(record.end) + guard begin <= end else { throw fail("invalid lexical scope.") } + guard try module(record.begin) == module(record.end) else { throw fail("lexical scope spans incompatible module placements.") } + scopeIdentity = try module(record.begin) + scope = begin.. Data { + data.withUnsafeBytes { bytes in + bytes.isEmpty ? Data() : Data(bytes: bytes.baseAddress!, count: bytes.count) + } + } + self.memory = owned(memory); self.available = owned(available) + } + } + struct Value: Identifiable { + var id: String { name } + let name: String + let typeName: String + let value: String + let address: UInt16? + let error: String? + } + enum Root: Hashable { case variable(String), watch(String) } + enum Component: Hashable { case index(Int), member(String), pointee } + struct TreePath: Hashable { + let root: Root + let components: [Component] + init(root: Root, components: [Component] = []) { self.root = root; self.components = components } + func appending(_ component: Component) -> TreePath { TreePath(root: root, components: components + [component]) } + } + struct TreeNode: Identifiable { + var id: TreePath { path } + let path: TreePath + let name: String + let typeName: String + let value: String + let address: UInt16? + let error: String? + let childCount: Int + } + struct TreePage { + let nodes: [TreeNode] + let totalCount: Int + let nextOffset: Int? + let error: String? + } + private final class VerificationCache { var result: Result? } + // Copies share only immutable snapshot provenance. Each newly captured + // evaluator gets a new cache; expanding 32 children must not rescan all code + // 32 times. Frame availability is checked separately on every root resolve. + private let verificationCache = VerificationCache() + private struct Problem: Error { let message: String; init(_ message: String) { self.message = message } } + private struct Operand { + let type: CMOCVariableDebug.CType + let address: Int? + let immediate: Int64? + } + let metadata: CMOCVariableDebug + let context: Context + var frameLocalsAvailable = true + private var function: CMOCVariableDebug.Function? { + metadata.functions.first { $0.body <= Int(context.pc) && Int(context.pc) < $0.end } + } + // A verified assembly entry/prologue establishes file identity without + // establishing a C frame. Keep stack-local eligibility on the body above. + private var fileScopeFunction: CMOCVariableDebug.Function? { + function ?? metadata.entryFunction(containing: context.pc) + } + private func verified() throws { + if let result = verificationCache.result { return try result.get() } + do { + try verifySnapshot() + verificationCache.result = .success(()) + } catch { + verificationCache.result = .failure(error) + throw error + } + } + private func verifySnapshot() throws { + guard context.memory.count == 65536, context.available.count == 65536 else { throw Problem("A complete paused memory snapshot is required.") } + guard metadata.sourceMap.verifiesRuntime(memory: context.memory, available: context.available) else { + throw Problem("The running code no longer matches this build, or its memory is unavailable.") + } + } + private func candidates(named name: String? = nil) -> [CMOCVariableDebug.Variable] { + let location = metadata.sourceMap.location(at: context.pc) + return metadata.variables.filter { variable in + if let name, variable.name != name { return false } + if let scope = variable.scope { + guard scope.contains(Int(context.pc)), function != nil else { return false } + // A block's stack reservation precedes its declarations. Do not + // expose a later declaration (or shadow an outer name) early. + if variable.offset != nil, let location, location.path == variable.sourcePath, + location.line < variable.line { return false } + } else if variable.isStatic, variable.sourcePath != fileScopeFunction?.sourcePath { return false } + return true + } + } + private func resolve(_ name: String) throws -> CMOCVariableDebug.Variable { + let matches = candidates(named: name) + let locals = matches.filter { $0.scope != nil }.sorted { $0.scope!.count < $1.scope!.count } + if let first = locals.first { + guard locals.count == 1 || locals[1].scope != first.scope else { throw Problem("The name ‘\(name)’ is ambiguous in this scope.") } + return first + } + let sameFile = matches.filter { $0.sourcePath == fileScopeFunction?.sourcePath } + let globals = sameFile.isEmpty ? matches : sameFile + guard globals.count == 1, let variable = globals.first else { + throw Problem(globals.isEmpty ? "‘\(name)’ is not available in the current C scope." : "The name ‘\(name)’ is ambiguous; stop in its source file.") + } + return variable + } + private func operand(_ variable: CMOCVariableDebug.Variable) throws -> Operand { + if let address = variable.address { return Operand(type: variable.type, address: address, immediate: nil) } + guard frameLocalsAvailable else { + throw Problem("This frame’s local storage cannot be verified. Pause inside a supported unoptimized function body with a preserved frame pointer.") + } + guard let offset = variable.offset, function?.frame == true else { + throw Problem("Local variables require an unoptimized, preserved frame pointer. Rebuild with -O0 -fno-omit-frame-pointer and pause inside the function body.") + } + let address = Int(context.u) + offset + guard address >= 0, address + variable.type.size <= 65536 else { throw Problem("The variable's stack storage is outside logical memory.") } + return Operand(type: variable.type, address: address, immediate: nil) + } + private func bytes(at address: Int, count: Int) throws -> [UInt8] { + guard address >= 0, count >= 0, address <= 65536 - count, + !(address..<(address + count)).contains(where: { context.available[$0] == 0 }) else { + throw Problem("This memory is unavailable for inspection (including hardware I/O).") + } + return Array(context.memory[address..<(address + count)]) + } + private func integer(_ value: Operand) throws -> Int64 { + if let immediate = value.immediate { return immediate } + if value.type.kind == "floating" { + throw Problem("Floating-point values can be inspected, but floating-point watch arithmetic is not supported.") + } + guard ["integer", "pointer"].contains(value.type.kind), let address = value.address else { + throw Problem("This operation requires an integer or pointer value.") + } + let data = try bytes(at: address, count: value.type.size) + var result: Int64 = 0 + for byte in data { result = (result << 8) | Int64(byte) } + if value.type.kind == "integer", value.type.signed == true, let first = data.first, first & 0x80 != 0 { + result -= Int64(1) << (data.count * 8) + } + return result + } + private func floating(_ operand: Operand) throws -> String { + guard let format = operand.type.floatingFormat else { + throw Problem("This build does not identify its floating-point format. Rebuild with the current VCC Plus compiler.") + } + let expectedSize: Int + switch format { + case "coco-basic-40": expectedSize = 5 + case "ieee754-binary32-be": expectedSize = 4 + default: throw Problem("Unsupported floating-point format ‘\(format)’; inspect its bytes in Memory.") + } + guard operand.type.size == expectedSize, let address = operand.address else { + throw Problem("The floating-point storage does not match its compiler-described format.") + } + let data = try bytes(at: address, count: expectedSize) + let value: Double + if format == "coco-basic-40" { + // CMOC RealConstantExpr::getRepresentation and Color BASIC's packed + // format: exponent byte, sign bit, 31 fraction bits; hidden leading 1. + // Exponent zero represents zero regardless of the remaining bytes. + if data[0] == 0 { return "0" } + let fraction = (UInt32(data[1] & 0x7f) << 24) | (UInt32(data[2]) << 16) + | (UInt32(data[3]) << 8) | UInt32(data[4]) + let magnitude = ldexp(1 + Double(fraction) / 2147483648, Int32(data[0]) - 129) + value = data[1] & 0x80 == 0 ? magnitude : -magnitude + } else { + // Decode the target byte order explicitly, independent of host CPU. + let bits = data.reduce(UInt32(0)) { ($0 << 8) | UInt32($1) } + value = Double(Float(bitPattern: bits)) + } + if value.isNaN { return "NaN" } + if value.isInfinite { return value.sign == .minus ? "-Infinity" : "Infinity" } + if value == 0 { return value.sign == .minus ? "-0" : "0" } + // Enough significant decimal digits to distinguish adjacent target + // values (32-bit significand for BASIC, 24-bit for IEEE binary32). + return String(format: expectedSize == 5 ? "%.11g" : "%.9g", + locale: Locale(identifier: "en_US_POSIX"), value) + } + private func describe(_ operand: Operand, depth: Int = 0) throws -> String { + let type = operand.type + switch type.kind { + case "integer": return String(try integer(operand)) + case "pointer": return String(format: "$%04llX", try integer(operand)) + case "array": + guard let address = operand.address, let element = type.element, let count = type.count else { throw Problem("Array layout is unavailable.") } + if depth >= 2 { return "[\(count) elements]" } + let values = try (0.. 8 ? ", …]" : "]") + case "aggregate": + guard let address = operand.address, let members = type.members else { throw Problem("Aggregate layout is unavailable.") } + if depth >= 2 { return "{…}" } + let values = try members.prefix(4).map { member in + member.name + " = " + (try describe(Operand(type: member.type, address: address + member.offset, immediate: nil), depth: depth + 1)) + } + return "{" + values.joined(separator: ", ") + (members.count > 4 ? ", …}" : "}") + case "floating": return try floating(operand) + default: throw Problem("This compiler type is not supported by the watch evaluator.") + } + } + func visibleVariables() -> [Value] { + let names = Set(candidates().map(\.name)).sorted() + let verificationError: Error? + do { try verified(); verificationError = nil } catch { verificationError = error } + return names.map { name in + do { + if let verificationError { throw verificationError } + let variable = try resolve(name), value = try operand(variable) + return Value(name: name, typeName: value.type.name, value: try describe(value), + address: value.address.flatMap(UInt16.init(exactly:)), error: nil) + } catch { + let type = (try? resolve(name))?.type.name ?? "" + return Value(name: name, typeName: type, value: "Unavailable", address: nil, error: message(error)) + } + } + } + func evaluate(_ expression: String) -> Value { + do { + try verified() + var parser = try Parser(expression) + let tree = try parser.parse() + let result = try evaluate(tree, depth: 0) + return Value(name: expression, typeName: result.type.name, value: try describe(result), + address: result.address.flatMap(UInt16.init(exactly:)), error: nil) + } catch { return Value(name: expression, typeName: "", value: "Unavailable", address: nil, error: message(error)) } + } + // Lazy tree access resolves typed paths from the current root and frame. + // No stored node is a capability to read an address from an older snapshot. + func variableRootPaths() -> [TreePath] { + Set(candidates().map(\.name)).sorted().map { TreePath(root: .variable($0)) } + } + func variableRoots() -> [TreeNode] { variableRootPaths().map { treeNode(at: $0) } } + func variableTreeRoots() -> [TreeNode] { variableRoots() } + func watchRoot(_ expression: String) -> TreeNode { treeNode(at: .init(root: .watch(expression))) } + func watchTreeRoot(_ expression: String) -> TreeNode { watchRoot(expression) } + func treeNode(at path: TreePath) -> TreeNode { + do { + try verified() + return try makeTreeNode(path: path, operand: treeOperand(at: path)) + } catch { return treeError(path, error) } + } + func children(of path: TreePath, offset: Int = 0) -> TreePage { + do { + try verified() + guard path.components.count < 12 else { throw Problem("The 12-level inspection limit has been reached.") } + let parent = try treeOperand(at: path) + let total = treeChildCount(parent.type) + guard offset >= 0, offset <= total else { throw Problem("This child page is outside the declared bounds.") } + let end = min(total, offset + 32) + let nodes = (offset.. TreeNode in + let component: Component + switch parent.type.kind { + case "array": component = .index(index) + case "aggregate": component = .member(parent.type.members![index].name) + default: component = .pointee + } + let child = path.appending(component) + do { return try makeTreeNode(path: child, operand: treeOperand(at: child)) } + catch { return treeError(child, error) } + } + return TreePage(nodes: nodes, totalCount: total, nextOffset: end < total ? end : nil, error: nil) + } catch { return TreePage(nodes: [], totalCount: 0, nextOffset: nil, error: message(error)) } + } + private func treeName(_ path: TreePath) -> String { + if let last = path.components.last { + switch last { case .index(let i): return "[\(i)]"; case .member(let name): return name; case .pointee: return "Pointee" } + } + switch path.root { case .variable(let name), .watch(let name): return name } + } + private func treeError(_ path: TreePath, _ error: Error) -> TreeNode { + TreeNode(path: path, name: treeName(path), typeName: "", value: "Unavailable", address: nil, + error: message(error), childCount: 0) + } + private func treeChildCount(_ type: CMOCVariableDebug.CType) -> Int { + switch type.kind { + case "array": return min(max(type.count ?? 0, 0), 65535) + case "aggregate": return min(type.members?.count ?? 0, 1024) + case "pointer": return 1 // Explicit expansion explains null/unknown targets. + default: return 0 + } + } + private func makeTreeNode(path: TreePath, operand: Operand) throws -> TreeNode { + let type = operand.type + let count = treeChildCount(type) + let summary: String + // Aggregate rows do not read children. An unavailable member cannot + // prevent expansion of its inspectable siblings. + do { + switch type.kind { + case "array": summary = "[\(count) elements]" + case "aggregate": summary = "{\(count) members}" + default: summary = try describe(operand) + } + } catch { + return TreeNode(path: path, name: treeName(path), typeName: type.name, value: "Unavailable", + address: operand.address.flatMap(UInt16.init(exactly:)), error: message(error), childCount: 0) + } + let atLimit = path.components.count >= 12 && count > 0 + return TreeNode(path: path, name: treeName(path), typeName: type.name, value: summary, + address: operand.address.flatMap(UInt16.init(exactly:)), + error: atLimit ? "The 12-level inspection limit has been reached." : nil, + childCount: atLimit ? 0 : count) + } + private struct TreeVisit: Hashable { + let address: Int + let name: String + let kind: String + let size: Int + } + private func treeOperand(at path: TreePath) throws -> Operand { + guard path.components.count <= 12 else { throw Problem("The 12-level inspection limit has been reached.") } + var value: Operand + switch path.root { + case .variable(let name): value = try operand(resolve(name)) + case .watch(let expression): + var parser = try Parser(expression) + value = try evaluate(parser.parse(), depth: 0) + } + var visited = Set() + func visit(_ operand: Operand) -> TreeVisit? { + operand.address.map { TreeVisit(address: $0, name: operand.type.name, kind: operand.type.kind, size: operand.type.size) } + } + if let root = visit(value) { visited.insert(root) } + for component in path.components { + switch component { + case .index(let index): + guard value.type.kind == "array", let count = value.type.count, let element = value.type.element, + let first = value.address, index >= 0, index < count, element.size > 0 else { + throw Problem("Array index is outside its declared bounds or its element layout is unavailable.") + } + let (displacement, overflow) = index.multipliedReportingOverflow(by: element.size) + let (address, additionOverflow) = first.addingReportingOverflow(displacement) + guard !overflow, !additionOverflow, address >= 0, element.size <= 65536, + address <= 65536 - element.size else { throw Problem("Indexed address is outside logical memory.") } + value = Operand(type: element, address: address, immediate: nil) + case .member(let name): + guard value.type.kind == "aggregate", let first = value.address, + let member = value.type.members?.first(where: { $0.name == name }) else { + throw Problem("No inspectable member named ‘\(name)’.") + } + let (address, overflow) = first.addingReportingOverflow(member.offset) + guard !overflow, address >= 0, member.type.size >= 0, member.type.size <= 65536, + address <= 65536 - member.type.size else { throw Problem("Member address is outside logical memory.") } + value = Operand(type: member.type, address: address, immediate: nil) + case .pointee: + value = try dereference(value) + if let next = visit(value), visited.contains(next) { throw Problem("Pointer cycle: this object already appears in the expanded path.") } + } + if let next = visit(value) { visited.insert(next) } + } + return value + } + private func message(_ error: Error) -> String { (error as? Problem)?.message ?? error.localizedDescription } + private indirect enum Expr { + case identifier(String), number(Int64), unary(String, Expr), binary(String, Expr, Expr), index(Expr, Expr), member(Expr, String, Bool) + } + private func evaluate(_ expression: Expr, depth: Int) throws -> Operand { + guard depth <= 32 else { throw Problem("Watch expression is too deeply nested.") } + func eval(_ value: Expr) throws -> Operand { try evaluate(value, depth: depth + 1) } + func literal(_ value: Int64) -> Operand { Operand(type: .init(name: "watch integer (64-bit)", kind: "integer", size: 8, signed: true), address: nil, immediate: value) } + switch expression { + case .identifier(let name): return try operand(resolve(name)) + case .number(let value): return literal(value) + case .unary(let operation, let expression): + let value = try eval(expression) + if operation == "&" { + guard let address = value.address else { throw Problem("Address-of requires stored data.") } + return Operand(type: .init(name: value.type.name + " *", kind: "pointer", size: 2, element: value.type), address: nil, immediate: Int64(address)) + } + if operation == "*" { return try dereference(value) } + let number = try integer(value) + switch operation { + case "+": return literal(number) + case "-": guard number != Int64.min else { throw Problem("Integer overflow in watch.") }; return literal(-number) + case "~": return literal(~number) + case "!": return literal(number == 0 ? 1 : 0) + default: throw Problem("Unsupported unary operation.") + } + case .index(let target, let index): + let base = try eval(target), number = try integer(eval(index)) + let element: CMOCVariableDebug.CType, address: Int64 + if base.type.kind == "array", let next = base.type.element, let first = base.address, let count = base.type.count { + guard number >= 0, number < count else { throw Problem("Array index is outside its declared bounds.") } + element = next; address = Int64(first) + } else if base.type.kind == "pointer", let next = base.type.element { + element = next; address = try integer(base) + } else { throw Problem("Indexing requires an array or pointer.") } + guard element.size > 0, number >= -65536, number <= 65536 else { throw Problem("Invalid element size or index.") } + let result = address + number * Int64(element.size) + guard result >= 0, result + Int64(element.size) <= 65536 else { throw Problem("Indexed address is outside logical memory.") } + return Operand(type: element, address: Int(result), immediate: nil) + case .member(let target, let name, let pointer): + let source = try eval(target), base = try pointer ? dereference(source) : source + guard base.type.kind == "aggregate", let address = base.address, + let member = base.type.members?.first(where: { $0.name == name }) else { throw Problem("No inspectable member named ‘\(name)’.") } + return Operand(type: member.type, address: address + member.offset, immediate: nil) + case .binary(let operation, let left, let right): + let lhs = try eval(left) + let a = try integer(lhs) + if operation == "&&", a == 0 { return literal(0) } + if operation == "||", a != 0 { return literal(1) } + let rhs = try eval(right), b = try integer(rhs) + if lhs.type.kind == "pointer", ["+", "-"].contains(operation), rhs.type.kind == "integer", let element = lhs.type.element { + guard element.size > 0, b >= -65536, b <= 65536 else { throw Problem("Invalid pointer arithmetic.") } + let address = a + (operation == "+" ? b : -b) * Int64(element.size) + guard (0...65535).contains(address) else { throw Problem("Pointer arithmetic leaves logical memory.") } + return Operand(type: lhs.type, address: nil, immediate: address) + } + switch operation { + case "+": let (r,o) = a.addingReportingOverflow(b); guard !o else { throw Problem("Integer overflow in watch.") }; return literal(r) + case "-": let (r,o) = a.subtractingReportingOverflow(b); guard !o else { throw Problem("Integer overflow in watch.") }; return literal(r) + case "*": let (r,o) = a.multipliedReportingOverflow(by: b); guard !o else { throw Problem("Integer overflow in watch.") }; return literal(r) + case "/", "%": guard b != 0, !(a == Int64.min && b == -1) else { throw Problem("Invalid division in watch.") }; return literal(operation == "/" ? a / b : a % b) + case "&": return literal(a & b) + case "|": return literal(a | b) + case "^": return literal(a ^ b) + case "<<", ">>": + guard (0...31).contains(b) else { throw Problem("Shift count must be between 0 and 31.") } + if operation == ">>" { return literal(a >> b) } + let (shifted, overflow) = a.multipliedReportingOverflow(by: Int64(1) << b) + guard !overflow else { throw Problem("Integer overflow in watch.") }; return literal(shifted) + case "==": return literal(a == b ? 1 : 0) + case "!=": return literal(a != b ? 1 : 0) + case "<": return literal(a < b ? 1 : 0) + case "<=": return literal(a <= b ? 1 : 0) + case ">": return literal(a > b ? 1 : 0) + case ">=": return literal(a >= b ? 1 : 0) + case "&&": return literal(a != 0 && b != 0 ? 1 : 0) + case "||": return literal(a != 0 || b != 0 ? 1 : 0) + default: throw Problem("Unsupported binary operation.") + } + } + } + private func dereference(_ value: Operand) throws -> Operand { + guard value.type.kind == "pointer", let element = value.type.element, element.size > 0 else { throw Problem("Dereference requires a pointer to a known data type.") } + let address = try integer(value) + guard address > 0, address + Int64(element.size) <= 65536 else { throw Problem("Null or out-of-range pointer.") } + return Operand(type: element, address: Int(address), immediate: nil) + } + private struct Parser { + var tokens: [String] = [] + var index = 0 + init(_ text: String) throws { + guard text.utf8.count <= 1024 else { throw Problem("Watch expression is too long.") } + let chars = Array(text) + var i = 0 + while i < chars.count { + let c = chars[i] + if c.isWhitespace { i += 1; continue } + if c.isASCII && (c.isLetter || c == "_" || c.isNumber) { + let begin = i; i += 1 + while i < chars.count, chars[i].isASCII && (chars[i].isLetter || chars[i].isNumber || chars[i] == "_") { i += 1 } + tokens.append(String(chars[begin..", "==", "!=", "<=", ">=", "&&", "||", "<<", ">>"].contains(pair) { tokens.append(pair); i += 2; continue } + guard "()+-*/%&|^~!<>[].".contains(c) else { throw Problem("Only read-only expressions are supported; assignments and function calls are unavailable.") } + tokens.append(String(c)); i += 1 + } + guard !tokens.isEmpty, tokens.count <= 128 else { throw Problem("Enter a variable or a short read-only expression.") } + } + mutating func parse() throws -> Expr { + let result = try binary(minimum: 0, depth: 0) + guard index == tokens.count else { throw Problem("Unsupported expression syntax. Function calls and assignments are not evaluated.") } + return result + } + func precedence(_ token: String) -> Int? { + switch token { + case "||": return 0 + case "&&": return 1 + case "|": return 2 + case "^": return 3 + case "&": return 4 + case "==", "!=": return 5 + case "<", "<=", ">", ">=": return 6 + case "<<", ">>": return 7 + case "+", "-": return 8 + case "*", "/", "%": return 9 + default: return nil + } + } + mutating func binary(minimum: Int, depth: Int) throws -> Expr { + guard depth <= 32 else { throw Problem("Watch expression is too deeply nested.") } + var left = try unary(depth: depth + 1) + while index < tokens.count, let p = precedence(tokens[index]), p >= minimum { + let operation = tokens[index]; index += 1 + left = .binary(operation, left, try binary(minimum: p + 1, depth: depth + 1)) + } + return left + } + mutating func unary(depth: Int) throws -> Expr { + guard depth <= 32, index < tokens.count else { throw Problem("Incomplete or overly nested watch expression.") } + let token = tokens[index]; index += 1 + if ["*", "&", "+", "-", "~", "!"].contains(token) { return .unary(token, try unary(depth: depth + 1)) } + var result: Expr + if token == "(" { + result = try binary(minimum: 0, depth: depth + 1); try expect(")") + } else if token.first?.isNumber == true { + let number: Int64? + if token.lowercased().hasPrefix("0x") { number = Int64(token.dropFirst(2), radix: 16) } + else { number = Int64(token, radix: 10) } + guard let number else { throw Problem("Invalid integer literal.") }; result = .number(number) + } else if token.first?.isLetter == true || token.first == "_" { result = .identifier(token) } + else { throw Problem("Expected a variable, number or parenthesized expression.") } + while index < tokens.count { + if tokens[index] == "[" { + index += 1; let subscriptValue = try binary(minimum: 0, depth: depth + 1); try expect("]") + result = .index(result, subscriptValue) + } else if [".", "->"].contains(tokens[index]) { + let pointer = tokens[index] == "->"; index += 1 + guard index < tokens.count, tokens[index].first?.isLetter == true || tokens[index].first == "_" else { throw Problem("Expected a member name.") } + result = .member(result, tokens[index], pointer); index += 1 + } else { break } + } + return result + } + mutating func expect(_ token: String) throws { + guard index < tokens.count, tokens[index] == token else { throw Problem("Expected ‘\(token)’.") }; index += 1 + } + } +} diff --git a/platforms/macos/App/CMOCWorkspaceRecovery.swift b/platforms/macos/App/CMOCWorkspaceRecovery.swift new file mode 100644 index 0000000..7e74ce0 --- /dev/null +++ b/platforms/macos/App/CMOCWorkspaceRecovery.swift @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import Darwin + +/// Recovery copies only. This store never writes to the project or guest media. +/// Each editor session owns one file per project, so two apps cannot overwrite +/// one another's drafts. Restore into a new session before discarding an old copy. +final class CMOCWorkspaceRecovery: @unchecked Sendable { + struct Draft: Codable, Equatable, Sendable { + let path: String + let text: String + let savedText: String + let savedHash: String + init(path: String, text: String, savedText: String, savedHash: String) { + self.path = path; self.text = text; self.savedText = savedText; self.savedHash = savedHash + } + } + struct Record: Identifiable, Sendable { + let id: UUID + let projectPath: String + let modifiedAt: Date + let drafts: [Draft] + let isFromRunningSession: Bool + fileprivate let file: URL + fileprivate let digest: String + fileprivate let processID: Int32 + } + struct Scan: Sendable { + let records: [Record] + let issues: [String] + } + private struct Envelope: Codable { + let version: Int + let sessionID: UUID + let processID: Int32 + let projectPath: String + let modifiedAt: Date + let drafts: [Draft] + } + static let maximumDrafts = 128 + static let maximumTextBytes = 16 * 1024 * 1024 + static let maximumRecordBytes = 64 * 1024 * 1024 + static let maximumScanRecords = 64 + static let maximumScanTextBytes = 64 * 1024 * 1024 + let root: URL + let sessionID: UUID + private let processID: Int32 + private let canonicalRoot: URL + private let lock = NSLock() + + init(root: URL, sessionID: UUID = UUID(), processID: Int32 = getpid()) { + self.root = root.standardizedFileURL + self.canonicalRoot = root.standardizedFileURL.resolvingSymlinksInPath() + self.sessionID = sessionID; self.processID = processID + } + private func failure(_ message: String) -> CMOCBuildError { + .message("Draft recovery: " + message) + } + private func projectPath(_ directory: URL) -> String { + directory.standardizedFileURL.resolvingSymlinksInPath().path + } + private func kind(_ url: URL) throws -> FileAttributeType? { + do { return try FileManager.default.attributesOfItem(atPath: url.path)[.type] as? FileAttributeType } + catch let error as NSError where error.domain == NSCocoaErrorDomain && [NSFileReadNoSuchFileError, NSFileNoSuchFileError].contains(error.code) { return nil } + } + private func folder(for project: String, create: Bool) throws -> URL? { + guard root.resolvingSymlinksInPath().path == canonicalRoot.path else { throw failure("The recovery folder location changed. Copies were left untouched.") } + if let type = try kind(root) { + guard type == .typeDirectory else { throw failure("The recovery folder must be a real directory, not a link.") } + } else if create { + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) + } else { return nil } + let directory = root.appendingPathComponent(CMOCProject.sha256(Data(project.utf8)), isDirectory: true) + if let type = try kind(directory) { + guard type == .typeDirectory else { throw failure("A project recovery folder is a link or is not a directory.") } + } else if create { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + } else { return nil } + return directory + } + private func validate(_ drafts: [Draft]) throws { + guard drafts.count <= Self.maximumDrafts, + Set(drafts.map { $0.path.lowercased() }).count == drafts.count else { + throw failure("Too many drafts or duplicate draft paths. Existing copies were kept.") + } + var total = 0 + for draft in drafts { + try CMOCProject.validateRelativePath(draft.path) + let text = try CMOCProject.sourceBytes(draft.text), saved = try CMOCProject.sourceBytes(draft.savedText) + guard CMOCProject.sha256(saved) == draft.savedHash else { throw failure("The saved-file identity for \(draft.path) is inconsistent.") } + total += text.count + saved.count + guard total <= Self.maximumTextBytes else { throw failure("Drafts exceed the 16 MB recovery limit. Save your edits to the project.") } + } + } + private func read(_ url: URL) throws -> Data { + let descriptor = open(url.path, O_RDONLY | O_NOFOLLOW) + guard descriptor >= 0 else { throw failure("Cannot safely read \(url.lastPathComponent).") } + let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true) + defer { try? handle.close() } + var info = stat() + guard fstat(descriptor, &info) == 0, (info.st_mode & S_IFMT) == S_IFREG, + info.st_size >= 0, info.st_size <= Int64(Self.maximumRecordBytes) else { + throw failure("\(url.lastPathComponent) is not a bounded regular recovery file.") + } + let data = try handle.read(upToCount: Self.maximumRecordBytes + 1) ?? Data() + guard data.count <= Self.maximumRecordBytes else { throw failure("The recovery file grew beyond its size limit.") } + return data + } + private func alive(_ pid: Int32) -> Bool { + guard pid > 0 else { return false } + return kill(pid, 0) == 0 || errno == EPERM + } + private func record(_ file: URL, project: String) throws -> Record { + let data = try read(file) + let envelope: Envelope + do { envelope = try JSONDecoder().decode(Envelope.self, from: data) } + catch { throw failure("\(file.lastPathComponent) is damaged or has an unsupported structure. The file was kept.") } + guard envelope.version == 1, envelope.processID > 0, envelope.projectPath == project, + file.lastPathComponent == envelope.sessionID.uuidString + ".json", + envelope.modifiedAt.timeIntervalSince1970.isFinite else { + throw failure("\(file.lastPathComponent) has an invalid recovery identity. The file was kept.") + } + try validate(envelope.drafts) + return Record(id: envelope.sessionID, projectPath: project, modifiedAt: envelope.modifiedAt, + drafts: envelope.drafts, isFromRunningSession: envelope.sessionID != sessionID && alive(envelope.processID), + file: file, digest: CMOCProject.sha256(data), processID: envelope.processID) + } + func save(projectDirectory: URL, drafts: [Draft]) throws { + lock.lock(); defer { lock.unlock() } + try validate(drafts) + let project = projectPath(projectDirectory) + guard let directory = try folder(for: project, create: !drafts.isEmpty) else { return } + let file = directory.appendingPathComponent(sessionID.uuidString + ".json") + if let type = try kind(file), type != .typeRegular { throw failure("The session recovery file is not a regular file. It was kept.") } + if drafts.isEmpty { + if try kind(file) != nil { try FileManager.default.removeItem(at: file) } + return + } + let envelope = Envelope(version: 1, sessionID: sessionID, processID: processID, projectPath: project, + modifiedAt: Date(), drafts: drafts) + let data = try JSONEncoder().encode(envelope) + guard data.count <= Self.maximumRecordBytes else { throw failure("The encoded recovery copy exceeds its size limit. Existing copies were kept.") } + try data.write(to: file, options: .atomic) + } + func scan(projectDirectory: URL) throws -> Scan { + lock.lock(); defer { lock.unlock() } + let project = projectPath(projectDirectory) + guard let directory = try folder(for: project, create: false) else { return Scan(records: [], issues: []) } + let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) + guard files.count <= 1024 else { throw failure("Too many recovery files to inspect safely. Copies were left untouched.") } + var records: [Record] = [], issues: [String] = [] + var totalTextBytes = 0 + for file in files.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) where file.pathExtension == "json" { + guard records.count < Self.maximumScanRecords else { + issues.append("Draft recovery: More than 64 saved sessions are present. Export or discard reviewed copies, then refresh to inspect the remaining sessions. All copies were kept.") + break + } + do { + let recovered = try record(file, project: project) + let bytes = recovered.drafts.reduce(0) { $0 + $1.text.utf8.count + $1.savedText.utf8.count } + guard totalTextBytes + bytes <= Self.maximumScanTextBytes else { + issues.append("Draft recovery: Saved sessions exceed the 64 MB review limit. Export or discard reviewed copies, then refresh to inspect the remaining sessions. All copies were kept.") + break + } + totalTextBytes += bytes; records.append(recovered) + } catch { issues.append(error.localizedDescription) } + } + return Scan(records: records.sorted { $0.modifiedAt > $1.modifiedAt }, issues: issues) + } + func records(projectDirectory: URL) throws -> [Record] { + let result = try scan(projectDirectory: projectDirectory) + guard result.issues.isEmpty else { throw failure(result.issues.joined(separator: "\n")) } + return result.records + } + func discard(_ record: Record) throws { + lock.lock(); defer { lock.unlock() } + guard let directory = try folder(for: record.projectPath, create: false), + directory.appendingPathComponent(record.id.uuidString + ".json").resolvingSymlinksInPath().path == record.file.resolvingSymlinksInPath().path else { + throw failure("The recovery record no longer belongs to this store.") + } + let current = try self.record(record.file, project: record.projectPath) + guard current.digest == record.digest else { throw failure("This recovery copy changed after it was shown. Review it again before discarding.") } + guard !current.isFromRunningSession else { throw failure("Another running editor session owns this recovery copy.") } + try FileManager.default.removeItem(at: record.file) + } +} diff --git a/platforms/macos/App/CartridgeControlsView.swift b/platforms/macos/App/CartridgeControlsView.swift new file mode 100644 index 0000000..05d7674 --- /dev/null +++ b/platforms/macos/App/CartridgeControlsView.swift @@ -0,0 +1,269 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI + +struct CartridgeControlsView: View { + @ObservedObject var machine: MachineModel + @Environment(\.openWindow) private var openWindow + @State private var expandedSlots = Set() + + var body: some View { + VStack(spacing: 0) { + VStack(alignment: .leading, spacing: 14) { + SecondaryHeader(title: "Cartridges", badge: "mpi") + Picker("Cartridge connection", selection: Binding(get: { machine.cartridgeAssignments.multiPak }, set: machine.setMultiPak)) { + Text("Single cartridge").tag(false) + Text("Multi-Pak").tag(true) + }.pickerStyle(.segmented).accessibilityIdentifier("cartridge-connection") + Label("Changes restart the CoCo and clear the working program. Floppy and hard disks are retained; SDC mounts return to startup.cfg.", systemImage: "arrow.counterclockwise") + .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + }.padding(20) + Divider() + ScrollView { + VStack(alignment: .leading, spacing: 12) { + if machine.cartridgeAssignments.multiPak { + ForEach(1...4, id: \.self) { slot in row(slot) } + } else { row(0) } + if !machine.cartridgeRestoreErrors.isEmpty { + SecondaryAction(title: "Retry Unavailable Files", systemImage: "arrow.clockwise", action: machine.retryRememberedCartridges) + } + if let error = machine.diskSettingsError { + Label(error, systemImage: "exclamationmark.circle").foregroundStyle(.red).textSelection(.enabled) + if machine.diskSettingsNeedsSave { + SecondaryAction(title: "Retry Saving Settings", systemImage: "arrow.clockwise", action: machine.saveDiskAssignments) + } + } + if let error = machine.fileError ?? machine.error { + Label(error, systemImage: "exclamationmark.circle").foregroundStyle(.red).textSelection(.enabled) + } + SecondaryHelp(title: "About cartridge connections") { + Text("The single-cartridge assignment is retained while Multi-Pak is enabled. Each controller or sound device can occupy one Multi-Pak slot; choosing it elsewhere moves it. Software can route ROM and I/O ports independently of the startup slot.") + } + }.padding(20) + } + Divider() + VStack(alignment: .leading, spacing: 12) { + if machine.cartridgeAssignments.multiPak { + HStack(spacing: 16) { + Text("Startup slot").fontWeight(.medium) + Picker("Startup slot", selection: Binding(get: { machine.cartridgeAssignments.physicalSlot }, set: machine.selectPhysicalSlot)) { + ForEach(1...4, id: \.self) { Text("Slot \($0)").tag($0) } + }.pickerStyle(.segmented).labelsHidden().frame(maxWidth: 330) + .accessibilityIdentifier("cartridge-startup-slot") + Spacer(minLength: 0) + } + HStack { + Label("Live routing", systemImage: "arrow.triangle.branch") + Text("ROM: Slot \(machine.romSlot) · I/O ports: Slot \(machine.ioSlot)").monospacedDigit() + }.font(.caption).foregroundStyle(.secondary) + .accessibilityIdentifier("cartridge-live-routing") + } + MediaExecutionFooter(machine: machine, note: "After a change, press Run to continue.") + }.padding(20) + }.frame(minWidth: 680, minHeight: 440) + .disabled(machine.busy || machine.diskSaving || machine.diskBusy || machine.state == .closed) + } + + private func row(_ slot: Int) -> some View { + let assignment = machine.cartridgeAssignments.slots[slot] + return SecondaryCard { + VStack(alignment: .leading, spacing: 12) { + HStack(alignment: .center, spacing: 14) { + Text(slot == 0 ? "ROM" : "\(slot)") + .font(.system(.body, design: .monospaced).weight(.semibold)) + .frame(width: 38, height: 38) + .background(Color.accentColor.opacity(0.12), in: RoundedRectangle(cornerRadius: 7)) + .accessibilityLabel(slot == 0 ? "Single cartridge" : "Slot \(slot)") + VStack(alignment: .leading, spacing: 4) { + Text(title(assignment.kind)).fontWeight(.semibold) + Text(summary(slot)).font(.caption).foregroundStyle(.secondary) + .lineLimit(2).truncationMode(.middle) + }.frame(maxWidth: .infinity, alignment: .leading) + deviceMenu(slot) + contextualAction(slot) + } + if let warning = readiness(slot) { + Label(warning, systemImage: "exclamationmark.circle") + .font(.callout).foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true) + } + if let error = machine.cartridgeRestoreErrors[slot] { + Text(error).font(.callout).foregroundStyle(.red).textSelection(.enabled) + SecondaryAction(title: "Retry Files", systemImage: "arrow.clockwise", action: machine.retryRememberedCartridges) + .accessibilityLabel("Retry unavailable files for slot \(slot)") + } + if assignment.kind != .empty { + DisclosureGroup(isExpanded: Binding(get: { expandedSlots.contains(slot) }, set: { value in + if value { expandedSlots.insert(slot) } else { expandedSlots.remove(slot) } + })) { + details(slot).padding(.top, 10) + } label: { Label("Details", systemImage: "info.circle").font(.callout).accessibilityLabel("Details for slot \(slot)") } + } + } + }.modifier(MediaDropTarget(machine: machine, destination: .cartridge(slot))) + } + + private func title(_ kind: CartridgeAssignments.Kind) -> String { + switch kind { + case .empty: return "Empty slot" + case .rom: return "ROM cartridge" + case .floppy: return "Floppy controller (FD-502)" + case .hardDisk: return "Hard-disk controller" + case .ramDisk: return "RAM disk (512 KB)" + case .orchestra90: return "Orchestra-90" + case .speechSound: return "Speech/Sound Cartridge" + case .sdc: return "CoCo SDC" + } + } + private func summary(_ slot: Int) -> String { + let assignment = machine.cartridgeAssignments.slots[slot] + switch assignment.kind { + case .empty: return "Choose a device or drop a ROM file here" + case .rom: return assignment.url?.lastPathComponent ?? "No ROM selected" + case .floppy: return "FD0–FD3 · Mounted: \(machine.disks.filter(\.mounted).count)" + case .hardDisk: return "HD0–HD1 · Mounted: \(machine.hardDisks.filter(\.mounted).count)" + case .ramDisk: return "Volatile storage for supporting software" + case .orchestra90: return assignment.url?.lastPathComponent ?? "Stereo sound only · No program ROM" + case .sdc: return assignment.sdcFolderURL.map { "SD card: " + $0.lastPathComponent } ?? "Choose an SD card folder and SDC-DOS ROM" + case .speechSound: + return assignment.url != nil && assignment.speechROMURL != nil ? "Speech and music · Two chip ROMs selected" : "Two internal chip ROMs required" + } + } + private func readiness(_ slot: Int) -> String? { + let assignment = machine.cartridgeAssignments.slots[slot] + if assignment.kind == .rom && machine.cartridgeNames[slot].isEmpty { return "ROM unavailable — choose a replacement or retry." } + if assignment.kind == .floppy && !machine.diskEnabled { return "Choose a disk ROM in Floppy Disks to enable this controller." } + if assignment.kind == .sdc && (assignment.url == nil || assignment.sdcFolderURL == nil) { + return "Inactive — choose an SDC-DOS ROM and SD card folder in Details." + } + if assignment.kind == .speechSound && (assignment.url == nil || assignment.speechROMURL == nil) { + return "Inactive — choose both ROMs to enable speech and music." + } + return nil + } + private func deviceMenu(_ slot: Int) -> some View { + let current = machine.cartridgeAssignments.slots[slot].kind + return Menu { + Button { machine.openCartridgeROM(slot) } label: { + Label("ROM Cartridge…", systemImage: current == .rom ? "checkmark" : "folder") + }.accessibilityLabel("Choose ROM for slot \(slot)") + ForEach([CartridgeAssignments.Kind.floppy, .hardDisk, .ramDisk, .orchestra90, .speechSound, .sdc], id: \.rawValue) { kind in + Button { machine.requestCartridge(kind, slot: slot) } label: { + Label(menuTitle(kind, slot: slot), systemImage: current == kind ? "checkmark" : symbol(kind)) + }.disabled(current == kind).accessibilityLabel("Use \(kind == .floppy ? "floppy controller" : kind == .hardDisk ? "hard disk" : kind == .ramDisk ? "RAM disk" : kind == .orchestra90 ? "Orchestra-90" : kind == .sdc ? "CoCo SDC" : "Speech/Sound") in slot \(slot)") + } + Divider() + Button { machine.requestCartridge(.empty, slot: slot) } label: { + Label("Remove Cartridge", systemImage: "minus.circle") + }.disabled(current == .empty).accessibilityLabel("Remove cartridge from slot \(slot)") + } label: { Label("Device", systemImage: "slider.horizontal.3") } + .menuStyle(.borderlessButton).fixedSize().padding(.horizontal, 10).padding(.vertical, 6) + .background(.quaternary.opacity(0.6), in: RoundedRectangle(cornerRadius: 6)) + .accessibilityIdentifier("cartridge-device-\(slot)") + } + private func menuTitle(_ kind: CartridgeAssignments.Kind, slot: Int) -> String { + var result = title(kind) + if slot > 0, let previous = (1...4).first(where: { $0 != slot && machine.cartridgeAssignments.slots[$0].kind == kind }) { + result += " — moves from Slot \(previous)" + } + return result + } + private func symbol(_ kind: CartridgeAssignments.Kind) -> String { + switch kind { + case .floppy, .hardDisk: return "externaldrive" + case .ramDisk, .rom, .empty: return "memorychip" + case .orchestra90: return "music.note" + case .speechSound: return "waveform" + case .sdc: return "sdcard" + } + } + @ViewBuilder private func contextualAction(_ slot: Int) -> some View { + switch machine.cartridgeAssignments.slots[slot].kind { + case .rom: + SecondaryAction(title: "Choose ROM…", systemImage: "folder") { machine.openCartridgeROM(slot) } + .accessibilityLabel("Choose ROM for slot \(slot)") + case .floppy: + SecondaryAction(title: "Floppy Disks…", systemImage: "externaldrive") { openWindow(id: "disks") } + case .hardDisk: + SecondaryAction(title: "Hard Disks…", systemImage: "externaldrive") { openWindow(id: "hard-disks") } + case .orchestra90: + SecondaryAction(title: "Choose ROM…", systemImage: "folder") { machine.openCartridgeROM(slot, kind: .orchestra90) } + .accessibilityLabel("Choose Orchestra-90 ROM for slot \(slot)") + case .sdc: + SecondaryAction(title: "SD Card…", systemImage: "sdcard") { expandedSlots.insert(slot) } + .accessibilityLabel("Show CoCo SDC settings for slot \(slot)") + case .speechSound: + SecondaryAction(title: "ROMs…", systemImage: "memorychip") { expandedSlots.insert(slot) } + .accessibilityLabel("Show Speech/Sound ROMs for slot \(slot)") + case .ramDisk, .empty: EmptyView() + } + } + @ViewBuilder private func details(_ slot: Int) -> some View { + let assignment = machine.cartridgeAssignments.slots[slot] + VStack(alignment: .leading, spacing: 10) { + switch assignment.kind { + case .sdc: + Text("The selected folder represents an SD card. Choose this cartridge as the startup slot to boot SDC-DOS. Changing the ROM, folder or protection restarts the CoCo.") + romRow("SDC-DOS ROM", filename: assignment.url?.lastPathComponent, button: "Choose ROM…", label: "Choose SDC-DOS ROM for slot \(slot)") { machine.openCartridgeROM(slot, kind: .sdc) } + romRow("SD card folder", filename: assignment.sdcFolderURL?.path, button: "Choose Folder…", label: "Choose SD card folder for slot \(slot)") { machine.openSDCFolder(slot) } + if let folder = assignment.sdcFolderURL { + Button { NSWorkspace.shared.activateFileViewerSelecting([folder]) } label: { Label("Show SD Card Folder in Finder", systemImage: "folder") } + } + Toggle("Protect SD card files (read-only)", isOn: Binding(get: { assignment.sdcReadOnly ?? true }, set: { machine.setSDCReadOnly($0, slot: slot) })) + .accessibilityIdentifier("sdc-protected-\(slot)") + Text((assignment.sdcReadOnly ?? true) ? "Files are protected from guest writes and file-management commands." : "Guest writes save directly. File-management commands can create, rename or delete files in this folder.") + if (machine.cartridgeAssignments.multiPak ? slot > 0 : slot == 0), !machine.cartridgeNames[slot].isEmpty { + VStack(alignment: .leading, spacing: 5) { + Text("Current folder: \(machine.sdcDirectory.isEmpty ? "/" : machine.sdcDirectory)").textSelection(.enabled) + ForEach(0..<2) { drive in + Text("SDC\(drive): \(machine.sdcDriveNames.indices.contains(drive) && !machine.sdcDriveNames[drive].isEmpty ? machine.sdcDriveNames[drive] : "No image mounted")") + } + Text("Transfers · Read \(machine.sdcReadCount) · Written \(machine.sdcWriteCount)") + .monospacedDigit().accessibilityIdentifier("sdc-transfer-counts") + if let error = machine.sdcError, !error.isEmpty { + Label(error, systemImage: "exclamationmark.circle").foregroundStyle(.orange).textSelection(.enabled) + } + } + } + SecondaryHelp(title: "Using an SD card folder") { + Text("Keep extracted collections together with their original filenames and directories. In SDC-DOS, DRIVE 0,\"NAME.DSK\" mounts an image; DIR lists its BASIC files. Follow the software's launch instructions. SDC0–SDC1 are independent of FD0–FD3 and HD0–HD1.") + Text("Double Dragon: select the folder containing DDRAGON1.DSK through DDRAGON9.DSK, use 2 MB RAM, then enter DRIVE 0,\"DDRAGON1.DSK\" followed by RUN \"AUTOEXEC:0\". The game selects its later disks. Arrow keys move; Z starts and punches, X kicks, C jumps.") + Text("Profiles remember the folder, ROM and protection. Guest-selected mounts and current directory return to startup.cfg on restart. In System view, click the CoCo SDC cartridge or its slot for SD card controls. The transfer light reflects actual reads and writes.") + } + case .speechSound: + Text("Speech and music for supporting programs. This cartridge has no boot program; keep your disk controller as the startup slot.") + romRow("PIC firmware", filename: assignment.url?.lastPathComponent, button: "Choose PIC Firmware…", label: "Choose PIC firmware for slot \(slot)") { machine.openSpeechROM(slot, speech: false) } + romRow("Speech ROM", filename: assignment.speechROMURL?.lastPathComponent, button: "Choose Speech ROM…", label: "Choose speech ROM for slot \(slot)") { machine.openSpeechROM(slot, speech: true) } + Text("Sound, volume and mute use the normal Mac audio controls.") + case .orchestra90: + Text("Stereo playback works without a ROM in supporting software. The optional 8 KiB ROM adds the music program; choose its startup slot to boot it.") + Text(assignment.url.map { "Program ROM: \($0.lastPathComponent)" } ?? "No program ROM — stereo sound only").textSelection(.enabled) + if assignment.url != nil { + SecondaryAction(title: "Remove ROM…", systemImage: "minus.circle") { machine.requestOrchestraWithoutROM(slot) } + .accessibilityLabel("Remove Orchestra-90 ROM from slot \(slot)") + } + if assignment.url != nil && machine.cartridgeRestoreErrors[slot] == nil { + Text("William Tell demo: press a key at startup, then type S and Return to score. Wait for the cursor, then P and Return to play. Escape sends CoCo Break to stop.") + } + case .ramDisk: + Text("Requires RAM-disk-aware software; this is not a Disk BASIC drive. Resets retain data. Loading a profile, quitting, or removing the last RAM-disk assignment discards its contents. Profiles remember the device, not its data. This layout uses conventional controls.") + case .floppy: + Text("One FD-502 controller provides FD0–FD3. The selected disk ROM and mounted media are managed in Floppy Disks. Moving this controller retains its disks.") + case .hardDisk: + Text("This controller provides HD0 and HD1 and has no boot ROM. Use a compatible disk ROM or OS-9 boot disk. Moving it retains mounted images.") + case .rom: + Text("ROM file: \(assignment.url?.path ?? "Not selected")").textSelection(.enabled) + Text("Choosing another ROM restarts the CoCo. Removing this assignment does not delete its file.") + case .empty: EmptyView() + } + }.font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + private func romRow(_ title: String, filename: String?, button: String, label: String, action: @escaping () -> Void) -> some View { + HStack { + VStack(alignment: .leading, spacing: 3) { + Text(title).fontWeight(.medium) + Text(filename ?? "Not selected").lineLimit(1).truncationMode(.middle) + } + Spacer() + SecondaryAction(title: button, systemImage: "folder", action: action).accessibilityLabel(label) + } + } +} diff --git a/platforms/macos/App/CassetteControlsView.swift b/platforms/macos/App/CassetteControlsView.swift new file mode 100644 index 0000000..dfa8cc0 --- /dev/null +++ b/platforms/macos/App/CassetteControlsView.swift @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import Combine + +struct CassetteControlsView: View { + @ObservedObject var machine: MachineModel + @State private var tapeSeek: Double = 0 + @State private var seeking = false + private let refresh = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect() + + var body: some View { + VStack(spacing: 0) { + SecondaryHeader(title: "Cassette", badge: "cassette").padding(20) + Divider() + ScrollView { + VStack(alignment: .leading, spacing: 18) { + SecondaryCard { + VStack(alignment: .leading, spacing: 18) { + HStack(spacing: 12) { + Image(systemName: "recordingtape").font(.system(size: 26)).foregroundStyle(.secondary) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 4) { + Text(machine.tapeName).font(.headline).lineLimit(1).truncationMode(.middle) + Text(machine.tapeTransportDescription).font(.callout).foregroundStyle(.secondary) + .accessibilityIdentifier("cassette-transport-status") + }.frame(maxWidth: .infinity, alignment: .leading) + SecondaryAction(title: "Insert…", systemImage: "folder", action: machine.openTape) + .disabled(machine.tapeDirty).accessibilityIdentifier("cassette-insert") + } + HStack(spacing: 12) { + Spacer(minLength: 0) + CassetteTransportButton(title: "Rewind", symbol: "backward.end.fill") { machine.tapeAction(2) } + .disabled(!machine.tapeMounted).accessibilityIdentifier("cassette-rewind") + CassetteTransportButton(title: "Play", symbol: "play.fill", prominent: machine.tapeMode == 0) { machine.tapeAction(1) } + .disabled(!machine.tapeMounted || machine.tapeMode == 2).accessibilityIdentifier("cassette-play") + CassetteTransportButton(title: "Stop", symbol: "stop.fill", prominent: machine.tapeMode != 0) { machine.tapeAction(0) } + .disabled(!machine.tapeMounted).accessibilityIdentifier("cassette-stop") + CassetteTransportButton(title: "Eject", symbol: "eject.fill") { machine.tapeAction(3) } + .disabled(!machine.tapeMounted || machine.tapeDirty).accessibilityIdentifier("cassette-eject") + Spacer(minLength: 0) + } + VStack(spacing: 4) { + Slider(value: $tapeSeek, in: 0...Double(max(1, machine.tapeLength)), onEditingChanged: { editing in + seeking = editing + if !editing { machine.seekTape(tapeSeek) } + }).accessibilityLabel("Tape position").disabled(!machine.tapeMounted || machine.tapeMode == 2) + HStack { + Text("Tape position") + Spacer() + Text("\(machine.tapePosition) / \(machine.tapeLength) \(machine.tapeWAV ? "samples" : "bytes")") + .monospacedDigit() + }.font(.caption).foregroundStyle(.secondary) + } + Divider() + HStack { + Menu { + Button("CAS") { machine.tapeAction(4) } + Button("WAV") { machine.tapeAction(5) } + } label: { Label("New Recording", systemImage: "record.circle") } + .fixedSize().disabled(machine.tapeDirty).accessibilityIdentifier("cassette-new-recording") + SecondaryAction(title: "Export Tape…", systemImage: "square.and.arrow.up", action: machine.exportTape) + .disabled(!machine.tapeMounted).accessibilityIdentifier("cassette-export") + Spacer() + Toggle("Fast CAS", isOn: Binding(get: { machine.tapeFast }, set: machine.setFastTape)) + .disabled(machine.tapeMode != 0) + .help("Accelerate supported CAS loads. Change this while the transport is stopped.") + } + recordingNotice + } + }.disabled(machine.busy || machine.state == .closed) + HStack(spacing: 12) { + Label("App sound", systemImage: "speaker.wave.2") + Toggle("Sound", isOn: Binding(get: { machine.audioEnabled }, set: machine.setAudio)) + .labelsHidden().accessibilityLabel("Sound") + Slider(value: $machine.volume, in: 0...1, onEditingChanged: { editing in + if !editing { machine.setAudio(machine.audioEnabled) } + }).frame(maxWidth: 220).accessibilityLabel("Volume") + Text(machine.volume == 0 ? "Muted" : "\(Int((machine.volume * 100).rounded()))%") + .monospacedDigit().frame(width: 45, alignment: .leading).foregroundStyle(.secondary) + Spacer(minLength: 0) + Text("All CoCo audio").font(.caption).foregroundStyle(.secondary) + }.disabled(machine.busy) + SecondaryHelp(title: "Recording and tape options") { + Text("New Recording creates an in-memory CAS or WAV tape and replaces the inserted tape. Export writes a Mac file. An unsaved recording must be exported or explicitly discarded before replacement.") + Text("Position counts bytes for CAS and samples for WAV. Rewind returns to the beginning; the position slider can seek when transport rules permit. Cue/fast-forward and independent tape pause are not available.") + Text("Fast CAS accelerates supported ROM load routines. Volume and Sound affect all emulator audio, including cartridges, not just the tape.") + } + if let error = machine.fileError ?? machine.error { Text(error).foregroundStyle(.red).textSelection(.enabled) } + }.padding(20) + }.modifier(MediaDropTarget(machine: machine, destination: .cassette)) + Divider() + HStack(alignment: .top, spacing: 10) { + Image(systemName: "info.circle").foregroundStyle(.secondary) + VStack(alignment: .leading, spacing: 4) { + Text("Play readies the tape. The CoCo starts its motor.").font(.callout) + Text("Closing this window preserves transport and unsaved recordings.") + .font(.caption).foregroundStyle(.secondary) + } + Spacer(minLength: 0) + }.padding(20) + }.frame(minWidth: 680, minHeight: 460) + .onReceive(refresh) { _ in machine.poll() } + .onAppear { tapeSeek = Double(machine.tapePosition) } + .onChange(of: machine.tapePosition) { _, position in if !seeking { tapeSeek = Double(position) } } + .onChange(of: machine.tapeLength) { _, _ in if !seeking { tapeSeek = Double(machine.tapePosition) } } + } + + private var recordingNotice: some View { + HStack { + Label(machine.tapeDirty || machine.tapeMode == 2 ? "Recording needs export to keep it" : "Recordings are saved only when you export them", systemImage: machine.tapeDirty || machine.tapeMode == 2 ? "exclamationmark.circle" : "info.circle") + .foregroundStyle(machine.tapeDirty || machine.tapeMode == 2 ? Color.orange : Color.secondary) + .font(.caption).fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 8) + if machine.tapeDirty || machine.tapeMode == 2 { + SecondaryAction(title: "Discard…", systemImage: "minus.circle", action: machine.discardTape) + .accessibilityIdentifier("cassette-discard") + } + }.frame(minHeight: 24).accessibilityIdentifier("cassette-recording-status") + } +} + +private struct CassetteTransportButton: View { + let title: String + let symbol: String + var prominent = false + let action: () -> Void + private var label: some View { + VStack(spacing: 6) { + Image(systemName: symbol).font(.system(size: 19, weight: .medium)).frame(height: 23) + Text(title).font(.callout).fontWeight(.medium) + }.frame(width: 72, height: 54) + } + var body: some View { + Group { + if prominent { Button(action: action) { label }.buttonStyle(.borderedProminent) } + else { Button(action: action) { label }.buttonStyle(.bordered) } + }.accessibilityLabel(title) + } +} diff --git a/platforms/macos/App/CocoKeyboard.swift b/platforms/macos/App/CocoKeyboard.swift new file mode 100644 index 0000000..04aa4ff --- /dev/null +++ b/platforms/macos/App/CocoKeyboard.swift @@ -0,0 +1,142 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +// Layout reference: keyboardLayout.cpp, copyright 2015 Joseph Forgione. +// Matrix positions follow the retained keyboardLayout.cpp. Host key codes are +// used for physical CoCo positions and nonprinting keys. Natural/Compact +// printable characters follow the current Mac layout, translated to CoCo chords. +enum KeyboardMode: String, Codable, CaseIterable { + case natural = "Natural", coco = "CoCo", compact = "Compact" +} +struct CocoKeyboard { + var mode: KeyboardMode = .natural { didSet { if mode != oldValue { releaseAll() } } } + static let shift = UInt64(1) << 55 + static let control = UInt64(1) << 52 + static let alt = UInt64(1) << 51 + private var held: [UInt16: UInt64] = [:] + private var shiftSensitive: Set = [] + private var shifted = false, controlled = false, option = false + var mask: UInt64 { + let chords = held.values.reduce(0, |) + // Natural punctuation can differ from the Mac's physical Shift state. + let shiftAlone = held.isEmpty && shifted ? Self.shift : 0 + return chords | shiftAlone | (controlled ? Self.control : 0) | (option ? Self.alt : 0) + } + mutating func modifiers(shift: Bool, control: Bool, alt: Bool) { + shifted = shift; controlled = control; option = alt + for code in shiftSensitive { + if let chord = held[code] { held[code] = (chord & ~Self.shift) | (shift ? Self.shift : 0) } + } + } + mutating func press(code: UInt16, characters: String) { + // Ignore host repeat; the guest implements repeat from held keys. + guard held[code] == nil else { return } + if code == 57 { + held[code] = UInt64(1) << 32 | (mode == .coco ? Self.shift : Self.control) + return + } + if mode == .compact && (code == 48 || (code == 50 && !shifted)) { + held[code] = UInt64(1) << (code == 48 ? 49 : 50) | (shifted ? Self.shift : 0) + shiftSensitive.insert(code); return + } + if mode == .coco { + // Physical US CoCo positions, independent of the host layout. + let physical: [UInt16: Int] = [0:1,11:2,8:3,2:4,14:5,3:6,5:7,4:8, + 34:9,38:10,40:11,37:12,46:13,45:14,31:15,35:16,12:17,15:18, + 1:19,17:20,32:21,9:22,13:23,7:24,16:25,6:26,49:31, + 29:32,18:33,19:34,20:35,21:36,23:37,22:38,26:39,28:40,25:41, + 27:42,41:43,43:44,24:45,47:46,44:47,50:0] + if let bit = physical[code] { + held[code] = UInt64(1) << bit | (shifted ? Self.shift : 0) + shiftSensitive.insert(code); return + } + } + let navigation: [UInt16: UInt64] = [119: UInt64(1) << 30 | Self.shift, + 83: UInt64(1) << 30 | Self.shift, 117: UInt64(1) << 29 | Self.control, + 65: UInt64(1) << 29 | Self.control, 114: UInt64(1) << 30 | Self.control, + 82: UInt64(1) << 30 | Self.control, 116: UInt64(1) << 27 | Self.shift, + 92: UInt64(1) << 27 | Self.shift, 121: UInt64(1) << 28 | Self.shift, + 85: UInt64(1) << 28 | Self.shift] + if let chord = navigation[code] { + held[code] = mode == .coco && (code == 119 || code == 83) ? UInt64(1) << 50 : chord + return + } + let special: [UInt16: Int] = [36: 48, 76: 48, 53: 50, 51: 29, + 123: 29, 124: 30, 125: 28, 126: 27, 115: 49, 122: 53, 120: 54, 111: 50, 89: 49, 91: 27, 84: 28, 86: 29, 88: 30] + if let bit = special[code] { + held[code] = UInt64(1) << bit | (shifted ? Self.shift : 0) + shiftSensitive.insert(code) + } else if let chord = Self.chord(for: characters) { + held[code] = chord + if let c = characters.utf8.first, (65...90).contains(c) || (97...122).contains(c) { + held[code] = (chord & ~Self.shift) | (shifted ? Self.shift : 0) + shiftSensitive.insert(code) + } + } + } + mutating func release(code: UInt16) { held.removeValue(forKey: code); shiftSensitive.remove(code) } + mutating func releaseAll() { held.removeAll(); shiftSensitive.removeAll(); shifted = false; controlled = false; option = false } + static func chord(for text: String) -> UInt64? { + guard text.utf8.count == 1, let c = text.utf8.first else { return nil } + // BASIC defaults to uppercase; physical letters are unshifted unless + // the Mac event is uppercase. Shifted letters remain available to games/OS-9. + if (65...90).contains(c) { return UInt64(1) << (c - 64) | shift } + if (97...122).contains(c) { return UInt64(1) << (c - 96) } + if c == 64 { return 1 } + if c == 32 { return UInt64(1) << 31 } + if (48...55).contains(c) { return UInt64(1) << (32 + c - 48) } + if (56...57).contains(c) { return UInt64(1) << (40 + c - 56) } + let base = Array(":;,-./".utf8) + if let index = base.firstIndex(of: c) { return UInt64(1) << (42 + index) } + let shifted = Array("!\"#$%&'()*+<=>?".utf8) + let positions = [33,34,35,36,37,38,39,40,41,42,43,44,45,46,47] + if let index = shifted.firstIndex(of: c) { return UInt64(1) << positions[index] | shift } + // Extended CoCo characters use Control combinations in the natural map. + let extended: [UInt8: Int] = [91: 40, 93: 41, 92: 47, 94: 39, 95: 45, 123: 44, 125: 46, 124: 33, 126: 35] + if let bit = extended[c] { return UInt64(1) << bit | control } + return nil + } +} + +// Clipboard input is translated independently of the selected physical keymap +// and joystick bindings. Validate the entire payload before sending any keys. +struct CocoPaste { + enum Mode { case text, mergeBASIC, newBASIC } + struct Failure: LocalizedError { + let message: String + var errorDescription: String? { message } + } + let chords: [UInt64] + init(_ source: String, mode: Mode) throws { + guard source.utf8.count <= 65536 else { throw Failure(message: "Paste is limited to 64 KiB of text.") } + let normalized = source.replacingOccurrences(of: "\r\n", with: "\n") + .replacingOccurrences(of: "\n\r", with: "\n").replacingOccurrences(of: "\r", with: "\n") + .replacingOccurrences(of: "\t", with: " ") + var text = normalized + if mode != .text { + var lines: [String] = [] + for raw in normalized.split(separator: "\n", omittingEmptySubsequences: false) { + let line = raw.trimmingCharacters(in: .whitespaces) + if line.isEmpty { continue } + let digits = line.prefix(while: { $0 >= "0" && $0 <= "9" }) + guard let number = Int(digits), number <= 63999 else { + throw Failure(message: "Every BASIC line must begin with a line number from 0 to 63999. Paste commands with Paste Text instead.") + } + guard line.utf8.count <= 249 else { + throw Failure(message: "BASIC line \(number) exceeds the safe 249-character paste limit. Shorten it before pasting; nothing has been sent.") + } + lines.append(line + "\n") + } + guard !lines.isEmpty else { throw Failure(message: "The clipboard contains no numbered BASIC lines.") } + text = (mode == .newBASIC ? "NEW\n" : "") + lines.joined() + } + var keys: [UInt64] = [] + for character in text { + if character == "\n" { keys.append(UInt64(1) << 48) } + else if let chord = CocoKeyboard.chord(for: String(character)) { keys.append(chord) } + else { throw Failure(message: "The CoCo keyboard cannot type “\(character)â€�. Replace that character before pasting; nothing has been sent.") } + } + guard !keys.isEmpty, keys.count <= 65536 else { throw Failure(message: "Paste must contain 1 to 65536 keystrokes.") } + chords = keys + } +} diff --git a/platforms/macos/App/CompanionLibraryAuthority.swift b/platforms/macos/App/CompanionLibraryAuthority.swift new file mode 100644 index 0000000..25f826a --- /dev/null +++ b/platforms/macos/App/CompanionLibraryAuthority.swift @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import CryptoKit +import Darwin + +#if !VCC_COMPANION_CLIENT +/// VCC Plus alone owns catalog loading, install receipts, downloads and caches. +/// The transport authenticates its caller before reaching this disk-only API. +@MainActor +final class CompanionLibraryAuthority { + private let model: SoftwareLibraryModel + init(model: SoftwareLibraryModel) { self.model = model } + + func handle(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse { + await model.load() + // Another native window may already be loading this same model. + for _ in 0..<200 where model.loading { + try Task.checkCancellation() + try await Task.sleep(nanoseconds: 50_000_000) + } + guard let catalog = model.catalog else { throw failure(model.error ?? "VCC Plus's Software Library is unavailable.") } + let disks = catalog.companionDisks(includingOwnedTitles: request.ownedTitlesVersion == 1) + func release() throws -> SoftwareLibraryRelease { + guard let id = request.releaseID, let value = disks.releases.first(where: { $0.id == id }) else { + throw failure("Choose a disk edition from VCC Plus's catalog.") + } + return value + } + switch request.operation { + case .snapshot: + return .init(snapshot: snapshot(disks)) + case .setFavorite: + guard let id = request.titleID, let enabled = request.enabled, + disks.titles.contains(where: { $0.id == id }) else { throw failure("This disk title is unavailable.") } + if model.state.isFavorite(id) != enabled { model.state.toggleFavorite(id) } + await model.state.flush() + if let message = model.state.saveError { throw failure(message) } + return .init(snapshot: snapshot(disks)) + case .setPreferredRelease: + let selected = try release() + guard request.titleID == selected.titleID else { throw failure("This disk edition does not belong to the selected title.") } + model.state.selectRelease(selected.id, for: selected.titleID) + await model.state.flush() + if let message = model.state.saveError { throw failure(message) } + return .init(snapshot: snapshot(disks)) + case .install: + let selected = try release() + guard model.installingReleaseID == nil || model.installingReleaseID == selected.id else { + throw failure("VCC Plus is already installing another title. Let it finish or cancel it there.") + } + guard !model.launchBusy, !model.hasPendingLaunch else { throw failure("Finish the current VCC Plus library action first.") } + if model.installingReleaseID == nil && model.state.installedReleases[selected.id] == nil { model.install(selected) } + return try await installStatus(selected, catalog: disks) + case .installStatus: + return try await installStatus(release(), catalog: disks) + case .cancelInstallation: + let selected = try release() + if model.installingReleaseID == selected.id { model.cancelInstallation() } + return .init(snapshot: snapshot(disks), isInstalling: model.installingReleaseID == selected.id) + case .removeInstallation: + let selected = try release() + await model.removeInstallation(selected.id) + if let message = model.installationErrors[selected.id] { throw failure(message) } + return .init(snapshot: snapshot(disks)) + case .diskMembers, .exportDisk: + let selected = try release() + let receipt = try await installedReceipt(selected) + let candidates = receipt.relativeFiles.filter(Self.diskMember).map { CompanionLibraryDisk(path: $0, mediaType: "disk") } + .sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending } + guard !candidates.isEmpty else { throw failure("This installation contains no supported floppy disk images.") } + if request.operation == .diskMembers { return .init(snapshot: snapshot(disks), receipt: receipt, disks: candidates) } + guard let member = request.memberPath, candidates.contains(where: { $0.path == member }) else { + throw failure("Choose a disk file from this installation.") + } + let destination = model.state.directory.appendingPathComponent("CompanionDisks", isDirectory: true) + let exported = try await Task.detached(priority: .userInitiated) { + try Self.exportDisk(receipt: receipt, member: member, destination: destination) + }.value + return .init(exportedDiskURL: exported) + case .thumbnail, .manual: + guard let id = request.assetID, + let asset = disks.releases.lazy.flatMap({ release in + release.assets + (release.ownedGame == nil ? [] : [release.primaryManualAsset].compactMap { $0 }) + }).first(where: { $0.id == id }) else { + throw failure("This supporting asset is unavailable for the disk library.") + } + if request.operation == .thumbnail { + let data = try await SoftwareLibraryArtworkCache.shared.thumbnail(for: asset, directory: model.artworkDirectory) + return .init(assetData: data) + } + guard asset.isManual else { throw failure("Choose a manual or instructions asset.") } + let local = try await SoftwareLibraryManualCache.shared.localCopy(for: asset, + directory: model.state.directory.appendingPathComponent("Manuals", isDirectory: true)) + return .init(assetFileURL: local) + } + } + + private func failure(_ message: String) -> CompanionLibraryFailure { .init(message: message) } + private func snapshot(_ catalog: SoftwareLibraryCatalog) -> CompanionLibrarySnapshot { + let titleIDs = Set(catalog.titles.map(\.id)), releaseIDs = Set(catalog.releases.map(\.id)) + return .init(catalog: catalog, + favorites: model.state.favoriteTitleIDs.intersection(titleIDs), + preferredReleaseIDs: model.state.preferredReleaseIDs.filter { titleIDs.contains($0.key) && releaseIDs.contains($0.value) }, + installations: model.state.installedReleases.values.filter { releaseIDs.contains($0.releaseID) }) + } + private func installedReceipt(_ release: SoftwareLibraryRelease) async throws -> SoftwareLibraryInstallationReceipt { + let receipts = try await model.installer.recoverInstallations() + guard let receipt = receipts.first(where: { $0.releaseID == release.id && $0.packageSHA256 == release.packageSHA256 }) else { + throw failure("Install this disk edition in VCC Plus first.") + } + return receipt + } + private func installStatus(_ release: SoftwareLibraryRelease, catalog: SoftwareLibraryCatalog) async throws -> CompanionLibraryResponse { + if let message = model.installationErrors[release.id] { throw failure(message) } + let active = model.installingReleaseID == release.id + return .init(snapshot: snapshot(catalog), progress: active ? model.installProgress : nil, + isInstalling: active) + } + nonisolated static func diskMember(_ path: String) -> Bool { + !path.isEmpty && !path.hasPrefix("/") && !path.contains("\\") && !path.contains(":") + && !path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + && path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." } + && ["dsk", "os9"].contains((path as NSString).pathExtension.lowercased()) + } + /// Every handoff gets a new writable copy. Verified originals and the + /// emulator's working image are never handed to the real CoCo for writing. + nonisolated private static func exportDisk(receipt: SoftwareLibraryInstallationReceipt, member: String, destination: URL) throws -> URL { + guard diskMember(member), receipt.relativeFiles.contains(member) else { throw CompanionLibraryFailure(message: "Invalid disk member.") } + let root = receipt.workingDirectory.standardizedFileURL + var source = root + for component in member.split(separator: "/") { + source.appendPathComponent(String(component)) + let values = try source.resourceValues(forKeys: [.isSymbolicLinkKey]) + guard values.isSymbolicLink != true else { throw CompanionLibraryFailure(message: "The disk path contains a symbolic link.") } + } + guard source.resolvingSymlinksInPath().path.hasPrefix(root.resolvingSymlinksInPath().path + "/") else { + throw CompanionLibraryFailure(message: "The disk path leaves its installation.") + } + let descriptor = open(source.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) + guard descriptor >= 0 else { throw CompanionLibraryFailure(message: "The installed disk could not be read.") } + let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true) + defer { try? handle.close() } + var info = stat() + guard fstat(descriptor, &info) == 0, (info.st_mode & S_IFMT) == S_IFREG, + info.st_size > 0, info.st_size <= 16 * 1024 * 1024 else { + throw CompanionLibraryFailure(message: "Choose a floppy image within the 16 MiB limit.") + } + let data = try handle.read(upToCount: 16 * 1024 * 1024 + 1) ?? Data() + guard data.count == Int(info.st_size) else { throw CompanionLibraryFailure(message: "The installed disk changed while being read.") } + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) + let folder = destination.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + do { + let copy = folder.appendingPathComponent(source.lastPathComponent) + try data.write(to: copy, options: .atomic) + return copy + } catch { try? FileManager.default.removeItem(at: folder); throw error } + } +} +#endif diff --git a/platforms/macos/App/CompanionLibraryTypes.swift b/platforms/macos/App/CompanionLibraryTypes.swift new file mode 100644 index 0000000..5daf3ac --- /dev/null +++ b/platforms/macos/App/CompanionLibraryTypes.swift @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import SwiftUI + +/// The companion receives immutable disk-only data, never a database handle. +protocol CompanionLibraryAccess: Sendable { + func libraryRequest(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse +} + +struct CompanionLibraryRequest: Codable, Sendable { + enum Operation: String, Codable, Sendable { + case snapshot, setFavorite, setPreferredRelease, install, installStatus + case cancelInstallation, removeInstallation, diskMembers, exportDisk, thumbnail, manual + } + var operation: Operation + var requestID = UUID() + var releaseID: String? = nil + var titleID: String? = nil + var memberPath: String? = nil + var assetID: String? = nil + var enabled: Bool? = nil + // Missing in old clients: do not send project titles to an Archive-only UI. + var ownedTitlesVersion: Int? = 1 +} + +struct CompanionLibraryResponse: Codable, Sendable { + var snapshot: CompanionLibrarySnapshot? = nil + var progress: SoftwareLibraryInstallProgress? = nil + var receipt: SoftwareLibraryInstallationReceipt? = nil + var disks: [CompanionLibraryDisk]? = nil + var exportedDiskURL: URL? = nil + var assetData: Data? = nil + var assetFileURL: URL? = nil + var isInstalling: Bool = false + var errorMessage: String? = nil +} + +struct CompanionLibrarySnapshot: Codable, Sendable { + let catalog: SoftwareLibraryCatalog + let favorites: Set + let preferredReleaseIDs: [String: String] + let installations: [SoftwareLibraryState.Installation] +} + +struct CompanionLibraryDisk: Codable, Identifiable, Equatable, Sendable { + let path: String + let mediaType: String + var id: String { path } +} + +struct SoftwareLibraryInstallProgress: Codable, Sendable { + enum Stage: String, Codable, Sendable { case downloading, verifying, extracting, preparing, complete } + let stage: Stage + let receivedBytes: Int64 + let totalBytes: Int64 + var fraction: Double? { totalBytes > 0 ? min(1, max(0, Double(receivedBytes) / Double(totalBytes))) : nil } +} + +struct SoftwareLibraryInstallationReceipt: Codable, Sendable { + let releaseID: String + let packageSHA256: String + let installedAt: Date + let workingDirectory: URL + let relativeFiles: [String] +} + +struct CompanionLibraryFailure: LocalizedError { + let message: String + var errorDescription: String? { message } +} + +private struct CompanionLibraryAccessKey: EnvironmentKey { + static let defaultValue: (any CompanionLibraryAccess)? = nil +} +extension EnvironmentValues { + var companionLibraryAccess: (any CompanionLibraryAccess)? { + get { self[CompanionLibraryAccessKey.self] } + set { self[CompanionLibraryAccessKey.self] = newValue } + } +} + +extension SoftwareLibraryCatalog { + /// Filter both releases and their containing title: alternate cartridge/tape + /// editions never leak through the edition picker in a disk-only client. + var companionDisksOnly: Self { + companionDisks(includingOwnedTitles: true) + } + func companionDisks(includingOwnedTitles: Bool) -> Self { + Self(titles: titles.compactMap { title in + let releases = title.releases.filter { + $0.mediaType == "disk" && (includingOwnedTitles || $0.metadata["owned_game"] == .null) + } + return releases.isEmpty ? nil : SoftwareLibraryTitle(id: title.id, name: title.name, + identityStatus: title.identityStatus, releases: releases) + }, metadata: metadata) + } +} diff --git a/platforms/macos/App/ConfigurationProfile.swift b/platforms/macos/App/ConfigurationProfile.swift new file mode 100644 index 0000000..32b9fd1 --- /dev/null +++ b/platforms/macos/App/ConfigurationProfile.swift @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import Combine + +enum ProfileFailure: LocalizedError { + case message(String) + var errorDescription: String? { if case .message(let text) = self { return text }; return nil } +} + +// Profiles contain configuration and local file references only, never ROM, +// disk, tape, RAM, or execution-state bytes. Version changes require migration. +struct ConfigurationProfile: Codable, Equatable, Identifiable { + var version = 1 + var id = UUID() + var name: String + var machine = MachineSettings() + var videoOutput = 1 + var sound = true + var volume = 0.5 + var systemROM: URL? + var media = DiskAssignments() + var input = InputSettings() + var cassette: URL? + var fastCassette = false + var bootNitros9: Bool? // Missing in older profiles means ordinary BASIC startup. + + enum Reference: Hashable { + case systemROM, floppyROM, cartridge(Int), speechROM(Int), sdcFolder(Int), floppy(Int), hardDisk(Int), cassette + var label: String { + switch self { + case .systemROM: return "System ROM" + case .floppyROM: return "Floppy ROM" + case .sdcFolder(let slot): return "SD card folder — \(slot == 0 ? "single cartridge" : "Multi-Pak slot \(slot)")" + case .speechROM(let slot): return "Speech ROM — \(slot == 0 ? "single cartridge" : "Multi-Pak slot \(slot)")" + case .cartridge(let slot): return slot == 0 ? "Single cartridge" : "Multi-Pak slot \(slot)" + case .floppy(let drive): return "Floppy drive \(drive)" + case .hardDisk(let drive): return "Hard disk \(drive)" + case .cassette: return "Cassette" + } + } + } + var references: [(key: Reference, url: URL)] { + var result: [(Reference, URL)] = [] + if let systemROM { result.append((.systemROM, systemROM)) } + if let url = media.rom { result.append((.floppyROM, url)) } + for (i, slot) in (media.cartridges?.slots ?? []).enumerated() { + if let url = slot.url { result.append((.cartridge(i), url)) } + if let url = slot.speechROMURL { result.append((.speechROM(i), url)) } + if let url = slot.sdcFolderURL { result.append((.sdcFolder(i), url)) } + } + for (i, drive) in media.drives.enumerated() { if let drive { result.append((.floppy(i), drive.url)) } } + for (i, drive) in (media.hardDisks?.drives ?? []).enumerated() { if let drive { result.append((.hardDisk(i), drive.url)) } } + if let cassette { result.append((.cassette, cassette)) } + return result + } + mutating func replace(_ reference: Reference, with url: URL) { + switch reference { + case .systemROM: systemROM = url + case .floppyROM: media.rom = url + case .cartridge(let i): media.cartridges?.slots[i].url = url + case .speechROM(let i): media.cartridges?.slots[i].speechROMURL = url + case .sdcFolder(let i): media.cartridges?.slots[i].sdcFolderURL = url + case .floppy(let i): media.drives[i]?.url = url + case .hardDisk(let i): media.hardDisks?.drives[i]?.url = url + case .cassette: cassette = url + } + } + func validate() throws { + guard version == 1, !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, name.count <= 100, + !name.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }), + machine.valid, (0...2).contains(videoOutput), volume.isFinite, (0...1).contains(volume) else { + throw ProfileFailure.message("Invalid profile settings or unsupported profile version.") + } + try media.validate(); _ = try input.validated() + guard references.allSatisfy({ _, url in + url.isFileURL && url.path.hasPrefix("/") && url.path.count <= 8192 && + (url.host == nil || url.host == "" || url.host == "localhost") && url.query == nil && url.fragment == nil + }) else { throw ProfileFailure.message("Profiles must reference local files. Choose replacement files on this Mac.") } + } +} + +struct ProfileStore { + static let maxBytes = 65536 + let directory: URL + static let standard = Self(directory: AppIdentity.supportDirectory.appendingPathComponent("Profiles", isDirectory: true)) + func file(_ id: UUID) -> URL { directory.appendingPathComponent(id.uuidString).appendingPathExtension("vccprofile") } + static func read(_ url: URL) throws -> ConfigurationProfile { + let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } + let data = try handle.read(upToCount: maxBytes + 1) ?? Data() + guard data.count <= maxBytes else { throw ProfileFailure.message("The profile exceeds 64 KB.") } + let profile = try JSONDecoder().decode(ConfigurationProfile.self, from: data) + try profile.validate(); return profile + } + static func write(_ profile: ConfigurationProfile, to url: URL) throws { + try profile.validate() + let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let data = try encoder.encode(profile) + guard data.count <= maxBytes else { throw ProfileFailure.message("The profile exceeds 64 KB.") } + try data.write(to: url, options: .atomic) + } + func load() throws -> [ConfigurationProfile] { + guard FileManager.default.fileExists(atPath: directory.path) else { return [] } + let urls = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) + .filter { $0.pathExtension == "vccprofile" } + guard urls.count <= 128 else { throw ProfileFailure.message("The profile library supports up to 128 profiles.") } + return try urls.map { url in + let value = try Self.read(url) + guard url.lastPathComponent == file(value.id).lastPathComponent else { + throw ProfileFailure.message("A profile's identifier does not match its library filename: \(url.lastPathComponent)") + } + return value + }.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } + } + func save(_ value: ConfigurationProfile) throws { + try value.validate() + let existing = try load() + guard !existing.contains(where: { $0.id != value.id && $0.name.caseInsensitiveCompare(value.name) == .orderedSame }) else { + throw ProfileFailure.message("A profile with that name already exists. Choose another name or update the existing profile.") + } + guard existing.count < 128 || existing.contains(where: { $0.id == value.id }) else { + throw ProfileFailure.message("The profile library supports up to 128 profiles.") + } + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try Self.write(value, to: file(value.id)) + } + func delete(_ id: UUID) throws { try FileManager.default.removeItem(at: file(id)) } +} + +@MainActor +final class ProfileLibrary: ObservableObject { + @Published private(set) var profiles: [ConfigurationProfile] = [] + @Published var error: String? + private let store: ProfileStore + init(store: ProfileStore = .standard) { self.store = store; reload() } + func reload() { do { profiles = try store.load(); error = nil } catch { self.error = error.localizedDescription } } + @discardableResult func save(_ profile: ConfigurationProfile) -> Bool { + do { try store.save(profile); reload(); return error == nil } + catch { self.error = error.localizedDescription; return false } + } + func delete(_ id: UUID) { do { try store.delete(id); reload() } catch { self.error = error.localizedDescription } } +} + +struct PreparedProfile { + let profile: ConfigurationProfile + var systemROM: Data? + var diskROM: Data? + var cartridges = Array(repeating: Data(), count: 5) + var floppies: [DiskFiles.Image?] = Array(repeating: nil, count: 4) + var hardDisks: [HardDiskFiles.Image?] = Array(repeating: nil, count: 2) + var cassette: Data? + static func read(_ profile: ConfigurationProfile) throws -> Self { + try profile.validate() + var result = Self(profile: profile) + var failures: [String] = [] + for (key, url) in profile.references { + do { + switch key { + case .systemROM: result.systemROM = try ROMImage.read(url) + case .floppyROM: result.diskROM = try DiskFiles.readROM(url) + case .cartridge(let i): + result.cartridges[i] = try DiskFiles.readCartridgeAssignment(profile.media.cartridges!.slots[i]) + case .sdcFolder: + try DiskFiles.validateSDCFolder(url) + case .speechROM(let i): + result.cartridges[i] = try DiskFiles.readCartridgeAssignment(profile.media.cartridges!.slots[i]) + case .floppy(let i): + let image = try DiskFiles.readImage(url) + guard !image.data.isEmpty else { throw ProfileFailure.message("The floppy image is empty.") } + result.floppies[i] = image + case .hardDisk(let i): result.hardDisks[i] = try HardDiskFiles.readImage(url) + case .cassette: result.cassette = try TapeImage.read(url) + } + } catch { failures.append("\(key.label): \(url.path)\n\(error.localizedDescription)") } + } + guard failures.isEmpty else { throw ProfileFailure.message("Profile files need attention. Use Replace… to select their locations.\n\n" + failures.joined(separator: "\n\n")) } + return result + } + func request() -> VCCMachineProfile { + let request = VCCMachineProfile(), p = profile, layout = p.media.cartridges ?? CartridgeAssignments() + let hard = p.media.hardDisks ?? HardDiskAssignments() + request.use6309 = p.machine.use6309; request.ram = p.machine.ram; request.overclock = p.machine.overclock + request.frameInterval = p.machine.frameInterval; request.fastForward = p.machine.fastForward + request.videoOutput = p.videoOutput; request.sound = p.sound; request.volume = Float(p.volume) + request.systemROM = systemROM; request.diskROM = diskROM; request.diskROMName = p.media.rom?.lastPathComponent ?? "" + request.multiPak = layout.multiPak; request.physicalSlot = layout.physicalSlot + request.kinds = layout.slots.map { NSNumber(value: $0.kind.rawValue) }; request.cartridgeROMs = cartridges + request.cartridgeNames = layout.slots.map { $0.url?.lastPathComponent ?? "" } + request.sdcFolders = layout.slots.map { $0.sdcFolderURL?.path ?? "" } + request.sdcReadOnly = layout.slots.map { NSNumber(value: $0.sdcReadOnly ?? true) } + request.images = floppies.map { $0?.data ?? Data() } + hardDisks.map { $0?.data ?? Data() } + request.imageNames = (p.media.drives + hard.drives).map { $0?.url.lastPathComponent ?? "" } + request.readOnly = floppies.map { NSNumber(value: $0?.readOnly ?? false) } + hardDisks.map { NSNumber(value: $0?.readOnly ?? false) } + request.protectedImages = (p.media.drives + hard.drives).map { NSNumber(value: $0?.writeProtected ?? false) } + request.clockEnabled = hard.clockEnabled; request.clockReadOnly = hard.clockReadOnly + request.cassette = cassette; request.cassetteWAV = p.cassette?.pathExtension.lowercased() == "wav" + request.fastCassette = p.fastCassette + return request + } +} + +// A derived, read-only companion to v1 profiles, not unversioned file metadata. +// It describes connected hardware; it never promises an arbitrary image boots. +struct ProfileGuidance { + let title: String + let coverage: String + let explanation: String + init(_ profile: ConfigurationProfile) { + let layout = profile.media.cartridges ?? CartridgeAssignments() + let slots = layout.multiPak ? Array(layout.slots.dropFirst()) : [layout.slots[0]] + let floppy = slots.contains { $0.kind == .floppy } + let hard = slots.contains { $0.kind == .hardDisk } + let rom = slots.contains { $0.kind == .rom } + let orchestra = slots.contains { $0.kind == .orchestra90 } + let ramDisk = slots.contains { $0.kind == .ramDisk } + let sdc = slots.contains { $0.kind == .sdc } + coverage = ramDisk ? "Custom configuration: conventional controls for RAM disk" : layout.multiPak ? "System view: Multi-Pak layout" : slots[0].kind == .empty ? "System view: computer, cassette and input" : "Custom configuration: conventional display for direct-connected hardware" + if sdc { + title = "CoCo SDC" + explanation = "The selected Mac folder represents an SD card. SDC-DOS lets supporting software browse and mount images from it. Select the SDC startup slot, then use DRIVE 0,\"NAME.DSK\" to mount an image. Read-only protection is on by default; when disabled, guest writes and file-management commands change files in that folder. Profiles remember the folder and ROM, not mounted-image or program state." + } else if ramDisk { + title = "Volatile RAM disk" + explanation = "The 512 KB RAM disk needs supporting software, not a boot ROM. It is not a Disk BASIC drive. Resets retain its contents; loading a profile, quitting, or removing its last assignment discards them. Profiles remember the assignment only. Existing floppy and hard-disk media remain separate." + } else if slots.contains(where: { $0.kind == .speechSound }) { + title = "Speech/Sound Cartridge" + explanation = "Supporting CoCo programs send speech and music commands to this cartridge. It needs both internal chip ROMs, but has no boot program; leave your disk controller as the startup slot. Sound and volume use the normal Mac controls. Profiles retain the ROM locations, not playback state." + } else if orchestra { + title = "Orchestra-90 stereo sound" + explanation = "Supporting software can play stereo through Orchestra-90 without a ROM. An optional 8 KiB ROM adds its music program; select that slot as the startup slot to boot it. Sound and volume use the normal Mac audio controls. The ROM location is remembered, but profiles do not save music or playback state." + } else if hard { + title = "Expanded storage" + explanation = "The floppy and virtual hard-disk controllers are separate devices. A compatible disk ROM or OS-9 boot disk is needed; attaching a VHD does not boot it." + } else if floppy { + title = "Floppy software" + explanation = "The FD-502-based controller serves FD0–FD3. With a compatible Disk BASIC ROM, DIR lists the selected disk. Follow that software's loading or boot instructions; insertion alone does not run it." + } else if rom { + title = "Cartridge software" + explanation = "The cartridge is program ROM, not a disk image. In Multi-Pak mode, the startup slot chooses the initial cartridge; software can change live routing. Loading this profile restarts and leaves the machine paused." + } else { + title = "BASIC and cassette" + explanation = "Choose a compatible system ROM, then Run. For tape loading, Play prepares the recorder and CLOAD in BASIC starts the computer-controlled transfer. After recording with CSAVE, export the tape to keep its file." + } + } +} diff --git a/platforms/macos/App/ControllerDevices.swift b/platforms/macos/App/ControllerDevices.swift new file mode 100644 index 0000000..963f4e7 --- /dev/null +++ b/platforms/macos/App/ControllerDevices.swift @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import GameController +import IOKit.hid + +struct ControllerReading: Identifiable, Equatable { + let id: String, name: String + var x = 0.0, y = 0.0, rx = 0.0, ry = 0.0 + var buttons: UInt32 = 0 + func sample(_ settings: PortSettings) -> JoystickSample { + JoystickSample(x: JoystickSample.axis(settings.rightStick ? rx : x, deadZone: settings.deadZone), + y: JoystickSample.axis(settings.rightStick ? ry : y, deadZone: settings.deadZone), + buttons: (buttons & (1 << (settings.fire1 - 1)) != 0 ? 1 : 0) + | (buttons & (1 << (settings.fire2 - 1)) != 0 ? 2 : 0)) + } +} + +// GameController handles macOS-supported pads (including PlayStation/Xbox). +// Native HID covers standard USB joysticks/gamepads such as the F310 in D mode. +// Never seize devices, match keyboards/mice, or install a system driver. +@MainActor +final class ControllerDevices { + private let manager = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone)) + private var devices: [IOHIDDevice] = [] + private var elements: [String: [IOHIDElement]] = [:] + private var controllerIDs: [ObjectIdentifier: (base: String, ordinal: Int)] = [:] + private var nextRefresh = Date.distantPast + init() { + let matches = [4, 5].map { [kIOHIDDeviceUsagePageKey: 1, kIOHIDDeviceUsageKey: $0] } + IOHIDManagerSetDeviceMatchingMultiple(manager, matches as CFArray) + IOHIDManagerScheduleWithRunLoop(manager, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue) + IOHIDManagerOpen(manager, IOOptionBits(kIOHIDOptionsTypeNone)) + GCController.shouldMonitorBackgroundEvents = false + } + deinit { + IOHIDManagerUnscheduleFromRunLoop(manager, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue) + IOHIDManagerClose(manager, IOOptionBits(kIOHIDOptionsTypeNone)) + } + private func property(_ device: IOHIDDevice, _ key: String) -> String { + IOHIDDeviceGetProperty(device, key as CFString).map { String(describing: $0) } ?? "" + } + private func identity(_ device: IOHIDDevice) -> String { + let serial = property(device, kIOHIDSerialNumberKey) + return "hid:\(property(device, kIOHIDVendorIDKey)):\(property(device, kIOHIDProductIDKey)):\(serial.isEmpty ? property(device, kIOHIDLocationIDKey) : serial)" + } + func read() -> [ControllerReading] { + if Date() >= nextRefresh { + devices = (IOHIDManagerCopyDevices(manager) as? Set ?? []).filter { !GCController.supportsHIDDevice($0) } + elements.removeAll() + for device in devices { + elements[identity(device)] = IOHIDDeviceCopyMatchingElements(device, nil, 0) as? [IOHIDElement] ?? [] + } + nextRefresh = Date().addingTimeInterval(0.5) + } + var readings: [ControllerReading] = [] + let controllers = GCController.controllers() + let connected = Set(controllers.map(ObjectIdentifier.init)) + controllerIDs = controllerIDs.filter { connected.contains($0.key) } + for controller in controllers { + guard let pad = controller.extendedGamepad else { continue } + let name = controller.vendorName ?? "Game controller" + let base = "gc:\(name):\(controller.productCategory)" + let identity = ObjectIdentifier(controller) + if controllerIDs[identity] == nil { + let used = Set(controllerIDs.values.filter { $0.base == base }.map(\.ordinal)) + var ordinal = 0 + while used.contains(ordinal) { ordinal += 1 } + controllerIDs[identity] = (base, ordinal) + } + let ordinal = controllerIDs[identity]!.ordinal + var value = ControllerReading(id: "\(base):\(ordinal)", name: name + (ordinal == 0 ? "" : " \(ordinal + 1)")) + let direction = pad.dpad.xAxis.value != 0 || pad.dpad.yAxis.value != 0 ? pad.dpad : pad.leftThumbstick + value.x = Double(direction.xAxis.value); value.y = -Double(direction.yAxis.value) + value.rx = Double(pad.rightThumbstick.xAxis.value); value.ry = -Double(pad.rightThumbstick.yAxis.value) + let buttons: [GCControllerButtonInput?] = [pad.buttonA,pad.buttonB,pad.buttonX,pad.buttonY, + pad.leftShoulder,pad.rightShoulder,pad.leftTrigger,pad.rightTrigger, + pad.buttonOptions,pad.buttonMenu,pad.leftThumbstickButton,pad.rightThumbstickButton] + for (index, button) in buttons.enumerated() where button?.isPressed == true { value.buttons |= 1 << index } + readings.append(value) + } + for device in devices { + var value = ControllerReading(id: identity(device), name: property(device, kIOHIDProductKey)) + var hasValue = false + var hat: Int? + var axes: [UInt32: Double] = [:] + for element in elements[value.id] ?? [] { + let type = IOHIDElementGetType(element) + guard (1...3).contains(type.rawValue) else { continue } + let page = IOHIDElementGetUsagePage(element), usage = IOHIDElementGetUsage(element) + guard page == 1 || page == 9 else { continue } + let raw: IOHIDValue? = withUnsafeTemporaryAllocation(of: Unmanaged.self, capacity: 1) { buffer in + guard IOHIDDeviceGetValue(device, element, buffer.baseAddress!) == kIOReturnSuccess else { return nil } + return buffer[0].takeUnretainedValue() + } + guard let raw else { continue } + hasValue = true + let integer = IOHIDValueGetIntegerValue(raw) + if page == 9, (1...16).contains(usage), integer != 0 { value.buttons |= 1 << (usage - 1) } + if page == 1 { + let low = IOHIDElementGetLogicalMin(element), high = IOHIDElementGetLogicalMax(element) + guard high > low else { continue } + let normalized = min(1, max(-1, 2 * Double(integer - low) / Double(high - low) - 1)) + switch usage { + case 0x30...0x35: axes[usage] = normalized + case 0x39: if (low...high).contains(integer), high - low == 7 { hat = integer - low } + default: break + } + } + } + value.x = axes[0x30] ?? 0; value.y = axes[0x31] ?? 0 + value.rx = axes[0x33] ?? axes[0x32] ?? 0; value.ry = axes[0x34] ?? axes[0x35] ?? 0 + if let hat { + value.x = [1,2,3].contains(hat) ? 1 : ([5,6,7].contains(hat) ? -1 : 0) + value.y = [7,0,1].contains(hat) ? -1 : ([3,4,5].contains(hat) ? 1 : 0) + } + // A removed device may remain in our half-second inventory cache. + if hasValue { readings.append(value) } + } + return readings.sorted { $0.id < $1.id } + } +} diff --git a/platforms/macos/App/DebugSourceListing.swift b/platforms/macos/App/DebugSourceListing.swift new file mode 100644 index 0000000..973f7e1 --- /dev/null +++ b/platforms/macos/App/DebugSourceListing.swift @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// Immutable LWASM listing. Source filenames are descriptive metadata only; +/// importing a listing never opens those paths or loads its bytes into the CPU. +struct DebugSourceListing: Sendable { + struct Line: Identifiable, Sendable { + let id: Int + let text: String + let sourceFile: String? + let sourceLine: Int? + let address: UInt16? + let bytes: [UInt8] + var location: String { + guard let sourceLine else { return "Listing line \(id + 1)" } + return "\(sourceFile ?? "Source"):\(sourceLine)" + } + } + enum ImportError: LocalizedError { + case tooLarge, encoding, format, notFile, relocatable + var errorDescription: String? { + switch self { + case .tooLarge: return "Use a listing smaller than 8 MB, with at most 50,000 lines and 4,096 characters per line." + case .encoding: return "The listing must be UTF-8 or BOM-marked UTF-16 text." + case .format: return "No addressed LWASM byte lines were found. Generate a listing with LWASM --list and use final logical CPU addresses." + case .notFile: return "Choose a regular listing file." + case .relocatable: return "This listing uses relocatable sections. Its addresses need a linker map before they can match CPU addresses. Open a final absolute LWASM listing; CMOC/link-map integration is planned separately." + } + } + } + static let maximumBytes = 8 * 1024 * 1024 + let name: String + let lines: [Line] + let byAddress: [UInt16: [Int]] + var addressedLineCount: Int { byAddress.values.reduce(0) { $0 + $1.count } } + + static func read(_ url: URL) throws -> Self { + let access = url.startAccessingSecurityScopedResource() + defer { if access { url.stopAccessingSecurityScopedResource() } } + guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw ImportError.notFile } + let file = try FileHandle(forReadingFrom: url) + defer { try? file.close() } + let data = try file.read(upToCount: maximumBytes + 1) ?? Data() + return try parse(data, name: url.lastPathComponent) + } + + static func parse(_ data: Data, name: String) throws -> Self { + guard data.count <= maximumBytes else { throw ImportError.tooLarge } + let encoding: String.Encoding = data.starts(with: [0xff, 0xfe]) || data.starts(with: [0xfe, 0xff]) ? .utf16 : .utf8 + guard var text = String(data: data, encoding: encoding), !text.contains("\0") else { throw ImportError.encoding } + if text.hasPrefix("\u{feff}") { text.removeFirst() } + text = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") + let rawLines = text.split(separator: "\n", omittingEmptySubsequences: false) + guard rawLines.count <= 50_000 else { throw ImportError.tooLarge } + // LWASM list.c: address/marker + 16 byte digits + space, followed by + // (17-column filename):line or --list-nofiles' decimal line number. + // Cycle-count columns stay in the displayed text, without interpretation. + let metadata = try NSRegularExpression(pattern: #"^(?:\((.{0,17})\):([0-9]{5,})|([0-9]{5,})) (.*)$"#) + let section = try NSRegularExpression(pattern: #"(?i)^\s*(?:[a-z_.$@?][a-z0-9_.$@?]*\s+)?(?:section|endsection)\b"#) + var lines: [Line] = [] + var addresses: [UInt16: [Int]] = [:] + for (index, raw) in rawLines.enumerated() { + guard raw.count <= 4096 else { throw ImportError.tooLarge } + let string = String(raw), octets = Array(string.utf8) + var sourceFile: String?, sourceLine: Int?, address: UInt16? + var sourceText = string, bytes: [UInt8] = [] + if octets.count >= 22, octets[21] == 32 { + let remainder = String(decoding: octets.dropFirst(22), as: UTF8.self) + let ns = remainder as NSString + if let match = metadata.firstMatch(in: remainder, range: NSRange(location: 0, length: ns.length)) { + func group(_ i: Int) -> String? { match.range(at: i).location == NSNotFound ? nil : ns.substring(with: match.range(at: i)) } + sourceFile = group(1)?.trimmingCharacters(in: .whitespaces) + sourceLine = (group(2) ?? group(3)).flatMap(Int.init) + sourceText = group(4) ?? "" + if section.firstMatch(in: sourceText, range: NSRange(sourceText.startIndex..., in: sourceText)) != nil { + throw ImportError.relocatable + } + let digits = String(decoding: octets[5..<21], as: UTF8.self).trimmingCharacters(in: .whitespaces) + // A space denotes a logical address. '.' (OS-9 data) and + // 's' (structure offset) are not CPU-code associations. + if octets[4] == 32, digits.count > 0, digits.count % 2 == 0, + digits.allSatisfy({ $0.isASCII && $0.isHexDigit }), + octets.prefix(4).allSatisfy({ (48...57).contains($0) || (65...70).contains($0) || (97...102).contains($0) }), + let value = UInt16(String(decoding: octets.prefix(4), as: UTF8.self), radix: 16) { + address = value + let chars = Array(digits) + bytes = stride(from: 0, to: chars.count, by: 2).compactMap { UInt8(String(chars[$0...($0 + 1)]), radix: 16) } + addresses[value, default: []].append(index) + } + } + } + lines.append(Line(id: index, text: sourceText, sourceFile: sourceFile, sourceLine: sourceLine, address: address, bytes: bytes)) + } + guard !addresses.isEmpty else { throw ImportError.format } + return Self(name: name, lines: lines, byAddress: addresses) + } + + func line(at address: UInt16, preferring selected: Int?) -> Int? { + guard let candidates = byAddress[address] else { return nil } + return selected.flatMap { candidates.contains($0) ? $0 : nil } ?? candidates.first + } + + func find(_ query: String, after selected: Int?) -> Int? { + guard !query.isEmpty else { return nil } + let start = selected.map { ($0 + 1) % lines.count } ?? 0 + for offset in 0.. 1 { + Text("Several listing lines share this address. Select the intended line; the breakpoint applies to every execution at that CPU address.") + .font(.caption).foregroundStyle(.secondary) + } + } else if debugger.sourceFollowPC { + Text("No source line at PC $\(DebuggerModel.hex(debugger.programCounter)).").font(.caption) + .accessibilityIdentifier("debugger-source-no-match") + } + Text("Logical CPU addresses · Load the matching program separately.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + .help("Listing bytes are not verified against current memory. Use a final absolute listing for the loaded program and its current MMU mapping.") + }.padding(8) + } else { + VStack(alignment: .leading, spacing: 8) { + Label("Open a source listing", systemImage: "doc.text.magnifyingglass").font(.headline) + Text("Open a LWASM .lst or text listing generated with --list. View source, follow exact PC addresses, search, and share breakpoints with disassembly.") + Text("A listing is debugging information. Opening it does not load a program or change the machine.").foregroundStyle(.secondary) + }.padding(16).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + } + if let message = debugger.sourceMessage { + Text(message).font(.caption).foregroundStyle(.orange).padding(8) + .accessibilityIdentifier("debugger-source-message") + } + }.background(Color(nsColor: .textBackgroundColor)) + } + + private func row(_ line: DebugSourceListing.Line) -> some View { + let isPC = line.id == debugger.currentSourceLine + let selected = line.id == debugger.visibleSourceLine + return HStack(spacing: 8) { + if let address = line.address { + let action = "\(debugger.allBreakpoints.contains(address) ? "Remove" : "Set") breakpoint at \(DebuggerModel.hex(address)), listing line \(line.id + 1)" + Button { debugger.toggleBreakpoint(at: address) } label: { + Image(systemName: debugger.breakpoints.contains(address) ? "circle.fill" : debugger.disabledBreakpoints.contains(address) ? "circle.dashed" : "circle") + .foregroundStyle(debugger.breakpoints.contains(address) ? Color.red : Color.secondary) + .frame(width: 22, height: 24) + }.buttonStyle(.plain).disabled(!debugger.commandsAvailable) + .help(action).accessibilityLabel(action) + .accessibilityIdentifier("debugger-source-breakpoint-\(line.id)") + } else { Color.clear.frame(width: 22, height: 24) } + Text(String(line.id + 1)).foregroundStyle(.secondary).frame(width: 42, alignment: .trailing) + Button { + debugger.selectSourceLine(line.id) + } label: { + HStack(spacing: 8) { + Text(line.address.map { DebuggerModel.hex($0) } ?? "—").frame(width: 42, alignment: .leading) + Image(systemName: "arrow.right").opacity(isPC ? 1 : 0).frame(width: 12) + Text(line.text.isEmpty ? " " : line.text).fixedSize(horizontal: true, vertical: false) + }.frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()) + }.buttonStyle(.plain).accessibilityIdentifier("debugger-source-line-\(line.id)") + }.font(.system(size: 12, design: .monospaced)).padding(.horizontal, 8) + .background(selected ? Color.accentColor.opacity(0.16) : Color.clear) + .contextMenu { + if let address = line.address { + Button("Show Disassembly") { debugger.showDisassembly(at: address) } + Button("Show in Memory") { debugger.showMemory(at: address) } + Button("Set PC Here") { debugger.setPC(to: address) }.disabled(!debugger.canEdit) + Button(debugger.allBreakpoints.contains(address) ? "Remove Breakpoint" : "Add Breakpoint") { debugger.toggleBreakpoint(at: address) } + .disabled(!debugger.commandsAvailable) + if debugger.allBreakpoints.contains(address) { + Button(debugger.breakpoints.contains(address) ? "Disable Breakpoint" : "Enable Breakpoint") { + debugger.setBreakpoint(address, enabled: !debugger.breakpoints.contains(address)) + }.disabled(!debugger.commandsAvailable) + } + } + Button("Copy Source Line") { + NSPasteboard.general.clearContents(); NSPasteboard.general.setString(line.text, forType: .string) + } + } + } + + private func open() { + let panel = NSOpenPanel(); panel.title = "Open LWASM Source Listing" + panel.canChooseDirectories = false; panel.allowsMultipleSelection = false + // Allow .lst and text listings regardless of their Finder type association. + panel.begin { result in + guard result == .OK, let url = panel.url else { return } + Task { await debugger.loadListing(url) } + } + } +} diff --git a/platforms/macos/App/DebuggerModel.swift b/platforms/macos/App/DebuggerModel.swift new file mode 100644 index 0000000..63f3b6c --- /dev/null +++ b/platforms/macos/App/DebuggerModel.swift @@ -0,0 +1,319 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import Combine + +/// A window-owned inspector of the shared machine. It never owns another CPU +/// and only asks for immutable captures on the machine's existing serial queue. +@MainActor +final class DebuggerModel: ObservableObject { + let machine: MachineModel + @Published private(set) var snapshot: VCCDebuggerSnapshot? + @Published private(set) var changedRegisters: Set = [] + @Published var followPC = true + enum CodePane: String, CaseIterable { case disassembly = "Disassembly", source = "Source" } + @Published var codePane = CodePane.disassembly + @Published private(set) var listing: DebugSourceListing? + @Published private(set) var listingLoading = false + @Published var sourceFollowPC = true + @Published var selectedSourceLine: Int? + @Published var sourceSearch = "" + @Published var sourceMessage: String? + private var listingRequest = UUID() + @Published var addressText = "8000" + enum MemorySpace: String, CaseIterable { case mapped = "Mapped CPU", physical = "Physical RAM" } + enum MemoryPane: String, CaseIterable { case memory = "Memory", mmu = "MMU" } + @Published var memoryPane = MemoryPane.memory + @Published private(set) var memorySpace = MemorySpace.mapped + @Published var memoryAddressText = "0000" + @Published var physicalAddressText = "000000" + @Published var pcText = "" + @Published var breakpointText = "" + @Published var editAddressText = "" + @Published var editByteText = "" + @Published var validationMessage: String? + @Published private(set) var commandPending = false + private var address: UInt16 = 0x8000 + @Published private(set) var highlightedByte: UInt32? + private var memoryAddress: UInt16 = 0 + private var physicalAddress: UInt32 = 0 + private var readRequest: UUID? + + init(machine: MachineModel) { self.machine = machine } + + var paused: Bool { machine.state == .paused } + var loaded: Bool { machine.state == .paused || machine.state == .running } + var commandsAvailable: Bool { loaded && !machine.busy && !machine.diskSaving && !commandPending } + var canEdit: Bool { commandsAvailable && paused } + var breakpoints: [UInt16] { snapshot?.breakpoints.map { $0.uint16Value } ?? [] } + var disabledBreakpoints: [UInt16] { snapshot?.disabledBreakpoints.map { $0.uint16Value } ?? [] } + var allBreakpoints: [UInt16] { (breakpoints + disabledBreakpoints).sorted() } + var programCounter: UInt16 { snapshot?.registers["PC"]?.uint16Value ?? 0 } + var currentSourceLine: Int? { listing?.line(at: programCounter, preferring: selectedSourceLine) } + var visibleSourceLine: Int? { sourceFollowPC ? currentSourceLine : selectedSourceLine } + + func loadListing(_ url: URL) async { + let request = UUID(); listingRequest = request; listingLoading = true; sourceMessage = nil + let result = await Task.detached(priority: .userInitiated) { Result { try DebugSourceListing.read(url) } }.value + guard listingRequest == request else { return } + listingLoading = false + switch result { + case .success(let listing): + self.listing = listing; selectedSourceLine = nil; sourceFollowPC = true; codePane = .source + case .failure(let error): sourceMessage = error.localizedDescription + } + } + + func unloadListing() { + listingRequest = UUID(); listingLoading = false; listing = nil; selectedSourceLine = nil; sourceMessage = nil + // Source breakpoints are the shared logical-address breakpoints. Closing + // a document must not silently remove a user's execution controls. + } + + func selectSourceLine(_ index: Int) { + guard listing?.lines.indices.contains(index) == true else { return } + selectedSourceLine = index; sourceFollowPC = false; sourceMessage = nil + } + + func findSource() { + guard let listing else { return } + guard let index = listing.find(sourceSearch, after: selectedSourceLine) else { + sourceMessage = sourceSearch.isEmpty ? "Enter text to find in the listing." : "No matching source line."; return + } + selectSourceLine(index) + } + + func showDisassembly(at address: UInt16) { + addressText = Self.hex(address); goToAddress(); codePane = .disassembly + } + var physical: Bool { memorySpace == .physical } + var memory: [UInt8] { snapshot.map { Array(physical ? $0.physicalMemory : $0.memory) } ?? [] } + var memoryAvailable: [UInt8] { physical ? Array(repeating: 1, count: memory.count) : snapshot.map { Array($0.memoryAvailable) } ?? [] } + var displayedMemoryAddress: UInt32 { snapshot.map { physical ? $0.physicalAddress : UInt32($0.memoryAddress) } ?? 0 } + var installedRAM: UInt32 { snapshot?.mmu.ramByteCount ?? 0 } + var memoryAddressWidth: Int { physical ? 6 : 4 } + var canEditMemory: Bool { canEdit && !physical } + var canPreviousMemory: Bool { (physical ? physicalAddress : UInt32(memoryAddress)) > 0 } + var canNextMemory: Bool { + physical ? physicalAddress + 256 < installedRAM : UInt32(memoryAddress) + 256 < 65536 + } + func memoryLocation(offset: Int) -> UInt32 { + let address = displayedMemoryAddress + UInt32(offset) + return physical ? address : address & 0xffff + } + + // A leading $ or 0x is accepted; all debugger addresses and byte values + // are explicitly hexadecimal. Reject overflow instead of truncating it. + static func hexadecimal(_ text: String, maximum: UInt32 = 0xffff) -> UInt16? { + guard let value = hexadecimalAddress(text, maximum: min(maximum, 0xffff)) else { return nil } + return UInt16(value) + } + + static func hexadecimalAddress(_ text: String, maximum: UInt32) -> UInt32? { + var value = text.trimmingCharacters(in: .whitespacesAndNewlines) + if value.hasPrefix("$") { value.removeFirst() } + else if value.lowercased().hasPrefix("0x") { value.removeFirst(2) } + guard !value.isEmpty, value.allSatisfy({ $0.isASCII && $0.isHexDigit }), + let parsed = UInt32(value, radix: 16), parsed <= maximum else { return nil } + return parsed + } + + static func hex(_ value: T, width: Int = 4) -> String { + String(format: "%0*X", width, UInt32(truncatingIfNeeded: value)) + } + + func poll() async { + defer { + // A queued immutable read can finish after the window disappears. + // Discard that result, and permit a fresh capture on reopening. + readRequest = nil + commandPending = false + } + while !Task.isCancelled { + refresh() + do { try await Task.sleep(nanoseconds: 200_000_000) } + catch { return } + } + } + + func refresh() { + guard !commandPending else { return } + capture() + } + + private func capture(releasesCommand: Bool = false) { + guard readRequest == nil, !machine.busy else { + if releasesCommand { commandPending = false } + return + } + let request = UUID() + readRequest = request + let requestedPhysicalAddress = physicalAddress + let requestedPhysicalMemory = physical + machine.readDebugger(address: address, followPC: followPC, memoryAddress: memoryAddress, + physicalAddress: requestedPhysicalAddress, physicalMemory: requestedPhysicalMemory) { [weak self] capture in + guard let self, self.readRequest == request else { return } + self.readRequest = nil + if releasesCommand { self.commandPending = false } + guard let capture else { return } + let registers = capture.registers + if let previous = self.snapshot, previous.machine.generation == capture.machine.generation { + let changes = Set(registers.compactMap { key, value in + previous.registers[key] != value ? key : nil + }) + // Preserve the last instruction's highlights while paused; + // repeated inspection is not another instruction. + if !changes.isEmpty { self.changedRegisters = changes } + } else { self.changedRegisters = [] } + self.snapshot = capture + // The bridge clamps an old physical location after a RAM-size + // change. Preserve an unfinished text draft; only explicit Go + // normalizes it to the newly accepted location. + if requestedPhysicalMemory && self.physicalAddress == requestedPhysicalAddress { + self.physicalAddress = capture.physicalAddress + } + } + } + + private func perform(_ operation: (@escaping () -> Void) -> Void) { + commandPending = true + operation { [weak self] in + guard let self else { return } + // Do not accept a pre-command read or enable another breakpoint + // mutation until its authoritative post-command list arrives. + self.readRequest = nil + self.capture(releasesCommand: true) + } + } + + func toggleExecution() { + guard commandsAvailable else { return } + validationMessage = nil + if machine.state == .running { perform(machine.debuggerPause) } + else { perform(machine.debuggerContinue) } + } + + func step() { + guard canEdit else { return } + validationMessage = nil + changedRegisters = [] + perform(machine.debuggerStep) + } + + func goToAddress() { + guard let value = Self.hexadecimal(addressText) else { + validationMessage = "Enter a hexadecimal address from 0000 to FFFF."; return + } + address = value; addressText = Self.hex(value); followPC = false + validationMessage = nil; refresh() + } + + func setMemorySpace(_ space: MemorySpace) { + highlightedByte = nil; memorySpace = space; validationMessage = nil; refresh() + } + + func showPhysicalMemory(at value: UInt32) { + guard value < installedRAM else { + validationMessage = "That physical address is outside installed RAM."; return + } + highlightedByte = nil + physicalAddress = value & ~UInt32(15) + physicalAddressText = Self.hex(physicalAddress, width: 6) + memorySpace = .physical; memoryPane = .memory + validationMessage = nil; refresh() + } + + func pageMemory(forward: Bool) { + guard forward ? canNextMemory : canPreviousMemory else { return } + if physical { + showPhysicalMemory(at: forward ? physicalAddress + 256 : physicalAddress >= 256 ? physicalAddress - 256 : 0) + } else { + showMemory(at: forward ? memoryAddress + 256 : memoryAddress >= 256 ? memoryAddress - 256 : 0) + } + } + + func showMemory(at value: UInt16) { + memorySpace = .mapped; memoryPane = .memory + highlightedByte = nil + memoryAddress = value & 0xfff0 + memoryAddressText = Self.hex(memoryAddress) + validationMessage = nil; refresh() + } + + func revealGraphicsByte(_ address: UInt32, physical: Bool) { + if physical { showPhysicalMemory(at: address) } + else if let logical = UInt16(exactly: address) { showMemory(at: logical) } + highlightedByte = address + } + + func goToMemory() { + if physical { + guard installedRAM > 0, let value = Self.hexadecimalAddress(physicalAddressText, maximum: installedRAM - 1) else { + validationMessage = "Enter a physical RAM address from 000000 to \(Self.hex(installedRAM > 0 ? installedRAM - 1 : 0, width: 6))."; return + } + showPhysicalMemory(at: value); return + } + guard let value = Self.hexadecimal(memoryAddressText) else { + validationMessage = "Enter a hexadecimal memory address from 0000 to FFFF."; return + } + showMemory(at: value) + } + + func setPC() { + guard canEdit else { return } + guard let value = Self.hexadecimal(pcText) else { + validationMessage = "Enter the new program counter in hexadecimal, from 0000 to FFFF."; return + } + setPC(to: value) + } + + func setPC(to value: UInt16) { + guard canEdit else { return } + validationMessage = nil; pcText = Self.hex(value) + perform { machine.debuggerSetPC(value, completion: $0) } + } + + func addBreakpoint() { + guard let value = Self.hexadecimal(breakpointText) else { + validationMessage = "Enter a hexadecimal breakpoint address from 0000 to FFFF."; return + } + configureBreakpoints(Array(Set(breakpoints + [value])).sorted(), disabled: disabledBreakpoints.filter { $0 != value }) + } + + func toggleBreakpoint(at value: UInt16) { + if allBreakpoints.contains(value) { + configureBreakpoints(breakpoints.filter { $0 != value }, disabled: disabledBreakpoints.filter { $0 != value }) + } else { configureBreakpoints((breakpoints + [value]).sorted(), disabled: disabledBreakpoints) } + } + + func setBreakpoint(_ value: UInt16, enabled: Bool) { + guard allBreakpoints.contains(value) else { return } + configureBreakpoints(enabled ? Array(Set(breakpoints + [value])).sorted() : breakpoints.filter { $0 != value }, + disabled: enabled ? disabledBreakpoints.filter { $0 != value } : Array(Set(disabledBreakpoints + [value])).sorted()) + } + + func removeAllBreakpoints() { configureBreakpoints([], disabled: []) } + + private func configureBreakpoints(_ addresses: [UInt16], disabled: [UInt16]) { + guard commandsAvailable else { return } + validationMessage = nil + perform { machine.debuggerConfigureBreakpoints(addresses.map { NSNumber(value: $0) }, disabled: disabled.map { NSNumber(value: $0) }, completion: $0) } + } + + func selectByte(offset: Int) { + guard !physical, let snapshot, offset >= 0, offset < memory.count, offset < memoryAvailable.count, + memoryAvailable[offset] != 0 else { return } + highlightedByte = memoryLocation(offset: offset) + editAddressText = Self.hex(snapshot.memoryAddress &+ UInt16(offset)) + editByteText = Self.hex(UInt16(memory[offset]), width: 2) + } + + func writeByte() { + guard canEditMemory else { return } + guard let target = Self.hexadecimal(editAddressText), + let byte = Self.hexadecimal(editByteText, maximum: 0xff) else { + validationMessage = "Enter a hexadecimal address (0000–FFFF) and byte (00–FF)."; return + } + validationMessage = nil + perform { machine.debuggerWriteMemory(address: target, data: Data([UInt8(byte)]), completion: $0) } + } +} diff --git a/platforms/macos/App/DebuggerView.swift b/platforms/macos/App/DebuggerView.swift new file mode 100644 index 0000000..4a8cb5a --- /dev/null +++ b/platforms/macos/App/DebuggerView.swift @@ -0,0 +1,510 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit + +struct DebuggerView: View { + // The machine publishes at display cadence. Rendering this inspector is + // driven by its own bounded snapshot stream and local editing state. + private let machine: MachineModel + @StateObject private var debugger: DebuggerModel + @StateObject private var memoryTools: MemoryToolsModel + @StateObject private var graphics = GraphicsPreviewModel() + @StateObject private var trace: TraceModel + private enum Workspace: String, CaseIterable { case inspector = "Inspector", memory = "Memory Tools", graphics = "Graphics Preview", trace = "Trace" } + @State private var workspace = Workspace.inspector + + init(machine: MachineModel) { + self.machine = machine + _debugger = StateObject(wrappedValue: DebuggerModel(machine: machine)) + _memoryTools = StateObject(wrappedValue: MemoryToolsModel(machine: machine)) + _trace = StateObject(wrappedValue: TraceModel(machine: machine)) + } + + var body: some View { + VStack(spacing: 0) { + executionToolbar + Divider() + if debugger.loaded { + HStack { + Picker("Debugger workspace", selection: $workspace) { + ForEach(Workspace.allCases, id: \.self) { Text($0.rawValue).tag($0) } + }.pickerStyle(.segmented).labelsHidden().frame(width: 460) + .accessibilityIdentifier("debugger-workspace") + Spacer() + }.padding(.horizontal, 12).padding(.vertical, 6) + Divider() + if workspace == .memory { MemoryToolsView(model: memoryTools) } + else if workspace == .graphics { + GraphicsPreviewView(model: graphics, machine: machine) { address, physical in + debugger.revealGraphicsByte(address, physical: physical) + workspace = .inspector + } + } + else if workspace == .trace { TraceView(model: trace) } + else { + HSplitView { + VSplitView { + codeInspector.frame(minHeight: debugger.codePane == .source ? 340 : 220) + // Keep the combined minimum stable when Source needs + // more room, rather than overflowing a restored window. + memoryInspector.frame(minHeight: debugger.codePane == .source ? 145 : 265, + idealHeight: debugger.codePane == .source ? 180 : 310) + }.frame(minWidth: 590, idealWidth: 740) + inspector.frame(minWidth: 265, idealWidth: 285, maxWidth: 360) + } + } + } else { + VStack(spacing: 12) { + Image(systemName: "ladybug").font(.system(size: 36)).foregroundStyle(.secondary) + Text("Load a machine to begin debugging").font(.title2) + Text("Open a system ROM or choose a system profile in the main window.") + .foregroundStyle(.secondary) + }.frame(maxWidth: .infinity, maxHeight: .infinity) + } + Divider() + statusBar + } + .frame(minWidth: 920, minHeight: 640) + .task { await debugger.poll() } + .onChange(of: debugger.followPC) { _, _ in debugger.refresh() } + } + + private var codeInspector: some View { + VStack(spacing: 0) { + HStack { + Picker("Code view", selection: $debugger.codePane) { + ForEach(DebuggerModel.CodePane.allCases, id: \.self) { Text($0.rawValue).tag($0) } + }.pickerStyle(.segmented).labelsHidden().frame(width: 225) + .accessibilityIdentifier("debugger-code-pane") + Spacer(minLength: 8) + if debugger.codePane == .disassembly { disassemblyNavigation } + }.padding(.horizontal, 12).padding(.vertical, 6) + Divider() + if debugger.codePane == .source { DebugSourceView(debugger: debugger) } + else { disassembly } + } + } + + private var executionToolbar: some View { + HStack(spacing: 14) { + Label(machine.state == .running ? "Running" : debugger.loaded ? "Paused" : "No machine", + systemImage: machine.state == .running ? "play.circle.fill" : "pause.circle") + .foregroundStyle(machine.state == .running ? Color.green : Color.secondary) + .frame(width: 100, alignment: .leading) + .accessibilityIdentifier("debugger-state") + Button(action: debugger.toggleExecution) { + Label(machine.state == .running ? "Pause" : "Continue", + systemImage: machine.state == .running ? "pause.fill" : "play.fill") + }.disabled(!debugger.commandsAvailable).accessibilityIdentifier("debugger-run") + Button(action: debugger.step) { Label("Step", systemImage: "arrow.right.to.line") } + .disabled(!debugger.canEdit || (workspace == .graphics && !graphics.readyToStep(machine: machine))) + .accessibilityIdentifier("debugger-step") + .help("Execute one instruction, then remain paused.") + Divider().frame(height: 22) + Text(machine.use6309 ? "HD6309" : "MC6809").font(.system(.body, design: .monospaced)) + Spacer() + Text("PC").foregroundStyle(.secondary) + Text("$" + DebuggerModel.hex(debugger.programCounter)) + .font(.system(.body, design: .monospaced)).textSelection(.enabled) + .accessibilityIdentifier("debugger-pc") + TextField("New PC", text: $debugger.pcText).frame(width: 80) + .font(.system(.body, design: .monospaced)).textFieldStyle(.roundedBorder) + .onSubmit { debugger.setPC() }.disabled(!debugger.canEdit) + .accessibilityLabel("New program counter in hexadecimal") + .accessibilityIdentifier("debugger-pc-entry") + Button("Set PC", action: debugger.setPC).disabled(!debugger.canEdit) + .accessibilityIdentifier("debugger-set-pc") + .help("Change the next instruction address without resetting the machine.") + }.padding(.horizontal, 16).padding(.vertical, 9) + } + + private var disassemblyNavigation: some View { + HStack(spacing: 6) { + TextField("Address", text: $debugger.addressText).frame(width: 80) + .font(.system(.body, design: .monospaced)).textFieldStyle(.roundedBorder) + .onSubmit { debugger.goToAddress() } + .accessibilityLabel("Disassembly address in hexadecimal") + .accessibilityIdentifier("debugger-address") + Button("Go", action: debugger.goToAddress).accessibilityIdentifier("debugger-go") + Toggle("Follow PC", isOn: $debugger.followPC).toggleStyle(.checkbox) + .accessibilityIdentifier("debugger-follow-pc") + } + } + + private var disassembly: some View { + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 10) { + Text("").frame(width: 22) + Text("Address").frame(width: 65, alignment: .leading) + Text("Bytes").frame(width: 132, alignment: .leading) + Text("Instruction").frame(maxWidth: .infinity, alignment: .leading) + }.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 12).padding(.vertical, 5) + ScrollView { + LazyVStack(alignment: .leading, spacing: 0) { + if let snapshot = debugger.snapshot { + ForEach(Array(snapshot.instructions.enumerated()), id: \.offset) { _, instruction in + instructionRow(instruction) + } + } + } + }.accessibilityIdentifier("debugger-disassembly") + }.background(Color(nsColor: .textBackgroundColor)) + } + + private func instructionRow(_ instruction: VCCDebugInstruction) -> some View { + let isPC = instruction.address == debugger.programCounter + let breakpoint = debugger.allBreakpoints.contains(instruction.address) + let enabled = debugger.breakpoints.contains(instruction.address) + return HStack(spacing: 10) { + Button { debugger.toggleBreakpoint(at: instruction.address) } label: { + Image(systemName: enabled ? "circle.fill" : breakpoint ? "circle.dashed" : "circle") + .foregroundStyle(enabled ? Color.red : Color.secondary.opacity(0.6)) + .frame(width: 22, height: 24).contentShape(Rectangle()) + }.buttonStyle(.plain).disabled(!debugger.commandsAvailable) + .help("\(breakpoint ? "Remove" : "Add") breakpoint at \(DebuggerModel.hex(instruction.address))").accessibilityLabel("\(breakpoint ? "Remove" : "Add") breakpoint at \(DebuggerModel.hex(instruction.address))") + .accessibilityIdentifier("debugger-breakpoint-\(DebuggerModel.hex(instruction.address))") + Text(DebuggerModel.hex(instruction.address)).frame(width: 65, alignment: .leading) + Text(instruction.bytes.map { String(format: "%02X", $0) }.joined(separator: " ")) + .foregroundStyle(.secondary).frame(width: 132, alignment: .leading) + Text(instruction.mnemonic).fontWeight(isPC ? .semibold : .regular) + .frame(width: 62, alignment: .leading) + Text(instruction.operand).frame(maxWidth: .infinity, alignment: .leading) + if isPC { Image(systemName: "arrow.left").foregroundStyle(Color.accentColor).accessibilityLabel("Current instruction") } + } + .font(.system(size: 12, design: .monospaced)).padding(.horizontal, 12) + .background(isPC ? Color.accentColor.opacity(0.12) : Color.clear) + .contentShape(Rectangle()) + .contextMenu { + Button(breakpoint ? "Remove Breakpoint" : "Add Breakpoint") { debugger.toggleBreakpoint(at: instruction.address) } + .disabled(!debugger.commandsAvailable) + if breakpoint { + Button(enabled ? "Disable Breakpoint" : "Enable Breakpoint") { debugger.setBreakpoint(instruction.address, enabled: !enabled) } + .disabled(!debugger.commandsAvailable) + } + Button("Show in Memory") { debugger.showMemory(at: instruction.address) } + Button("Set PC Here") { debugger.setPC(to: instruction.address) }.disabled(!debugger.canEdit) + Button("Copy Instruction") { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString("\(DebuggerModel.hex(instruction.address)) \(instruction.mnemonic) \(instruction.operand)", forType: .string) + } + } + } + + private var memoryInspector: some View { + VStack(spacing: 0) { + HStack { + Picker("Memory inspector", selection: $debugger.memoryPane) { + ForEach(DebuggerModel.MemoryPane.allCases, id: \.self) { Text($0.rawValue).tag($0) } + }.pickerStyle(.segmented).labelsHidden().frame(width: 180) + .accessibilityIdentifier("debugger-memory-pane") + Spacer() + if debugger.memoryPane == .memory { + Button { + graphics.inspectAddress(debugger.highlightedByte ?? debugger.displayedMemoryAddress, physical: debugger.physical) + workspace = .graphics + } label: { Label("Preview as Graphics", systemImage: "rectangle.on.rectangle") } + .accessibilityIdentifier("debugger-preview-memory") + } + if debugger.installedRAM > 0 { + Text("\(debugger.installedRAM / 1024) KB installed").font(.caption).foregroundStyle(.secondary) + } + }.padding(.horizontal, 12).padding(.vertical, 6) + Divider() + if debugger.memoryPane == .memory { memory } else { mmu } + } + } + + private var memory: some View { + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 8) { + Picker("Address space", selection: Binding(get: { debugger.memorySpace }, set: debugger.setMemorySpace)) { + ForEach(DebuggerModel.MemorySpace.allCases, id: \.self) { Text($0.rawValue).tag($0) } + }.labelsHidden().frame(width: 150).accessibilityIdentifier("debugger-memory-space") + .help("Mapped CPU follows the current MMU and ROM overlays. Physical RAM shows installed RAM directly.") + Spacer() + Button { debugger.pageMemory(forward: false) } label: { Image(systemName: "chevron.left") } + .disabled(!debugger.canPreviousMemory).help("Show the previous block of memory").accessibilityLabel("Previous memory block") + .accessibilityIdentifier("debugger-memory-previous") + Button { debugger.pageMemory(forward: true) } label: { Image(systemName: "chevron.right") } + .disabled(!debugger.canNextMemory).help("Show the next block of memory").accessibilityLabel("Next memory block") + .accessibilityIdentifier("debugger-memory-next") + TextField("Address", text: Binding(get: { + debugger.physical ? debugger.physicalAddressText : debugger.memoryAddressText + }, set: { + if debugger.physical { debugger.physicalAddressText = $0 } else { debugger.memoryAddressText = $0 } + })).frame(width: 86) + .font(.system(.body, design: .monospaced)).textFieldStyle(.roundedBorder) + .onSubmit { debugger.goToMemory() } + .accessibilityLabel(debugger.physical ? "Physical RAM address in hexadecimal" : "Memory address in hexadecimal") + .accessibilityIdentifier("debugger-memory-address") + Button("Go", action: debugger.goToMemory).accessibilityIdentifier("debugger-memory-go") + }.padding(12) + Divider() + ScrollView([.vertical, .horizontal]) { + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 3) { + Text("Address").frame(width: 58, alignment: .leading) + ForEach(0..<16) { Text(String(format: "%02X", $0)).frame(width: 24) } + Text("ASCII").frame(width: 128, alignment: .leading) + }.foregroundStyle(.secondary).padding(.bottom, 4) + ForEach(0..<((debugger.memory.count + 15) / 16), id: \.self) { row in + memoryRow(row) + } + }.font(.system(size: 11, design: .monospaced)).padding(12) + }.accessibilityIdentifier("debugger-memory") + Divider() + if debugger.physical { + Text("Physical RAM is read-only here. ROM overlays and I/O are excluded; the bytes may differ from the CPU's view.") + .font(.caption).foregroundStyle(.secondary).padding(10) + .accessibilityIdentifier("debugger-physical-read-only") + } else { + HStack(spacing: 8) { + Text("Edit RAM").font(.caption).foregroundStyle(.secondary) + TextField("Address", text: $debugger.editAddressText).frame(width: 75) + .accessibilityLabel("RAM edit address in hexadecimal").accessibilityIdentifier("debugger-edit-address") + TextField("Byte", text: $debugger.editByteText).frame(width: 48) + .accessibilityLabel("RAM byte in hexadecimal").accessibilityIdentifier("debugger-edit-byte") + .onSubmit { debugger.writeByte() } + Button(action: debugger.writeByte) { Label("Write", systemImage: "pencil") }.accessibilityIdentifier("debugger-write-memory") + Spacer() + Text("I/O: — · RAM edits require Pause").font(.caption).foregroundStyle(.secondary) + }.textFieldStyle(.roundedBorder).disabled(!debugger.canEditMemory).padding(10) + } + }.background(Color(nsColor: .textBackgroundColor)) + } + + private var mmu: some View { + ScrollView { + if let state = debugger.snapshot?.mmu { + VStack(alignment: .leading, spacing: 10) { + HStack { + Label(state.enabled ? "MMU enabled" : "MMU disabled", systemImage: "memorychip") + .font(.headline).accessibilityIdentifier("debugger-mmu-enabled") + Spacer() + Text("Task \(state.activeTask) selected").font(.caption) + .accessibilityIdentifier("debugger-mmu-task") + DebuggerHelpButton(title: "MMU mapping", text: "Each row maps an 8 KB CPU window. Task columns show programmed banks. Effective read shows the current selection, including fixed banks while MMU is disabled. RAM backing buttons inspect physical bytes, including RAM hidden by ROM overlays.") + } + Text("All-RAM: \(state.allRAM ? "on" : "off") · ROM map: \(state.romMap) · Bank prefix: $\(DebuggerModel.hex(state.prefix, width: 3))") + .font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary) + .help("The prefix supplies high bits for future bank-register writes; changing it does not rewrite existing bank selections.") + VStack(spacing: 0) { + HStack(spacing: 10) { + Text("CPU range").frame(width: 88, alignment: .leading) + Text("Task 0").frame(width: 58, alignment: .leading) + .fontWeight(state.enabled && state.activeTask == 0 ? .bold : .regular) + Text("Task 1").frame(width: 58, alignment: .leading) + .fontWeight(state.enabled && state.activeTask == 1 ? .bold : .regular) + Text("Effective read").frame(width: 175, alignment: .leading) + Text("RAM backing").frame(width: 90, alignment: .leading) + }.font(.caption).foregroundStyle(.secondary).padding(.bottom, 5) + ForEach(Array(state.effective.enumerated()), id: \.offset) { index, mapping in + mmuRow(index, mapping: mapping, state: state) + } + } + Divider() + Text(state.ramVectors + ? "FE00–FEFF: fixed RAM at $\(DebuggerModel.hex(state.vectorRAMAddress, width: 6)) (RAM vectors on)." + : "FE00–FEFF follows the final bank's mapping (RAM vectors off).") + .accessibilityIdentifier("debugger-mmu-vectors") + Text("FF00–FFEF: device I/O. FFF0–FFFF: system ROM vectors at $7FF0–$7FFF.") + Text("Disassembly and breakpoints continue to use logical CPU addresses.") + .foregroundStyle(.secondary) + }.font(.caption).padding(12).frame(minWidth: 540, maxWidth: .infinity, alignment: .leading) + } + }.background(Color(nsColor: .textBackgroundColor)) + } + + private func mmuRow(_ index: Int, mapping: VCCMemoryMapping, state: VCCMMUSnapshot) -> some View { + let start = index * 8192 + let source = mapping.source == 0 ? "RAM" : mapping.source == 1 ? "System ROM" : "Cartridge ROM" + let offset = mapping.source == 0 ? "" : " $" + DebuggerModel.hex(mapping.sourceAddress) + return HStack(spacing: 10) { + Text("\(DebuggerModel.hex(start))–\(DebuggerModel.hex(start + 8191))") + .frame(width: 88, alignment: .leading) + Text(state.task0.count > index ? DebuggerModel.hex(state.task0[index].uint16Value, width: 3) : "—") + .frame(width: 58, alignment: .leading) + .foregroundStyle(state.enabled && state.activeTask == 0 ? Color.accentColor : Color.secondary) + Text(state.task1.count > index ? DebuggerModel.hex(state.task1[index].uint16Value, width: 3) : "—") + .frame(width: 58, alignment: .leading) + .foregroundStyle(state.enabled && state.activeTask == 1 ? Color.accentColor : Color.secondary) + Text("[\(DebuggerModel.hex(mapping.page, width: 3))] \(source)\(offset)") + .frame(width: 175, alignment: .leading).fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier("debugger-mmu-source-\(index)") + Button("$" + DebuggerModel.hex(mapping.ramAddress, width: 6)) { debugger.showPhysicalMemory(at: mapping.ramAddress) } + .buttonStyle(.link).frame(width: 90, alignment: .leading) + .accessibilityLabel("Inspect RAM backing for CPU \(DebuggerModel.hex(start)) at \(DebuggerModel.hex(mapping.ramAddress, width: 6))") + .accessibilityIdentifier("debugger-mmu-ram-\(index)") + }.font(.system(size: 11, design: .monospaced)).padding(.vertical, 4) + } + + private func memoryRow(_ row: Int) -> some View { + let bytes = debugger.memory + let available = debugger.memoryAvailable + let start = row * 16 + let address = debugger.memoryLocation(offset: start) + let ascii = (start.. String in + guard index < available.count, available[index] != 0 else { return "—" } + let byte = bytes[index] + return byte >= 32 && byte <= 126 ? String(UnicodeScalar(byte)) : "." + }.joined() + return HStack(spacing: 3) { + Text(DebuggerModel.hex(address, width: debugger.memoryAddressWidth)).foregroundStyle(.secondary).frame(width: 58, alignment: .leading) + ForEach(0..<16) { column in + let index = start + column + let readable = index < bytes.count && index < available.count && available[index] != 0 + let value = readable ? String(format: "%02X", bytes[index]) : "—" + let location = DebuggerModel.hex(debugger.memoryLocation(offset: index), width: debugger.memoryAddressWidth) + Group { + if debugger.physical { + // A selectable Text with a custom accessibility label can + // recurse through NSTextView's value/label bridge on macOS. + // Static bytes remain readable by VoiceOver without that + // extra text-editor accessibility node. + Text(value).foregroundStyle(.primary).frame(width: 24, height: 18) + .accessibilityLabel("Physical RAM \(location), \(value)") + } else { + Button { debugger.selectByte(offset: index) } label: { + Text(value).frame(width: 24, height: 18).contentShape(Rectangle()) + }.buttonStyle(.plain).disabled(!readable) + .accessibilityLabel("Memory \(location), \(readable ? value : "unavailable")") + } + } + .background(debugger.highlightedByte == debugger.memoryLocation(offset: index) && readable ? Color.accentColor.opacity(0.24) : Color.clear, in: RoundedRectangle(cornerRadius: 3)) + } + Text(ascii).foregroundStyle(.secondary).frame(width: 128, alignment: .leading) + } + } + + private var inspector: some View { + ScrollView { + VStack(alignment: .leading, spacing: 16) { + HStack { + Label("Registers", systemImage: "cpu").font(.headline) + Spacer() + DebuggerHelpButton(title: "Registers", text: "Changed registers are highlighted after execution. Addresses and register values are hexadecimal.") + } + Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 7) { + ForEach(registerNames, id: \.self) { name in + let value = debugger.snapshot?.registers[name]?.uint16Value ?? 0 + let changed = debugger.changedRegisters.contains(name) + GridRow { + Text(name).foregroundStyle(.secondary).frame(width: 30, alignment: .leading) + Text("$" + DebuggerModel.hex(value, width: ["A", "B", "E", "F", "DP", "CC", "MD"].contains(name) ? 2 : 4)) + .foregroundStyle(changed ? Color.accentColor : Color.primary) + .fontWeight(changed ? .semibold : .regular) + .textSelection(.enabled).accessibilityIdentifier("debugger-register-\(name)") + if changed { Image(systemName: "arrow.triangle.2.circlepath").font(.caption2).foregroundStyle(Color.accentColor).accessibilityLabel("Changed") } + } + } + }.font(.system(.body, design: .monospaced)) + flags + Divider() + breakpointInspector + }.padding(16) + }.background(Color(nsColor: .controlBackgroundColor)) + } + + private var registerNames: [String] { + machine.use6309 ? ["A", "B", "E", "F", "X", "Y", "U", "S", "V", "PC", "DP", "CC", "MD"] : ["A", "B", "X", "Y", "U", "S", "PC", "DP", "CC"] + } + + private var flags: some View { + let cc = debugger.snapshot?.registers["CC"]?.uint8Value ?? 0 + let names = ["E", "F", "H", "I", "N", "Z", "V", "C"] + let descriptions = ["Entire state saved", "FIRQ masked", "Half carry", "IRQ masked", "Negative", "Zero", "Overflow", "Carry"] + return VStack(alignment: .leading, spacing: 5) { + Text("Condition Codes").font(.caption).foregroundStyle(.secondary) + HStack(spacing: 4) { + ForEach(0..<8) { index in + let active = cc & (1 << (7 - index)) != 0 + Text(names[index]).font(.system(.caption, design: .monospaced)).fontWeight(active ? .bold : .regular) + .frame(width: 23, height: 23) + .background(active ? Color.accentColor.opacity(0.18) : Color.secondary.opacity(0.06), in: RoundedRectangle(cornerRadius: 4)) + .foregroundStyle(active ? Color.accentColor : Color.secondary) + .help(descriptions[index] + (active ? ": set" : ": clear")) + .accessibilityLabel(descriptions[index] + (active ? ", set" : ", clear")) + } + } + } + } + + private var breakpointInspector: some View { + VStack(alignment: .leading, spacing: 10) { + HStack { + Label("Breakpoints", systemImage: "circle.fill").font(.headline) + Spacer() + Text("\(debugger.allBreakpoints.count)").foregroundStyle(.secondary) + DebuggerHelpButton(title: "Breakpoints", text: "Click a circle beside an instruction, or enter an address. Execution pauses before that instruction. Uncheck to disable without removing. Breakpoints use logical CPU addresses and belong to this session.") + } + HStack { + TextField("Hex address", text: $debugger.breakpointText) + .textFieldStyle(.roundedBorder).font(.system(.body, design: .monospaced)) + .onSubmit { debugger.addBreakpoint() } + .accessibilityLabel("New breakpoint address in hexadecimal") + .accessibilityIdentifier("debugger-breakpoint-address") + Button(action: debugger.addBreakpoint) { Label("Add", systemImage: "plus") }.accessibilityIdentifier("debugger-add-breakpoint") + }.disabled(!debugger.commandsAvailable) + if debugger.allBreakpoints.isEmpty { + Text("Click a circle beside an instruction, or enter an address. Execution pauses before that instruction.") + .font(.caption).foregroundStyle(.secondary) + } + ForEach(debugger.allBreakpoints, id: \.self) { address in + let action = "\(debugger.breakpoints.contains(address) ? "Disable" : "Enable") breakpoint at \(DebuggerModel.hex(address))" + HStack { + Toggle("Enabled", isOn: Binding(get: { debugger.breakpoints.contains(address) }, set: { debugger.setBreakpoint(address, enabled: $0) })) + .toggleStyle(.checkbox).labelsHidden().disabled(!debugger.commandsAvailable) + .help(action).accessibilityLabel(action) + .accessibilityIdentifier("debugger-breakpoint-enabled-\(DebuggerModel.hex(address))") + Button("$" + DebuggerModel.hex(address)) { + debugger.showDisassembly(at: address) + }.buttonStyle(.plain).font(.system(.body, design: .monospaced)) + Spacer() + Button { debugger.toggleBreakpoint(at: address) } label: { Image(systemName: "minus.circle") } + .buttonStyle(.plain).disabled(!debugger.commandsAvailable) + .help("Remove breakpoint at \(DebuggerModel.hex(address))").accessibilityLabel("Remove breakpoint at \(DebuggerModel.hex(address))") + } + } + if !debugger.allBreakpoints.isEmpty { + Button(action: debugger.removeAllBreakpoints) { Label("Remove All", systemImage: "minus.circle") }.disabled(!debugger.commandsAvailable) + } + } + } + + private var statusBar: some View { + HStack(alignment: .firstTextBaseline, spacing: 12) { + if let error = debugger.validationMessage ?? machine.error { + Image(systemName: "exclamationmark.triangle").foregroundStyle(.orange) + Text(error).foregroundStyle(.primary).textSelection(.enabled) + .accessibilityIdentifier("debugger-error") + } else { + Text(debugger.snapshot?.stopReason.isEmpty == false ? debugger.snapshot!.stopReason : "Inspection preserves the running machine. Pause to step or edit RAM.") + .foregroundStyle(.secondary).accessibilityIdentifier("debugger-status") + } + Spacer(minLength: 12) + if let snapshot = debugger.snapshot { + Text("\(snapshot.machine.cycles.formatted()) cycles").monospacedDigit().foregroundStyle(.secondary) + } + }.font(.caption).padding(.horizontal, 14).padding(.vertical, 10) + } +} + +// A native, keyboard-accessible help popover keeps panel toolbars compact. +// Its local presentation state is independent of live machine snapshots. +struct DebuggerHelpButton: View { + let title: String + let text: String + @State private var presented = false + var body: some View { + Button { presented.toggle() } label: { + Image(systemName: "questionmark.circle").frame(width: 22, height: 22) + }.buttonStyle(.plain).foregroundStyle(.secondary) + .accessibilityLabel(title + " help").help(title + " help") + .popover(isPresented: $presented) { + VStack(alignment: .leading, spacing: 8) { + Text(title).font(.headline) + Text(text).fixedSize(horizontal: false, vertical: true) + }.padding(18).frame(width: 340) + } + } +} diff --git a/platforms/macos/App/DevelopmentStarterSource.swift b/platforms/macos/App/DevelopmentStarterSource.swift new file mode 100644 index 0000000..7dfa73d --- /dev/null +++ b/platforms/macos/App/DevelopmentStarterSource.swift @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// Load the editable lesson from the same source shipped in the example tree. +final class DevelopmentStarterSource { + static func planet(withExtension ext: String) -> String? { + for bundle in [Bundle.main, Bundle(for: DevelopmentStarterSource.self)] { + if let file = bundle.url(forResource: "planet", withExtension: ext), + let source = try? String(contentsOf: file, encoding: .utf8) { + return source + } + } + return nil + } +} diff --git a/platforms/macos/App/DiskAssignments.swift b/platforms/macos/App/DiskAssignments.swift new file mode 100644 index 0000000..d327e43 --- /dev/null +++ b/platforms/macos/App/DiskAssignments.swift @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +// File references only. Guest writes and ROM contents never enter preferences. +struct DiskAssignments: Codable, Equatable, Sendable { + struct Drive: Codable, Equatable, Sendable { + var url: URL + var writeProtected: Bool + var temporary: Bool = false + init(url: URL, writeProtected: Bool, temporary: Bool = false) { + self.url = url; self.writeProtected = writeProtected; self.temporary = temporary + } + private enum CodingKeys: String, CodingKey { case url, writeProtected, temporary } + init(from decoder: Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + url = try values.decode(URL.self, forKey: .url) + writeProtected = try values.decode(Bool.self, forKey: .writeProtected) + temporary = try values.decodeIfPresent(Bool.self, forKey: .temporary) ?? false + } + } + var hardDisks: HardDiskAssignments? + var cartridges: CartridgeAssignments? + var version = 1 + var rom: URL? + var drives: [Drive?] = Array(repeating: nil, count: 4) + + func validate() throws { + try cartridges?.validate() + try hardDisks?.validate() + guard version == 1, drives.count == 4, + rom != nil || drives.allSatisfy({ $0 == nil }), + ([rom] + drives.map { $0?.url }).compactMap({ $0 }).allSatisfy({ + $0.isFileURL && $0.host.map { $0.isEmpty || $0 == "localhost" } != false && $0.path.hasPrefix("/") + }) else { throw DiskAssignmentStore.Failure.invalid } + } +} + +struct DiskAssignmentStore: Sendable { + let url: URL + static var standard: Self { + Self(url: AppIdentity.supportDirectory + .appendingPathComponent("DiskAssignments.json")) + } + enum Failure: LocalizedError { + case invalid + var errorDescription: String? { "The remembered disk settings are damaged or use an unsupported version. Select the disk files again." } + } + func load() throws -> DiskAssignments { + let file: FileHandle + do { file = try FileHandle(forReadingFrom: url) } + catch let error as CocoaError where error.code == .fileReadNoSuchFile || error.code == .fileNoSuchFile { + return DiskAssignments() + } + defer { try? file.close() } + let bytes = try file.read(upToCount: 65537) ?? Data() + guard bytes.count <= 65536 else { throw Failure.invalid } + let value = try JSONDecoder().decode(DiskAssignments.self, from: bytes) + try value.validate() + return value + } + func save(_ value: DiskAssignments) throws { + try value.validate() + let bytes = try JSONEncoder().encode(value) + guard bytes.count <= 65536 else { throw Failure.invalid } + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try bytes.write(to: url, options: .atomic) + } +} + +// Stored in the same atomic preferences file as the disk setup. Slot zero is +// the single-cartridge configuration; slots 1...4 survive switching modes. +struct CartridgeAssignments: Codable, Equatable, Sendable { + enum Kind: Int, Codable, Sendable { case empty = 0, rom = 1, floppy = 2, hardDisk = 3, ramDisk = 4, orchestra90 = 5, speechSound = 6, sdc = 7 } + struct Slot: Codable, Equatable, Sendable { + var kind: Kind = .empty + var url: URL? + var speechROMURL: URL? // SSC speech chip; url holds its PIC firmware. + var sdcFolderURL: URL? // Local folder representing the SD card; never copied into a profile. + var sdcReadOnly: Bool? // Older profiles default to protected storage. + } + var multiPak = false + var mpiConfigured = false + var physicalSlot = 4 + var slots = Array(repeating: Slot(), count: 5) + private static func localReference(_ url: URL?) -> Bool { + guard let url else { return true } + guard url.isFileURL, url.path.hasPrefix("/"), url.query == nil, url.fragment == nil else { return false } + return url.host == nil || url.host == "" || url.host == "localhost" + } + private static func validSlot(_ slot: Slot) -> Bool { + if slot.kind == .sdc { + guard slot.speechROMURL == nil else { return false } + return localReference(slot.url) && localReference(slot.sdcFolderURL) + } + guard slot.sdcFolderURL == nil, slot.sdcReadOnly == nil else { return false } + if slot.kind == .speechSound { return localReference(slot.url) && localReference(slot.speechROMURL) } + guard slot.speechROMURL == nil else { return false } + if slot.kind == .orchestra90 { return localReference(slot.url) } + if slot.kind == .rom { return slot.url != nil && localReference(slot.url) } + return slot.url == nil + } + func validate() throws { + guard slots.count == 5, (1...4).contains(physicalSlot), slots.allSatisfy(Self.validSlot) else { + throw DiskAssignmentStore.Failure.invalid + } + for kind: Kind in [.floppy, .hardDisk, .ramDisk, .orchestra90, .speechSound, .sdc] { + guard slots.dropFirst().filter({ $0.kind == kind }).count <= 1 else { + throw DiskAssignmentStore.Failure.invalid + } + } + } +} + +struct HardDiskAssignments: Codable, Equatable, Sendable { + var drives: [DiskAssignments.Drive?] = Array(repeating: nil, count: 2) + var clockEnabled = true + var clockReadOnly = true + func validate() throws { + guard drives.count == 2 else { throw DiskAssignmentStore.Failure.invalid } + for entry in drives { + guard let drive = entry else { continue } + let url: URL = drive.url + guard url.isFileURL, url.path.hasPrefix("/") else { + throw DiskAssignmentStore.Failure.invalid + } + if let host = url.host, !host.isEmpty, host != "localhost" { + throw DiskAssignmentStore.Failure.invalid + } + } + } +} diff --git a/platforms/macos/App/DiskControlsView.swift b/platforms/macos/App/DiskControlsView.swift new file mode 100644 index 0000000..b3cc89d --- /dev/null +++ b/platforms/macos/App/DiskControlsView.swift @@ -0,0 +1,255 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import Combine + +struct DiskControlsView: View { + @ObservedObject var machine: MachineModel + @Environment(\.openWindow) private var openWindow + @State private var controllerExpanded = false + private let refresh = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect() + + var body: some View { + VStack(spacing: 0) { + HStack { + SecondaryHeader(title: "Floppy Disks", badge: "floppy") + SecondaryAction(title: "Open Disk Image…", systemImage: "folder") { DiskImageEditorCoordinator.shared.open(machine: machine) } + .accessibilityIdentifier("disk-editor-open-image") + }.padding(20) + Divider() + ScrollView { + VStack(alignment: .leading, spacing: 14) { + connection + if machine.diskEnabled { + ForEach(Array(machine.disks.enumerated()), id: \.offset) { index, disk in + DiskDriveRow(machine: machine, index: index, disk: disk) + } + } + if !machine.diskRestoreErrors.isEmpty { + ForEach(machine.diskRestoreErrors.keys.sorted(), id: \.self) { key in + Text(machine.diskRestoreErrors[key] ?? "").foregroundStyle(.red).textSelection(.enabled) + } + SecondaryAction(title: "Retry Remembered Disks", systemImage: "arrow.clockwise", action: machine.retryRememberedDisks) + Text("Reconnect the files and retry, or choose replacements. Eject forgets an unavailable drive assignment.") + .font(.caption).foregroundStyle(.secondary) + } + DisclosureGroup(isExpanded: $controllerExpanded) { + controllerDetails.padding(.top, 12) + } label: { + Label("Controller Details", systemImage: "slider.horizontal.3").font(.callout).fontWeight(.medium) + }.accessibilityIdentifier("floppy-controller-details") + SecondaryHelp(title: "About floppy disks") { + Text("The FD-502 opens DSK, JVC, OS-9, DMK and VDK images. Save As preserves the mounted format.") + Text("Writable disks save automatically. Temporary changes stay in memory until Save As. Drive assignments are remembered.") + Text("A new blank disk must be formatted by the CoCo. For a 35-track disk in FD0, type DSKINI0 in BASIC. Then choose Save As to create its Mac file and enable automatic saving.") + Text("Changing media or save mode pauses emulation. Automatic saves keep emulation running.") + } + if let error = machine.diskSettingsError { + Label(error, systemImage: "exclamationmark.circle").foregroundStyle(.red).textSelection(.enabled) + if machine.diskSettingsNeedsSave { SecondaryAction(title: "Retry Saving", systemImage: "arrow.clockwise", action: machine.saveDiskAssignments) } + } + if let error = machine.fileError ?? machine.error { Text(error).foregroundStyle(.red).textSelection(.enabled) } + }.padding(20) + } + Divider() + MediaExecutionFooter(machine: machine, note: "Media changes pause the CoCo; press Run to continue.").padding(20) + }.frame(minWidth: 700, minHeight: 420) + .disabled(machine.busy || machine.diskSaving || machine.diskEditorLocked || machine.state == .closed) + .onReceive(refresh) { _ in machine.poll() } + } + + @ViewBuilder private var connection: some View { + if !machine.diskEnabled { + SecondaryCard { + VStack(alignment: .leading, spacing: 10) { + Label("Choose a disk ROM to enable the FD-502 controller", systemImage: "info.circle") + SecondaryAction(title: "Choose Disk ROM…", systemImage: "folder", action: machine.openDiskROM).disabled(machine.diskBusy) + } + } + } else if !machine.diskConnected { + Label("Controller disconnected · Mounted disks are retained", systemImage: "exclamationmark.circle") + .font(.callout).foregroundStyle(.orange) + SecondaryAction(title: "Configure Cartridges…", systemImage: "slider.horizontal.3") { openWindow(id: "cartridges") } + } else { + HStack { + Label("FD-502 connected", systemImage: "cable.connector") + Spacer() + Text(machine.diskSaving ? "Saving automatically…" : "Writable disks save automatically") + }.font(.caption).foregroundStyle(.secondary).frame(minHeight: 18) + } + } + private var controllerDetails: some View { + VStack(alignment: .leading, spacing: 12) { + HStack { + VStack(alignment: .leading, spacing: 3) { + Text("Disk ROM").fontWeight(.medium) + Text(machine.diskEnabled ? machine.diskROMName : "Not selected").lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary) + } + Spacer() + SecondaryAction(title: machine.diskEnabled ? "Change Disk ROM…" : "Choose Disk ROM…", systemImage: "folder", action: machine.openDiskROM) + .disabled(machine.diskBusy) + } + if machine.diskEnabled { + HStack { + Text(machine.diskBusy ? "Disk operation in progress" : "Controller ready") + Text(machine.diskMotor ? "Motor on" : "Motor off") + Spacer() + if machine.diskSelectedDrive >= 0 { + Text("FD\(machine.diskSelectedDrive) · Track \(machine.diskTrack) · Sector \(machine.diskSector)") + .monospacedDigit() + } + }.font(.caption).foregroundStyle(.secondary) + SecondaryAction(title: "Disable Controller…", systemImage: "minus.circle", action: machine.disableDisks) + .disabled(machine.dirtyDisks || machine.diskBusy) + .accessibilityLabel("Disable floppy controller") + Text("Disabling ejects all four disks and cold-restarts the CoCo. Save or discard pending changes first.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } else if !machine.diskRestoreErrors.isEmpty { + SecondaryAction(title: "Forget Remembered Setup…", systemImage: "minus.circle", action: machine.forgetUnavailableDisks) + } + }.font(.callout) + } +} + +private struct DiskDriveRow: View { + @ObservedObject var machine: MachineModel + let index: Int + let disk: VCCDiskSnapshot + @State private var options = false + private struct CopySource: Identifiable { + let id = UUID() + let name: String + let epoch: UInt64 + } + @State private var copySource: CopySource? + private var assigned: Bool { disk.mounted || machine.diskAssignments.drives[index] != nil } + private var manualSave: Bool { + disk.dirty && (machine.diskTemporary[index] || machine.diskAssignments.drives[index] == nil || disk.writeProtected || disk.sourceReadOnly) + } + private var mode: String { + if disk.writeProtected { return "Write protected" } + if machine.diskTemporary[index] { return "Temporary changes" } + return machine.diskAssignments.drives[index] == nil ? "No backing file · Use Save As" : "Saves automatically" + } + var body: some View { + SecondaryCard { + VStack(alignment: .leading, spacing: 12) { + HStack(spacing: 14) { + MediaDriveIdentity(name: "FD\(index)", mounted: disk.mounted) + VStack(alignment: .leading, spacing: 4) { + Text(disk.mounted ? disk.name : machine.diskAssignments.drives[index]?.url.lastPathComponent ?? "No disk inserted") + .fontWeight(.semibold).lineLimit(1).truncationMode(.middle) + Text(disk.mounted ? "\(disk.tracks) tracks · \(disk.sides) \(disk.sides == 1 ? "side" : "sides") · \(mode)" : assigned ? "Unavailable — reconnect or replace the file" : "Insert an image or create a blank disk") + .font(.caption).foregroundStyle(assigned && !disk.mounted ? Color.orange : Color.secondary) + .fixedSize(horizontal: false, vertical: true) + }.frame(maxWidth: .infinity, alignment: .leading) + SecondaryAction(title: assigned ? "Replace…" : "Insert…", systemImage: "folder") { machine.openDisk(index) } + .disabled(disk.dirty).accessibilityLabel("Insert disk in drive \(index)") + if assigned { + if disk.mounted { + SecondaryAction(title: "Edit…", systemImage: "pencil") { DiskImageEditorCoordinator.shared.edit(index, machine: machine) } + .accessibilityIdentifier("floppy-edit-\(index)").accessibilityLabel("Edit…") + .help("Edit files inside the disk. The CoCo stays paused and locked until the editor closes.") + } + SecondaryAction(title: "Eject", systemImage: "eject") { machine.ejectDisk(index) } + .disabled(disk.dirty).accessibilityLabel("Eject disk from drive \(index)") + } else { + newDiskMenu + } + } + if disk.mounted { + HStack { + DisclosureGroup(isExpanded: $options) { EmptyView() } label: { Text("Disk options").font(.callout) } + .accessibilityIdentifier("floppy-options-\(index)") + Spacer() + actions + } + if options { + HStack(spacing: 24) { + Toggle("Write protected", isOn: Binding(get: { disk.writeProtected }, set: { machine.protectDisk(index, $0) })) + .disabled(disk.sourceReadOnly || disk.formatWriteProtected).accessibilityLabel("Write protect drive \(index)") + .help(disk.formatWriteProtected ? "Write protection is stored in the disk image header." : disk.sourceReadOnly ? "The source file is read-only. Reopen a writable copy to enable writes." : "Prevent the CoCo from changing this disk.") + Toggle("Temporary changes", isOn: Binding(get: { machine.diskTemporary[index] }, set: { machine.setDiskTemporary(index, $0) })) + .accessibilityLabel("Temporary changes in drive \(index)") + Spacer(minLength: 0) + }.font(.callout) + Text("Temporary changes stay in memory. Turning this off saves pending changes to the assigned writable file. Save As chooses a file and retains this mode.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + if manualSave { + HStack { + Label("Unsaved changes · Save As to keep them", systemImage: "exclamationmark.circle").foregroundStyle(.orange) + Spacer() + SecondaryAction(title: "Save As…", systemImage: "square.and.arrow.up") { machine.exportDisk(index) } + .accessibilityLabel("Save disk from drive \(index) as") + }.font(.callout).frame(minHeight: 24) + } + } + if let error = machine.diskSaveErrors[index] { + Text(error).font(.callout).foregroundStyle(.red).textSelection(.enabled) + SecondaryAction(title: "Retry Save", systemImage: "arrow.clockwise") { machine.retryDiskSave(index) } + .disabled(machine.diskTemporary[index] || disk.writeProtected).accessibilityLabel("Retry saving drive \(index)") + } + } + }.modifier(MediaDropTarget(machine: machine, destination: .floppy(index))) + .sheet(item: $copySource) { source in + VCCDriveWireTransferView(machine: machine, drive: index, sourceName: source.name, sourceEpoch: source.epoch) + } + .disabled(machine.diskBusy) + } + private var newDiskMenu: some View { + Menu { + Button("Standard DSK") { machine.createDisk(index) } + Button("DMK Track Image") { machine.createDisk(index, format: .trackDMK) } + Button("VDK Disk Image") { machine.createDisk(index, format: .sectorVDK) } + } label: { + Label("New Disk", systemImage: "doc.badge.plus") + } + .fixedSize().disabled(disk.dirty).accessibilityLabel("New disk in drive \(index)") + .accessibilityIdentifier("floppy-new-\(index)") + } + private var actions: some View { + Menu { + Button { machine.exportDisk(index) } label: { Label("Save As…", systemImage: "square.and.arrow.up") } + .disabled(!disk.mounted).accessibilityLabel("Save disk from drive \(index) as") + Button { + copySource = CopySource(name: disk.name, epoch: machine.inputEpoch) + } label: { Label("Send a Copy to DriveWire…", systemImage: "paperplane") } + .disabled(!disk.mounted || machine.busy || machine.diskSaving || machine.diskEditorLocked) + .accessibilityIdentifier("floppy-send-copy-\(index)") + .help("Send an independent copy of the current disk, including changes in memory, to a running DriveWire session.") + newDiskMenu + if manualSave || machine.diskSaveErrors[index] != nil { + Divider() + Button { machine.discardDisk(index) } label: { Label("Discard Changes and Eject…", systemImage: "eject") } + .accessibilityLabel("Discard changes in drive \(index)") + } + } label: { Label("Actions", systemImage: "ellipsis.circle") } + .fixedSize().accessibilityIdentifier("floppy-actions-\(index)") + } +} + +// Shared presentation only; drive and execution commands remain in MachineModel. +struct MediaDriveIdentity: View { + let name: String + let mounted: Bool + var body: some View { + Text(name).font(.system(.body, design: .monospaced).weight(.semibold)) + .frame(width: 42, height: 42) + .background(mounted ? Color.accentColor.opacity(0.12) : Color.secondary.opacity(0.10), in: RoundedRectangle(cornerRadius: 7)) + } +} + +struct MediaExecutionFooter: View { + @ObservedObject var machine: MachineModel + let note: String + var body: some View { + HStack(spacing: 12) { + SecondaryAction(title: machine.state == .running ? "Pause" : "Run", systemImage: machine.state == .running ? "pause.fill" : "play.fill") { + if machine.state == .running { machine.pause() } else { machine.resume() } + }.disabled(machine.diskEditorLocked || machine.state == .empty || machine.state == .closed) + Text(note).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 0) + Text(machine.executionDescription).font(.caption).foregroundStyle(.secondary) + } + } +} diff --git a/platforms/macos/App/DiskEditorFileTable.swift b/platforms/macos/App/DiskEditorFileTable.swift new file mode 100644 index 0000000..c957575 --- /dev/null +++ b/platforms/macos/App/DiskEditorFileTable.swift @@ -0,0 +1,324 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import SwiftUI +import UniformTypeIdentifiers + +private let diskEditorMoveType = NSPasteboard.PasteboardType("com.brianholman.vccplus.disk-editor-files") + +/// Bounded diagnostics live only in the isolated UI-test app's own fixture folder. +enum DiskEditorPromiseDiagnostics { + #if VCC_UI_TESTING + private static let lock = NSLock() + #endif + static func record(_ phase: String) { + #if VCC_UI_TESTING + lock.lock(); defer { lock.unlock() } + guard let path = ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_PROMISE_TRACE"] else { return } + let url = URL(fileURLWithPath: path) + let line = Data((phase + "\n").utf8) + if !FileManager.default.fileExists(atPath: path) { _ = FileManager.default.createFile(atPath: path, contents: nil) } + guard let handle = try? FileHandle(forWritingTo: url) else { return } + defer { try? handle.close() } + guard let end = try? handle.seekToEnd(), end < 16_384 else { return } + try? handle.write(contentsOf: line) + #endif + } +} + +#if VCC_UI_TESTING +/// Observe actual mouse delivery without changing native drag eligibility. +private final class DiskEditorNativeTableView: NSTableView { + var dragTrace: ((String) -> Void)? + override func mouseDown(with event: NSEvent) { + dragTrace?("mouse-down row=\(row(at: convert(event.locationInWindow, from: nil))) key=\(window?.isKeyWindow ?? false)") + super.mouseDown(with: event) + } + override func canDragRows(with rowIndexes: IndexSet, at mouseDownPoint: NSPoint) -> Bool { + let allowed = super.canDragRows(with: rowIndexes, at: mouseDownPoint) + dragTrace?("can-drag native=\(allowed) rows=\(rowIndexes)") + return allowed + } +} +#endif + +/// Native table supplies Finder multi-file promises and accepts ordinary host +/// file URLs. Directory navigation stays inside the validated image namespace. +struct DiskEditorFileTable: NSViewRepresentable { + @ObservedObject var model: DiskImageEditorModel + func makeCoordinator() -> Coordinator { Coordinator(model) } + func makeNSView(context: Context) -> NSScrollView { + #if VCC_UI_TESTING + let table = DiskEditorNativeTableView() + #else + let table = NSTableView() + #endif + table.identifier = NSUserInterfaceItemIdentifier("disk-editor-files") + table.setAccessibilityIdentifier("disk-editor-files"); table.allowsMultipleSelection = true + table.usesAlternatingRowBackgroundColors = true; table.rowHeight = 25 + table.delegate = context.coordinator; table.dataSource = context.coordinator + table.target = context.coordinator; table.doubleAction = #selector(Coordinator.activate) + let coordinator = context.coordinator + #if VCC_UI_TESTING + table.dragTrace = { [weak coordinator] in coordinator?.trace($0) } + #endif + table.registerForDraggedTypes([diskEditorMoveType, .fileURL]); table.setDraggingSourceOperationMask(.copy, forLocal: false) + table.setDraggingSourceOperationMask(model.os9 ? .move : .copy, forLocal: true) + let menu = NSMenu(); menu.delegate = context.coordinator; menu.autoenablesItems = false; table.menu = menu + context.coordinator.table = table; context.coordinator.configureColumns() + let scroll = NSScrollView(); scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = true; scroll.documentView = table + return scroll + } + func updateNSView(_ scroll: NSScrollView, context: Context) { + context.coordinator.model = model; context.coordinator.update() + } + @MainActor final class Coordinator: NSObject, NSTableViewDataSource, NSTableViewDelegate, NSMenuDelegate { + var model: DiskImageEditorModel + weak var table: NSTableView? + var rows: [DiskEditorEntry] = [] + var last: [DiskEditorEntry] = [] + var os9: Bool? + private var restoringSelection = false + private var dragRequest: DiskEditorMoveRequest? + #if VCC_UI_TESTING + private var dragTraceCount = 0 + private var dragTraceLines: [String] = [] + #endif + fileprivate func trace(_ message: @autoclosure () -> String) { + #if VCC_UI_TESTING + guard dragTraceCount < 250 else { return }; dragTraceCount += 1 + let line = message() + dragTraceLines.append(line) + if dragTraceLines.count > 40 { dragTraceLines.removeFirst() } + let text = "DiskEditorDrag VCC_UI_TESTING\n" + dragTraceLines.joined(separator: "\n") + table?.setAccessibilityHelp(text) + table?.setAccessibilityValue(text) + NSLog("DiskEditorDrag %@", line) + #endif + } + init(_ model: DiskImageEditorModel) { self.model = model } + func configureColumns() { + guard let table else { return } + for column in table.tableColumns { table.removeTableColumn(column) } + let definitions: [(String, CGFloat)] = model.os9 + ? [("Name", 250), ("Size", 95), ("Type", 120), ("Attributes", 110), ("Owner", 80), ("Modified", 150)] + : [("Name", 290), ("Size", 110), ("File Type", 200), ("Encoding", 120)] + for (title, width) in definitions { + let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(title)); column.title = title; column.width = width; column.minWidth = title == "Name" ? 160 : 70 + column.sortDescriptorPrototype = NSSortDescriptor(key: title, ascending: true); table.addTableColumn(column) + } + table.sortDescriptors = [NSSortDescriptor(key: "Name", ascending: true)]; os9 = model.os9 + trace("configure os9=\(model.os9) local-mask=\(model.os9 ? "move" : "copy")") + } + func update() { + table?.setDraggingSourceOperationMask(model.os9 ? .move : .copy, forLocal: true) + if os9 != model.os9 { configureColumns() } + guard last != model.contents.entries else { return } + last = model.contents.entries; reload() + } + func reload() { + guard let table else { return } + restoringSelection = true + defer { restoringSelection = false } + let descriptor = table.sortDescriptors.first, key = descriptor?.key ?? "Name", ascending = descriptor?.ascending ?? true + rows = model.contents.entries.sorted { + let result: ComparisonResult + if key == "Size" { result = $0.size == $1.size ? .orderedSame : $0.size < $1.size ? .orderedAscending : .orderedDescending } + else if key == "Modified" { result = $0.modified == $1.modified ? .orderedSame : $0.modified < $1.modified ? .orderedAscending : .orderedDescending } + else { result = value($0, key).localizedStandardCompare(value($1, key)) } + return ascending ? result == .orderedAscending : result == .orderedDescending + } + // Reloading emits a selection notification. Preserve the selection + // before that callback can clear the model's authoritative IDs. + let selectedIDs = model.selection + table.reloadData() + let selection = IndexSet(rows.indices.filter { selectedIDs.contains(rows[$0].id) }) + table.selectRowIndexes(selection, byExtendingSelection: false) + } + func numberOfRows(in tableView: NSTableView) -> Int { rows.count } + func value(_ entry: DiskEditorEntry, _ key: String) -> String { + switch key { + case "Name": return entry.name + case "Size": return entry.directory ? "—" : ByteCountFormatter.string(fromByteCount: entry.size, countStyle: .file) + case "Type", "File Type": return entry.type + case "Encoding": return entry.encoding + case "Attributes": return entry.attributes + case "Owner": return "\(entry.group).\(entry.owner)" + case "Modified": return entry.modified > 0 ? Date(timeIntervalSince1970: entry.modified).formatted(date: .abbreviated, time: .shortened) : "—" + default: return "" + } + } + func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { + guard rows.indices.contains(row), let column = tableColumn else { return nil } + let entry = rows[row], text = value(entry, column.identifier.rawValue) + let cell = NSTableCellView(); let label = NSTextField(labelWithString: text) + label.lineBreakMode = .byTruncatingMiddle; label.translatesAutoresizingMaskIntoConstraints = false + label.font = column.identifier.rawValue == "Size" ? .monospacedDigitSystemFont(ofSize: 13, weight: .regular) : .systemFont(ofSize: 13) + if column.identifier.rawValue == "Size" { label.alignment = .right } + cell.textField = label; cell.addSubview(label) + if column.identifier.rawValue == "Name" { + let icon = NSImageView(image: NSImage(systemSymbolName: entry.directory ? "folder" : "doc", accessibilityDescription: nil) ?? NSImage()) + icon.translatesAutoresizingMaskIntoConstraints = false; cell.addSubview(icon) + NSLayoutConstraint.activate([icon.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 5), icon.widthAnchor.constraint(equalToConstant: 17), icon.centerYAnchor.constraint(equalTo: cell.centerYAnchor), label.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 6)]) + } else { label.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 5).isActive = true } + NSLayoutConstraint.activate([label.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: -7), label.centerYAnchor.constraint(equalTo: cell.centerYAnchor)]) + return cell + } + func tableViewSelectionDidChange(_ notification: Notification) { + guard !restoringSelection, let table else { return } + let selected = Set(table.selectedRowIndexes.compactMap { rows.indices.contains($0) ? rows[$0].id : nil }) + if model.selection != selected { model.selection = selected } + } + func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { reload() } + @objc func activate() { + guard !model.busy, let table, rows.indices.contains(table.clickedRow) else { return } + model.activate([rows[table.clickedRow].id]) + } + func menuNeedsUpdate(_ menu: NSMenu) { + if let table, rows.indices.contains(table.clickedRow), !table.selectedRowIndexes.contains(table.clickedRow) { + table.selectRowIndexes(IndexSet(integer: table.clickedRow), byExtendingSelection: false) + } + menu.removeAllItems() + let move = NSMenuItem(title: "Move To…", action: #selector(moveSelected), keyEquivalent: "") + move.target = self; move.isEnabled = model.canMove; menu.addItem(move) + } + @objc private func moveSelected() { model.moveTo() } + func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? { + trace("writer row=\(row) busy=\(model.busy) os9=\(model.os9) selected=\(tableView.selectedRowIndexes)") + guard !model.busy, rows.indices.contains(row), !rows[row].directory else { return nil } + if !(dragRequest.map { model.moveSourceIsCurrent($0) } ?? false) { + let indexes = tableView.selectedRowIndexes.contains(row) ? tableView.selectedRowIndexes : IndexSet(integer: row) + dragRequest = model.moveRequest(for: indexes.compactMap { rows.indices.contains($0) ? rows[$0] : nil }) + } + let payload = dragRequest.flatMap { try? JSONEncoder().encode(DiskEditorDragPayload($0)) } + trace("writer request=\(dragRequest?.id.uuidString ?? "none") files=\(dragRequest?.files.count ?? 0) payload=\(payload?.count ?? 0)") + return DiskEditorFilePromise.make(bytes: model.contents.bytes, entry: rows[row], machine: model.machine, sourceURL: model.sourceURL, movePayload: payload, volumeID: model.contents.volumeID) + } + func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forRowIndexes rowIndexes: IndexSet) { + let paths = rowIndexes.compactMap { rows.indices.contains($0) ? rows[$0].path : nil } + // The advertised payload was frozen when AppKit asked for writers, + // before it negotiates destination types. Do not add a type here. + if dragRequest?.files.map(\.path) != paths { dragRequest = nil } + trace("begin rows=\(rowIndexes) request=\(dragRequest?.id.uuidString ?? "none") types=\(session.draggingPasteboard.types?.map(\.rawValue) ?? [])") + } + func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) { + trace("ended operation=\(operation.rawValue)") + dragRequest = nil + } + private func ownedMove(_ info: NSDraggingInfo) -> DiskEditorMoveRequest? { + guard let source = info.draggingSource as? NSTableView else { trace("refuse source-not-table class=\(info.draggingSource.map { String(describing: type(of: $0)) } ?? "nil")"); return nil } + guard source === table else { trace("refuse different-table"); return nil } + guard let request = dragRequest else { trace("refuse no-request"); return nil } + guard model.moveSourceIsCurrent(request) else { trace("refuse stale-source"); return nil } + guard let data = info.draggingPasteboard.data(forType: diskEditorMoveType), data.count <= DiskEditorIO.limit else { trace("refuse missing-or-oversized-payload"); return nil } + guard let payload = try? JSONDecoder().decode(DiskEditorDragPayload.self, from: data), payload == DiskEditorDragPayload(request) else { trace("refuse mismatched-payload"); return nil } + return request + } + private func destination(in table: NSTableView, for info: NSDraggingInfo) -> (path: String, row: Int)? { + // proposedRow describes an insertion boundary, which can be the row + // after the folder under the pointer. Folder moves target the row + // actually under the pointer, then explicitly use an on-row drop. + let row = table.row(at: table.convert(info.draggingLocation, from: nil)) + if rows.indices.contains(row) { return rows[row].directory ? (rows[row].path, row) : nil } + return (model.path, -1) + } + func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation operation: NSTableView.DropOperation) -> NSDragOperation { + trace("validate proposed=\(row) operation=\(operation.rawValue) hovered=\(tableView.row(at: tableView.convert(info.draggingLocation, from: nil))) source=\(info.draggingSource.map { String(describing: type(of: $0)) } ?? "nil") types=\(info.draggingPasteboard.types?.map(\.rawValue) ?? [])") + guard !model.busy else { return [] } + if info.draggingSource is NSTableView || info.draggingPasteboard.availableType(from: [diskEditorMoveType]) != nil { + guard let request = ownedMove(info) else { return [] } + guard let target = destination(in: tableView, for: info) else { trace("refuse target-not-folder"); return [] } + guard target.path.caseInsensitiveCompare(request.sourcePath) != .orderedSame else { trace("refuse same-folder"); return [] } + trace("validate move target-row=\(target.row)") + tableView.setDropRow(target.row, dropOperation: .on) + return .move + } + tableView.setDropRow(-1, dropOperation: .on); return .copy + } + func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation operation: NSTableView.DropOperation) -> Bool { + trace("accept proposed=\(row) operation=\(operation.rawValue)") + guard !model.busy else { return false } + if info.draggingSource is NSTableView || info.draggingPasteboard.availableType(from: [diskEditorMoveType]) != nil { + guard let request = ownedMove(info), let target = destination(in: tableView, for: info), target.path.caseInsensitiveCompare(request.sourcePath) != .orderedSame else { trace("accept refused"); return false } + trace("accept move files=\(request.files.count) target-row=\(target.row)") + model.move(request, to: target.path); return true + } + guard let urls = info.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty else { return false } + model.proposeImport(urls); return true + } + } +} + +enum DiskEditorFilePromise { + @MainActor static func make(bytes: Data, entry: DiskEditorEntry, machine: any DiskEditorHost, sourceURL: URL?, movePayload: Data? = nil, volumeID: String? = nil) -> NSFilePromiseProvider { + let delegate = DiskEditorPromiseDelegate(bytes: bytes, entry: entry, machine: machine, sourceURL: sourceURL, volumeID: volumeID) + // Keep ordinary exports on the plain provider. The owned subtype uses + // only the designated initializer. Both providers have weak delegates; + // documented strong userInfo keeps the immutable snapshot alive. + let provider: NSFilePromiseProvider + if let movePayload { + let owned = DiskEditorOwnedFilePromise(payload: movePayload) + owned.fileType = UTType.data.identifier; owned.delegate = delegate; provider = owned + } else { provider = NSFilePromiseProvider(fileType: UTType.data.identifier, delegate: delegate) } + provider.userInfo = delegate + return provider + } +} +/// Advertise the owned move identity before AppKit starts type negotiation. +/// Use NSFilePromiseProvider's designated init(), never its convenience init +/// which would dispatch back to an unimplemented Swift subclass initializer. +private final class DiskEditorOwnedFilePromise: NSFilePromiseProvider { + private let payload: Data + init(payload: Data) { self.payload = payload; super.init() } + override func writableTypes(for pasteboard: NSPasteboard) -> [NSPasteboard.PasteboardType] { + super.writableTypes(for: pasteboard) + [diskEditorMoveType] + } + override func pasteboardPropertyList(forType type: NSPasteboard.PasteboardType) -> Any? { + type == diskEditorMoveType ? payload : super.pasteboardPropertyList(forType: type) + } + override func writingOptions(forType type: NSPasteboard.PasteboardType, pasteboard: NSPasteboard) -> NSPasteboard.WritingOptions { + type == diskEditorMoveType ? [] : super.writingOptions(forType: type, pasteboard: pasteboard) + } +} +/// Finder can request every selected row concurrently. Chain the complete +/// async jobs, rather than only their delegate callbacks, so the shared machine +/// guard and snapshot reader are used by one promise at a time. +private actor DiskEditorPromiseExports { + static let shared = DiskEditorPromiseExports() + private var tail: Task? + func write(snapshot: Data, entryPath: String, machine: any DiskEditorHost, source: URL?, destination: URL, volumeID: String?) async throws { + let previous = tail + let job = Task { + await previous?.value + DiskEditorPromiseDiagnostics.record("promise snapshot read begin") + let reader = try DiskImageEditorStore(data: snapshot, selectedVolumeID: volumeID) + let data = try await reader.read(entryPath) + DiskEditorPromiseDiagnostics.record("promise snapshot read complete; await machine export") + try await machine.savePromisedDiskEditorExport(data, to: destination, protecting: source) + } + tail = Task { _ = try? await job.value } + try await job.value + } +} +private final class DiskEditorPromiseDelegate: NSObject, NSFilePromiseProviderDelegate { + let bytes: Data, entry: DiskEditorEntry + let volumeID: String? + let machine: any DiskEditorHost, sourceURL: URL? + private let queue: OperationQueue = { let q = OperationQueue(); q.maxConcurrentOperationCount = 1; return q }() + init(bytes: Data, entry: DiskEditorEntry, machine: any DiskEditorHost, sourceURL: URL?, volumeID: String?) { self.bytes = bytes; self.entry = entry; self.machine = machine; self.sourceURL = sourceURL; self.volumeID = volumeID } + func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String { DiskEditorPromiseDiagnostics.record("promise filename"); return entry.name } + func operationQueue(for filePromiseProvider: NSFilePromiseProvider) -> OperationQueue { queue } + func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, writePromiseTo url: URL, completionHandler: @escaping (Error?) -> Void) { + // A Finder promise may be fulfilled after another edit or after closing + // this window. Its immutable snapshot is the version the user dragged. + DiskEditorPromiseDiagnostics.record("promise write entered") + let snapshot = bytes, entryPath = entry.path, machine = machine, source = sourceURL, selectedVolume = volumeID + Task.detached { + do { + try await DiskEditorPromiseExports.shared.write(snapshot: snapshot, entryPath: entryPath, + machine: machine, source: source, destination: url, volumeID: selectedVolume) + DiskEditorPromiseDiagnostics.record("promise export complete") + completionHandler(nil) + } catch { DiskEditorPromiseDiagnostics.record("promise export error"); completionHandler(error) } + } + } +} diff --git a/platforms/macos/App/DiskEditorSession.swift b/platforms/macos/App/DiskEditorSession.swift new file mode 100644 index 0000000..217b749 --- /dev/null +++ b/platforms/macos/App/DiskEditorSession.swift @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// An immutable copy of a mounted disk; mutations belong to the editor only. +struct DiskEditorSession: Sendable { + let id: UUID + let token: UInt64 + let drive: Int + let name: String + let data: Data + let canApply: Bool + let sourceURL: URL? + let temporary: Bool + let applyRestriction: String? + let hardDisk: Bool + + init(id: UUID, token: UInt64, drive: Int, name: String, data: Data, canApply: Bool, + sourceURL: URL?, temporary: Bool, applyRestriction: String?, hardDisk: Bool = false) { + self.id = id; self.token = token; self.drive = drive; self.name = name; self.data = data + self.canApply = canApply; self.sourceURL = sourceURL; self.temporary = temporary + self.applyRestriction = applyRestriction; self.hardDisk = hardDisk + } + var driveLabel: String { "\(hardDisk ? "HD" : "FD")\(drive)" } +} + + +/// The editor owns its working copy and native interface. Each application owns +/// media identity, guest exclusion, restart policy and the final atomic commit. +@MainActor +protocol DiskEditorHost: AnyObject { + func beginDiskEditor(inDrive drive: Int) async throws -> DiskEditorSession + func beginHardDiskEditor(inDrive drive: Int) async throws -> DiskEditorSession + func cancelDiskEditor(_ session: DiskEditorSession) async throws + func applyDiskEditor(_ session: DiskEditorSession, data: Data, restartConfirmed: Bool) async throws + func saveDiskEditorExport(_ data: Data, to url: URL, protecting sourceURL: URL?, replacing expected: Data?, requireNew: Bool) async throws + func saveDiskEditorImageCopy(_ data: Data, to url: URL, protecting sourceURL: URL?, replacing expected: Data?, requireNew: Bool) async throws + func savePromisedDiskEditorExport(_ data: Data, to url: URL, protecting sourceURL: URL?) async throws + func saveOfflineDiskEditor(_ data: Data, to url: URL, replacing original: Data) async throws + func mountedEditorDrive(for url: URL) -> Int? + func mountedHardDiskEditorDrive(for url: URL) -> Int? + func diskEditorSourceIsAssigned(_ url: URL) -> Bool + func diskEditorPresentation(for session: DiskEditorSession?) -> DiskEditorPresentation +} + +struct DiskEditorPresentation { + let context: String + let applyHint: String + let applyButtonTitle: String + let applyConfirmationTitle: String + let applyConfirmationMessage: String + let applyConfirmationAction: String + let closeNotice: String +} + +extension DiskEditorHost { + func beginHardDiskEditor(inDrive drive: Int) async throws -> DiskEditorSession { + throw DiskEditorFailure.message("Hard-disk editing is unavailable in this application.") + } + func mountedHardDiskEditorDrive(for url: URL) -> Int? { nil } + func saveDiskEditorImageCopy(_ data: Data, to url: URL, protecting sourceURL: URL?, replacing expected: Data?, requireNew: Bool) async throws { + try await saveDiskEditorExport(data, to: url, protecting: sourceURL, replacing: expected, requireNew: requireNew) + } + func diskEditorPresentation(for session: DiskEditorSession?) -> DiskEditorPresentation { + DiskEditorPresentation( + context: session.map { "\($0.driveLabel) · CoCo paused and locked" } ?? "Unmounted image · CoCo unchanged", + applyHint: session == nil ? "Edits remain in a private copy until saved." : "Applying changes requires a CoCo restart.", + applyButtonTitle: session.map { "Apply to \($0.driveLabel)…" } ?? "Save Changes…", + applyConfirmationTitle: session == nil ? "Save changes to this disk image?" : "Apply disk changes and restart the CoCo?", + applyConfirmationMessage: session == nil ? "The original image will be replaced only if its bytes have not changed outside the editor." : "Restarting clears the running guest program and its memory so it cannot reuse old filesystem information. Mounted media and edited disk bytes are retained. Save any program or recording you need before applying.", + applyConfirmationAction: session == nil ? "Save Changes" : "Restart and Apply", + closeNotice: "Apply your disk changes, save an edited copy, or close the Disk Image Editor. The machine remains paused while its disk is locked.") + } +} + +#if !VCC_COMPANION_CLIENT +extension MachineModel: DiskEditorHost { } +#endif + +/// Editor-local limits keep the shared source independent of emulator ROM and +/// cartridge helpers. The reader is the same bounded import reader as the editor. +enum DiskEditorIO { + static let limit = 16 * 1024 * 1024 + static let imageLimit = 512 * 1024 * 1024 + static let extensions = ["dsk", "jvc", "os9", "dmk", "vdk", "vhd", "img"] + + /// Run off the main actor. Both apps use this exact identity/compare/write + /// implementation; application-specific media command guards remain outside. + static func write(_ bytes: Data, to url: URL, protecting references: [URL], + allowEmpty: Bool = false, replacing expected: Data? = nil, + requireNew: Bool = false, coordinated: Bool = true, maximum: Int = limit) throws { + try validateExport(bytes, to: url, allowEmpty: allowEmpty, maximum: maximum) + if !coordinated { + try writeValidated(bytes, to: url, protecting: references, allowEmpty: allowEmpty, replacing: expected, requireNew: requireNew, maximum: maximum) + return + } + var coordinationError: NSError? + var writeError: Error? + DiskEditorPromiseDiagnostics.record("development export before coordinate") + NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &coordinationError) { target in + DiskEditorPromiseDiagnostics.record("development export inside coordinate") + do { try writeValidated(bytes, to: target, protecting: references, allowEmpty: allowEmpty, replacing: expected, requireNew: requireNew, maximum: maximum) } + catch { writeError = error } + } + if let error = coordinationError ?? writeError as NSError? { throw error } + } + private static func validateExport(_ bytes: Data, to url: URL, allowEmpty: Bool, maximum: Int) throws { + guard url.isFileURL, (allowEmpty || !bytes.isEmpty), bytes.count <= maximum else { + throw DiskEditorFailure.message("Choose a regular file within the \(maximum / (1024 * 1024)) MiB export limit.") + } + } + private static func writeValidated(_ bytes: Data, to url: URL, protecting references: [URL], + allowEmpty: Bool, replacing expected: Data?, requireNew: Bool, maximum: Int) throws { + try validateExport(bytes, to: url, allowEmpty: allowEmpty, maximum: maximum) + let path = url.standardizedFileURL.resolvingSymlinksInPath().path + let attributes = try? FileManager.default.attributesOfItem(atPath: url.path) + if let attributes, attributes[.type] as? FileAttributeType != .typeRegular { + throw DiskEditorFailure.message("Choose a regular disk image or disk ROM file.") + } + if attributes != nil, !FileManager.default.isWritableFile(atPath: url.path) { + throw DiskEditorFailure.message("The disk file is no longer writable. Restore write access and retry, or use Save As.") + } + let inode = attributes?[.systemFileNumber] as? NSNumber + let volume = attributes?[.systemNumber] as? NSNumber + for reference in references { + let resolved = reference.standardizedFileURL.resolvingSymlinksInPath() + let other = try? FileManager.default.attributesOfItem(atPath: resolved.path) + let sameIdentity = inode != nil && volume != nil && + inode == other?[.systemFileNumber] as? NSNumber && volume == other?[.systemNumber] as? NSNumber + let inside = other?[.type] as? FileAttributeType == .typeDirectory && path.hasPrefix(resolved.path + "/") + if path == resolved.path || sameIdentity || inside { + throw DiskEditorFailure.message("Choose a separate file outside your assigned media and source document. To replace a mounted disk or cassette, eject it first using its normal media controls.") + } + } + if let expected { + guard attributes != nil, try DiskImageEditorStore.hostBytes(url, maximum: maximum) == expected else { + throw DiskEditorFailure.message("This source file changed on disk. Reload it or save a separate copy.") + } + } + try bytes.write(to: url, options: requireNew ? .withoutOverwriting : .atomic) + } + struct Image: Sendable { let data: Data; let readOnly: Bool } + static func readImage(_ url: URL) throws -> Image { + guard extensions.contains(url.pathExtension.lowercased()) else { + throw DiskEditorFailure.message("Choose a DSK, JVC, OS-9, DMK, VDK, raw VHD or IMG disk image.") + } + let bytes = try DiskImageEditorStore.hostBytes(url, maximum: imageLimit) + return Image(data: bytes, readOnly: !FileManager.default.isWritableFile(atPath: url.path)) + } +} + +enum DiskEditorFailure: LocalizedError { + case message(String) + var errorDescription: String? { switch self { case .message(let text): text } } +} diff --git a/platforms/macos/App/DiskFiles.swift b/platforms/macos/App/DiskFiles.swift new file mode 100644 index 0000000..033c03d --- /dev/null +++ b/platforms/macos/App/DiskFiles.swift @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +enum DiskFiles { + static let extensions = ["dsk", "jvc", "os9", "dmk", "vdk"] + static let limit = 16 * 1024 * 1024 + struct Image: Sendable { let data: Data; let readOnly: Bool } + enum Failure: LocalizedError { + case notFile, tooLarge, extensionType, romSize, changed, readOnly, cartridgeROM, orchestraROM + var errorDescription: String? { + switch self { + case .orchestraROM: return "Choose an 8 KiB Orchestra-90 ROM. The stereo sound hardware can also be used without a ROM." + case .cartridgeROM: return "Choose a raw cartridge ROM (1 byte to 256 KiB), not a Windows DLL or a disk image." + case .notFile: return "Choose a regular disk image or disk ROM file." + case .tooLarge: return "Disk images must be no larger than 16 MiB." + case .extensionType: return "Choose a DSK, JVC, OS-9, DMK or VDK floppy disk image." + case .romSize: return "Choose an 8 or 16 KiB disk ROM, such as disk11.rom. The CoCo 3 system ROM is selected separately." + case .changed: return "The disk file changed outside this drive. Use Save As to keep your changes in a separate file, or reinsert the disk." + case .readOnly: return "The disk file is no longer writable. Restore write access and retry, or use Save As." + } + } + } + private static func read(_ url: URL, limit: Int) throws -> Data { + guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw Failure.notFile } + let file = try FileHandle(forReadingFrom: url) + defer { try? file.close() } + var bytes = Data() + while bytes.count <= limit { + guard let chunk = try file.read(upToCount: min(1024 * 1024, limit + 1 - bytes.count)), !chunk.isEmpty else { break } + bytes.append(chunk) + } + return bytes + } + static func readROM(_ url: URL) throws -> Data { + let bytes = try read(url, limit: 16384) + guard bytes.count == 8192 || bytes.count == 16384 else { throw Failure.romSize } + return bytes + } + static func readCartridgeROM(_ url: URL) throws -> Data { + guard !extensions.contains(url.pathExtension.lowercased()), !["dll", "exe"].contains(url.pathExtension.lowercased()) else { throw Failure.cartridgeROM } + let bytes = try read(url, limit: 262144) + guard !bytes.isEmpty, bytes.count <= 262144, !bytes.starts(with: [0x4d, 0x5a]) else { throw Failure.cartridgeROM } + return bytes + } + static func readOrchestraROM(_ url: URL) throws -> Data { + let bytes = try readCartridgeROM(url) + guard bytes.count == 8192 else { throw Failure.orchestraROM } + return bytes + } + static func readSpeechChipROM(_ url: URL, speech: Bool) throws -> Data { + let size = speech ? 2048 : 4096 + let bytes = try read(url, limit: size) + guard bytes.count == size else { + throw ProfileFailure.message(speech ? "Choose the 2 KiB SP0256-AL2 speech ROM." : "Choose the 4 KiB PIC7040 firmware ROM.") + } + return bytes + } + static func readSDCROM(_ url: URL) throws -> Data { + let bytes = try readCartridgeROM(url) + guard bytes.count == 8192 || bytes.count == 16384 else { + throw ProfileFailure.message("Choose an 8 or 16 KiB SDC-DOS ROM. The CoCo system ROM and FD-502 disk ROM are separate.") + } + return bytes + } + static func validateSDCFolder(_ url: URL) throws { + guard url.isFileURL, try url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true, + FileManager.default.isReadableFile(atPath: url.path) else { + throw ProfileFailure.message("The SD card folder is unavailable. Reconnect it or choose its new location in Cartridges.") + } + } + static func readCartridgeAssignment(_ slot: CartridgeAssignments.Slot) throws -> Data { + if slot.kind == .sdc { + guard let rom = slot.url, let folder = slot.sdcFolderURL else { + throw ProfileFailure.message("CoCo SDC needs an SDC-DOS ROM and an SD card folder. Choose both in Cartridges.") + } + try validateSDCFolder(folder) + return try readSDCROM(rom) + } + if slot.kind == .speechSound { + guard let pic = slot.url, let speech = slot.speechROMURL else { + throw ProfileFailure.message("Speech/Sound needs both its PIC firmware and speech ROM. Choose both files in Cartridges.") + } + return try readSpeechChipROM(pic, speech: false) + readSpeechChipROM(speech, speech: true) + } + guard let url = slot.url else { return Data() } + return try slot.kind == .orchestra90 ? readOrchestraROM(url) : readCartridgeROM(url) + } + static func readImage(_ url: URL) throws -> Image { + guard extensions.contains(url.pathExtension.lowercased()) else { throw Failure.extensionType } + let bytes = try read(url, limit: limit) + guard bytes.count <= limit else { throw Failure.tooLarge } + return Image(data: bytes, readOnly: !FileManager.default.isWritableFile(atPath: url.path)) + } + /// A separate BASIC export must not bypass mounted-media write protection, + /// pending saves, temporary changes or source-document conflict handling. + static func exportBASIC(_ bytes: Data, to url: URL, protecting references: [URL]) throws { + try writeDevelopmentFile(bytes, to: url, protecting: references) + } + + static func writeDevelopmentFile(_ bytes: Data, to url: URL, protecting references: [URL], + allowEmpty: Bool = false, replacing expected: Data? = nil, + requireNew: Bool = false) throws { + try DiskEditorIO.write(bytes, to: url, protecting: references, allowEmpty: allowEmpty, + replacing: expected, requireNew: requireNew) + } + /// File promises already own destination coordination through completion. + static func writeReceivedFilePromise(_ bytes: Data, to url: URL, protecting references: [URL]) throws { + try DiskEditorIO.write(bytes, to: url, protecting: references, allowEmpty: true, + requireNew: true, coordinated: false) + } + static func export(_ bytes: Data, to url: URL) throws { + try bytes.write(to: url, options: .atomic) + } + // Coordinate with cooperating document apps and compare with the last bytes + // we read/wrote. Never recreate a missing source or overwrite external edits. + static func saveAutomatically(_ bytes: Data, to url: URL, expected: Data) throws { + var coordinationError: NSError? + var writeError: Error? + NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &coordinationError) { target in + do { + // The selected .dsk may be a symlink to a differently named file. + let current = try read(target, limit: limit) + guard current.count <= limit else { throw Failure.tooLarge } + guard FileManager.default.isWritableFile(atPath: target.path) else { throw Failure.readOnly } + guard current == expected else { throw Failure.changed } + try export(bytes, to: target) + } catch { writeError = error } + } + if let error = coordinationError { throw error } + if let error = writeError { throw error } + } +} diff --git a/platforms/macos/App/DiskImageEditorModel.swift b/platforms/macos/App/DiskImageEditorModel.swift new file mode 100644 index 0000000..877b7d8 --- /dev/null +++ b/platforms/macos/App/DiskImageEditorModel.swift @@ -0,0 +1,625 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import Combine +import SwiftUI +import UniformTypeIdentifiers + +struct DiskEditorEntry: Identifiable, Hashable, Sendable { + let name: String, path: String, type: String, encoding: String, attributes: String + let size: Int64, modified: TimeInterval + let directory: Bool + let owner: Int, group: Int, permissions: Int + var id: String { path } + init(_ value: [String: Any]) { + name = value["name"] as? String ?? ""; path = value["path"] as? String ?? name + type = value["type"] as? String ?? ""; encoding = value["encoding"] as? String ?? "" + attributes = value["attributes"] as? String ?? "" + size = (value["size"] as? NSNumber)?.int64Value ?? 0 + modified = (value["modified"] as? NSNumber)?.doubleValue ?? 0 + directory = value["is_directory"] as? Bool ?? false + owner = (value["owner"] as? NSNumber)?.intValue ?? 0 + group = (value["group"] as? NSNumber)?.intValue ?? 0 + permissions = (value["permissions"] as? NSNumber)?.intValue ?? 0 + } +} + +struct DiskEditorVolume: Identifiable, Hashable, Sendable { + let id: String, name: String, format: String + let offset: Int64, byteCount: Int64 + init(_ value: [String: Any]) { + id = value["id"] as? String ?? ""; name = value["name"] as? String ?? "Volume" + format = value["format"] as? String ?? "" + offset = (value["offset_bytes"] as? NSNumber)?.int64Value ?? 0 + byteCount = (value["byte_count"] as? NSNumber)?.int64Value ?? 0 + } +} + +struct DiskEditorContents: Sendable { + let entries: [DiskEditorEntry] + let bytes: Data + let format: String + let capacity: Int64?, used: Int64?, free: Int64? + let preservedBytes: Int64 + let volumes: [DiskEditorVolume] + let volumeID: String +} + +/// Retained C libraries and working-image I/O never run on the main actor. +actor DiskImageEditorStore { + let directory: URL + private let image: URL + private let volume: URL + private var volumeID: String + init(data: Data, selectedVolumeID: String? = nil) throws { + guard !data.isEmpty, data.count <= DiskEditorIO.imageLimit else { throw DiskEditorFailure.message("Choose a disk image within the 512 MiB limit.") } + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCDiskEditor-" + UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + directory = folder; image = folder.appendingPathComponent("Working.dsk") + volume = folder.appendingPathComponent("Volume.dsk"); volumeID = "" + do { + try data.write(to: image, options: .atomic) + let discovered = try VCCDiskImageEditorBackend.discoverVolumes(at: image).map(DiskEditorVolume.init) + guard let chosen = selectedVolumeID ?? discovered.first?.id, + discovered.contains(where: { $0.id == chosen }) else { throw DiskEditorFailure.message("The selected volume is unavailable in this image.") } + volumeID = chosen + try VCCDiskImageEditorBackend.extractVolume(chosen, imageURL: image, outputURL: volume) + } + catch { try? FileManager.default.removeItem(at: folder); throw error } + } + deinit { + let folder = directory + Task.detached { try? FileManager.default.removeItem(at: folder) } + } + func contents(at path: String) throws -> DiskEditorContents { + let info = try VCCDiskImageEditorBackend.inspectImage(at: volume) + let rows = try VCCDiskImageEditorBackend.listDirectory(path, imageURL: volume) + let volumes = try VCCDiskImageEditorBackend.discoverVolumes(at: image).map(DiskEditorVolume.init) + let bytes = try Data(contentsOf: image) + let selectedSize = volumes.first(where: { $0.id == volumeID })?.byteCount ?? 0 + return DiskEditorContents(entries: rows.map(DiskEditorEntry.init), bytes: bytes, + format: info["format"] as? String ?? "", + capacity: (info["capacity_bytes"] as? NSNumber)?.int64Value, + used: (info["used_bytes"] as? NSNumber)?.int64Value, + free: (info["free_bytes"] as? NSNumber)?.int64Value, + preservedBytes: Int64(bytes.count) - selectedSize, volumes: volumes, volumeID: volumeID) + } + func selectVolume(_ id: String) throws -> DiskEditorContents { + let previous = volumeID + do { + try VCCDiskImageEditorBackend.extractVolume(id, imageURL: image, outputURL: volume) + volumeID = id + return try contents(at: "") + } catch { + try? VCCDiskImageEditorBackend.extractVolume(previous, imageURL: image, outputURL: volume) + volumeID = previous + throw error + } + } + func restore(_ bytes: Data, path: String) throws -> DiskEditorContents { + let before = try Data(contentsOf: image) + do { + try bytes.write(to: image, options: .atomic) + try VCCDiskImageEditorBackend.extractVolume(volumeID, imageURL: image, outputURL: volume) + return try contents(at: path) + } catch { + try before.write(to: image, options: .atomic) + try VCCDiskImageEditorBackend.extractVolume(volumeID, imageURL: image, outputURL: volume) + throw error + } + } + enum Change: Sendable { + case importFiles([URL], type: Int, ascii: Bool, replace: Bool) + case folder(String) + case rename(String, String) + case delete([DiskEditorEntry]) + case os9Metadata(String, permissions: Int, ownerUser: Int, ownerGroup: Int) + case moveFiles([String], String) + } + func change(_ change: Change, path: String) throws -> DiskEditorContents { + let before = try Data(contentsOf: image) + do { + switch change { + case let .importFiles(urls, type, ascii, replace): + for url in urls { + let data = try Self.hostBytes(url) + try VCCDiskImageEditorBackend.importData(data, named: url.lastPathComponent, directory: path, + imageURL: volume, fileType: type, ascii: ascii, replace: replace) + } + case let .folder(name): try VCCDiskImageEditorBackend.makeDirectory(name, in: path, imageURL: volume) + case let .rename(old, name): try VCCDiskImageEditorBackend.renameEntry(old, to: name, imageURL: volume) + case let .delete(entries): + for entry in entries { try VCCDiskImageEditorBackend.deleteEntry(entry.path, directory: entry.directory, imageURL: volume) } + case let .os9Metadata(path, permissions, user, group): + try VCCDiskImageEditorBackend.setOS9Metadata(for: path, imageURL: volume, ownerUser: user, ownerGroup: group, permissions: permissions) + case let .moveFiles(files, destination): + try VCCDiskImageEditorBackend.moveFiles(files, toDirectory: destination, imageURL: volume) + } + try VCCDiskImageEditorBackend.replaceVolume(volumeID, imageURL: image, volumeURL: volume) + return try contents(at: path) + } catch { + // ToolShed edits only the expendable working image. A short write + // or full disk must not leave even this session half-mutated. + try before.write(to: image, options: .atomic) + try VCCDiskImageEditorBackend.extractVolume(volumeID, imageURL: image, outputURL: volume) + throw error + } + } + func read(_ path: String) throws -> Data { try VCCDiskImageEditorBackend.readFile(path, imageURL: volume) } + func info(_ path: String) throws -> String { try VCCDiskImageEditorBackend.identifyFile(path, imageURL: volume) } + static func hostBytes(_ url: URL, maximum: Int = DiskEditorIO.limit) throws -> Data { + guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw DiskEditorFailure.message("Import regular files, not folders.") } + let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } + var data = Data() + while let chunk = try handle.read(upToCount: min(65536, maximum + 1 - data.count)), !chunk.isEmpty { + data.append(chunk) + guard data.count <= maximum else { throw DiskEditorFailure.message("This file exceeds the \(maximum / (1024 * 1024)) MiB limit.") } + } + return data + } +} + +struct DiskEditorImportRequest: Identifiable { + let id = UUID() + let urls: [URL] + var type: Int = 3 + var ascii = true +} +struct DiskEditorNameRequest: Identifiable { + let id = UUID() + let entry: DiskEditorEntry? + var name: String +} +struct DiskEditorInformation: Identifiable { + let id = UUID() + let entry: DiskEditorEntry + let details: String +} +struct DiskEditorMoveRequest: Identifiable, Sendable { + let id = UUID() + let editorID: UUID, revision: UUID, sessionID: UUID + let sourcePath: String + let files: [DiskEditorEntry] + let bytes: Data +} +struct DiskEditorDragPayload: Codable, Equatable { + let editorID: UUID, revision: UUID, sessionID: UUID + let sourcePath: String, files: [String] + init(_ request: DiskEditorMoveRequest) { + editorID = request.editorID; revision = request.revision; sessionID = request.sessionID + sourcePath = request.sourcePath; files = request.files.map(\.path) + } +} + +@MainActor +final class DiskImageEditorModel: ObservableObject { + let editorID = UUID() + private(set) var revision = UUID() + let store: DiskImageEditorStore + let machine: any DiskEditorHost + let session: DiskEditorSession? + let sourceURL: URL? + let name: String + let original: Data + let sourceReadOnly: Bool + weak var window: NSWindow? + @Published private(set) var contents: DiskEditorContents + @Published var selection = Set() + @Published private(set) var path = "" + @Published private(set) var busy = false + @Published var error: String? + @Published var notice: String? + @Published var importing: DiskEditorImportRequest? + @Published var naming: DiskEditorNameRequest? + @Published var information: DiskEditorInformation? + @Published var moving: DiskEditorMoveRequest? + @Published private(set) var undoStates: [Data] = [] + @Published private(set) var redoStates: [Data] = [] + private var backPaths: [String] = [] + var onFinished: (() -> Void)? + var changed: Bool { contents.bytes != original } + var selected: [DiskEditorEntry] { contents.entries.filter { selection.contains($0.id) } } + var os9: Bool { contents.format == "os9" } + var canApply: Bool { session?.canApply ?? !sourceReadOnly } + var presentation: DiskEditorPresentation { machine.diskEditorPresentation(for: session) } + var displayPath: String { "/" + path } + var canBack: Bool { !backPaths.isEmpty } + var canMove: Bool { os9 && !busy && !selected.isEmpty && selected.count <= 4096 && selected.allSatisfy { !$0.directory } } + + init(store: DiskImageEditorStore, machine: any DiskEditorHost, session: DiskEditorSession?, sourceURL: URL?, + name: String, original: Data, contents: DiskEditorContents, sourceReadOnly: Bool) { + self.store = store; self.machine = machine; self.session = session; self.sourceURL = sourceURL + self.name = name; self.original = original; self.contents = contents; self.sourceReadOnly = sourceReadOnly + } + private func accept(_ value: DiskEditorContents) { + if value.bytes != contents.bytes { revision = UUID() } + contents = value; selection.formIntersection(Set(value.entries.map(\.id))) + } + func moveRequest(for files: [DiskEditorEntry]) -> DiskEditorMoveRequest? { + guard os9, !busy, !files.isEmpty, files.count <= 4096, files.allSatisfy({ !$0.directory && contents.entries.contains($0) }), + Set(files.map(\.id)).count == files.count else { return nil } + return DiskEditorMoveRequest(editorID: editorID, revision: revision, sessionID: session?.id ?? editorID, + sourcePath: path, files: files, bytes: contents.bytes) + } + func moveSourceIsCurrent(_ request: DiskEditorMoveRequest) -> Bool { + os9 && request.editorID == editorID && request.revision == revision && request.sessionID == (session?.id ?? editorID) && + request.sourcePath == path && request.bytes == contents.bytes && request.files.allSatisfy { !$0.directory && contents.entries.contains($0) } + } + func moveTo() { + guard let request = moveRequest(for: selected) else { return } + error = nil + moving = request + } + func moveDestination(_ request: DiskEditorMoveRequest, path destination: String) async throws -> DiskEditorContents { + guard moveSourceIsCurrent(request), !busy else { throw DiskEditorFailure.message("The disk or source folder changed. Close Move To and select the files again.") } + let result = try await store.contents(at: destination) + try Task.checkCancellation() + guard moveSourceIsCurrent(request), !busy, result.bytes == request.bytes else { + throw DiskEditorFailure.message("The disk changed while choosing a folder. Close Move To and select the files again.") + } + return result + } + func move(_ request: DiskEditorMoveRequest, to destination: String, expectedDestination: DiskEditorContents? = nil) { + guard !busy else { return } + guard moveSourceIsCurrent(request) else { error = "The dragged files or disk changed. Select the files again before moving them."; return } + guard destination.caseInsensitiveCompare(request.sourcePath) != .orderedSame else { + error = "These files are already in this folder. Choose a different destination."; return + } + work { + let target = try await self.store.contents(at: destination) + guard self.moveSourceIsCurrent(request), target.bytes == request.bytes, + expectedDestination.map({ $0.bytes == target.bytes && $0.entries == target.entries }) ?? true else { + throw DiskEditorFailure.message("The disk or destination changed. Choose the destination again.") + } + let names = Set(target.entries.map { $0.name.lowercased() }) + if let collision = request.files.first(where: { names.contains($0.name.lowercased()) }) { + throw DiskEditorFailure.message("The destination already contains \(collision.name). Rename it or choose another folder; moving never overwrites files.") + } + try await self.commit(.moveFiles(request.files.map(\.path), destination)) + self.moving = nil + self.notice = "Moved \(request.files.count) \(request.files.count == 1 ? "file" : "files") to /\(destination). Undo is available." + } + } + private func work(_ operation: @escaping () async throws -> Void) { + guard !busy else { return }; busy = true; error = nil; notice = nil + Task { do { try await operation() } catch { self.error = error.localizedDescription }; self.busy = false } + } + func selectVolume(_ id: String) { + guard !busy, id != contents.volumeID else { return } + work { + let value = try await self.store.selectVolume(id) + self.revision = UUID(); self.path = ""; self.backPaths = []; self.selection = [] + self.moving = nil; self.information = nil; self.naming = nil; self.importing = nil + self.accept(value) + } + } + func refresh() { + work { self.accept(try await self.store.contents(at: self.path)) } + } + func navigate(_ next: String, remember: Bool = true) { + work { + let value = try await self.store.contents(at: next) + if remember { self.backPaths.append(self.path) } + self.path = next; self.selection = []; self.accept(value) + } + } + func back() { guard let next = backPaths.popLast() else { return }; navigate(next, remember: false) } + func up() { navigate(path.split(separator: "/").dropLast().joined(separator: "/")) } + func activate(_ ids: Set) { + selection = ids + guard let entry = selected.first, selected.count == 1 else { return } + if entry.directory { navigate(entry.path) } else { export() } + } + func change(_ change: DiskImageEditorStore.Change) { + work { try await self.commit(change) } + } + private func commit(_ change: DiskImageEditorStore.Change) async throws { + let before = contents.bytes + let value = try await store.change(change, path: path) + if value.bytes != before { + undoStates.append(before); redoStates.removeAll() + while undoStates.count > 1 && (undoStates.count > 32 || undoStates.reduce(0, { $0 + $1.count }) > 64 * 1024 * 1024) { undoStates.removeFirst() } + } + accept(value) + } + private func confirm(_ alert: NSAlert, accepting response: NSApplication.ModalResponse = .alertFirstButtonReturn) async -> Bool { + guard let window else { return false } + return await withCheckedContinuation { continuation in + alert.beginSheetModal(for: window) { continuation.resume(returning: $0 == response) } + } + } + func undo() { + guard !busy, let bytes = undoStates.last else { return } + let current = contents.bytes + work { + let value = try await self.restoreNavigable(bytes) + self.undoStates.removeLast(); self.redoStates.append(current); self.accept(value) + } + } + func redo() { + guard !busy, let bytes = redoStates.last else { return } + let current = contents.bytes + work { + let value = try await self.restoreNavigable(bytes) + self.redoStates.removeLast(); self.undoStates.append(current); self.accept(value) + } + } + private func restoreNavigable(_ bytes: Data) async throws -> DiskEditorContents { + // Undoing creation of the currently open folder returns to the root. + do { return try await store.restore(bytes, path: path) } + catch { + let value = try await store.restore(bytes, path: "") + path = ""; backPaths = []; return value + } + } + func chooseImport() { + let panel = NSOpenPanel(); panel.title = "Import Files into Disk Image"; panel.canChooseDirectories = false; panel.allowsMultipleSelection = true + guard let window else { return } + panel.beginSheetModal(for: window) { response in + guard response == .OK else { return } + Task { @MainActor in self.proposeImport(panel.urls) } + } + } + func proposeImport(_ urls: [URL]) { + guard !busy, !urls.isEmpty else { return } + guard urls.count <= 72 else { error = "Import at most 72 files at once."; return } + var request = DiskEditorImportRequest(urls: urls) + let ext = urls.first?.pathExtension.lowercased() ?? "" + request.type = ext == "bas" ? 0 : ext == "dat" ? 1 : ["txt", "asc"].contains(ext) ? 3 : 2 + request.ascii = ["bas", "txt", "asc"].contains(ext) + importing = request + } + func importNeedsReplacement(_ urls: [URL]) -> Bool { + // Both filesystem readers compare ASCII names without casing; use the + // same identity when deciding whether replacement consent is needed. + let names = Set(contents.entries.map { $0.name.lowercased() }) + return urls.contains { names.contains($0.lastPathComponent.lowercased()) } + } + func confirmImport(_ request: DiskEditorImportRequest) { + importing = nil + let collisions = importNeedsReplacement(request.urls) + work { + if collisions { + let alert = NSAlert(); alert.messageText = "Replace existing files?"; alert.informativeText = "The selected names already exist in this directory. Replacement changes only the editor's working copy until you apply it." + alert.addButton(withTitle: "Replace"); alert.addButton(withTitle: "Cancel") + guard await self.confirm(alert) else { return } + } + try await self.commit(.importFiles(request.urls, type: request.type, ascii: request.ascii, replace: collisions)) + } + } + func newFolder() { naming = DiskEditorNameRequest(entry: nil, name: "") } + func rename() { guard selected.count == 1, let entry = selected.first else { return }; naming = DiskEditorNameRequest(entry: entry, name: entry.name) } + func confirmName(_ request: DiskEditorNameRequest) { + naming = nil + if let entry = request.entry { change(.rename(entry.path, request.name)) } else { change(.folder(request.name)) } + } + func delete() { + let entries = selected; guard !entries.isEmpty else { return } + let alert = NSAlert(); alert.messageText = entries.count == 1 ? "Delete \(entries[0].name)?" : "Delete \(entries.count) entries?" + alert.informativeText = "This changes the working copy. Undo is available until the editor closes. Nonempty folders must be emptied first." + alert.addButton(withTitle: "Delete"); alert.addButton(withTitle: "Cancel") + work { + guard await self.confirm(alert) else { return } + try await self.commit(.delete(entries)) + } + } + func showInfo() { + guard selected.count == 1, let entry = selected.first else { return } + work { + var text = "\(entry.name)\n\(entry.type)\n\(ByteCountFormatter.string(fromByteCount: entry.size, countStyle: .file))" + if !entry.directory && self.os9 { + do { + let data = try await self.store.read(entry.path) + if data.starts(with: [0x87, 0xcd]) || data.starts(with: [0x4a, 0xfc]) { + do { text += "\n\n" + (try await self.store.info(entry.path)) } + catch { text += "\n\nModule information unavailable: " + error.localizedDescription } + } + } catch { text += "\n\nContent inspection unavailable: " + error.localizedDescription } + } + self.information = DiskEditorInformation(entry: entry, details: text) + } + } + func applyInformation(_ info: DiskEditorInformation, permissions: Int, ownerUser: Int, ownerGroup: Int) { + guard os9, (0...127).contains(permissions), (0...255).contains(ownerUser), (0...255).contains(ownerGroup) else { + error = "Choose valid OS-9 access flags and group/user values from 0 to 255."; return + } + guard contents.entries.first(where: { $0.id == info.entry.id }) == info.entry else { + error = "This entry changed. Close File Information and open it again before saving."; return + } + work { + try await self.commit(.os9Metadata(info.entry.path, permissions: permissions, ownerUser: ownerUser, ownerGroup: ownerGroup)) + self.information = nil + } + } + func export() { + let files = selected.filter { !$0.directory }; guard !files.isEmpty, let window else { return } + let snapshot = contents.bytes, volumeID = contents.volumeID + if files.count == 1 { + let panel = NSSavePanel(); panel.title = "Export Disk File"; panel.nameFieldStringValue = files[0].name + panel.beginSheetModal(for: window) { response in + guard response == .OK, let url = panel.url else { return } + Task { @MainActor in self.export(files, targets: [url], snapshot: snapshot, volumeID: volumeID) } + } + } else { + let panel = NSOpenPanel(); panel.title = "Choose Export Folder"; panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true + panel.beginSheetModal(for: window) { response in + guard response == .OK, let url = panel.url else { return } + Task { @MainActor in self.export(files, targets: files.map { url.appendingPathComponent($0.name) }, snapshot: snapshot, volumeID: volumeID, confirmReplacement: true) } + } + } + } + private func export(_ entries: [DiskEditorEntry], targets: [URL], snapshot: Data, volumeID: String, confirmReplacement: Bool = false) { + work { + let existing = try await Task.detached { try targets.map { url -> Data? in + if FileManager.default.fileExists(atPath: url.path) { return try DiskImageEditorStore.hostBytes(url) } + return nil + } }.value + if confirmReplacement && existing.contains(where: { $0 != nil }) { + let alert = NSAlert(); alert.messageText = "Replace exported files?" + alert.informativeText = "Some filenames already exist in the selected folder. Replace those files with the selected disk files?" + alert.addButton(withTitle: "Replace"); alert.addButton(withTitle: "Cancel") + guard await self.confirm(alert) else { return } + } + let reader = try await Task.detached { try DiskImageEditorStore(data: snapshot, selectedVolumeID: volumeID) }.value + for (index, pair) in zip(entries, targets).enumerated() { + let (entry, target) = pair + let data = try await reader.read(entry.path) + try await self.machine.saveDiskEditorExport(data, to: target, protecting: self.sourceURL, + replacing: existing[index], requireNew: existing[index] == nil) + } + self.notice = "Exported \(entries.count) \(entries.count == 1 ? "file" : "files")." + } + } + func saveCopy() { + guard let window else { return } + let panel = NSSavePanel(); panel.title = "Save Edited Disk Copy"; let ext = sourceURL?.pathExtension.lowercased() ?? (session?.hardDisk == true ? "vhd" : "dsk") + panel.nameFieldStringValue = ((name as NSString).deletingPathExtension) + " Edited." + ext + panel.allowedContentTypes = [UTType(filenameExtension: ext) ?? .data] + panel.beginSheetModal(for: window) { response in + guard response == .OK, let url = panel.url else { return } + Task { @MainActor in + self.work { + let existing = try await Task.detached { () -> Data? in + if FileManager.default.fileExists(atPath: url.path) { return try DiskImageEditorStore.hostBytes(url, maximum: DiskEditorIO.imageLimit) } + return nil + }.value + try await self.saveCopy(to: url, replacing: existing) + } + } + } + } + func saveCopy(to url: URL, replacing expected: Data?) async throws { + let data = contents.bytes + try await machine.saveDiskEditorImageCopy(data, to: url, protecting: sourceURL, + replacing: expected, requireNew: expected == nil) + notice = "Saved edited copy. The original disk is unchanged." + } + func apply() { + guard !busy, changed, canApply else { return } + let alert = NSAlert() + alert.messageText = presentation.applyConfirmationTitle + alert.informativeText = presentation.applyConfirmationMessage + alert.addButton(withTitle: presentation.applyConfirmationAction); alert.addButton(withTitle: "Cancel") + work { + guard await self.confirm(alert) else { return } + if let session = self.session { + try await self.machine.applyDiskEditor(session, data: self.contents.bytes, restartConfirmed: true) + } else { + guard let source = self.sourceURL else { throw DiskEditorFailure.message("The source image is unavailable. Save an edited copy instead.") } + try await self.machine.saveOfflineDiskEditor(self.contents.bytes, to: source, replacing: self.original) + } + self.onFinished?() + } + } + func close() { + guard !busy else { return } + work { + if self.changed { + let alert = NSAlert(); alert.messageText = "Discard unapplied disk edits?" + alert.informativeText = "The original disk is unchanged. Any separately exported files or edited copy you saved are kept." + alert.addButton(withTitle: "Keep Editing"); alert.addButton(withTitle: "Discard Changes") + guard await self.confirm(alert, accepting: .alertSecondButtonReturn) else { return } + } + if let session = self.session { try await self.machine.cancelDiskEditor(session) } + self.onFinished?() + } + } +} + +@MainActor +final class DiskImageEditorCoordinator: NSObject, NSWindowDelegate { + static let shared = DiskImageEditorCoordinator() + private var editor: DiskImageEditorModel? + private var window: NSWindow? + private var opening = false + func edit(_ drive: Int, machine: any DiskEditorHost) { + guard !opening, editor == nil else { window?.makeKeyAndOrderFront(nil); return } + opening = true + Task { + var acquired: DiskEditorSession? + do { + let session = try await machine.beginDiskEditor(inDrive: drive); acquired = session + try await present(data: session.data, name: session.name, source: session.sourceURL, session: session, machine: machine, sourceReadOnly: !session.canApply) + } catch { + if let acquired { try? await machine.cancelDiskEditor(acquired) } + showError(error) + } + opening = false + } + } + func editHardDisk(_ drive: Int, machine: any DiskEditorHost) { + guard !opening, editor == nil else { window?.makeKeyAndOrderFront(nil); return } + opening = true + Task { + var acquired: DiskEditorSession? + do { + let session = try await machine.beginHardDiskEditor(inDrive: drive); acquired = session + try await present(data: session.data, name: session.name, source: session.sourceURL, session: session, machine: machine, sourceReadOnly: !session.canApply) + } catch { + if let acquired { try? await machine.cancelDiskEditor(acquired) } + showError(error) + } + opening = false + } + } + func open(machine: any DiskEditorHost) { + guard editor == nil, !opening else { window?.makeKeyAndOrderFront(nil); return } + let panel = NSOpenPanel(); panel.title = "Open Disk Image for Editing"; panel.allowedContentTypes = DiskEditorIO.extensions.compactMap { UTType(filenameExtension: $0) } + panel.canChooseDirectories = false + panel.begin { response in + guard response == .OK, let url = panel.url else { return } + Task { @MainActor in self.open(url, machine: machine) } + } + } + func open(_ url: URL, machine: any DiskEditorHost) { + guard editor == nil, !opening else { window?.makeKeyAndOrderFront(nil); return } + if let drive = machine.mountedEditorDrive(for: url) { edit(drive, machine: machine); return } + if let drive = machine.mountedHardDiskEditorDrive(for: url) { editHardDisk(drive, machine: machine); return } + guard !machine.diskEditorSourceIsAssigned(url) else { + showError(DiskEditorFailure.message("This image is assigned to another device or an SD card folder. Eject or remove that assignment before opening it in Disk Image Editor.")) + return + } + opening = true + Task { + do { + let image = try await Task.detached { try DiskEditorIO.readImage(url) }.value + try await present(data: image.data, name: url.lastPathComponent, source: url, session: nil, machine: machine, sourceReadOnly: image.readOnly) + } catch { showError(error) } + opening = false + } + } + private func present(data: Data, name: String, source: URL?, session: DiskEditorSession?, machine: any DiskEditorHost, sourceReadOnly: Bool) async throws { + let store = try await Task.detached { try DiskImageEditorStore(data: data) }.value + let contents = try await store.contents(at: "") + let model = DiskImageEditorModel(store: store, machine: machine, session: session, sourceURL: source, name: name, original: data, contents: contents, sourceReadOnly: sourceReadOnly) + var size = NSSize(width: 1050, height: 700) + #if VCC_UI_TESTING + // Exercise the real compact layout without relying on a synthetic + // WindowServer edge-drag gesture. Never enabled in the normal app. + if CommandLine.arguments.contains("--disk-editor-compact-fixture") { size = NSSize(width: 760, height: 448) } + #endif + let window = NSWindow(contentRect: NSRect(origin: .zero, size: size), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false) + window.title = "Disk Image Editor"; window.subtitle = name; window.isReleasedWhenClosed = false; window.delegate = self + let content = NSHostingView(rootView: DiskImageEditorView(model: model)) + // This AppKit window owns its minimum size. Inferred hosting constraints + // must not pin the initial table dimensions and prevent shrinking. + content.sizingOptions = [] + window.contentView = content; window.minSize = NSSize(width: 760, height: 480) + model.window = window + model.onFinished = { [weak self, weak window] in window?.delegate = nil; window?.close(); self?.window = nil; self?.editor = nil } + self.window = window; editor = model; window.center(); window.makeKeyAndOrderFront(nil) + } + func windowShouldClose(_ sender: NSWindow) -> Bool { editor?.close(); return false } + func prepareToQuit() -> Bool { + guard editor != nil || opening else { return true } + window?.makeKeyAndOrderFront(nil) + let alert = NSAlert(); alert.messageText = "Finish disk editing before quitting" + alert.informativeText = editor?.presentation.closeNotice ?? "Finish opening the Disk Image Editor before quitting." + alert.addButton(withTitle: "Return to Editor") + if let window { alert.beginSheetModal(for: window) } else { alert.runModal() } + return false + } + private func showError(_ error: Error) { + let alert = NSAlert(); alert.messageText = "Cannot open Disk Image Editor"; alert.informativeText = error.localizedDescription + if let parent = NSApp.keyWindow ?? NSApp.mainWindow { alert.beginSheetModal(for: parent) } else { alert.runModal() } + } +} diff --git a/platforms/macos/App/DiskImageEditorView.swift b/platforms/macos/App/DiskImageEditorView.swift new file mode 100644 index 0000000..499277e --- /dev/null +++ b/platforms/macos/App/DiskImageEditorView.swift @@ -0,0 +1,331 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit + +struct DiskImageEditorView: View { + @ObservedObject var model: DiskImageEditorModel + var body: some View { + VStack(spacing: 0) { + actionBar + Divider() + HStack(alignment: .top, spacing: 12) { + VStack(alignment: .leading, spacing: 5) { + Label(model.name, systemImage: "externaldrive").font(.headline) + if model.contents.volumes.count > 1 { + Picker("Volume", selection: Binding(get: { model.contents.volumeID }, set: { model.selectVolume($0) })) { + ForEach(model.contents.volumes) { volume in Text(volume.name).tag(volume.id) } + }.frame(maxWidth: 420).disabled(model.busy) + .accessibilityIdentifier("disk-editor-volume") + .help("Choose a filesystem within this image. Other volumes and unrecognized regions stay unchanged.") + } + Text(model.displayPath).font(.callout.monospaced()).foregroundStyle(.secondary) + .accessibilityIdentifier("disk-editor-path") + if model.session != nil { + Label(model.presentation.context, systemImage: "lock.fill") + .font(.caption).foregroundStyle(.secondary) + } else { Text(model.presentation.context).font(.caption).foregroundStyle(.secondary) } + if model.contents.preservedBytes > 0 { + Text("Outside selected volume: \(space(model.contents.preservedBytes)) · Preserved unchanged") + .font(.caption).foregroundStyle(.secondary) + .accessibilityIdentifier("disk-editor-preserved-data") + .help("Other volumes and extra data are preserved. Total, Used and Free describe only the selected filesystem.") + } + } + Spacer() + if model.changed { Text("Unapplied changes").font(.caption).foregroundStyle(.secondary) } + if model.busy { ProgressView().controlSize(.small).accessibilityLabel("Working with disk image") } + }.padding(16) + Divider() + DiskEditorFileTable(model: model).accessibilityIdentifier("disk-editor-files") + if let error = model.error { + HStack(alignment: .top) { + Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.red).textSelection(.enabled) + Spacer(); Button("Dismiss") { model.error = nil } + }.font(.callout).padding(12).accessibilityIdentifier("disk-editor-error") + } else if let notice = model.notice { Text(notice).font(.callout).frame(maxWidth: .infinity, alignment: .leading).padding(12) } + Divider() + HStack { + Text(model.os9 ? "OS-9 RBF" : "Disk BASIC") + Text("· \(model.contents.entries.count) \(model.contents.entries.count == 1 ? "entry" : "entries")") + Spacer() + Text("Total \(space(model.contents.capacity)) Used \(space(model.contents.used)) Free \(space(model.contents.free))") + .monospacedDigit().accessibilityIdentifier("disk-editor-space") + .help(model.os9 ? "Volume capacity and allocated/free space from the OS-9 allocation bitmap." : "Allocatable file space from the Disk BASIC granule map. The reserved directory track is excluded.") + }.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 16).padding(.vertical, 10) + Divider() + HStack { + if !model.canApply { + Label(model.session?.applyRestriction ?? "The original is read-only. Save an edited copy to keep changes.", systemImage: "lock") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } else { + Text(model.presentation.applyHint) + .font(.caption).foregroundStyle(.secondary) + } + Spacer() + Button("Close") { model.close() }.accessibilityIdentifier("disk-editor-close") + Button("Save Edited Copy…") { model.saveCopy() }.accessibilityIdentifier("disk-editor-save-copy") + Button(model.presentation.applyButtonTitle) { model.apply() } + .disabled(!model.changed || !model.canApply).accessibilityIdentifier("disk-editor-apply") + }.padding(14).disabled(model.busy) + } + .frame(minWidth: 760, minHeight: 440) + .sheet(item: $model.importing) { request in DiskEditorImportSheet(model: model, request: request) } + .sheet(item: $model.naming) { request in DiskEditorNameSheet(model: model, request: request) } + .sheet(item: $model.information) { information in DiskEditorInformationSheet(model: model, information: information) } + .sheet(item: $model.moving) { request in DiskEditorMoveSheet(model: model, request: request) } + } + // This window is hosted directly in AppKit. Keep its actions in the content + // rather than relying on a SwiftUI scene to install an NSToolbar. + private var actionBar: some View { + HStack(spacing: 8) { + HStack(spacing: 4) { + action("Back", "chevron.left", "disk-editor-back", disabled: !model.canBack) { model.back() } + action("Up", "arrow.up", "disk-editor-up", disabled: model.path.isEmpty) { model.up() } + action("Refresh", "arrow.clockwise", "disk-editor-refresh") { model.refresh() } + } + Divider().frame(height: 22) + HStack(spacing: 4) { + action("Import", "square.and.arrow.down", "disk-editor-import") { model.chooseImport() } + action("Export", "square.and.arrow.up", "disk-editor-export", disabled: !model.selected.contains(where: { !$0.directory })) { model.export() } + action("New Folder", "folder.badge.plus", "disk-editor-new-folder", disabled: !model.os9) { model.newFolder() } + action("Rename", "pencil", "disk-editor-rename", disabled: model.selected.count != 1) { model.rename() } + action("Move To…", "folder", "disk-editor-move", disabled: !model.canMove) { model.moveTo() } + .help("Move selected regular files to another folder in this OS-9 image.") + action("Delete", "trash", "disk-editor-delete", disabled: model.selected.isEmpty) { model.delete() } + action("Info", "info.circle", "disk-editor-info", disabled: model.selected.count != 1) { model.showInfo() } + } + Spacer(minLength: 12) + HStack(spacing: 4) { + Button { model.undo() } label: { Label("Undo", systemImage: "arrow.uturn.backward") } + .keyboardShortcut("z", modifiers: .command).help("Undo disk edit").accessibilityIdentifier("disk-editor-undo") + .accessibilityLabel("Undo") + .disabled(model.busy || model.undoStates.isEmpty) + Button { model.redo() } label: { Label("Redo", systemImage: "arrow.uturn.forward") } + .keyboardShortcut("z", modifiers: [.command, .shift]).help("Redo disk edit").accessibilityIdentifier("disk-editor-redo") + .accessibilityLabel("Redo") + .disabled(model.busy || model.redoStates.isEmpty) + } + }.labelStyle(.iconOnly).buttonStyle(.bordered).padding(.horizontal, 14).padding(.vertical, 10) + } + private func space(_ value: Int64?) -> String { + guard let value else { return "Unavailable" } + return ByteCountFormatter.string(fromByteCount: value, countStyle: .file) + } + private func action(_ name: String, _ symbol: String, _ id: String, disabled: Bool = false, perform: @escaping () -> Void) -> some View { + Button(action: perform) { Label(name, systemImage: symbol) }.help(name) + .accessibilityLabel(name).accessibilityIdentifier(id).disabled(model.busy || disabled) + } +} + +private struct DiskEditorMoveSheet: View { + @ObservedObject var model: DiskImageEditorModel + let request: DiskEditorMoveRequest + @State private var destination: String + @State private var selectedFolder: String? + @State private var contents: DiskEditorContents? + @State private var loading = true + @State private var error: String? + init(model: DiskImageEditorModel, request: DiskEditorMoveRequest) { + self.model = model; self.request = request + _destination = State(initialValue: request.sourcePath) + } + private func open(_ path: String) { destination = path; selectedFolder = nil; model.error = nil } + var body: some View { + VStack(alignment: .leading, spacing: 14) { + Text("Move \(request.files.count == 1 ? request.files[0].name : "\(request.files.count) files")").font(.headline) + Text("Choose a folder inside this OS-9 image. Existing files are never replaced.") + .font(.callout).foregroundStyle(.secondary) + HStack { + Button("Root", systemImage: "externaldrive") { open("") }.accessibilityIdentifier("disk-editor-move-root") + Button("Up", systemImage: "arrow.up") { open(destination.split(separator: "/").dropLast().joined(separator: "/")) } + .disabled(destination.isEmpty).keyboardShortcut(.upArrow, modifiers: .command).accessibilityIdentifier("disk-editor-move-up") + Text("/" + destination).font(.callout.monospaced()).lineLimit(1).truncationMode(.middle).help("/" + destination) + .accessibilityLabel("Destination folder").accessibilityValue("/" + destination).accessibilityIdentifier("disk-editor-move-path") + Spacer() + if loading { ProgressView().controlSize(.small) } + } + List(selection: $selectedFolder) { + ForEach(contents?.entries.filter(\.directory) ?? []) { folder in + Label(folder.name, systemImage: "folder").frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()).tag(folder.path) + .accessibilityIdentifier("disk-editor-move-folder-" + folder.path) + .onTapGesture(count: 2) { open(folder.path) } + } + }.accessibilityLabel("Folders in destination directory").accessibilityIdentifier("disk-editor-move-folders") + if let message = error ?? model.error { + Label(message, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.red) + .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("disk-editor-move-error") + } + HStack { + Button("Open Folder") { if let path = selectedFolder { open(path) } } + .disabled(loading || selectedFolder == nil).keyboardShortcut(.downArrow, modifiers: .command) + .accessibilityIdentifier("disk-editor-move-open") + Spacer() + Button("Cancel") { model.moving = nil }.keyboardShortcut(.cancelAction).accessibilityIdentifier("disk-editor-move-cancel") + Button("Move Here") { model.move(request, to: destination, expectedDestination: contents) } + .keyboardShortcut(.defaultAction).accessibilityIdentifier("disk-editor-move-confirm") + .disabled(loading || contents == nil || destination.caseInsensitiveCompare(request.sourcePath) == .orderedSame || !model.moveSourceIsCurrent(request)) + } + }.padding(20).frame(width: 540, height: 420).disabled(model.busy) + .task(id: destination + "/" + model.revision.uuidString) { + loading = true; contents = nil; error = nil + do { contents = try await model.moveDestination(request, path: destination) } + catch { if !Task.isCancelled { self.error = error.localizedDescription } } + if !Task.isCancelled { loading = false } + } + } +} + +private struct DiskEditorInformationSheet: View { + @ObservedObject var model: DiskImageEditorModel + let information: DiskEditorInformation + @State private var permissions: Int + @State private var ownerUser: String + @State private var ownerGroup: String + + init(model: DiskImageEditorModel, information: DiskEditorInformation) { + self.model = model + self.information = information + _permissions = State(initialValue: information.entry.permissions & 0x7f) + _ownerUser = State(initialValue: String(information.entry.owner)) + _ownerGroup = State(initialValue: String(information.entry.group)) + } + private func ownerID(_ text: String) -> Int? { + guard !text.isEmpty, text.utf8.allSatisfy({ (48...57).contains($0) }), + let value = Int(text), (0...255).contains(value) else { return nil } + return value + } + private var valid: Bool { ownerID(ownerUser) != nil && ownerID(ownerGroup) != nil } + private var changed: Bool { + permissions != (information.entry.permissions & 0x7f) || + ownerID(ownerUser) != information.entry.owner || ownerID(ownerGroup) != information.entry.group + } + private func access(_ title: String, bit: Int, id: String) -> some View { + Toggle(title, isOn: Binding(get: { permissions & bit != 0 }, set: { enabled in + if enabled { permissions |= bit } else { permissions &= ~bit } + })).toggleStyle(.checkbox).accessibilityIdentifier(id) + .accessibilityLabel(bit <= 4 ? "Owner \(title)" : bit <= 32 ? "Public \(title)" : title) + } + var body: some View { + VStack(alignment: .leading, spacing: 16) { + Text("File Information").font(.headline) + Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 6) { + GridRow { Text("Name").foregroundStyle(.secondary); Text(information.entry.name).textSelection(.enabled) } + GridRow { Text("Path").foregroundStyle(.secondary); Text("/" + information.entry.path).textSelection(.enabled) } + GridRow { Text("Entry type").foregroundStyle(.secondary); Text(information.entry.directory ? "Directory" : "File").accessibilityIdentifier("disk-editor-info-directory") } + GridRow { Text("Type").foregroundStyle(.secondary); Text(information.entry.type) } + GridRow { Text("Size").foregroundStyle(.secondary); Text("\(information.entry.size) bytes").monospacedDigit() } + } + if model.os9 { + GroupBox("OS-9 Access") { + VStack(alignment: .leading, spacing: 0) { + Grid(alignment: .leading, horizontalSpacing: 20, verticalSpacing: 10) { + GridRow { + Text("Owner") + access("Read", bit: 1, id: "disk-editor-info-owner-read") + access("Write", bit: 2, id: "disk-editor-info-owner-write") + access("Execute", bit: 4, id: "disk-editor-info-owner-execute") + } + GridRow { + Text("Public") + access("Read", bit: 8, id: "disk-editor-info-public-read") + access("Write", bit: 16, id: "disk-editor-info-public-write") + access("Execute", bit: 32, id: "disk-editor-info-public-execute") + } + }.padding(8) + access("Single access (non-shareable)", bit: 64, id: "disk-editor-info-single-access") + .help("Allows only one opener at a time; this is the OS-9 single-access attribute.") + .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8).padding(.bottom, 8) + } + } + GroupBox("OS-9 Ownership") { + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 10) { + Text("Group ID") + TextField("Group ID", text: $ownerGroup).frame(width: 70).accessibilityIdentifier("disk-editor-info-owner-group") + Spacer() + Text("User ID") + TextField("User ID", text: $ownerUser).frame(width: 70).accessibilityIdentifier("disk-editor-info-owner-user") + }.textFieldStyle(.roundedBorder).padding(8) + if let group = ownerID(ownerGroup), let user = ownerID(ownerUser) { + Text("Owner ID: \(group * 256 + user)").monospacedDigit().font(.callout) + .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8) + .accessibilityIdentifier("disk-editor-info-owner-id") + } + Text("OS-9 stores one owner ID. The Owner column shows its high and low bytes as group.user; enter each from 0 to 255.") + .font(.caption).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8).padding(.bottom, 8) + } + } + if !valid { + Label("Group ID and User ID must each be a whole number from 0 to 255.", systemImage: "exclamationmark.triangle") + .font(.callout).foregroundStyle(.red).accessibilityIdentifier("disk-editor-info-validation") + } + } + ScrollView { + Text(information.details).font(.system(.callout, design: .monospaced)).textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + }.frame(minHeight: 90, maxHeight: .infinity).accessibilityIdentifier("disk-editor-info-details") + if let error = model.error { + Label(error, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.red) + .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("disk-editor-info-error") + } + HStack { + if model.os9 { + Text("Changes stay in the editor until the disk image is applied or saved.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + Spacer() + Button("Cancel") { model.information = nil }.keyboardShortcut(.cancelAction).accessibilityIdentifier("disk-editor-info-cancel") + Button("Save Changes") { + guard let user = ownerID(ownerUser), let group = ownerID(ownerGroup) else { return } + model.applyInformation(information, permissions: permissions, ownerUser: user, ownerGroup: group) + }.keyboardShortcut(.defaultAction).disabled(!valid || !changed).accessibilityIdentifier("disk-editor-info-save") + } else { + Spacer() + Button("Done") { model.information = nil }.keyboardShortcut(.defaultAction).accessibilityIdentifier("disk-editor-info-done") + } + } + }.padding(20).frame(width: 590, height: model.os9 ? 660 : 440).disabled(model.busy) + } +} + +private struct DiskEditorImportSheet: View { + @ObservedObject var model: DiskImageEditorModel + @State var request: DiskEditorImportRequest + var body: some View { + VStack(alignment: .leading, spacing: 16) { + Text("Import into \(model.displayPath)").font(.headline) + Text(request.urls.map(\.lastPathComponent).joined(separator: "\n")).lineLimit(6).textSelection(.enabled) + if !model.os9 { + Picker("File Type", selection: $request.type) { + Text("BASIC program").tag(0); Text("BASIC data").tag(1); Text("Machine language").tag(2); Text("Text").tag(3) + }.accessibilityIdentifier("disk-editor-import-type") + Picker("Encoding", selection: $request.ascii) { Text("ASCII").tag(true); Text("Binary / Tokenized").tag(false) } + .accessibilityIdentifier("disk-editor-import-encoding") + Text("Bytes are copied unchanged. Choose Binary / Tokenized for a tokenized BASIC program. These settings apply to every selected file.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + HStack { + Spacer(); Button("Cancel") { model.importing = nil }.keyboardShortcut(.cancelAction) + Button("Import") { model.confirmImport(request) }.keyboardShortcut(.defaultAction).accessibilityIdentifier("disk-editor-import-confirm") + } + }.padding(22).frame(width: 470) + } +} + +private struct DiskEditorNameSheet: View { + @ObservedObject var model: DiskImageEditorModel + @State var request: DiskEditorNameRequest + var body: some View { + VStack(alignment: .leading, spacing: 16) { + Text(request.entry == nil ? "New Folder" : "Rename Entry").font(.headline) + TextField("Name", text: $request.name).accessibilityIdentifier("disk-editor-name") + if !model.os9 { Text("Disk BASIC names use up to 8 characters plus a 3-character extension.").font(.caption).foregroundStyle(.secondary) } + HStack { + Spacer(); Button("Cancel") { model.naming = nil }.keyboardShortcut(.cancelAction) + Button(request.entry == nil ? "Create Folder" : "Rename") { model.confirmName(request) } + .keyboardShortcut(.defaultAction).accessibilityIdentifier("disk-editor-name-confirm") + .disabled(request.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + }.padding(22).frame(width: 420) + } +} diff --git a/platforms/macos/App/DisplayShader.txt b/platforms/macos/App/DisplayShader.txt new file mode 100644 index 0000000..ec0b00a --- /dev/null +++ b/platforms/macos/App/DisplayShader.txt @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include +using namespace metal; +struct RasterVertex { float4 position [[position]]; float2 uv; }; +vertex RasterVertex vccVertex(uint index [[vertex_id]]) { + const float2 positions[] = {float2(-1,-1), float2(3,-1), float2(-1,3)}; + const float2 coords[] = {float2(0,1), float2(2,1), float2(0,-1)}; + return {float4(positions[index],0,1), coords[index]}; +} +fragment float4 vccFragment(RasterVertex input [[stage_in]], texture2d frame [[texture(0)]], constant float4& region [[buffer(0)]], constant float2& effects [[buffer(1)]]) { + constexpr sampler nearest(coord::normalized, address::clamp_to_edge, filter::nearest); + // Fractional viewport edges can cover a fragment center just outside the + // picture. Clamp to active texel centers so no guest-border pixel leaks in. + const float2 halfTexel = 0.5 / float2(frame.get_width(), frame.get_height()); + const float2 uv = clamp(region.xy + input.uv * region.zw, + region.xy + halfTexel, region.xy + region.zw - halfTexel); + constexpr sampler smooth(coord::normalized, address::clamp_to_edge, filter::linear); + float3 color = effects.x > 0.5 ? frame.sample(smooth, uv).rgb : frame.sample(nearest, uv).rgb; + const uint row = uint(floor((uv.y - region.y) * frame.get_height())); + if (row & 1) color *= 1.0 - effects.y; + return float4(color, 1.0); +} diff --git a/platforms/macos/App/EmulatorDisplay.swift b/platforms/macos/App/EmulatorDisplay.swift new file mode 100644 index 0000000..841db7f --- /dev/null +++ b/platforms/macos/App/EmulatorDisplay.swift @@ -0,0 +1,266 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import MetalKit + +struct EmulatorDisplay: NSViewRepresentable { + @ObservedObject var machine: MachineModel + @ObservedObject private var preferences: DisplayPreferences + var presentationToken = "display" + init(machine: MachineModel, presentationToken: String = "display") { + self.machine = machine; self.presentationToken = presentationToken + self.preferences = machine.displayPreferences + } + func makeNSView(context: Context) -> KeyboardDisplay { + let view = KeyboardDisplay(frame: .zero, device: MTLCreateSystemDefaultDevice()) + view.machine = machine + view.input = machine.input + machine.input.acceptsInput = { [weak view] in + guard let view else { return false } + return view.inputEnabled && view.window?.isKeyWindow == true && view.window?.firstResponder === view + } + view.keyChanged = { [weak machine] in machine?.setKeyboard($0) } + view.displayFailed = { [weak machine] message in + DispatchQueue.main.async { machine?.displayError = message } + } + view.configure() + return view + } + func updateNSView(_ view: KeyboardDisplay, context: Context) { + if view.presentationToken != presentationToken { + let restoreFocus = !view.presentationToken.isEmpty && view.window?.isKeyWindow == true + view.releaseKeys(); view.presentationToken = presentationToken + if restoreFocus { DispatchQueue.main.async { view.window?.makeFirstResponder(view) } } + } + view.style = preferences.style + view.pixels = machine.pixels + #if VCC_UI_TESTING + view.setAccessibilityValue(machine.uiTestSession + ",\(view.uiTestKeyDowns),\(machine.videoOutput.rawValue)") + #endif + view.activeVideoRect = machine.activeVideoRect + view.synchronizeInput() + view.inputEnabled = machine.state == .running && !machine.busy + if view.inputEpoch != machine.inputEpoch { + view.inputEpoch = machine.inputEpoch; view.releaseKeys() + } + if view.focusRequest != machine.focusRequest { + view.focusRequest = machine.focusRequest + DispatchQueue.main.async { view.window?.makeFirstResponder(view) } + } + view.requestFrame() + } + static func dismantleNSView(_ view: KeyboardDisplay, coordinator: ()) { view.releaseKeys() } +} + +final class KeyboardDisplay: MTKView, MTKViewDelegate, NSUserInterfaceValidations { + weak var machine: MachineModel? + @objc func copy(_ sender: Any?) { machine?.copyScreenText() } + @objc func paste(_ sender: Any?) { machine?.pasteClipboard() } + func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool { + if item.action == #selector(paste(_:)) { return machine?.canPaste == true } + if item.action == #selector(copy(_:)) { return machine.map { !$0.busy && ($0.state == .running || $0.state == .paused) } ?? false } + return false + } + + #if VCC_UI_TESTING + private(set) var uiTestKeyDowns: UInt64 = 0 + #endif + var presentationToken = "" + var pixels: Data? + var activeVideoRect = VideoGeometry.fullFrame + var style = DisplayStyle() + var inputEnabled = false { + didSet { if !inputEnabled && oldValue { releaseKeys() } } + } + var inputEpoch: UInt64 = 0, focusRequest: UInt64 = 0 + var keyChanged: ((UInt64) -> Void)? + var displayFailed: ((String) -> Void)? + var input: InputHub? + private var settingsEpoch: UInt64 = .max + private var tracking: NSTrackingArea? + private var capsRelease: DispatchWorkItem? + private var keyboard = CocoKeyboard() + func synchronizeInput() { + if settingsEpoch != input?.epoch { + settingsEpoch = input?.epoch ?? 0 + releaseKeys(); keyboard.mode = input?.settings.keyboard ?? .natural + } + } + private var renderer: MetalRenderer? + private var frameRequested = false + private(set) var submittedFrames: UInt64 = 0 + + // SwiftUI can keep a Metal view layer-backed without servicing AppKit's + // needsDisplay invalidation. In that state Core Animation stretches the last + // presented drawable as the view resizes, even while the guest keeps running. + // Drive MTKView's explicit draw path instead; coalesce updates on the main + // queue so drawing never reenters a SwiftUI update or drawable-size callback. + func requestFrame() { + guard !frameRequested else { return } + frameRequested = true + DispatchQueue.main.async { [weak self] in + guard let self else { return } + self.frameRequested = false + guard self.window?.isVisible == true, !self.isHiddenOrHasHiddenAncestor, + self.bounds.width > 0, self.bounds.height > 0 else { return } + self.draw() + } + } + override func layout() { super.layout(); requestFrame() } + override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); requestFrame() } + override func viewDidChangeBackingProperties() { super.viewDidChangeBackingProperties(); requestFrame() } + private var focusObservers: [NSObjectProtocol] = [] + override var acceptsFirstResponder: Bool { true } + override func accessibilityFrame() -> NSRect { + guard let window else { return super.accessibilityFrame() } + return window.convertToScreen(convert(bounds, to: nil)) + } + func configure() { + colorPixelFormat = .bgra8Unorm + isPaused = true; enableSetNeedsDisplay = false; framebufferOnly = true + autoResizeDrawable = true; delegate = self + setAccessibilityElement(true) + setAccessibilityEnabled(true) + setAccessibilityRole(.group) + setAccessibilityRoleDescription("Emulator display") + setAccessibilityLabel("CoCo display") + setAccessibilityIdentifier("coco-display") + setAccessibilityHelp("Click here or press Option-Command-K to type into the CoCo. Option-Command-U returns to Mac controls. Escape is Break, Home is Clear. Guest graphics are not available as accessible text.") + do { + guard let device else { throw MetalRenderer.Failure.unavailable } + renderer = try MetalRenderer(device: device, library: MetalRenderer.library(device: device, bundle: Bundle(for: KeyboardDisplay.self))) + } catch { displayFailed?(error.localizedDescription) } + focusObservers.append(NotificationCenter.default.addObserver(forName: NSApplication.didResignActiveNotification, + object: nil, queue: .main) { [weak self] _ in self?.releaseKeys() }) + focusObservers.append(NotificationCenter.default.addObserver(forName: NSWindow.didResignKeyNotification, + object: nil, queue: .main) { [weak self] note in + if let window = note.object as? NSWindow, window === self?.window { self?.releaseKeys() } + }) + } + deinit { for observer in focusObservers { NotificationCenter.default.removeObserver(observer) } } + override func updateTrackingAreas() { + super.updateTrackingAreas() + if let tracking { removeTrackingArea(tracking) } + let area = NSTrackingArea(rect: bounds, options: [.mouseMoved, .mouseEnteredAndExited, .activeInKeyWindow, .inVisibleRect], owner: self) + addTrackingArea(area); tracking = area + } + private func moveMouse(_ event: NSEvent) { + guard inputEnabled, window?.firstResponder === self else { return } + let point = convert(event.locationInWindow, from:nil) + guard let normalized = VideoGeometry.mouse(point,in:bounds.size,source:activeVideoRect,scaling:style.scaling,drawableSize:drawableSize) else { + input?.mouseLeave(); return + } + input?.mouseMove(x:normalized.x,y:normalized.y) + } + override func mouseMoved(with event: NSEvent) { moveMouse(event) } + override func mouseDragged(with event: NSEvent) { moveMouse(event) } + override func rightMouseDragged(with event: NSEvent) { moveMouse(event) } + override func mouseExited(with event: NSEvent) { input?.mouseLeave() } + override func mouseDown(with event: NSEvent) { + window?.makeFirstResponder(self); moveMouse(event) + if inputEnabled { input?.mouseButton(0, down: true) } + } + override func mouseUp(with event: NSEvent) { input?.mouseButton(0, down: false) } + override func rightMouseDown(with event: NSEvent) { + window?.makeFirstResponder(self); moveMouse(event) + if inputEnabled { input?.mouseButton(1, down: true) } + } + override func rightMouseUp(with event: NSEvent) { input?.mouseButton(1, down: false) } + override func resignFirstResponder() -> Bool { releaseKeys(); return super.resignFirstResponder() } + func releaseKeys() { capsRelease?.cancel(); keyboard.releaseAll(); keyChanged?(0); input?.release() } + private func updateModifiers(_ event: NSEvent) { + keyboard.modifiers(shift: event.modifierFlags.contains(.shift), + control: event.modifierFlags.contains(.control), alt: event.modifierFlags.contains(.option)) + } + override func flagsChanged(with event: NSEvent) { + guard inputEnabled, !event.modifierFlags.contains(.command) else { releaseKeys(); return } + synchronizeInput(); updateModifiers(event) + if event.keyCode == 57 { + keyboard.press(code: 57, characters: "") + capsRelease?.cancel() + let release = DispatchWorkItem { [weak self] in + guard let self else { return }; self.keyboard.release(code: 57); self.keyChanged?(self.keyboard.mask) + } + capsRelease = release; DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: release) + } + keyChanged?(keyboard.mask) + } + override func keyDown(with event: NSEvent) { + guard inputEnabled, !event.modifierFlags.contains(.command) else { releaseKeys(); super.keyDown(with: event); return } + guard !event.isARepeat else { return } + synchronizeInput() + if input?.key(event.keyCode, down: true) == true { return } + updateModifiers(event) + let modified = event.modifierFlags.intersection([.control, .option]).isEmpty + ? event.characters : event.charactersIgnoringModifiers + keyboard.press(code: event.keyCode, characters: modified ?? "") + #if VCC_UI_TESTING + if keyboard.mask != 0 { uiTestKeyDowns += 1 } + #endif + keyChanged?(keyboard.mask) + } + override func keyUp(with event: NSEvent) { + _ = input?.key(event.keyCode, down: false) + keyboard.release(code: event.keyCode); keyChanged?(keyboard.mask) + } + func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { requestFrame() } + func draw(in view: MTKView) { + guard let renderer, let drawable = currentDrawable else { return } + do { + let scale = bounds.width > 0 ? CGFloat(drawable.texture.width)/bounds.width : 1 + if try renderer.encode(pixels:pixels,target:drawable.texture,drawable:drawable,activeArea:activeVideoRect,inset:VideoGeometry.border*scale,style:style) != nil { + submittedFrames &+= 1 + } + } + catch { displayFailed?(error.localizedDescription) } + } +} + +// Shared with native menus; observes only user-driven appearance changes. +struct DisplayAppearanceControls: View { + @ObservedObject var preferences: DisplayPreferences + var body: some View { + Picker("Scaling", selection: $preferences.style.scaling) { + ForEach(DisplayScaling.allCases, id: \.self) { Text($0.label).tag($0) } + }.accessibilityIdentifier("display-scaling") + Toggle("Scanlines", isOn: $preferences.style.scanlines).accessibilityIdentifier("display-scanlines") + } +} + +struct DisplayControlsView: View { + let machine: MachineModel + @ObservedObject private var menu: MachineMenuState + init(machine: MachineModel) { self.machine = machine; self.menu = machine.menuState } + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 16) { + SecondaryHeader(title: "Display Settings", symbol: "display", subtitle: "Adjust the picture without restarting your CoCo.") + SecondaryCard { + Label("Video Signal", systemImage: "cable.connector").font(.headline) + Picker("Video Signal", selection: Binding(get: { menu.values.videoOutput }, set: machine.setVideoOutput)) { + ForEach(DisplayOutput.allCases, id: \.self) { Text($0.label).tag($0) } + }.disabled(menu.values.busy || menu.values.state == .closed) + Text("Composite TV reproduces the artifact colors used by many CoCo games. RGB provides a direct monitor signal.") + .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + SecondaryCard { + Label("Appearance", systemImage: "slider.horizontal.3").font(.headline) + DisplayAppearanceControls(preferences: machine.displayPreferences) + SecondaryHelp(title: "How scaling works") { + Text("Sharp and Smooth use the largest picture that fits while preserving its proportions. Integer Pixels keeps exact whole-pixel multiples and can leave a large dark-green border, including inside the expanded monitor. Choose Sharp — Fit Window to use more of the screen. If even 1× cannot fit, Integer Pixels fits proportionally instead. Scanlines fade out at small sizes to keep the picture readable.") + Text("These choices are remembered for this Mac and apply to Display, System and the expanded monitor. They do not change machine profiles.") + }.accessibilityIdentifier("display-scaling-help") + SecondaryAction(title: "Reset Display Appearance", systemImage: "arrow.counterclockwise") { + machine.displayPreferences.style = DisplayStyle() + } + } + SecondaryCard { + Label("Screenshot", systemImage: "camera").font(.headline) + Text("Save the active picture as a PNG at native resolution, without the surrounding window or display effects.") + .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + SecondaryAction(title: "Save CoCo Screen…", systemImage: "square.and.arrow.up", action: machine.saveScreenshot) + .disabled(menu.values.busy || !(menu.values.state == .running || menu.values.state == .paused)) + } + }.padding(24).frame(maxWidth: 600, alignment: .leading) + }.frame(minWidth: 520, minHeight: 500) + } +} diff --git a/platforms/macos/App/GraphicsPreviewModel.swift b/platforms/macos/App/GraphicsPreviewModel.swift new file mode 100644 index 0000000..7a8b6b9 --- /dev/null +++ b/platforms/macos/App/GraphicsPreviewModel.swift @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import Combine + +@MainActor +final class GraphicsPreviewModel: ObservableObject { + enum Source: String, CaseIterable { case current = "Current Video Page", address = "At Address" } + enum Mode: Int, CaseIterable { + case sg4, pmode0, pmode1, pmode2, pmode3, pmode4, hscreen1, hscreen2, hscreen3, hscreen4 + var label: String { + if self == .sg4 { return "Text / SG4" } + if rawValue <= Self.pmode4.rawValue { return "PMODE \(rawValue - 1)" } + return "HSCREEN \(rawValue - 5)" + } + var supportsColorSet: Bool { rawValue >= Self.pmode0.rawValue && rawValue <= Self.pmode4.rawValue } + } + struct Request: Equatable { + var source = Source.current + var physical = false + var address: UInt32 = 0x0e00 + var mode = Mode.pmode1 + var alternate = false + } + struct Pixel: Equatable { var x = 0; var y = 0 } + struct Frame { + let capture: VCCDebugGraphicsCapture + let image: CGImage + let highlights: CGImage? + let changes: Int? + } + @Published var request = Request() + @Published var addressText = "0E00" + @Published var addressError: String? + @Published private(set) var frame: Frame? + @Published private(set) var error: String? + @Published var selection = Pixel() + private var epoch: UInt64 = 0 + + func readyToStep(machine: MachineModel) -> Bool { + if error != nil { return true } + guard let snapshot = frame?.capture.machine else { return false } + return snapshot.state == .paused && snapshot.generation == machine.basicDebug.generation && + snapshot.cycles == machine.basicDebug.cycles + } + + func inspectAddress(_ address: UInt32, physical: Bool) { + addressText = DebuggerModel.hex(address, width: physical ? 6 : 4) + addressError = nil + request.physical = physical + request.address = address + request.source = .address + } + + func applyAddress() { + guard let value = DebuggerModel.hexadecimalAddress(addressText, maximum: request.physical ? 0x7fffff : 0xffff) else { + addressError = request.physical ? "Enter a physical address from $000000 to $7FFFFF." : "Enter a CPU address from $0000 to $FFFF." + return + } + inspectAddress(value, physical: request.physical) + } + + private static func image(_ rgba: Data, width: Int, height: Int) -> CGImage? { + guard width > 0, height > 0, rgba.count == width * height * 4, + let provider = CGDataProvider(data: rgba as CFData) else { return nil } + return CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, + bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue), + provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent) + } + + // A translucent overlay preserves the colors underneath. Work is bounded + // by one native raster and is only performed for an observed single step. + static func differences(_ before: Data, _ after: Data) -> (Data, Int) { + guard before.count == after.count, after.count.isMultiple(of: 4) else { return (Data(), 0) } + var mask = Data(count: after.count) + var changes = 0 + before.withUnsafeBytes { (old: UnsafeRawBufferPointer) in + after.withUnsafeBytes { (new: UnsafeRawBufferPointer) in + mask.withUnsafeMutableBytes { (out: UnsafeMutableRawBufferPointer) in + for i in stride(from: 0, to: new.count, by: 4) { + if old[i] != new[i] || old[i+1] != new[i+1] || old[i+2] != new[i+2] || old[i+3] != new[i+3] { + out[i] = 255; out[i+1] = 94; out[i+2] = 190; out[i+3] = 210 + changes += 1 + } + } + } + } + } + return (mask, changes) + } + + func poll(machine: MachineModel) async { + let intent = request + epoch &+= 1 + let token = epoch + frame = nil + error = nil + var lastRead: (epoch: UInt64, snapshot: VCCMachineSnapshot)? + while !Task.isCancelled, token == epoch, intent == request { + // Repeated polling of an unchanged paused machine needs no extra + // bitmap. Commands increment inputEpoch, including paused RAM edits. + if machine.canQuickLoad, machine.state == .running || lastRead?.snapshot.state != .paused || + lastRead?.epoch != machine.inputEpoch || lastRead?.snapshot.cycles != machine.basicDebug.cycles || + lastRead?.snapshot.generation != machine.basicDebug.generation { + let inputEpoch = machine.inputEpoch + let sample = await machine.readGraphicsPreview(currentPage: intent.source == .current, + address: intent.address, physical: intent.physical, mode: intent.mode.rawValue, + alternatePalette: intent.mode.supportsColorSet && intent.alternate) + guard !Task.isCancelled, epoch == token, request == intent else { return } + if let sample, inputEpoch == machine.inputEpoch, sample.machine.generation == machine.basicDebug.generation { + lastRead = (inputEpoch, sample.machine) + accept(sample, step: machine.lastDebuggerStep) + } + } + do { try await Task.sleep(for: .milliseconds(250)) } catch { return } + } + } + + private func accept(_ sample: VCCDebugGraphicsCapture, step: (generation: UInt64, before: UInt64, after: UInt64)?) { + if let message = sample.errorMessage { + error = message; frame = nil + return + } + guard let bitmap = Self.image(sample.rgba, width: sample.width, height: sample.height) else { + error = "This page could not be rendered."; frame = nil + return + } + var highlights: CGImage? + var changes: Int? + if let previous = frame, let step, previous.capture.machine.state == .paused, sample.machine.state == .paused, + sample.machine.generation == step.generation, sample.machine.cycles == step.after, + previous.capture.machine.cycles == step.before, sample.hasSameLayout(as: previous.capture) { + let (mask, count) = Self.differences(previous.capture.rgba, sample.rgba) + changes = count + if count > 0 { highlights = Self.image(mask, width: sample.width, height: sample.height) } + } + if selection.x >= sample.width || selection.y >= sample.height { selection = Pixel() } + error = nil + frame = Frame(capture: sample, image: bitmap, highlights: highlights, changes: changes) + } +} diff --git a/platforms/macos/App/GraphicsPreviewView.swift b/platforms/macos/App/GraphicsPreviewView.swift new file mode 100644 index 0000000..b7de343 --- /dev/null +++ b/platforms/macos/App/GraphicsPreviewView.swift @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI + +struct GraphicsPreviewView: View { + @ObservedObject var model: GraphicsPreviewModel + let machine: MachineModel + let showMemory: (UInt32, Bool) -> Void + @State private var zoom = 0 + @State private var showChanges = true + @State private var pixelX = "0" + @State private var pixelY = "0" + @State private var pointError: String? + + var body: some View { + VStack(spacing: 0) { + HStack { + Picker("Preview source", selection: $model.request.source) { + ForEach(GraphicsPreviewModel.Source.allCases, id: \.self) { Text($0.rawValue).tag($0) } + }.pickerStyle(.segmented).labelsHidden().frame(width: 250) + .accessibilityIdentifier("graphics-source") + Spacer() + Picker("Zoom", selection: $zoom) { + Text("Fit").tag(0) + ForEach([1, 2, 3, 4], id: \.self) { Text("\($0)×").tag($0) } + }.frame(width: 120).accessibilityIdentifier("graphics-zoom") + }.padding(.horizontal, 16).padding(.vertical, 10) + if model.request.source == .address { addressControls } + Divider() + if let frame = model.frame { + HStack(spacing: 0) { + viewport(frame) + Divider() + inspector(frame).frame(width: 220) + } + } else { + VStack(spacing: 10) { + if let error = model.error { + Image(systemName: "rectangle.slash").font(.title).foregroundStyle(.secondary) + Text(error).multilineTextAlignment(.center) + } else { ProgressView().controlSize(.small).accessibilityLabel("Reading graphics memory") } + }.padding().frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + .task(id: model.request) { await model.poll(machine: machine) } + .onChange(of: model.selection, initial: true) { _, point in + pixelX = String(point.x); pixelY = String(point.y); pointError = nil + } + } + + private var addressControls: some View { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 10) { + Picker("Address space", selection: $model.request.physical) { + Text("Mapped CPU").tag(false) + Text("Physical RAM").tag(true) + }.labelsHidden().fixedSize().accessibilityIdentifier("graphics-space") + TextField("Hex address", text: $model.addressText).frame(width: 82) + .textFieldStyle(.roundedBorder).font(.system(.body, design: .monospaced)) + .onSubmit { model.applyAddress() }.accessibilityLabel("Start address in hexadecimal") + .accessibilityIdentifier("graphics-address") + Button("Go", action: model.applyAddress).accessibilityIdentifier("graphics-go") + Divider().frame(height: 18) + Picker("Mode", selection: $model.request.mode) { + ForEach(GraphicsPreviewModel.Mode.allCases, id: \.self) { Text($0.label).tag($0) } + }.frame(width: 160).accessibilityIdentifier("graphics-mode") + if model.request.mode.supportsColorSet { + Picker("Colors", selection: $model.request.alternate) { + Text("Set 0").tag(false) + Text("Set 1").tag(true) + }.frame(width: 130).accessibilityIdentifier("graphics-palette") + } + Spacer() + } + if let error = model.addressError { + Text(error).font(.caption).foregroundStyle(.red) + } + }.padding(.horizontal, 16).padding(.bottom, 10) + } + + private func viewport(_ frame: GraphicsPreviewModel.Frame) -> some View { + GeometryReader { bounds in + let width = CGFloat(frame.capture.width), height = CGFloat(frame.capture.height) + let availableScale = min(max(1, bounds.size.width - 24) / width, max(1, bounds.size.height - 24) / height) + let fit = availableScale >= 1 ? floor(availableScale) : availableScale + let scale = zoom == 0 ? fit : CGFloat(zoom) + ScrollView([.horizontal, .vertical]) { + ZStack(alignment: .topLeading) { + Image(decorative: frame.image, scale: 1).interpolation(.none).resizable() + if showChanges, let mask = frame.highlights { + Image(decorative: mask, scale: 1).interpolation(.none).resizable() + } + let size = max(7, scale) + Rectangle().strokeBorder(.white, lineWidth: 2) + .overlay(Rectangle().strokeBorder(.black, lineWidth: 1)) + .frame(width: size, height: size) + .position(x: (CGFloat(model.selection.x)+0.5)*scale, y: (CGFloat(model.selection.y)+0.5)*scale) + .allowsHitTesting(false) + } + .frame(width: width*scale, height: height*scale).clipped() + .contentShape(Rectangle()) + .onTapGesture { point in + model.selection = .init(x: min(Int(width)-1, max(0, Int(point.x / scale))), + y: min(Int(height)-1, max(0, Int(point.y / scale)))) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel("Graphics memory image, \(frame.capture.width) by \(frame.capture.height) pixels") + .accessibilityHint("Use the X and Y fields in Pixel Inspector to select a pixel.") + .accessibilityIdentifier("graphics-raster") + .padding(12) + .frame(minWidth: bounds.size.width, minHeight: bounds.size.height) + }.background(Color(nsColor: .underPageBackgroundColor)) + } + } + + private func inspector(_ frame: GraphicsPreviewModel.Frame) -> some View { + let capture = frame.capture + let width = capture.physical ? 6 : 4 + let pixel = capture.pixel(x: model.selection.x, y: model.selection.y) + return ScrollView { + VStack(alignment: .leading, spacing: 14) { + VStack(alignment: .leading, spacing: 5) { + Text(capture.modeName).font(.headline) + Text("\(capture.width) × \(capture.height) pixels") + Text((capture.physical ? "Physical RAM" : "Mapped CPU") + " · $" + DebuggerModel.hex(capture.address, width: width)) + .font(.caption).foregroundStyle(.secondary).textSelection(.enabled) + } + Divider() + Label("Pixel Inspector", systemImage: "scope").font(.headline) + HStack(spacing: 6) { + Text("X") + TextField("X", text: $pixelX).accessibilityIdentifier("graphics-x") + Text("Y") + TextField("Y", text: $pixelY).accessibilityIdentifier("graphics-y") + Button { select(capture) } label: { Image(systemName: "return") } + .help("Inspect the pixel at the entered X and Y coordinates").accessibilityLabel("Inspect pixel").accessibilityIdentifier("graphics-inspect") + }.textFieldStyle(.roundedBorder).onSubmit { select(capture) } + if let pointError { Text(pointError).font(.caption).foregroundStyle(.red) } + if let pixel { + Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 7) { + GridRow { + Text("Address") + Text("$" + DebuggerModel.hex(pixel.address, width: width)).accessibilityIdentifier("graphics-byte-address") + } + if pixel.available { + GridRow { Text("Byte"); Text("$" + DebuggerModel.hex(pixel.value, width: 2)) } + GridRow { Text("Bit mask"); Text("$" + DebuggerModel.hex(pixel.mask, width: 2)) } + } + }.monospacedDigit().textSelection(.enabled) + if !pixel.available { Text("This byte is unavailable.").font(.caption).foregroundStyle(.secondary) } + if let address = pixel.attributeAddress, let value = pixel.attributeValue { + Text("Attribute $\(DebuggerModel.hex(value.uint8Value, width: 2)) at $\(DebuggerModel.hex(address.uint32Value, width: width))") + .font(.caption).textSelection(.enabled) + } + Button { showMemory(pixel.address, capture.physical) } label: { + Label("Show Byte in Memory", systemImage: "memorychip") + }.disabled(!pixel.available).accessibilityIdentifier("graphics-reveal") + } + Divider() + Toggle("Highlight step changes", isOn: $showChanges).toggleStyle(.checkbox) + if let changes = frame.changes { + Text("\(changes.formatted()) \(changes == 1 ? "pixel" : "pixels") changed") + .font(.caption).foregroundStyle(.secondary).accessibilityIdentifier("graphics-changes") + } + }.padding(16).frame(maxWidth: .infinity, alignment: .leading) + } + } + + private func select(_ capture: VCCDebugGraphicsCapture) { + guard let x = Int(pixelX), let y = Int(pixelY), (0.. Void + @Environment(\.dismiss) private var dismiss + @State private var size: String + init(machine: MachineModel, drive: Int, initialSize: Int, create: @escaping (Int) -> Void) { + self.machine = machine; self.drive = drive; self.create = create + _size = State(initialValue: String(initialSize)) + } + private var parsedSize: Int? { + let value = size.trimmingCharacters(in: .whitespacesAndNewlines) + guard !value.isEmpty, value.allSatisfy({ $0.isASCII && $0.isNumber }), let number = Int(value), (1...524288).contains(number) else { return nil } + return number + } + private var canCreate: Bool { + parsedSize != nil && !machine.busy && !machine.diskSaving && machine.state != .closed + && machine.hardDisks.indices.contains(drive) && !machine.hardDisks[drive].dirty + } + var body: some View { + VStack(alignment: .leading, spacing: 18) { + Label("New disk in HD\(drive)", systemImage: "doc.badge.plus").font(.title2) + Text("Creates a blank in-memory image in this drive. Any currently mounted image is replaced; its Mac file is kept.") + .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + HStack { + Text("Capacity (KiB)") + TextField("132480", text: $size).frame(width: 130) + .accessibilityLabel("New hard disk size in KiB").accessibilityIdentifier("new-hard-disk-size") + Text("1–524,288 KiB").font(.caption).foregroundStyle(.secondary) + } + Text(parsedSize == nil ? "Enter a whole number from 1 through 524288." : "132480 KiB is the conventional VCC image size.") + .font(.caption).foregroundStyle(parsedSize == nil ? Color.orange : Color.secondary) + .frame(minHeight: 16, alignment: .leading) + Label("Format or partition the disk in the CoCo, then use Save As to keep it. No operating system is installed.", systemImage: "info.circle") + .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + HStack { + Spacer() + Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction) + Button { if let value = parsedSize, canCreate { dismiss(); create(value) } } label: { Label("Create Disk", systemImage: "doc.badge.plus") } + .keyboardShortcut(.defaultAction).disabled(!canCreate) + .accessibilityIdentifier("create-hard-disk-confirm") + } + }.padding(24).frame(width: 470) + } +} + +private struct HardDiskDriveRow: View { + @ObservedObject var machine: MachineModel + let index: Int + let disk: VCCDiskSnapshot + let newDisk: () -> Void + @State private var options = false + private var assigned: Bool { disk.mounted || machine.hardSettings.drives[index] != nil } + private var manualSave: Bool { + disk.dirty && (machine.hardTemporary[index] || machine.hardSettings.drives[index] == nil || disk.writeProtected || disk.sourceReadOnly) + } + private var mode: String { + if disk.writeProtected { return "Write protected" } + if machine.hardTemporary[index] { return "Temporary changes" } + return machine.hardSettings.drives[index] == nil ? "No backing file · Use Save As" : "Saves automatically" + } + private var capacity: String { + let bytes = Double(disk.byteCount) + return bytes >= 1048576 ? String(format: "%.1f MiB", bytes / 1048576) : String(format: "%.0f KiB", bytes / 1024) + } + var body: some View { + SecondaryCard { + VStack(alignment: .leading, spacing: 12) { + HStack(spacing: 14) { + MediaDriveIdentity(name: "HD\(index)", mounted: disk.mounted) + VStack(alignment: .leading, spacing: 4) { + Text(disk.mounted ? disk.name : machine.hardSettings.drives[index]?.url.lastPathComponent ?? "No disk inserted") + .fontWeight(.semibold).lineLimit(1).truncationMode(.middle) + Text(disk.mounted ? "\(capacity) · \(mode)" : assigned ? "Unavailable — reconnect or replace the file" : "Insert an image or create a blank disk") + .font(.caption).foregroundStyle(assigned && !disk.mounted ? Color.orange : Color.secondary) + .fixedSize(horizontal: false, vertical: true) + }.frame(maxWidth: .infinity, alignment: .leading) + SecondaryAction(title: assigned ? "Replace…" : "Insert…", systemImage: "folder") { machine.openHardDisk(index) } + .disabled(disk.dirty).accessibilityLabel("Insert hard disk \(index)") + if disk.mounted { + SecondaryAction(title: "Edit…", systemImage: "pencil") { + DiskImageEditorCoordinator.shared.editHardDisk(index, machine: machine) + }.accessibilityLabel("Edit hard disk \(index)").accessibilityIdentifier("hard-disk-edit-\(index)") + .disabled(machine.diskEditorLocked) + } + if assigned { + SecondaryAction(title: "Eject", systemImage: "eject") { machine.ejectHardDisk(index) } + .disabled(disk.dirty).accessibilityLabel("Eject hard disk \(index)") + } else { + SecondaryAction(title: "New…", systemImage: "doc.badge.plus", action: newDisk) + .disabled(disk.dirty).accessibilityLabel("New hard disk \(index)") + } + } + if disk.mounted { + HStack { + DisclosureGroup(isExpanded: $options) { EmptyView() } label: { Text("Disk options").font(.callout) } + .accessibilityIdentifier("hard-disk-options-\(index)") + Spacer() + actions + } + if options { + HStack(spacing: 24) { + Toggle("Write protected", isOn: Binding(get: { disk.writeProtected }, set: { machine.setHardProtection(index, $0) })) + .disabled(disk.sourceReadOnly).accessibilityLabel("Write protect hard disk \(index)") + .help(disk.sourceReadOnly ? "The source file is read-only. Reopen a writable copy to enable writes." : "Prevent the CoCo from changing this image.") + Toggle("Temporary changes", isOn: Binding(get: { machine.hardTemporary[index] }, set: { machine.setHardTemporary(index, $0) })) + .accessibilityLabel("Temporary changes in hard disk \(index)") + Spacer(minLength: 0) + }.font(.callout) + Text("\(disk.byteCount / 256) sectors · Temporary changes stay in memory. Turning this off allows pending changes to save. Save As retains this mode.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + if manualSave { + HStack { + Label("Unsaved changes · Save As to keep them", systemImage: "exclamationmark.circle").foregroundStyle(.orange) + Spacer() + SecondaryAction(title: "Save As…", systemImage: "square.and.arrow.up") { machine.exportHardDisk(index) } + .accessibilityLabel("Save hard disk \(index) as") + }.font(.callout).frame(minHeight: 24) + } + } + if let error = machine.hardRestoreErrors[index] { Text(error).font(.callout).foregroundStyle(.red).textSelection(.enabled) } + if let error = machine.hardSaveErrors[index] { + Text(error).font(.callout).foregroundStyle(.red).textSelection(.enabled) + SecondaryAction(title: "Retry Save", systemImage: "arrow.clockwise") { machine.retryHardSave(index) } + .disabled(disk.writeProtected || machine.hardTemporary[index]).accessibilityLabel("Retry saving hard disk \(index)") + } + } + }.modifier(MediaDropTarget(machine: machine, destination: .hardDisk(index))) + } + private var actions: some View { + Menu { + Button { machine.exportHardDisk(index) } label: { Label("Save As…", systemImage: "square.and.arrow.up") } + .disabled(!disk.mounted).accessibilityLabel("Save hard disk \(index) as") + Button(action: newDisk) { Label("New Disk…", systemImage: "doc.badge.plus") } + .disabled(disk.dirty).accessibilityLabel("New hard disk \(index)") + if manualSave || machine.hardSaveErrors[index] != nil { + Divider() + Button { machine.ejectHardDisk(index, discard: true) } label: { Label("Discard Changes and Eject…", systemImage: "eject") } + .accessibilityLabel("Discard hard disk \(index) changes") + } + } label: { Label("Actions", systemImage: "ellipsis.circle") } + .fixedSize().accessibilityIdentifier("hard-disk-actions-\(index)") + } +} diff --git a/platforms/macos/App/HardDiskFiles.swift b/platforms/macos/App/HardDiskFiles.swift new file mode 100644 index 0000000..cdf89e0 --- /dev/null +++ b/platforms/macos/App/HardDiskFiles.swift @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import CryptoKit + +enum HardDiskFiles { + static let limit = 512 * 1024 * 1024 + struct Image: Sendable { let data: Data; let readOnly: Bool; let digest: String } + enum Failure: LocalizedError { + case format, changed, readOnly, patch + var errorDescription: String? { + switch self { + case .format: return "Choose a raw VHD, OS9 or IMG file containing whole 256-byte sectors, from 256 bytes to 512 MiB. PC virtual-machine VHD containers are not supported." + case .changed: return "The hard disk changed outside this drive. Use Save As to keep your changes separately, or reinsert the image." + case .readOnly: return "The hard disk file is no longer writable. Restore write access and retry, or use Save As." + case .patch: return "Invalid hard disk save snapshot. Your in-memory changes are retained." + } + } + } + private struct Stamp: Equatable { + let size: UInt64, inode: UInt64 + let modified: Date + } + private static func stamp(_ url: URL) throws -> Stamp { + let attributes = try FileManager.default.attributesOfItem(atPath: url.path) + guard attributes[.type] as? FileAttributeType == .typeRegular, + let size = attributes[.size] as? NSNumber, let inode = attributes[.systemFileNumber] as? NSNumber, + let modified = attributes[.modificationDate] as? Date, + size.uint64Value > 0, size.uint64Value <= limit, size.uint64Value % 256 == 0 else { throw Failure.format } + return Stamp(size: size.uint64Value, inode: inode.uint64Value, modified: modified) + } + static func digest(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() } + private static func digestFile(_ url: URL) throws -> String { + let file = try FileHandle(forReadingFrom: url); defer { try? file.close() } + var hash = SHA256(); var count = 0 + while let data = try file.read(upToCount: 1024 * 1024), !data.isEmpty { + count += data.count; guard count <= limit else { throw Failure.format }; hash.update(data: data) + } + return hash.finalize().map { String(format: "%02x", $0) }.joined() + } + static func readImage(_ selected: URL) throws -> Image { + guard ["vhd", "os9", "img"].contains(selected.pathExtension.lowercased()) else { throw Failure.format } + let url = selected.resolvingSymlinksInPath(); let before = try stamp(url) + let file = try FileHandle(forReadingFrom: url); defer { try? file.close() } + var data = Data(); data.reserveCapacity(Int(before.size)) + while let chunk = try file.read(upToCount: min(1024 * 1024, limit + 1 - data.count)), !chunk.isEmpty { + data.append(chunk); guard data.count <= limit else { throw Failure.format } + } + guard data.count == before.size, before == (try stamp(url)) else { throw Failure.changed } + // Microsoft VHD uses a footer; these extensions mean raw sector images here. + if data.count >= 512 && data.suffix(512).starts(with: Data("conectix".utf8)) { throw Failure.format } + return Image(data: data, readOnly: !FileManager.default.isWritableFile(atPath: url.path), digest: digest(data)) + } + static func export(_ data: Data, to url: URL) throws -> String { + guard !data.isEmpty, data.count <= limit, data.count % 256 == 0 else { throw Failure.format } + try data.write(to: url, options: .atomic); return digest(data) + } + // Copy-on-write filesystem copies keep normal saves small on APFS. Hash the + // entire source to detect external edits, apply only captured dirty sectors, + // then atomically replace it. No host file I/O runs on the emulation queue. + static func saveAutomatically(_ patches: Data, length: Int, to url: URL, expected: String) throws -> String { + guard length > 0, length <= limit, length % 256 == 0, patches.count % 260 == 0 else { throw Failure.patch } + var coordinationError: NSError?, writeError: Error?, result: String? + NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &coordinationError) { target in + let temporary = target.deletingLastPathComponent().appendingPathComponent(".vcc-\(UUID().uuidString).tmp") + defer { try? FileManager.default.removeItem(at: temporary) } + do { + let before = try stamp(target) + guard length >= before.size else { throw Failure.patch } + guard FileManager.default.isWritableFile(atPath: target.path) else { throw Failure.readOnly } + try FileManager.default.copyItem(at: target, to: temporary) + guard try digestFile(temporary) == expected else { throw Failure.changed } + let file = try FileHandle(forWritingTo: temporary) + do { + try file.truncate(atOffset: UInt64(length)) + for offset in stride(from: 0, to: patches.count, by: 260) { + let sector = (0..<4).reduce(UInt32(0)) { $0 | (UInt32(patches[offset + $1]) << (8 * $1)) } + let position = UInt64(sector) * 256 + guard position + 256 <= length else { throw Failure.patch } + try file.seek(toOffset: position); try file.write(contentsOf: patches[(offset + 4)..<(offset + 260)]) + } + try file.synchronize(); try file.close() + } catch { try? file.close(); throw error } + let next = try digestFile(temporary) + guard before == (try stamp(target)) else { throw Failure.changed } + guard FileManager.default.isWritableFile(atPath: target.path) else { throw Failure.readOnly } + _ = try FileManager.default.replaceItemAt(target, withItemAt: temporary) + result = next + } catch { writeError = error } + } + if let error = coordinationError { throw error } + if let error = writeError { throw error } + guard let result else { throw Failure.patch }; return result + } +} diff --git a/platforms/macos/App/HardwarePresentation.swift b/platforms/macos/App/HardwarePresentation.swift new file mode 100644 index 0000000..b9968ea --- /dev/null +++ b/platforms/macos/App/HardwarePresentation.swift @@ -0,0 +1,260 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import SwiftUI + +// Guest events only. A brief hold makes transfers between UI polls visible; +// pausing consumes counters and clears the hold immediately. +struct ActivityTracker { + enum State: String { case empty, loaded, read, write } + private var previous: (UInt64, UInt64)? + private var until: Double = 0 + private var held = State.loaded + mutating func update(reads: UInt64, writes: UInt64, mounted: Bool, running: Bool, now: Double) -> State { + defer { previous = (reads, writes) } + guard mounted, running else { until = 0; held = .loaded; return mounted ? .loaded : .empty } + if let previous, reads < previous.0 || writes < previous.1 { until = 0; held = .loaded } + else if let previous, writes > previous.1 { held = .write; until = now + 0.16 } + else if let previous, reads > previous.0 { + if held != .write || now >= until { held = .read; until = now + 0.16 } + } + return now < until ? held : .loaded + } +} + +struct HardwareState: Equatable { + var values: [String: String] = ["scene":"on", "mpi":"off", "ram":"512kb", "cpu":"6809", "startup":"4", "floppy":"off", "hard":"off", "floppyCase":"off", "hardCase":"off", "tape":"empty", "tapeActivity":"empty", "printerPower":"off", "printerPaper":"blank", "sdcActivity":"empty"] + var custom = false + var activities = Array(repeating: ActivityTracker.State.empty, count: 7) + static let ramKeys = ["128kb", "512kb", "2mb", "8mb"] + init() { + for n in 1...4 { values["slot\(n)"] = "empty" } + for id in ["fd0","fd1","fd2","fd3","hd0","hd1"] { values[id] = "empty"; values[id + "Activity"] = "empty" } + } + init(snapshot: VCCMachineSnapshot, activities: [ActivityTracker.State], sdcActivity: ActivityTracker.State = .empty) { + self.init(); self.activities = activities + values["cpu"] = snapshot.use6309 ? "6309" : "6809" + values["ram"] = Self.ramKeys[min(3, Int(snapshot.ramConfiguration))] + values["mpi"] = snapshot.multiPakEnabled ? "on" : "off" + values["startup"] = String(snapshot.physicalSlot) + values["floppy"] = snapshot.diskConnected ? "on" : "off" + values["hard"] = snapshot.hardDiskConnected ? "on" : "off" + values["floppyCase"] = snapshot.diskConnected || snapshot.hardDiskConnected ? "on" : "off" + values["hardCase"] = values["floppyCase"] + custom = !snapshot.multiPakEnabled && snapshot.cartridgeKinds.first?.intValue != 0 + || snapshot.multiPakEnabled && snapshot.cartridgeKinds.dropFirst().contains { $0.intValue == 4 } + for n in 1...4 { + let kind = snapshot.cartridgeKinds[n].intValue + let available = !snapshot.cartridgeNames[n].isEmpty + values["slot\(n)"] = available && (0...7).contains(kind) ? ["empty","rom","floppy","hard","empty","orchestra","speech","sdc"][kind] : "empty" + } + for (i, disk) in (snapshot.disks + snapshot.hardDisks).enumerated() { + let id = i < 4 ? "fd\(i)" : "hd\(i-4)" + values[id] = disk.mounted ? "loaded" : "empty" + values[id + "Activity"] = activities[i].rawValue + } + values["sdcActivity"] = sdcActivity.rawValue + values["printerPower"] = snapshot.printerEnabled ? "on" : "off" + values["printerPaper"] = snapshot.printerByteCount > 0 ? "printed" : "blank" + values["tape"] = snapshot.tapeMounted ? "loaded" : "empty" + values["tapeActivity"] = activities[6].rawValue + } +} + +@MainActor +final class PresentationSettings: ObservableObject { + enum Mode: String { case display, system } + @Published var mode: Mode { didSet { defaults.set(mode.rawValue, forKey: "interface.presentation") } } + @Published var expanded: Bool { didSet { defaults.set(expanded, forKey: "interface.expanded") } } + @Published var showConnections: Bool { didSet { defaults.set(showConnections, forKey: "interface.connections") } } + @Published var showClickableAreas: Bool { didSet { defaults.set(showClickableAreas, forKey: "interface.clickableAreas") } } + @Published private(set) var controlsFocusRequest: UInt64 = 0 + // UI history is independent of saved machine profiles and Restore Defaults. + func shouldIntroduce(_ profile: SystemProfile) -> Bool { + !defaults.bool(forKey: "interface.usageGuide.seen." + profile.rawValue) + } + func didShowGuide(_ profile: SystemProfile) { + defaults.set(true, forKey: "interface.usageGuide.seen." + profile.rawValue) + } + let windows: WindowPlacements + func focusControls() { controlsFocusRequest += 1 } + private let defaults: UserDefaults + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + windows = WindowPlacements(defaults: defaults) + expanded = defaults.bool(forKey: "interface.expanded") + showConnections = defaults.bool(forKey: "interface.connections") + showClickableAreas = defaults.object(forKey: "interface.clickableAreas") == nil + ? true : defaults.bool(forKey: "interface.clickableAreas") + mode = Mode(rawValue: defaults.string(forKey: "interface.presentation") ?? "") ?? .system + } +} + +// Pure, absolute geometry: return never inverts an accumulated transform. +struct SystemGeometry { + static let canvas = CGRect(x: -120, y: 0, width: 960, height: 457) + // The approved PNG includes transparent margins and its soft shelf shadow. + // Keep its 2:1 aspect ratio; the separate target follows the visible object. + static let libraryArtwork = CGRect(x: 420, y: 0, width: 304, height: 152) + static let monitor = CGRect(x: 48, y: 4, width: 285, height: 256) + static let screen = CGRect(x: 90, y: 44.5, width: 202, height: 151.1) + let scene: CGRect + let monitor: CGRect + let screen: CGRect + init(size: CGSize, system: Bool, expanded: Bool, contentBounds: CGRect = Self.canvas) { + let scale = min(size.width / 960, size.height / 457) + // Translate the shared scene, monitor and controls together. Keep the + // full-scene scale so removing the tower does not enlarge the hardware. + let offset = system ? (Self.canvas.midX - contentBounds.midX) * scale : 0 + scene = CGRect(x: (size.width - 960 * scale) / 2 + offset, y: (size.height - 457 * scale) / 2, width: 960 * scale, height: 457 * scale) + if !system { + monitor = .zero + // Metal fits the current active raster, including wider CoCo 3 modes. + screen = CGRect(origin:.zero,size:size) + } else { + let m: CGRect + if expanded { + let s = min((size.width - 24) / Self.monitor.width, (size.height - 16) / Self.monitor.height) + m = CGRect(x: (size.width-Self.monitor.width*s)/2, y: (size.height-Self.monitor.height*s)/2, width: Self.monitor.width*s, height: Self.monitor.height*s) + } else { + m = CGRect(x: scene.minX+(Self.monitor.minX+120)*scale, y: scene.minY+Self.monitor.minY*scale, width: Self.monitor.width*scale, height: Self.monitor.height*scale) + } + monitor = m + let s = m.width / Self.monitor.width + screen = CGRect(x: m.minX+(Self.screen.minX-Self.monitor.minX)*s, y: m.minY+(Self.screen.minY-Self.monitor.minY)*s, width: Self.screen.width*s, height: Self.screen.height*s) + } + } + func monitorRect(_ r: CGRect) -> CGRect { + let s = monitor.width / Self.monitor.width + return CGRect(x: monitor.minX + (r.minX - Self.monitor.minX) * s, + y: monitor.minY + (r.minY - Self.monitor.minY) * s, width: r.width * s, height: r.height * s) + } + func rect(_ r: CGRect) -> CGRect { + let s = scene.width/960 + return CGRect(x: scene.minX+(r.minX+120)*s, y: scene.minY+r.minY*s, width: r.width*s, height: r.height*s) + } +} + +struct ArtworkLayer: Decodable { + let file: String + let bounds: [Double] + let when: [String:String] + let part: String + var rect: CGRect { CGRect(x: bounds[0], y: bounds[1], width: bounds[2], height: bounds[3]) } + func visible(_ values: [String:String]) -> Bool { when.allSatisfy { values[$0.key] == $0.value } } +} + +private final class ArtworkBundleMarker: NSObject {} + +@MainActor +final class HardwareArtwork { + static let shared = HardwareArtwork() + let layers: [ArtworkLayer] + private var images: [String:NSImage] = [:] + let directory: URL? + init(bundle: Bundle? = nil) { + let bundle = bundle ?? Bundle(for: ArtworkBundleMarker.self) + directory = bundle.url(forResource: "Hardware", withExtension: nil) + if let directory, let data = try? Data(contentsOf: directory.appendingPathComponent("layers.json")), + let decoded = try? JSONDecoder().decode([ArtworkLayer].self, from: data) { layers = decoded } + else { layers = [] } + } + func layoutBounds(_ values: [String:String]) -> CGRect { + guard values["floppyCase"] != "on", values["hardCase"] != "on" else { return SystemGeometry.canvas } + let visible = layers.filter { $0.visible(values) }.map(\.rect) + return visible.reduce(SystemTarget.library.rect) { $0.union($1) } + } + func cartridgeHitRect(slot: Int, values: [String:String]) -> CGRect? { + func bounds(_ n: Int) -> CGRect? { + let matching = layers.filter { $0.when["mpi"] == "on" && $0.when["slot\(n)"] == values["slot\(n)"] && $0.when.keys.allSatisfy { $0 == "mpi" || $0 == "slot\(n)" } } + return matching.map(\.rect).reduce(nil) { (r: CGRect?, next) in r.map { $0.union(next) } ?? next } + } + guard var rect = bounds(slot) else { return nil } + for n in 1..= 8 ? rect.insetBy(dx: 1, dy: 1) : nil + } + func image(_ name: String) -> NSImage? { + if let image = images[name] { return image } + guard let directory, let image = NSImage(contentsOf: directory.appendingPathComponent(name)) else { return nil } + images[name] = image; return image + } +} + +struct HardwareBadge: View { + let name: String + let label: String + var body: some View { + Group { + if let image = HardwareArtwork.shared.image(name + ".pdf") { Image(nsImage: image).resizable().scaledToFit() } + else { Text(label) } + }.accessibilityElement(children: .ignore).accessibilityLabel(label) + } +} + +// Each cropped asset has a persistent native layer. Video polls never redraw +// artwork; I/O changes only hide/show small pre-rendered layers. Resizing +// regenerates the visible layers at the window's current backing scale. +struct HardwareCanvas: NSViewRepresentable { + let values: [String:String] + let part: String + func makeNSView(context: Context) -> LayeredHardwareView { LayeredHardwareView(part: part) } + func updateNSView(_ view: LayeredHardwareView, context: Context) { view.apply(values) } +} +final class LayeredHardwareView: NSView { + override var isFlipped: Bool { true } + override func hitTest(_ point: NSPoint) -> NSView? { nil } + private let assets: [ArtworkLayer] + private var artworkLayers: [CALayer] = [] + private var values: [String:String] = [:] + private var renderedSizes: [CGSize] + private let part: String + private(set) var rasterizations = 0 + init(part: String) { + self.part = part + assets = HardwareArtwork.shared.layers.filter { $0.part == part } + renderedSizes = Array(repeating: .zero, count: assets.count) + super.init(frame: .zero) + wantsLayer = true; layer?.isGeometryFlipped = true + setAccessibilityElement(false) + for _ in assets { + let child = CALayer(); child.isHidden = true + layer?.addSublayer(child); artworkLayers.append(child) + } + } + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + func apply(_ next: [String:String]) { + guard values != next else { return }; values = next; needsLayout = true + } + override func viewDidChangeBackingProperties() { super.viewDidChangeBackingProperties(); renderedSizes = Array(repeating: .zero, count: assets.count); needsLayout = true } + override func layout() { + super.layout() + let canvas = part == "monitor" ? SystemGeometry.monitor : SystemGeometry.canvas + let scale = min(bounds.width/canvas.width, bounds.height/canvas.height) + guard scale > 0 else { return } + let backing = window?.backingScaleFactor ?? 2 + CATransaction.begin(); CATransaction.setDisableActions(true) + for i in assets.indices { + let asset = assets[i], child = artworkLayers[i], r = asset.rect + child.isHidden = !asset.visible(values) + let disconnected = (asset.when["floppyCase"] != nil && values["floppy"] != "on") || + (asset.when["hardCase"] != nil && values["hard"] != "on") + child.opacity = disconnected ? 0.42 : 1 + child.frame = CGRect(x:(r.minX-canvas.minX)*scale,y:(r.minY-canvas.minY)*scale,width:r.width*scale,height:r.height*scale) + guard !child.isHidden else { continue } + let size = CGSize(width: ceil(r.width*scale*backing), height: ceil(r.height*scale*backing)) + if renderedSizes[i] != size, let image = HardwareArtwork.shared.image(asset.file) { + let rep = NSBitmapImageRep(bitmapDataPlanes:nil,pixelsWide:max(1,Int(size.width)),pixelsHigh:max(1,Int(size.height)),bitsPerSample:8,samplesPerPixel:4,hasAlpha:true,isPlanar:false,colorSpaceName:.deviceRGB,bytesPerRow:0,bitsPerPixel:0)! + NSGraphicsContext.saveGraphicsState(); NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep:rep) + image.draw(in:CGRect(origin:.zero,size:size),from:.zero,operation:.sourceOver,fraction:1,respectFlipped:false,hints:nil) + NSGraphicsContext.restoreGraphicsState() + child.contents = rep.cgImage; child.contentsScale = backing + renderedSizes[i] = size; rasterizations += 1 + } + } + CATransaction.commit() + } +} diff --git a/platforms/macos/App/Info.plist b/platforms/macos/App/Info.plist new file mode 100644 index 0000000..9c43de0 --- /dev/null +++ b/platforms/macos/App/Info.plist @@ -0,0 +1,72 @@ + + + + + VCCCompanionProtocolVersion + 1 + CFBundleName + VCC Plus OSS + CFBundleIconFile + AppIcon + UTExportedTypeDeclarations + + + UTTypeIdentifier + com.brianholman.vccplus.mac.configuration-profile + UTTypeDescription + VCC Plus Configuration Profile + UTTypeConformsTo + + public.json + + UTTypeTagSpecification + + public.filename-extension + + vccprofile + + + + + UTImportedTypeDeclarations + + + UTTypeIdentifier + org.vcc.mac.configuration-profile + UTTypeDescription + Legacy VCC Configuration Profile + UTTypeConformsTo + public.json + UTTypeTagSpecification + public.filename-extensionvccprofile + + + CFBundleDocumentTypes + + + CFBundleTypeName + CoCo media + CFBundleTypeRole + Viewer + LSHandlerRank + Alternate + CFBundleTypeExtensions + + dsk + jvc + dmk + vdk + os9 + vhd + img + cas + wav + rom + ccc + pak + bin + + + + + diff --git a/platforms/macos/App/InputControlsView.swift b/platforms/macos/App/InputControlsView.swift new file mode 100644 index 0000000..72f35fb --- /dev/null +++ b/platforms/macos/App/InputControlsView.swift @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI + +struct InputControlsView: View { + @ObservedObject var input: InputHub + @State private var expandedPort: Int? + @State private var showControllerTest = false + private var keyboardDescription: String { + switch input.settings.keyboard { + case .natural: return "Follows the characters you type on your Mac." + case .coco: return "Uses physical US CoCo key positions." + case .compact: return "Adds Tab for Clear and the grave key for Break." + } + } + var body: some View { + VStack(alignment: .leading, spacing: 0) { + SecondaryHeader(title: "Keyboard and Joysticks", badge: "joystick", subtitle: "Changes apply immediately and are remembered.") + .padding(20) + Divider() + ScrollView { + VStack(alignment: .leading, spacing: 16) { + SecondaryCard { + Label("Keyboard", systemImage: "keyboard").font(.headline) + Picker("Keyboard mode", selection: $input.settings.keyboard) { + ForEach(KeyboardMode.allCases, id: \.self) { Text($0.rawValue).tag($0) } + }.accessibilityIdentifier("input-keyboard") + Text(keyboardDescription + " Command shortcuts stay with the Mac.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + HStack { + Label("CoCo joystick ports", systemImage: "gamecontroller").font(.headline) + Spacer() + Button(action: input.swap) { Label("Swap assignments", systemImage: "arrow.left.arrow.right") } + .accessibilityIdentifier("input-swap") + .help("Swap the right and left CoCo port assignments, including their options.") + } + // Display left before right; hardware port 0 remains the right joystick. + ForEach([1, 0], id: \.self) { port in portCard(port) } + SecondaryCard { + DisclosureGroup(isExpanded: $showControllerTest) { + controllerTest.padding(.top, 8) + } label: { + HStack { + Label("Controller Test", systemImage: "gamecontroller").font(.headline) + Spacer() + Text(input.devices.isEmpty ? "None connected" : "\(input.devices.count) connected") + .font(.caption).foregroundStyle(.secondary) + } + } + } + SecondaryHelp(title: "Using keyboard, mouse and controller input") { + Text("Click the CoCo display to play. Keyboard joystick keys are reserved for the selected port. Mouse movement uses the display area; left and right clicks are Fire 1 and Fire 2.") + Text("For Logitech F310, use the underside D switch and reconnect USB. Standard gamepads use the left stick or D-pad. Controller Test shows button numbers as you press them; select those numbers for Fire 1 and Fire 2.") + Text("A remembered disconnected controller stays assigned and sends neutral input until it reconnects.") + } + if let error = input.error { + Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.red) + .fixedSize(horizontal: false, vertical: true) + } + }.padding(20) + } + }.frame(minWidth: 620, minHeight: 540) + } + private func buttons(_ value: UInt32) -> String { + let pressed = (1...16).filter { value & (1 << ($0 - 1)) != 0 }.map(String.init) + return pressed.isEmpty ? "none" : pressed.joined(separator: ", ") + } + private func portSummary(_ port: Int) -> String { + let config = input.settings[port] + switch config.source { + case .none: return "No input assigned" + case .keyboard: return config.keys.rawValue + " · " + config.interface.label + case .mouse: return "Display pointer · " + config.interface.label + case .controller: + let name = config.device.isEmpty ? "Choose a controller in Options" : + input.devices.first { $0.id == config.device }?.name ?? "Remembered controller — disconnected" + return name + " · " + config.interface.label + } + } + private func portCard(_ port: Int) -> some View { + let config = Binding(get: { input.settings[port] }, set: { input.settings[port] = $0 }) + return SecondaryCard { + HStack(alignment: .firstTextBaseline) { + VStack(alignment: .leading, spacing: 3) { + Text(port == 0 ? "Right CoCo joystick" : "Left CoCo joystick").font(.headline) + Text(port == 0 ? "JOYSTK 0–1" : "JOYSTK 2–3").font(.caption).foregroundStyle(.secondary) + } + Spacer() + Picker("Input source", selection: config.source) { + ForEach(JoystickSource.allCases, id: \.self) { Text($0.rawValue).tag($0) } + }.labelsHidden().frame(width: 180).accessibilityLabel(port == 0 ? "Right joystick input source" : "Left joystick input source") + .accessibilityIdentifier("input-source-\(port)") + } + Text(portSummary(port)).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + if config.wrappedValue.source != .none { + DisclosureGroup(isExpanded: Binding(get: { expandedPort == port }, set: { expandedPort = $0 ? port : nil })) { + portOptions(port, config: config).padding(.top, 8) + } label: { Label("Options", systemImage: "slider.horizontal.3") } + .accessibilityIdentifier("input-options-\(port)") + Text("X: \(input.preview[port].x >> 8) Y: \(input.preview[port].y >> 8) Fire 1: \(input.preview[port].buttons & 1 == 0 ? "up" : "down") Fire 2: \(input.preview[port].buttons & 2 == 0 ? "up" : "down")") + .font(.system(.caption, design: .monospaced)) + .accessibilityIdentifier("input-port-preview-\(port)") + } + }.onChange(of: input.settings[port].source) { _, new in + if new != .none { expandedPort = port } + else if expandedPort == port { expandedPort = nil } + } + } + @ViewBuilder private func portOptions(_ port: Int, config: Binding) -> some View { + VStack(alignment: .leading, spacing: 12) { + if config.wrappedValue.source == .keyboard { + Picker("Keys", selection: config.keys) { + ForEach(JoystickKeys.allCases, id: \.self) { Text($0.rawValue).tag($0) } + } + } + if config.wrappedValue.source == .controller { + Picker("Controller", selection: config.device) { + Text("Choose a controller").tag("") + if !config.wrappedValue.device.isEmpty && !input.devices.contains(where: { $0.id == config.wrappedValue.device }) { + Text("Remembered controller — disconnected").tag(config.wrappedValue.device) + } + ForEach(input.devices) { Text($0.name).tag($0.id) } + }.accessibilityIdentifier("input-controller-\(port)") + Toggle("Use right stick", isOn: config.rightStick) + HStack { + Picker("Fire 1", selection: config.fire1) { ForEach(1...16, id: \.self) { Text("Button \($0)").tag($0) } } + Picker("Fire 2", selection: config.fire2) { ForEach(1...16, id: \.self) { Text("Button \($0)").tag($0) } } + } + HStack { + Text("Dead zone") + Slider(value: config.deadZone, in: 0...0.5).accessibilityLabel("\(port == 0 ? "Right" : "Left") joystick dead zone") + Text("\(Int(config.wrappedValue.deadZone * 100))%").monospacedDigit().frame(width: 38, alignment: .trailing) + } + } + Picker("CoCo interface", selection: config.interface) { + ForEach(JoystickInterface.allCases, id: \.self) { Text($0.label).tag($0) } + } + } + } + private var controllerTest: some View { + VStack(alignment: .leading, spacing: 12) { + if input.devices.isEmpty { + Text("Connect a supported controller to see its sticks and button numbers.").foregroundStyle(.secondary) + } + ForEach(input.devices) { device in + VStack(alignment: .leading, spacing: 4) { + Text(device.name).font(.headline) + Text("Left: \(String(format: "% .2f", device.x)), \(String(format: "% .2f", device.y))\nRight: \(String(format: "% .2f", device.rx)), \(String(format: "% .2f", device.ry))\nButtons: \(buttons(device.buttons))") + .font(.system(.caption, design: .monospaced)).fixedSize(horizontal: false, vertical: true) + .accessibilityLabel("Controller preview: \(device.name), X \(device.x), Y \(device.y), buttons \(buttons(device.buttons))") + .accessibilityIdentifier("controller-preview-\(device.id)") + } + } + Text("Move either stick and press buttons to identify them. This preview does not change either port assignment.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + } +} diff --git a/platforms/macos/App/InputHub.swift b/platforms/macos/App/InputHub.swift new file mode 100644 index 0000000..7e2d37b --- /dev/null +++ b/platforms/macos/App/InputHub.swift @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import Combine + +/// Cached host observations, kept separate from core acknowledgement. This DTO +/// permits authored diagnostics tests without opening HID devices or polling. +struct InputDiagnosticObservation { + var preview: [JoystickSample]? + var submitted: [JoystickSample]? + var submittedInterfaces: [JoystickInterface]? + var applicationActive: Bool? + var displayAcceptsInput: Bool? + var pollAgeMilliseconds: Int? + var submissionAgeMilliseconds: Int? + var settingsError = false +} + +@MainActor +final class InputHub: ObservableObject { + @Published var settings: InputSettings { didSet { + guard settings != oldValue else { return } + release(); epoch &+= 1 + do { try store.save(settings); error = nil } catch { self.error = "Could not save input settings: \(error.localizedDescription)" } + } } + @Published private(set) var devices: [ControllerReading] = [] + @Published private(set) var preview = [JoystickSample(), JoystickSample()] + @Published private(set) var error: String? + private(set) var epoch: UInt64 = 0 + var acceptsInput: () -> Bool = { false } + private let store: InputSettingsStore + private let controller: VCCMachineController + private let hardware: ControllerDevices + private var timer: Timer? + private var routing = InputRouting() + private var last: [JoystickSample] = [] + private var lastActive = false + private var lastPollUptime: TimeInterval? + private var lastSubmissionUptime: TimeInterval? + private var lastApplicationActive: Bool? + private var lastDisplayAcceptsInput: Bool? + private var submitted: [JoystickSample]? + private var submittedInterfaces: [JoystickInterface]? + init(controller: VCCMachineController, store: InputSettingsStore = .standard) { + self.controller = controller; self.store = store; hardware = ControllerDevices() + do { settings = try store.load() } catch { + settings = InputSettings(); self.error = "Could not read input settings: \(error.localizedDescription)" + } + timer = Timer.scheduledTimer(withTimeInterval: 1 / 60, repeats: true) { [weak self] _ in + MainActor.assumeIsolated { self?.poll() } + } + #if VCC_UI_TESTING + // Keep the authored preview moving even during native menu tracking. + if let timer { RunLoop.main.add(timer, forMode: .common) } + #endif + } + deinit { timer?.invalidate() } + func swap() { var next = settings; next.right = settings.left; next.left = settings.right; settings = next } + func key(_ code: UInt16, down: Bool) -> Bool { + routing.key(code, down: down, settings: settings) + } + func mouseMove(x: Double, y: Double) { + guard x.isFinite, y.isFinite else { return } + routing.mouse.x = Int(min(1, max(0, x)) * 16383) + routing.mouse.y = Int(min(1, max(0, y)) * 16383) + } + func mouseLeave() { routing.mouse = JoystickSample() } + func mouseButton(_ button: Int, down: Bool) { + guard (0...1).contains(button) else { return } + if down { routing.mouse.buttons |= 1 << button } else { routing.mouse.buttons &= ~(1 << button) } + } + func release() { + routing.release(); last = [] + lastPollUptime = nil; lastApplicationActive = nil; lastDisplayAcceptsInput = nil + submit([JoystickSample(), JoystickSample()]) + } + private func poll() { + #if VCC_UI_TESTING + // Exercise the real preview/selection views with changing input even + // when no physical controller is attached to the test Mac. + let phase = ProcessInfo.processInfo.systemUptime + let readings = [ControllerReading(id: "ui-fixture", name: "Authored test controller", + x: sin(phase), y: cos(phase), rx: sin(phase * 2), ry: cos(phase * 2))] + #else + let readings = hardware.read() + #endif + if devices != readings { devices = readings } + let displayAcceptsInput = acceptsInput(), applicationActive = NSApp.isActive + let active = displayAcceptsInput && applicationActive + lastPollUptime = ProcessInfo.processInfo.systemUptime + lastApplicationActive = applicationActive; lastDisplayAcceptsInput = displayAcceptsInput + if active != lastActive { last = []; lastActive = active } + let delivered = routing.delivery(settings: settings, devices: readings, active: active) + let samples = routing.samples(settings: settings, devices: readings) + if preview != samples { preview = samples } + if delivered != last { + last = delivered + submit(delivered) + } + } + private func submit(_ samples: [JoystickSample]) { + submitted = samples; submittedInterfaces = (0..<2).map { settings[$0].interface } + lastSubmissionUptime = ProcessInfo.processInfo.systemUptime + for port in 0..<2 { + controller.setJoystick(UInt(port), x: UInt(samples[port].x), y: UInt(samples[port].y), + buttons: UInt(samples[port].buttons), mode: UInt(settings[port].interface.rawValue)) + } + } + + /// Reads cached native observations and a caller-supplied immutable machine + /// snapshot. It never polls HID, changes focus/settings, or queues input. + func diagnostics(machine: VCCMachineSnapshot) -> [String: Any] { + let now = ProcessInfo.processInfo.systemUptime + func age(_ time: TimeInterval?) -> Int? { time.map { Int(max(0, now - $0) * 1000) } } + return Self.diagnostics(settings: settings, devices: devices, + observation: InputDiagnosticObservation(preview: lastPollUptime == nil ? nil : preview, + submitted: submitted, submittedInterfaces: submittedInterfaces, + applicationActive: lastApplicationActive, displayAcceptsInput: lastDisplayAcceptsInput, + pollAgeMilliseconds: age(lastPollUptime), submissionAgeMilliseconds: age(lastSubmissionUptime), + settingsError: error != nil), machine: machine) + } + + static func unavailableDiagnostics(machine: VCCMachineSnapshot) -> [String: Any] { + var result = diagnostics(settings: InputSettings(), devices: [], observation: InputDiagnosticObservation(), machine: machine) + result["configuration_available"] = false; result["settings_error"] = NSNull() + if let ports = result["ports"] as? [[String: Any]] { + result["ports"] = ports.map { value -> [String: Any] in + var port = value + port["source"] = "unknown" + for key in ["interface", "dead_zone", "controller_connected", "controller_mapping", "keyboard_binding"] { port[key] = NSNull() } + return port + } + } + return result + } + + static func diagnostics(settings: InputSettings, devices: [ControllerReading], + observation: InputDiagnosticObservation, machine: VCCMachineSnapshot) -> [String: Any] { + func interface(_ mode: Int) -> String { + switch mode { case 0: return "standard"; case 1: return "software"; case 2: return "tandy"; case 3: return "coco_max"; default: return "unknown" } + } + func source(_ value: JoystickSource) -> String { + switch value { case .none: return "none"; case .keyboard: return "keyboard"; case .mouse: return "mouse"; case .controller: return "controller" } + } + func buttons(_ value: Int) -> [String] { [(value & 1) != 0 ? "fire1" : nil, (value & 2) != 0 ? "fire2" : nil].compactMap { $0 } } + func sample(_ value: JoystickSample, mode: Int) -> [String: Any] { + ["x": value.x, "y": value.y, "buttons": buttons(value.buttons), "interface": interface(mode)] + } + let available = machine.state == .running || machine.state == .paused + let focusActive: Bool? = observation.applicationActive.flatMap { app in observation.displayAcceptsInput.map { app && $0 } } + let ports: [[String: Any]] = (0..<2).map { port in + let config = settings[port] + let preview: Any = observation.preview.flatMap { values in + values.indices.contains(port) ? sample(values[port], mode: config.interface.rawValue) : nil + } ?? NSNull() + let submitted: Any = observation.submitted.flatMap { values in + guard values.indices.contains(port), let modes = observation.submittedInterfaces, modes.indices.contains(port) else { return nil } + return sample(values[port], mode: modes[port].rawValue) + } ?? NSNull() + let actual: Any + if available, machine.joystickInputs.indices.contains(port) { + let value = machine.joystickInputs[port] + actual = sample(JoystickSample(x: Int(value.x), y: Int(value.y), buttons: Int(value.buttons)), mode: Int(value.mode)) + } else { actual = NSNull() } + return ["port": port == 0 ? "right" : "left", "source": source(config.source), + "interface": interface(config.interface.rawValue), "dead_zone": config.deadZone, + "controller_connected": config.source == .controller ? devices.contains { $0.id == config.device } as Any : NSNull(), + "controller_mapping": config.source == .controller + ? ["stick": config.rightStick ? "right" : "left", "fire1_button": config.fire1, "fire2_button": config.fire2] as Any : NSNull(), + "keyboard_binding": config.source == .keyboard ? config.keys.rawValue as Any : NSNull(), + "preview": preview, "submitted": submitted, "actual": actual] + } + return ["source": "shared_machine", "axis_min": 0, "axis_max": 16383, "axis_center": 8191, + "x_direction": "right", "y_direction": "down", "configuration_available": true, "settings_error": observation.settingsError, + "host_observation": ["age_ms": observation.pollAgeMilliseconds as Any? ?? NSNull(), + "application_active": observation.applicationActive as Any? ?? NSNull(), + "display_accepts_input": observation.displayAcceptsInput as Any? ?? NSNull(), + "active": focusActive as Any? ?? NSNull()], + "submission_age_ms": observation.submissionAgeMilliseconds as Any? ?? NSNull(), + "submission_is_delivery_confirmation": false, + "machine_observation": ["available": available, "generation": machine.generation, + "frame": machine.frames, "cycles": machine.cycles, + "keyboard_held": available ? machine.keyboardInputHeld as Any : NSNull()], + "ports": ports] + } + +} diff --git a/platforms/macos/App/InputSettings.swift b/platforms/macos/App/InputSettings.swift new file mode 100644 index 0000000..1c3ad9a --- /dev/null +++ b/platforms/macos/App/InputSettings.swift @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +enum JoystickSource: String, Codable, CaseIterable { + case none = "None", keyboard = "Keyboard", mouse = "Mouse", controller = "Controller" +} +enum JoystickInterface: Int, Codable, CaseIterable { + case standard = 0, software = 1, tandy = 2, cocoMax = 3 + var label: String { ["Standard", "Software high resolution", "Tandy high resolution", "CoCoMax"][rawValue] } +} +enum JoystickKeys: String, Codable, CaseIterable { + case arrows = "Arrows + Z / X", wasd = "W A S D + F / G", keypad = "Keypad 8 2 4 6 + 0 / ." + // up, down, left, right, fire 1, fire 2 + var codes: [UInt16] { + switch self { + case .arrows: return [126,125,123,124,6,7] + case .wasd: return [13,1,0,2,3,5] + case .keypad: return [91,84,86,88,82,65] + } + } +} +struct PortSettings: Codable, Equatable { + var source: JoystickSource = .none + var interface: JoystickInterface = .standard + var keys: JoystickKeys = .arrows + var device = "" + var rightStick = false + var fire1 = 1, fire2 = 2 + var deadZone = 0.15 +} +struct InputSettings: Codable, Equatable { + var keyboard: KeyboardMode = .natural + var right = PortSettings(), left = PortSettings(keys: .wasd) + subscript(port: Int) -> PortSettings { + get { port == 0 ? right : left } + set { if port == 0 { right = newValue } else { left = newValue } } + } + func validated() throws -> Self { + for p in [right, left] { + guard p.deadZone.isFinite, (0...0.5).contains(p.deadZone), + (1...16).contains(p.fire1), (1...16).contains(p.fire2), p.device.count < 1024 else { + throw CocoaError(.coderReadCorrupt) + } + } + return self + } +} +struct InputSettingsStore { + let url: URL + static let standard = InputSettingsStore(url: AppIdentity.supportDirectory.appendingPathComponent("InputSettings.json")) + func load() throws -> InputSettings { + guard FileManager.default.fileExists(atPath: url.path) else { return InputSettings() } + return try JSONDecoder().decode(InputSettings.self, from: Data(contentsOf: url)).validated() + } + func save(_ value: InputSettings) throws { + _ = try value.validated() + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try JSONEncoder().encode(value).write(to: url, options: .atomic) + } +} +struct JoystickSample: Equatable { + var x = 8191, y = 8191, buttons = 0 + static func axis(_ value: Double, deadZone: Double) -> Int { + guard value.isFinite else { return 8191 } + let v = min(1, max(-1, value)), dead = min(0.5, max(0, deadZone)) + if abs(v) <= dead { return 8191 } + let adjusted = (abs(v) - dead) / (1 - dead) * (v < 0 ? -1 : 1) + return Int(((adjusted + 1) * 8191.5).rounded()) + } + static func keyboard(_ held: Set, keys: JoystickKeys) -> Self { + let down = keys.codes.map { held.contains($0) } + func axis(_ low: Bool, _ high: Bool) -> Int { low == high ? 8191 : (low ? 0 : 16383) } + return Self(x: axis(down[2], down[3]), y: axis(down[0], down[1]), buttons: (down[4] ? 1 : 0) | (down[5] ? 2 : 0)) + } +} + +// Device-independent host state. Focus loss drops held keys/buttons; a missing +// remembered controller always yields neutral input, never another device. +struct InputRouting { + private(set) var held: Set = [] + var mouse = JoystickSample() + mutating func key(_ code: UInt16, down: Bool, settings: InputSettings) -> Bool { + let reserved = [settings.right, settings.left].contains { $0.source == .keyboard && $0.keys.codes.contains(code) } + if down && reserved { held.insert(code) } else { held.remove(code) } + return reserved + } + mutating func release() { held.removeAll(); mouse = JoystickSample() } + func samples(settings: InputSettings, devices: [ControllerReading]) -> [JoystickSample] { + (0..<2).map { port in + let config = settings[port] + switch config.source { + case .none: return JoystickSample() + case .keyboard: return .keyboard(held, keys: config.keys) + case .mouse: return mouse + case .controller: return devices.first { $0.id == config.device }?.sample(config) ?? JoystickSample() + } + } + } + mutating func delivery(settings: InputSettings, devices: [ControllerReading], active: Bool) -> [JoystickSample] { + guard active else { release(); return [JoystickSample(), JoystickSample()] } + return samples(settings: settings, devices: devices) + } +} diff --git a/platforms/macos/App/InterfaceValidation.swift b/platforms/macos/App/InterfaceValidation.swift new file mode 100644 index 0000000..2e157a5 --- /dev/null +++ b/platforms/macos/App/InterfaceValidation.swift @@ -0,0 +1,405 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#if DEBUG +import Foundation + +// Opt-in native UI validation. Uses a fresh temporary directory, an isolated +// preference suite and authored media. Never reads the user's assignments. +// An explicit --orchestra-listening SYSTEM_ROM ORCHESTRA_ROM invocation can +// replace only those two fixture ROMs for a manual listening check. +// --speech-listening SYSTEM_ROM PIC_ROM SPEECH_ROM similarly opts into real +// chip ROMs for an isolated, bounded speech check. +// --sdc-validation SYSTEM_ROM SDC_ROM CARD_FOLDER [--sdc-6309] boots protected +// real SDC media at BASIC without typing commands. --sdc-fixture uses authored +// media only. Both modes run exclusively inside this isolated context. +@MainActor +final class InterfaceValidation { + let directory: URL + let defaults: UserDefaults + private let controller = VCCMachineController() + private var measurement: Task? + private let suite: String + init() throws { + directory = FileManager.default.temporaryDirectory.appendingPathComponent("vcc-interface-ui-" + UUID().uuidString) + suite = "VCCInterfaceUI-" + UUID().uuidString + defaults = UserDefaults(suiteName: suite)! + // Ordinary interaction tests represent a returning user; the dedicated + // first-use test exercises a fresh guide history through real commands. + if !CommandLine.arguments.contains("--first-guide-fixture") { + let presentation = PresentationSettings(defaults: defaults) + for profile in SystemProfile.allCases { presentation.didShowGuide(profile) } + } + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + // Synthetic system-profile payload: never read private bundled ROMs in UI tests. + let kit = directory.appendingPathComponent("Authored StarterKit") + try FileManager.default.createDirectory(at: kit, withIntermediateDirectories: true) + var rom = Data(repeating: 0x12, count: 32768) + rom[0] = 0x20; rom[1] = 0xfe; rom[32766] = 0x80; rom[32767] = 0 + try rom.write(to: kit.appendingPathComponent("coco3.rom")) + for name in ["disk11.rom", "rgbdos.rom", "sdcdos.rom"] { + try Data(repeating: 0,count:8192).write(to:kit.appendingPathComponent(name)) + } + // Explicit real-ROM acceptance uses only copies in this disposable kit. + // Library startup prefers the kit, so it must match the selected test ROMs. + if let system = ProcessInfo.processInfo.environment["VCC_BASIC_SYSTEM_ROM"], + let disk = ProcessInfo.processInfo.environment["VCC_BASIC_DISK_ROM"] { + let systemBytes = try ROMImage.read(URL(fileURLWithPath: system)) + let diskBytes = try DiskFiles.readROM(URL(fileURLWithPath: disk)) + try systemBytes.write(to: kit.appendingPathComponent("coco3.rom")) + try diskBytes.write(to: kit.appendingPathComponent("disk11.rom")) + } + for name in ["Hello World.dsk", "Hello Hard Disk.dsk", "Blank Disk.dsk"] { + try Data(repeating: 0,count:161280).write(to:kit.appendingPathComponent(name)) + } + if let resource = Bundle.main.url(forResource: "Blank OS9 Header", withExtension: "bin") { + try FileManager.default.copyItem(at: resource, to: kit.appendingPathComponent("Blank OS9 Header.bin")) + } + try Data([0x55,0x55,0x3c]).write(to:kit.appendingPathComponent("Hello World.cas")) + } + func makeModel() -> MachineModel { + MachineModel(diskStore: .init(url: directory.appendingPathComponent("assignments.json")), controller: controller, displayDefaults: defaults, + inputStore: .init(url: directory.appendingPathComponent("input.json")), + startupStore: .init(directory:directory,kit:.init(directory:directory.appendingPathComponent("Authored StarterKit")))) + } + func install(in model: MachineModel) async throws { + for _ in 0..<500 { if !model.busy { break }; try await Task.sleep(nanoseconds: 10_000_000) } + if CommandLine.arguments.contains("--first-guide-fixture") { return } + var profile = ConfigurationProfile(name: "Interface validation") + func file(_ name: String, _ bytes: Data) throws -> URL { + let url = directory.appendingPathComponent(name); try bytes.write(to: url); return url + } + profile.media.rom = try file("Authored controller.rom", Data(repeating: 0, count: 8192)) + profile.media.drives[0] = .init(url: try file("Authored FD0.dsk", Data(repeating: 0, count: 161280)), writeProtected: true, temporary: false) + #if VCC_UI_TESTING + if ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_TEST_HARD"] != "1", let image = ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_TEST_IMAGE"] { + // Explicit authored input for the isolated UI target only. The editor + // works on this private copy, never on the fixture's source image. + let input = try DiskFiles.readImage(URL(fileURLWithPath: image)) + let mounted = try file("Authored FD0.dsk", input.data) + profile.media.drives[0] = .init(url: mounted, writeProtected: false, temporary: false) + if let receipt = ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_TEST_RECEIPT"] { + try JSONSerialization.data(withJSONObject: ["mounted_image": mounted.path, "byte_count": input.data.count]) + .write(to: URL(fileURLWithPath: receipt), options: .atomic) + } + } + #endif + var hard = HardDiskAssignments() + hard.drives[0] = .init(url: try file("Authored HD0.vhd", Data(repeating: 0, count: 4096)), writeProtected: true, temporary: false) + #if VCC_UI_TESTING + if ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_TEST_HARD"] == "1", + let image = ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_TEST_IMAGE"] { + let input = try DiskEditorIO.readImage(URL(fileURLWithPath: image)) + let mounted = try file("Authored HD0.vhd", input.data) + hard.drives[0] = .init(url: mounted, writeProtected: false, temporary: false) + hard.drives[1] = .init(url: try file("Authored HD1.vhd", input.data), writeProtected: false, temporary: false) + if let receipt = ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_TEST_RECEIPT"] { + try JSONSerialization.data(withJSONObject: ["mounted_image": mounted.path, "byte_count": input.data.count]) + .write(to: URL(fileURLWithPath: receipt), options: .atomic) + } + } + #endif + profile.media.hardDisks = hard + let rom = try file("Authored cartridge.ccc", Data(repeating: 0x12, count: 8192)) + var cartridges = CartridgeAssignments(); cartridges.multiPak = true; cartridges.mpiConfigured = true + cartridges.slots[1] = .init(kind: .rom, url: rom); cartridges.slots[2] = .init(kind: .rom, url: rom) + cartridges.slots[3].kind = .hardDisk; cartridges.slots[4].kind = .floppy + profile.media.cartridges = cartridges + profile.cassette = try file("Authored tape.cas", Data([0x55, 0x55, 0x3c])) + profile.sound = false + #if VCC_UI_TESTING + profile.sound = true; profile.volume = 0 + #endif + #if VCC_UI_TESTING + if CommandLine.arguments.contains("--shell-permission-fixture") { + // Poll DWINIT until the test enables networking, then issue a single + // real Becker channel request. This fixture never sends a shell command. + var code: [UInt8] = [0x1a, 0x50] // ORCC: mask interrupts + let poll = code.count + func send(_ bytes: [UInt8]) { + for byte in bytes { code += [0x86, byte, 0xb7, 0xff, 0x42] } // LDA immediate, STA Becker + } + send([0x5a, 0]) + code += [0xb6, 0xff, 0x41, 0x27] // LDA status, BEQ poll + code.append(UInt8(bitPattern: Int8(poll - code.count - 1))) + code += [0xb6, 0xff, 0x42] // consume DWINIT result + let request = Array("tcp connect macshell 2323\r".utf8) + send([0x45, 0, 0x64, 0, UInt8(request.count)] + request) + code += [0x20, 0xfe] + var rom = Data(repeating: 0x12, count: 32768) + rom.replaceSubrange(0.. index + 2 else { + throw ProfileFailure.message("Supply system ROM and cartridge paths.") + } + var cartridgeProfile = ConfigurationProfile(name: "Authored cartridge validation setup") + cartridgeProfile.systemROM = URL(fileURLWithPath: CommandLine.arguments[index + 1]) + cartridgeProfile.machine.use6309 = CommandLine.arguments.contains("--cartridge-6309") + cartridgeProfile.input = InputSettings() + var layout = CartridgeAssignments() + layout.multiPak = true; layout.mpiConfigured = true; layout.physicalSlot = 4 + layout.slots[4] = .init(kind: .rom, url: URL(fileURLWithPath: CommandLine.arguments[index + 2])) + cartridgeProfile.media.cartridges = layout + cartridgeProfile.sound = false + await model.loadProfile(cartridgeProfile) + guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) } + model.resume() + print("Cartridge validation fixture: \(directory.path)") + return + } + let realSDC = CommandLine.arguments.firstIndex(of: "--sdc-validation") + if realSDC != nil || CommandLine.arguments.contains("--sdc-fixture") { + #if !VCC_UI_TESTING + guard CommandLine.arguments.contains("--interface-validation") else { + throw ProfileFailure.message("SDC validation requires --interface-validation to isolate settings and media.") + } + #endif + var sdcProfile = ConfigurationProfile(name: realSDC == nil ? "Authored SDC validation" : "SDC compatibility validation") + sdcProfile.machine.ram = 2 // 2 MB: the Double Dragon build's requirement. + sdcProfile.machine.use6309 = CommandLine.arguments.contains("--sdc-6309") + sdcProfile.input = InputSettings() // No joystick key capture; the game uses CoCo keys. + sdcProfile.sound = true; sdcProfile.volume = realSDC == nil ? 0 : 0.3 + let card: URL, sdcROM: URL + if let index = realSDC { + guard CommandLine.arguments.count > index + 3 else { + throw ProfileFailure.message("Supply system ROM, SDC-DOS ROM and SD card folder paths.") + } + sdcProfile.systemROM = URL(fileURLWithPath: CommandLine.arguments[index + 1]) + sdcROM = URL(fileURLWithPath: CommandLine.arguments[index + 2]) + card = URL(fileURLWithPath: CommandLine.arguments[index + 3], isDirectory: true) + } else { + card = directory.appendingPathComponent("Authored SD Card", isDirectory: true) + try FileManager.default.createDirectory(at: card, withIntermediateDirectories: true) + try Data(repeating: 0, count: 161280).write(to: card.appendingPathComponent("ONE.DSK")) + try Data("0=ONE.DSK\n".utf8).write(to: card.appendingPathComponent("startup.cfg")) + sdcROM = try file("Authored SDC-DOS.rom", Data(repeating: 0x12, count: 16384)) + } + var sdcLayout = CartridgeAssignments() + sdcLayout.multiPak = true; sdcLayout.mpiConfigured = true; sdcLayout.physicalSlot = 4 + // Optional isolated artwork check at each real Multi-Pak depth. + if let index = CommandLine.arguments.firstIndex(of: "--sdc-slot"), + CommandLine.arguments.count > index + 1, + let slot = Int(CommandLine.arguments[index + 1]), (1...4).contains(slot) { + sdcLayout.physicalSlot = slot + } + sdcLayout.slots[sdcLayout.physicalSlot] = .init(kind: .sdc, url: sdcROM, sdcFolderURL: card, sdcReadOnly: true) + sdcProfile.media.cartridges = sdcLayout + await model.loadProfile(sdcProfile) + guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) } + if realSDC == nil { + model.loadDiagnostic() + for _ in 0..<500 { if !model.busy { break }; try await Task.sleep(nanoseconds: 10_000_000) } + } + model.resume() + print("SDC validation fixture: \(directory.path); protected card: \(card.path)") + return + } + if let index = CommandLine.arguments.firstIndex(of: "--audio-game-listening") { + guard CommandLine.arguments.count > index + 2 else { throw ProfileFailure.message("Supply a ROM directory and DOS-boot disk image.") } + let roms = URL(fileURLWithPath: CommandLine.arguments[index + 1], isDirectory: true) + let input = try DiskFiles.readImage(URL(fileURLWithPath: CommandLine.arguments[index + 2])) + profile.systemROM = roms.appendingPathComponent("coco3.rom") + profile.media.rom = roms.appendingPathComponent("disk11.rom") + profile.media.drives[0] = .init(url: try file("Audio validation copy.dsk", input.data), writeProtected: false, temporary: true) + var layout = CartridgeAssignments(); layout.multiPak = true; layout.mpiConfigured = true; layout.physicalSlot = 4 + layout.slots[1] = .init(kind: .speechSound, url: roms.appendingPathComponent("pic-7040-510.bin"), speechROMURL: roms.appendingPathComponent("sp0256-al2.bin")) + layout.slots[2] = .init(kind: .orchestra90, url: roms.appendingPathComponent("orch90.rom")) + layout.slots[4].kind = .floppy; profile.media.cartridges = layout + profile.sound = true; profile.volume = 0.25 + await model.loadProfile(profile) + guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) } + model.resume() + measurement = Task { @MainActor in + do { + try await Task.sleep(nanoseconds: 3_000_000_000) + for bit in [4, 15, 19, 48] { // DOS through the normal keyboard + controller.setKeyboardMask(UInt64(1) << bit) + try await Task.sleep(nanoseconds: 100_000_000) + controller.setKeyboardMask(0) + try await Task.sleep(nanoseconds: 150_000_000) + } + try await Task.sleep(nanoseconds: 35_000_000_000) + let before = await withCheckedContinuation { done in controller.snapshot { done.resume(returning: $0) } } + try await Task.sleep(nanoseconds: 3_000_000_000) + let after = await withCheckedContinuation { done in controller.snapshot { done.resume(returning: $0) } } + #if VCC_UI_TESTING + if let path = ProcessInfo.processInfo.environment["VCC_AUDIO_GAME_RECEIPT"] { + let receipt: [String: Any] = ["frames_before": before.frames, "frames_after": after.frames, + "consumed_before": before.audioConsumed, "consumed_after": after.audioConsumed, + "signal_before": before.audioSignalSamples, "signal_after": after.audioSignalSamples, + "starts_before": before.audioStarts, "starts_after": after.audioStarts, + "audio_enabled": after.audioEnabled, "volume": model.volume, + "tape_position": after.tapePosition] + try JSONSerialization.data(withJSONObject: receipt).write(to: URL(fileURLWithPath: path), options: .atomic) + } + #endif + model.pause() + } catch { controller.setKeyboardMask(0); model.pause() } + } + return + } + if let index = CommandLine.arguments.firstIndex(of: "--speech-listening") { + guard CommandLine.arguments.count > index + 3 else { throw ProfileFailure.message("Supply system, PIC and speech ROM paths.") } + profile.systemROM = URL(fileURLWithPath: CommandLine.arguments[index+1]) + profile.media.cartridges?.slots[1] = .init(kind: .speechSound, + url: URL(fileURLWithPath: CommandLine.arguments[index+2]), + speechROMURL: URL(fileURLWithPath: CommandLine.arguments[index+3])) + // Use the real system BASIC; the authored floppy ROM is not bootable. + profile.media.cartridges?.physicalSlot = 2 + profile.media.cartridges?.slots[2] = .init() + profile.sound = true; profile.volume = 0.4 + await model.loadProfile(profile) + guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) } + model.resume() + measurement = Task { @MainActor in + do { + try await Task.sleep(nanoseconds: 2_000_000_000) + let bytes = Array("HELLO FROM YOUR COLOR COMPUTER. \r".utf8) + let end = 0x3040 + bytes.count + // The authored guest routes the real cartridge SND input. + var code: [UInt8] = [0xb6,0xff,0x01,0x84,0xf7,0xb7,0xff,0x01, + 0xb6,0xff,0x03,0x8a,0x08,0xb7,0xff,0x03, + 0xb6,0xff,0x23,0x8a,0x08,0xb7,0xff,0x23,0x8e,0x30,0x40,0x8c,UInt8(end >> 8),UInt8(end & 255),0x27,12, + 0xe6,0x80,0xb6,0xff,0x7e,0x2a,0xfb,0xf7,0xff,0x7e,0x20,0xef,0x20,0xfe] + code += Array(repeating: 0x12, count: 64-code.count); code += bytes + let binary = Data([0,0,UInt8(code.count),0x30,0] + code + [0xff,0,0,0x30,0]) + await withCheckedContinuation { done in controller.quickLoadBinary(binary) { _ in done.resume() } } + try await Task.sleep(nanoseconds: 12_000_000_000) + model.pause() + } catch { model.pause() } + } + return + } + if let index = CommandLine.arguments.firstIndex(of: "--orchestra-listening") { + guard CommandLine.arguments.count > index + 2 else { throw ProfileFailure.message("Supply system and Orchestra-90 ROM paths for the listening check.") } + profile.systemROM = URL(fileURLWithPath: CommandLine.arguments[index+1]) + profile.media.cartridges?.slots[1] = .init(kind: .orchestra90, url: URL(fileURLWithPath: CommandLine.arguments[index+2])) + profile.media.cartridges?.physicalSlot = 1 + profile.sound = true; profile.volume = 0.25 + await model.loadProfile(profile) + guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) } + model.resume() + measurement = Task { @MainActor in + do { + @MainActor func key(_ bit: Int) async throws { + controller.setKeyboardMask(UInt64(1) << bit) + try await Task.sleep(nanoseconds: 100_000_000) + controller.setKeyboardMask(0) + try await Task.sleep(nanoseconds: 150_000_000) + } + try await Task.sleep(nanoseconds: 3_000_000_000) + try await key(31) // Copyright screen: any key. + try await Task.sleep(nanoseconds: 1_000_000_000) + try await key(19); try await key(48) // S, Return: score. + try await Task.sleep(nanoseconds: 5_000_000_000) + try await key(16); try await key(48) // P, Return: play. + NSLog("Orchestra-90 listening check: William Tell playback requested at 25%% volume.") + try await Task.sleep(nanoseconds: 75_000_000_000) + model.pause() + } catch { controller.setKeyboardMask(0) } + } + return + } + // Opt-in authored printer fixture: guest instructions drive the real PIA + // output path. No injected host bytes and no private system ROM needed. + if CommandLine.arguments.contains("--printer-fixture") { + var code: [UInt8] = [0x1a, 0x50, 0x86, 0, 0xb7, 0xff, 0x21, + 0x86, 0xff, 0xb7, 0xff, 0x20, 0x86, 4, 0xb7, 0xff, 0x21] + let start = UInt16(0x8000 + code.count) + for byte in "HELLO FROM PRINTER\r10 PRINT \"HELLO WORLD\"\r".utf8 { + for bit in [UInt8(0)] + (0..<8).map({ (byte >> $0) & 1 }) + [UInt8(1)] { + code += [0x86, bit << 1, 0xb7, 0xff, 0x20] + } + } + code += [0x8e, 0xff, 0xff, 0x30, 0x1f, 0x26, 0xfc, 0x7e, UInt8(start >> 8), UInt8(start & 255)] + var rom = Data(repeating: 0x12, count: 32768) + rom.replaceSubrange(0.. VCCMachineSnapshot { + await withCheckedContinuation { done in controller.snapshot { done.resume(returning: $0) } } + } + let baseline = await sample(), start = ProcessInfo.processInfo.systemUptime + var rows: [[String: Any]] = [] + for second in 1...120 { + try await Task.sleep(nanoseconds: 1_000_000_000) + let current = await sample() + rows.append(["elapsed": ProcessInfo.processInfo.systemUptime-start, + "frames": current.frames-baseline.frames, + "consumed": current.audioConsumed-baseline.audioConsumed, + "submitted": current.audioSubmitted-baseline.audioSubmitted, + "underruns": current.audioUnderruns-baseline.audioUnderruns, + "overruns": current.audioOverruns-baseline.audioOverruns, + "starts": current.audioStarts-baseline.audioStarts, + "generationChanged": current.generation != baseline.generation, + "error": current.errorMessage ?? ""]) + if second % 20 == 0 { + presentation.mode = second % 60 == 0 ? .display : .system + presentation.expanded = second % 60 == 40 + } + let data = try JSONSerialization.data(withJSONObject: rows, options: [.prettyPrinted, .sortedKeys]) + try data.write(to: directory.appendingPathComponent("measurement.json"), options: .atomic) + } + model.pause() + } catch is CancellationError { } + catch { NSLog("Interface measurement failed: %@", error.localizedDescription) } + } + } + func cleanUp() { + measurement?.cancel() + defaults.removePersistentDomain(forName: suite) + try? FileManager.default.removeItem(at: directory) + } +} +#endif diff --git a/platforms/macos/App/MCPAccess.swift b/platforms/macos/App/MCPAccess.swift new file mode 100644 index 0000000..ba8c7b0 --- /dev/null +++ b/platforms/macos/App/MCPAccess.swift @@ -0,0 +1,649 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit +import Combine +import Darwin + +fileprivate struct BASICEditProposal: Identifiable { + let id = UUID().uuidString + let requestID: String, revision: Int, line: Int?, before: String, after: String + var status = "pending" + var appliedRevision: Int? + var subject: String { line.map { "BASIC line " + String($0) } ?? "Complete BASIC listing" } + + func range(in source: String) -> NSRange? { + if let line { return BASICLanguage.lineRange(for: line, in: source) } + return NSRange(location: 0, length: (source as NSString).length) + } + + var result: [String: Any] { + var result: [String: Any] = ["proposal_id": id, "revision": revision, "status": status] + if let line { result["line_number"] = line } else { result["kind"] = "listing" } + if let appliedRevision { result["applied_revision"] = appliedRevision } + return result + } +} + +@MainActor +final class MCPAccess: ObservableObject { + static let shared = MCPAccess() + fileprivate weak var selected: BASICDevelopmentModel? + @Published fileprivate(set) var activeTitle: String? + @Published fileprivate(set) var message: String? + private var listener: MCPTransport? + private var pendingGrant = UUID() + private weak var pendingModel: BASICDevelopmentModel? + private weak var panelModel: BASICDevelopmentModel? + private var token = "" + private var sessionID = "" + private var documentID: UUID? + fileprivate var grantFile: MCPGrantFile? + private var documentChange: AnyCancellable? + private var panel: NSPanel? + private let guest = MCPBASICRun() + @Published fileprivate var canPropose = false + @Published fileprivate var current: BASICEditProposal? + private var history: [String: BASICEditProposal] = [:] + private var reviewWindow: NSPanel? + private var fixtureLabel: String? + private var regressionFixture = false + #if DEBUG + private var fixtureEditor: NSWindow? + #endif + #if DEBUG + private var fixturePoll: Task? + #endif + + func show(for model: BASICDevelopmentModel) { + panel?.close() + let window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 550, height: 510), + styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false) + window.title = "Connect to ChatGPT or Another Assistant" + window.isReleasedWhenClosed = false + window.contentMinSize = NSSize(width: 360, height: 230) + let content = NSHostingView(rootView: ScrollView { MCPAccessView(access: self, model: model) }) + content.sizingOptions = [] + window.contentView = content + window.center() + panel = window + panelModel = model + window.makeKeyAndOrderFront(nil) + } + + fileprivate func chooseGrant(for model: BASICDevelopmentModel, proposals: Bool) { + guard let owner = panel, panelModel === model, owner.isVisible, + !owner.isMiniaturized, owner.attachedSheet == nil else { return } + let draft = model.documentID, connection = sessionID, generation = pendingGrant + let picker = NSSavePanel() + picker.nameFieldStringValue = "VCC Plus OSS Connection.json" + picker.title = proposals ? "Save Review and Run Connection" : "Save Read-Only Connection" + picker.message = "Choose a new local file. Give it only to assistants you trust to read this program." + picker.beginSheetModal(for: owner) { [weak self, weak owner, weak model] response in + Task { @MainActor [weak self, weak owner, weak model] in + guard let self, let owner, let model else { return } + @MainActor func currentPresentation() -> Bool { + self.panel === owner && self.panelModel === model && owner.isVisible && + !owner.isMiniaturized && model.documentID == draft + } + guard currentPresentation(), self.sessionID == connection, self.pendingGrant == generation else { return } + defer { if currentPresentation() { owner.makeKeyAndOrderFront(nil) } } + guard response == .OK, let url = picker.url else { return } + do { try await self.grant(model, at: url, proposals: proposals, presentationIsCurrent: currentPresentation) } + catch is CancellationError { } + catch { + if currentPresentation() { self.message = "Could not create a new connection file. " + error.localizedDescription } + } + } + } + } + + private func grant(_ model: BASICDevelopmentModel, at url: URL, proposals: Bool = false, + presentationIsCurrent: (@MainActor () -> Bool)? = nil) async throws { + let ticket = UUID() + pendingGrant = ticket + pendingModel = model + defer { if pendingGrant == ticket { pendingModel = nil } } + let draft = model.documentID + let id = UUID().uuidString + let secret = UUID().uuidString + UUID().uuidString + let callback: MCPTransport.Handler = { [weak self] request in + guard let self else { return Data(#"{"error":"access_denied"}"#.utf8) } + return await self.reply(to: request, session: id) + } + let (server, file) = try await Task.detached(priority: .userInitiated) { + let server = try MCPTransport(handler: callback) + let data = try JSONSerialization.data(withJSONObject: ["socket": server.unixPath, "port": Int(server.port), + "version": 1, "toolset": 3, "token": secret, "canPropose": proposals]) + return (server, try MCPGrantFile(create: url, data: data)) + }.value + guard ticket == pendingGrant, model.documentID == draft, presentationIsCurrent?() != false else { + Task.detached { server.stop(); file.remove() } + throw CancellationError() + } + revoke() + selected = model + sessionID = id + token = secret + documentID = model.documentID + grantFile = file + listener = server + canPropose = proposals + activeTitle = model.title + message = nil + documentChange = model.$documentID.dropFirst().sink { [weak self] _ in _ = self?.revoke() } + } + + @discardableResult + func revoke() -> Task { + pendingGrant = UUID() + pendingModel = nil + token = "" + canPropose = false + current = nil + history.removeAll() + guest.reset() + reviewWindow?.orderOut(nil) + reviewWindow = nil + selected = nil + documentID = nil + sessionID = "" + documentChange = nil + activeTitle = nil + let old = listener, file = grantFile + listener = nil + grantFile = nil + return Task.detached { + old?.stop() + file?.remove() + } + } + + func closing(_ model: BASICDevelopmentModel) { + if selected === model || pendingModel === model { revoke() } + if panelModel === model { + panel?.close() + panel = nil + panelModel = nil + } + } + + private func reply(to data: Data, session: String) async -> Data { + func pack(_ value: [String: Any]) -> Data { + (try? JSONSerialization.data(withJSONObject: value)) ?? Data(#"{"error":"encoding_error"}"#.utf8) + } + guard let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + let supplied = request["token"] as? String, sessionID == session, + !token.isEmpty, supplied == token, let model = selected, model.documentID == documentID + else { return pack(["error": "access_denied"]) } + guard request["version"] as? Int == 1 else { return pack(["error": "version_mismatch"]) } + guard let args = request["arguments"] as? [String: Any] else { return pack(["error": "invalid_arguments"]) } + let id = model.documentID.uuidString + let result: [String: Any] + switch request["tool"] as? String { + case "get_capabilities" where args.isEmpty: + result = ["tools": ["get_capabilities", "get_machine_status", "read_source", "search_help", "read_topic"] + (canPropose ? ["propose_edit", "propose_listing", "get_proposal", "get_run", "read_screen_text", "send_keys", "get_debug_snapshot", "read_debug_memory"] : []), + "version": 1, "input_diagnostics": true, "session_id": session, "title": model.title, "document_id": id, + "app": "VCC Plus OSS", "build": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown"] + case "get_machine_status" where args.isEmpty: + let observed = await model.machine.mcpReadinessSnapshot() + guard sessionID == session, selected === model, model.documentID == documentID else { return pack(["error": "access_denied"]) } + refreshProposal(model) + var blockers: [String] = [] + if !canPropose { blockers.append("Save a review and run connection to start a shared program.") } + if current?.status != "applied" || current?.appliedRevision != model.sourceRevision { + blockers.append("Apply a proposal for the current BASIC draft.") + } + if model.editorLocked || model.machine.busy || guest.busy { blockers.append("Wait for the current operation to finish.") } + result = MCPMachineStatus.result(observed, workspace: .basic, buildBlockers: nil, runBlockers: blockers, + profile: model.machine.usageProfile, input: model.machine.inputDiagnostics(machine: observed)) + case "read_source" where args.count == 1: + guard args["document_id"] as? String == id else { return pack(["error": "access_denied"]) } + guard model.source.utf8.count <= 65536 else { return pack(["error": "source_too_large"]) } + result = ["document_id": id, "text": model.source, "revision": model.sourceRevision, "title": model.title] + case let name? where name == "propose_edit" || name == "propose_listing": + guard canPropose else { return pack(["error": "access_denied"]) } + return pack(propose(args, model: model, wholeListing: name == "propose_listing")) + case "get_proposal": + guard canPropose else { return pack(["error": "access_denied"]) } + guard args.count == 1, let id = args["proposal_id"] as? String, let proposal = history[id] else { + return pack(["error": "unknown_proposal"]) + } + refreshProposal(model) + return pack(["result": (history[id] ?? proposal).result]) + case let name? where ["get_run", "get_debug_snapshot", "read_debug_memory", "read_screen_text", "send_keys"].contains(name): + guard canPropose else { return pack(["error": "access_denied"]) } + let reply = await guest.handle(tool: name, arguments: args, model: model) + guard sessionID == session, selected === model, model.documentID == documentID else { return pack(["error": "access_denied"]) } + return pack(reply) + case let tool? where tool == "search_help" || tool == "read_topic": + let response = await MCPHelpIndex.toolResult(tool, arguments: args) + guard sessionID == session, selected === model, documentID == model.documentID else { + return pack(["error": "access_denied"]) + } + return pack(response) + default: + return pack(["error": "invalid_arguments"]) + } + guard sessionID == session, selected === model, documentID == model.documentID else { + return pack(["error": "access_denied"]) + } + return pack(["result": result]) + } + + private func update(_ proposal: BASICEditProposal) { + current = proposal + history[proposal.id] = proposal + } + + fileprivate func refreshProposal(_ model: BASICDevelopmentModel) { + guard var proposal = current else { return } + if proposal.status == "pending", proposal.revision != model.sourceRevision { + proposal.status = "stale" + update(proposal) + } + } + + private func propose(_ args: [String: Any], model: BASICDevelopmentModel, wholeListing: Bool) -> [String: Any] { + guard args["document_id"] as? String == model.documentID.uuidString else { return ["error": "access_denied"] } + func integer(_ key: String) -> Int? { + guard let number = args[key] as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), + !["d", "f"].contains(String(cString: number.objCType)) else { return nil } + return Int(exactly: number) + } + guard let revision = integer("revision"), revision >= 0, + let requestID = args["request_id"] as? String, (1...128).contains(requestID.utf8.count) + else { return ["error": "invalid_arguments"] } + let line: Int? + let replacement: String + if wholeListing { + guard args.count == 4, let listing = args["source"] as? String, + (1...12 * 1024).contains(listing.utf8.count) else { return ["error": "invalid_arguments"] } + let lines = listing.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n") + guard lines.allSatisfy({ $0.utf8.count <= 249 && $0.utf8.allSatisfy { $0 == 9 || (32...126).contains($0) } }) + else { return ["error": "invalid_listing"] } + let analysis = BASICLanguage.analyze(listing) + guard !analysis.hasErrors, !analysis.lines.isEmpty else { return ["error": "invalid_listing"] } + line = nil + replacement = listing + } else { + guard args.count == 5, let number = integer("line_number"), let text = args["replacement"] as? String, + (1...249).contains(text.utf8.count), text.utf8.allSatisfy({ $0 == 9 || (32...126).contains($0) }), + BASICLanguage.lineRange(for: number, in: text) != nil else { return ["error": "invalid_arguments"] } + line = number + replacement = text + } + refreshProposal(model) + if let retry = history.values.first(where: { $0.requestID == requestID }) { + guard retry.revision == revision, retry.line == line, retry.after == replacement else { return ["error": "request_id_conflict"] } + return ["result": retry.result] + } + guard revision == model.sourceRevision else { return ["error": "stale_revision"] } + guard current?.status != "pending" else { return ["error": "review_pending"] } + guard history.count < 128 else { return ["error": "session_proposal_limit"] } + guard model.source.utf8.count <= 65536 else { return ["error": "source_too_large"] } + let before: String + if let line { + guard let range = BASICLanguage.lineRange(for: line, in: model.source) else { return ["error": "line_not_found"] } + before = (model.source as NSString).substring(with: range) + } else { + before = model.source + } + guard before != replacement else { return ["error": wholeListing ? "unchanged_listing" : "unchanged_line"] } + let proposal = BASICEditProposal(requestID: requestID, revision: revision, line: line, before: before, after: replacement) + update(proposal) + showReview(model) + return ["result": proposal.result] + } + + fileprivate func showReview(_ model: BASICDevelopmentModel) { + guard selected === model, current != nil else { return } + if let reviewWindow { + if !regressionFixture { reviewWindow.makeKeyAndOrderFront(nil) } + return + } + let window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 595, height: 340), + styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false) + window.title = fixtureLabel.map { "Review BASIC Edit — " + $0 } ?? "Review BASIC Edit" + window.isReleasedWhenClosed = false + window.contentMinSize = NSSize(width: 440, height: 280) + let content = NSHostingView(rootView: ScrollView { MCPReviewView(access: self, model: model, guest: guest) }) + content.sizingOptions = [] + window.contentView = content + window.center() + reviewWindow = window + if !regressionFixture { + #if DEBUG + if let label = fixtureLabel, let bounds = window.screen?.visibleFrame { + let side: CGFloat = label.lowercased().contains("ollama") ? 1 : -1 + let offset = max(0, min(bounds.width / 4, (bounds.width - window.frame.width) / 2)) + window.setFrameOrigin(NSPoint(x: bounds.midX - window.frame.width / 2 + side * offset, y: window.frame.minY)) + } + #endif + window.makeKeyAndOrderFront(nil) + NSApp.requestUserAttention(.informationalRequest) + } + #if DEBUG + if let index = CommandLine.arguments.firstIndex(of: "--mcp-validation-dir"), CommandLine.arguments.indices.contains(index + 1) { + let directory = URL(fileURLWithPath: CommandLine.arguments[index + 1]) + try? Data(String(window.windowNumber).utf8).write(to: directory.appendingPathComponent("review-window-id")) + } + #endif + } + + fileprivate func decide(_ id: String, model: BASICDevelopmentModel, apply: Bool) { + guard var proposal = current, proposal.id == id, proposal.status == "pending" else { return } + guard selected === model, model.documentID == documentID, model.sourceRevision == proposal.revision else { + proposal.status = "stale"; update(proposal); return + } + guard apply else { proposal.status = "cancelled"; update(proposal); return } + guard !model.editorLocked, let range = proposal.range(in: model.source), + let editor = model.assistantEditor, editor.window != nil, let manager = editor.undoManager else { + message = "Open the BASIC source editor and finish any active edit before applying."; return + } + let source = model.source as NSString + guard source.substring(with: range) == proposal.before else { proposal.status = "stale"; update(proposal); return } + let revised = source.replacingCharacters(in: range, with: proposal.after) + // Remote decisions can arrive in the same AppKit event group. Give each + // approved replacement a top-level Undo without absorbing earlier typing. + let automaticGroups = manager.groupsByEvent + guard !manager.isUndoing, !manager.isRedoing, manager.groupingLevel <= (automaticGroups ? 1 : 0) + else { message = "Finish the current editor operation before applying."; return } + editor.breakUndoCoalescing() + if manager.groupingLevel == 1 { manager.endUndoGrouping() } + manager.groupsByEvent = false + manager.beginUndoGrouping() + defer { + manager.endUndoGrouping() + manager.groupsByEvent = automaticGroups + } + let action = BASICEditorAction(expectedSource: model.source, operation: .replace(source: revised, undoName: "Assistant BASIC Edit")) + guard editor.applyEditorAction(action, revealReplacementAt: range.location), + model.source == revised else { message = "The source editor could not apply this edit."; return } + proposal.status = "applied" + proposal.appliedRevision = model.sourceRevision + message = nil + update(proposal) + } + + fileprivate func undo(_ id: String, model: BASICDevelopmentModel) { + guard var proposal = current, proposal.id == id, proposal.status == "applied", selected === model, + documentID == model.documentID, proposal.appliedRevision == model.sourceRevision, + !model.editorLocked, let editor = model.assistantEditor, let manager = editor.undoManager, + manager.canUndo, manager.undoActionName == "Assistant BASIC Edit" else { return } + manager.undo() + guard let range = proposal.range(in: model.source), + (model.source as NSString).substring(with: range) == proposal.before else { return } + proposal.status = "undone"; update(proposal) + } + + fileprivate func run(_ id: String, model: BASICDevelopmentModel, both: Bool) { + guard let proposal = current, proposal.id == id, proposal.status == "applied", !guest.busy, + selected === model, documentID == model.documentID, proposal.appliedRevision == model.sourceRevision else { return } + guard !both || Self.isRevisedPlanetExample(model.source) else { return } + let owner = sessionID + Task { [self, model] in + await guest.start(model: model, bothChoices: both, isCurrent: { [weak self, weak model] in + guard let self, let model else { return false } + return self.sessionID == owner && self.selected === model && self.documentID == model.documentID + && self.current?.id == id && self.current?.status == "applied" && proposal.appliedRevision == model.sourceRevision + }) + } + } + + fileprivate static func isRevisedPlanetExample(_ source: String) -> Bool { + let before = "90 PALETTE 6,37:M$=\"Hello Cold Red Dot World!\"" + let after = "90 PALETTE 6,37:M$=\"Bring a warm coat!\"" + let starter = BASICLanguage.sample + guard starter.contains(before) else { return false } + let revised = starter.replacingOccurrences(of: before, with: after) + return revised.split(whereSeparator: \.isNewline) == source.split(whereSeparator: \.isNewline) + } + + #if DEBUG + private func captureFixtureContent(_ window: NSWindow, to file: URL) { + guard let content = window.contentView else { return } + content.layoutSubtreeIfNeeded() + content.displayIfNeeded() + guard let bitmap = content.bitmapImageRepForCachingDisplay(in: content.bounds) else { return } + content.cacheDisplay(in: content.bounds, to: bitmap) + try? bitmap.representation(using: .png, properties: [:])?.write(to: file) + } + + /// Available only after the app delegate has created an isolated interface-validation machine. + func validate(model: BASICDevelopmentModel, other: BASICDevelopmentModel, in directory: URL) async throws { + var info = stat() + guard lstat(directory.path, &info) == 0, (info.st_mode & S_IFMT) == S_IFDIR, info.st_uid == geteuid(), + info.st_mode & 0o077 == 0 else { throw POSIXError(.EACCES) } + let args = CommandLine.arguments + let review = args.firstIndex(of: "--mcp-edit-review").flatMap { args.indices.contains($0 + 1) ? args[$0 + 1] : nil } + let regression = review != nil && args.contains("--mcp-review-regression") + regressionFixture = regression + if regression { + try Data().write(to: directory.appendingPathComponent("regression-fixture"), options: .withoutOverwriting) + } + if let review { + fixtureLabel = review + if let i = args.firstIndex(of: "--mcp-rom-dir"), args.indices.contains(i + 1) { + try await MCPBASICRun.bootFixture(model.machine, romDirectory: URL(fileURLWithPath: args[i + 1])) + } + model.source = regression && args.contains("--mcp-blank-draft") ? "" : BASICLanguage.sample + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1050, height: 720), + styleMask: [.titled, .resizable, .miniaturizable], backing: .buffered, defer: false) + window.title = "BASIC Development — " + review + let content = NSHostingView(rootView: BASICDevelopmentView(model: model)) + content.sizingOptions = [] + window.contentView = content + window.center() + fixtureEditor = window + if regression { window.orderBack(nil) } else { window.orderFront(nil) } + content.layoutSubtreeIfNeeded() + } else { + model.source = "10 REM MCP LOCAL PROOF\n20 PRINT 6*7\n" + } + other.source = "10 REM PRIVATE UNSHARED EXAMPLE\n" + let path = directory.appendingPathComponent("grant.json") + try Data(other.documentID.uuidString.utf8).write(to: directory.appendingPathComponent("other-id"), options: .withoutOverwriting) + try await grant(model, at: path, proposals: review != nil) + if review == nil { show(for: model) } + if let id = panel?.windowNumber, id > 0 { + try Data(String(id).utf8).write(to: directory.appendingPathComponent("panel-window-id"), options: .withoutOverwriting) + if CommandLine.arguments.contains("--mcp-capture-panel") { + if let panel { captureFixtureContent(panel, to: directory.appendingPathComponent("access.png")) } + } + } + fixturePoll = Task { @MainActor [weak self] in + func consume(_ name: String) -> Bool { unlink(directory.appendingPathComponent(name).path) == 0 } + func mark(_ name: String) { try? Data().write(to: directory.appendingPathComponent(name)) } + while !Task.isCancelled { + try? await Task.sleep(nanoseconds: 200_000_000) + guard let self, !Task.isCancelled else { return } + if consume("revoke") { await self.revoke().value; mark("revoked") } + if (review == nil || regression), consume("edit") { model.source += review == nil ? "30 REM UPDATED DRAFT\n" : "9000 REM UPDATED DRAFT\n"; mark("edited") } + if consume("reconnect") { + do { try await self.grant(model, at: path, proposals: review != nil); mark("reconnected") } + catch { NSLog("MCP fixture reconnection failed: %@", error.localizedDescription) } + } + if regression, let proposal = self.current { + if consume("apply") { self.decide(proposal.id, model: model, apply: true); mark("applied") } + if consume("cancel") { self.decide(proposal.id, model: model, apply: false); mark("cancelled") } + if consume("undo") { self.undo(proposal.id, model: model); mark("undone") } + if consume("save-reopen"), proposal.status == "applied" { + let target = directory.appendingPathComponent("Reviewed.bas") + let reopened = BASICDevelopmentModel(machine: model.machine, directory: directory.appendingPathComponent("Reopened Workspace")) + if !FileManager.default.fileExists(atPath: target.path), model.saveSource(to: target), + reopened.openSource(at: target), reopened.source == model.source, !reopened.dirty { + mark("saved-and-reopened") + } + } + if consume("run-both") { self.run(proposal.id, model: model, both: true); mark("run-started") } + if consume("run") { self.run(proposal.id, model: model, both: false); mark("run-started") } + if consume("capture-review"), let window = self.reviewWindow { + window.orderFront(nil) + try? await Task.sleep(for: .milliseconds(350)) + self.captureFixtureContent(window, to: directory.appendingPathComponent("review.png")) + window.orderOut(nil) + } + if consume("capture-result"), self.guest.receipt != nil, let window = self.reviewWindow { + window.setContentSize(NSSize(width: 640, height: 480)) + window.orderFront(nil) + try? await Task.sleep(for: .milliseconds(400)) + let capture = Process() + capture.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture") + capture.arguments = ["-x", "-o", "-l", String(window.windowNumber), directory.appendingPathComponent("verified.png").path] + capture.terminationHandler = { _ in Task { @MainActor in window.orderOut(nil) } } + do { try capture.run() } catch { window.orderOut(nil) } + } + } + if consume("quit") { + await self.revoke().value + if review == nil || regression { model.source = model.savedSource } + other.source = other.savedSource + // AppKit's termination loop must be entered from a run-loop event, + // so the main actor remains available to finish asynchronous shutdown. + NSApp.perform(#selector(NSApplication.terminate(_:)), with: nil, afterDelay: 0) + return + } + } + } + } + #endif +} + +struct MCPGrantFile { + let url: URL + let device: dev_t + let inode: ino_t + + init(create url: URL, data: Data) throws { + let fd = open(url.path, O_CREAT | O_WRONLY | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + var info = stat() + do { + guard fstat(fd, &info) == 0 else { throw POSIXError(.EIO) } + try file.write(contentsOf: data) + try file.close() + } catch { + unlink(url.path) + throw error + } + self.url = url + device = info.st_dev + inode = info.st_ino + } + + func remove() { + var info = stat() + if lstat(url.path, &info) == 0 && info.st_dev == device && info.st_ino == inode { unlink(url.path) } + } +} + +private struct MCPAccessView: View { + @ObservedObject var access: MCPAccess + @ObservedObject var model: BASICDevelopmentModel + @State private var proposals = false + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Label(model.title, systemImage: "doc.text").font(.headline) + Text("A local assistant with the connection file can read this BASIC draft, including unsaved edits, search the installed manuals, and check the guest processor and mounted drive status. Its model provider may receive that text.") + + if let name = access.activeTitle, access.selected !== model { + Label("Another BASIC editor is sharing \(name).", systemImage: "link") + Button("Revoke That Connection") { access.revoke() } + } else if let name = access.activeTitle { + Label("Sharing: \(name)", systemImage: "link").accessibilityIdentifier("mcp.access.active") + if let file = access.grantFile { + MCPChatGPTSetup(grantURL: file.url, firstPrompt: "Use VCC Plus to identify my shared BASIC draft and read its source. Tell me its title and what the program does.") + } + if access.canPropose { + Text("Edits require native review. Starting a reviewed run permits bounded guest input and inspection of its screen, debugger registers, watches and program memory.") + if access.current != nil { Button("Show Edit Review…") { access.showReview(model) } } + } + Button("Revoke Access") { access.revoke() }.accessibilityIdentifier("mcp.access.revoke") + } else { + Toggle("Allow proposed edits and controls for runs I start", isOn: $proposals) + Button(proposals ? "Save Review and Run Connection…" : "Save Read-Only Connection…") { + access.chooseGrant(for: model, proposals: proposals) + }.accessibilityIdentifier("mcp.access.grant") + } + if let message = access.message { Text(message).foregroundStyle(.secondary) } + }.padding(18).frame(maxWidth: .infinity, alignment: .leading) + } +} + +private struct MCPReviewView: View { + @ObservedObject var access: MCPAccess + @ObservedObject var model: BASICDevelopmentModel + @ObservedObject var guest: MCPBASICRun + + var body: some View { + if let p = access.current { + VStack(alignment: .leading, spacing: 13) { + Label(model.title, systemImage: "doc.text").font(.headline) + if let revision = p.appliedRevision { + Text("\(p.subject) · Reviewed revision \(p.revision) → applied revision \(revision)").foregroundStyle(.secondary) + } else { + Text("\(p.subject) · Draft revision \(p.revision)").foregroundStyle(.secondary) + } + line(p.appliedRevision == nil ? "Current" : "Before", p.before, color: .red, listing: p.line == nil) + line(p.appliedRevision == nil ? "Proposed" : "Applied", p.after, color: .green, listing: p.line == nil) + switch p.status { + case "pending": + HStack { + Button("Cancel Edit") { access.decide(p.id, model: model, apply: false) } + Button("Apply Edit") { access.decide(p.id, model: model, apply: true) }.buttonStyle(.borderedProminent) + } + case "applied": + Text("Applied to the BASIC draft.").font(.headline) + HStack { + Button("Undo Edit") { access.undo(p.id, model: model) } + Button("Run") { access.run(p.id, model: model, both: false) } + if MCPAccess.isRevisedPlanetExample(model.source) { + Button("Run Both Choices") { access.run(p.id, model: model, both: true) } + .help("Verify the Earth and revised Mars greetings, their backgrounds, and a fresh PRINT 7 command.") + } + }.disabled(guest.busy || p.appliedRevision != model.sourceRevision) + if !guest.status.isEmpty { Text(guest.status).textSelection(.enabled) } + if let branches = guest.receipt?["branches"] as? [[String: Any]] { + ForEach(branches.indices, id: \.self) { index in + let branch = branches[index] + if let rgb = branch["background_rgb"] as? String, let value = UInt32(rgb.dropFirst(), radix: 16), + let text = branch["greeting"] as? String { + HStack(spacing: 8) { + RoundedRectangle(cornerRadius: 3) + .fill(Color(red: Double(value >> 16 & 255) / 255, green: Double(value >> 8 & 255) / 255, blue: Double(value & 255) / 255)) + .frame(width: 18, height: 18).accessibilityHidden(true) + Text(branch["key"] as? String == "2" ? "Mars" : "Earth").fontWeight(.semibold) + Text(text.trimmingCharacters(in: .whitespaces)) + Text(rgb).font(.system(.caption, design: .monospaced)) + }.textSelection(.enabled) + } + } + } + if let message = model.message { Text(message).foregroundStyle(.secondary) } + case "stale": Text("The draft changed. Ask the assistant to read it again and propose a fresh edit.") + case "undone": Text("Edit undone.") + default: Text("Edit cancelled.") + } + if let message = access.message { Text(message).foregroundStyle(.secondary) } + }.padding(18).frame(maxWidth: .infinity, alignment: .leading) + .onChange(of: model.sourceRevision) { _, _ in access.refreshProposal(model) } + } + } + + private func line(_ label: String, _ text: String, color: Color, listing: Bool) -> some View { + VStack(alignment: .leading, spacing: 4) { + Text(label).font(.caption.weight(.semibold)) + if listing && text.isEmpty { + Text("Empty draft").foregroundStyle(.secondary) + } else if listing && text.components(separatedBy: .newlines).count > 5 { + ScrollView { + Text(verbatim: text).frame(maxWidth: .infinity, alignment: .leading) + .font(.system(.body, design: .monospaced)).textSelection(.enabled) + }.frame(height: 110) + } else { + Text(verbatim: text).font(.system(.body, design: .monospaced)).textSelection(.enabled) + } + }.padding(9).frame(maxWidth: .infinity, alignment: .leading).background(color.opacity(0.10), in: RoundedRectangle(cornerRadius: 5)) + } +} diff --git a/platforms/macos/App/MCPArchiveAccess.swift b/platforms/macos/App/MCPArchiveAccess.swift new file mode 100644 index 0000000..d2cfbc8 --- /dev/null +++ b/platforms/macos/App/MCPArchiveAccess.swift @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import Foundation +import SwiftUI + +/// A separate grant with its own listener and no reference to a workspace or emulator. +@MainActor +final class MCPArchiveAccess: ObservableObject { + static let shared = MCPArchiveAccess(catalog: .shared) + private let catalog: ArchiveLibraryCatalog + private var listener: MCPTransport? + private var secret: String? + private var pending: UUID? + private var panel: NSPanel? + @Published private(set) var grantFile: MCPGrantFile? + @Published fileprivate var message: String? + + init(catalog: ArchiveLibraryCatalog) { self.catalog = catalog } + + func show() { + if let panel { + panel.makeKeyAndOrderFront(nil) + return + } + let window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 540, height: 380), + styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false) + window.title = "Archive Search Connection" + window.isReleasedWhenClosed = false + window.contentMinSize = NSSize(width: 360, height: 230) + let content = NSHostingView(rootView: ScrollView { MCPArchiveAccessView(access: self) }) + content.sizingOptions = [] + window.contentView = content + window.center() + panel = window + window.makeKeyAndOrderFront(nil) + } + + fileprivate func chooseGrant() { + let picker = NSSavePanel() + picker.nameFieldStringValue = "VCC Plus OSS Archive Search.json" + picker.title = "Save Archive Search Connection" + picker.message = "Choose a new file for the assistant that will search the Archive." + guard picker.runModal() == .OK, let url = picker.url else { return } + Task { + do { try await connect(at: url) } + catch is CancellationError {} + catch { message = "Could not save the connection. " + error.localizedDescription } + } + } + + func connect(at url: URL) async throws { + let ticket = UUID() + pending = ticket + defer { if pending == ticket { pending = nil } } + let token = UUID().uuidString + UUID().uuidString + let handler: MCPTransport.Handler = { [weak self] bytes in + guard let self else { return Self.denied } + return await self.reply(to: bytes, connection: token) + } + let (server, file) = try await Task.detached(priority: .userInitiated) { + let server = try MCPTransport(handler: handler) + let bytes = try JSONSerialization.data(withJSONObject: ["kind": "archive", "version": 2, "token": token, + "socket": server.unixPath, "port": Int(server.port)]) + return (server, try MCPGrantFile(create: url, data: bytes)) + }.value + guard pending == ticket else { + await Task.detached { server.stop(); file.remove() }.value + throw CancellationError() + } + revoke() + listener = server + secret = token + grantFile = file + message = nil + } + + @discardableResult + func revoke() -> Task { + pending = nil + secret = nil + let old = listener, file = grantFile + listener = nil + grantFile = nil + message = nil + return Task.detached { old?.stop(); file?.remove() } + } + + private nonisolated static let denied = Data(#"{"error":"access_denied"}"#.utf8) + + private func reply(to data: Data, connection: String) async -> Data { + guard let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + secret == connection, request["token"] as? String == connection else { return Self.denied } + let response: [String: Any] + if Self.integer(request["version"]) != 1 { + response = ["error": "version_mismatch"] + } else if let tool = request["tool"] as? String, let args = request["arguments"] as? [String: Any] { + do { response = try await perform(tool, args) } + catch ArchiveLibraryError.input(let message) { response = ["error": message] } + catch { response = ["error": "archive_index_unavailable"] } + } else { + response = ["error": "invalid_arguments"] + } + // The user can revoke or replace the grant while SQLite serves an asynchronous query. + guard secret == connection else { return Self.denied } + return (try? JSONSerialization.data(withJSONObject: response)) ?? Data(#"{"error":"encoding_error"}"#.utf8) + } + + private func perform(_ tool: String, _ args: [String: Any]) async throws -> [String: Any] { + switch tool { + case "search_archive": + guard Set(args.keys).isSubset(of: ["query", "category", "limit", "offset"]), + let query = args["query"] as? String, !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + query.unicodeScalars.count <= 256, + let limit = Self.integer(args["limit"] ?? 10), (1...50).contains(limit), + let offset = Self.integer(args["offset"] ?? 0), (0...250_000).contains(offset) + else { return ["error": "invalid_arguments"] } + let category = args["category"] as? String + if args["category"] != nil { + guard let category, !category.isEmpty, category.unicodeScalars.count <= 512 else { + return ["error": "invalid_arguments"] + } + } + let hits = try await catalog.search(query: query, collection: category, limit: limit, offset: offset) + var result: [String: Any] = ["results": hits.map(Self.publicCitation), "offset": offset] + if hits.count == limit && offset + limit <= 250_000 { result["next_offset"] = offset + limit } + return ["result": result] + case "get_archive_citation": + guard args.count == 1, let id = args["citation_id"] as? String, !id.isEmpty, id.utf8.count <= 128 + else { return ["error": "invalid_arguments"] } + guard let hit = try await catalog.citation(id: id) else { return ["error": "citation_unavailable"] } + return ["result": Self.publicCitation(hit)] + default: + return ["error": "access_denied"] + } + } + + private static func integer(_ value: Any?) -> Int? { + guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), + !CFNumberIsFloatType(number) else { return nil } + return Int(number.stringValue) + } + + private static func publicCitation(_ hit: ArchiveHit) -> [String: Any] { + var value: [String: Any] = ["citation_id": hit.id, "document_sha256": hit.document.id, + "title": hit.document.title, "collection": hit.document.collection, "citation": hit.citation, + "source_url": hit.sourceURL.absoluteString, "locator": hit.locator, "ocr": hit.ocr] + if let page = hit.page { value["pdf_page"] = page } + if let member = hit.document.memberPath { value["member_path"] = member } + return value + } +} + +private struct MCPArchiveAccessView: View { + @ObservedObject var access: MCPArchiveAccess + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Connect a local assistant to search the Archive and look up citations. Its model provider may receive your queries and the public references it finds.").fixedSize(horizontal: false, vertical: true) + if let file = access.grantFile { + Label("Archive search is available to this connection.", systemImage: "link") + Button("Revoke Archive Access") { access.revoke() } + Divider() + MCPChatGPTSetup(grantURL: file.url, firstPrompt: "Use Archive Search to find a reference to JOYSTK and give me its original source and page.") + } else { + Button("Save Archive Search Connection…") { access.chooseGrant() } + } + if let message = access.message { Text(message).font(.callout).textSelection(.enabled) } + }.padding().frame(maxWidth: .infinity, alignment: .leading) + } +} diff --git a/platforms/macos/App/MCPAssembly.swift b/platforms/macos/App/MCPAssembly.swift new file mode 100644 index 0000000..bb3dcd7 --- /dev/null +++ b/platforms/macos/App/MCPAssembly.swift @@ -0,0 +1,741 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import Combine +import SwiftUI + +struct AssemblyProjectEdit { + let path: String + let before: String + let after: String +} + +@MainActor +private final class AssemblyAccessWindowDelegate: NSObject, NSWindowDelegate { + let didClose: @MainActor (NSWindow) -> Void + init(didClose: @escaping @MainActor (NSWindow) -> Void) { self.didClose = didClose; super.init() } + func windowWillClose(_ notification: Notification) { + if let window = notification.object as? NSWindow { didClose(window) } + } +} + +/// A connection is bound to one native assembly document and its original source-file set. +@MainActor +final class MCPAssembly: ObservableObject { + static let shared = MCPAssembly() + static let tools = ["get_capabilities", "get_machine_status", "get_debug_snapshot", "read_debug_memory", "search_help", "read_topic", "read_project_file", "build_project", "get_build", "propose_fix", "propose_project_edits", "get_proposal", "get_run", "read_screen_text", "send_keys"] + private weak var model: AssemblyDevelopmentModel? + private weak var editors: AssemblyEditorPool? + private var transport: MCPTransport? + private var file: MCPGrantFile? + fileprivate var grantURL: URL? { file?.url } + private var scope = UUID() + private var token = "" + private var documentID: UUID? + private var files: Set = [] + private var last: AssemblyProjectSnapshot? + private var lastSourceRevision: UUID? + private var revision = 0 + private var selection: AnyCancellable? + private var editObservation: AnyCancellable? + private var window: NSPanel? + private var windowPresentation = UUID() + private lazy var windowDelegate = AssemblyAccessWindowDelegate { [weak self] closing in + guard let self, self.window === closing else { return } + self.windowPresentation = UUID() + } + private var buildTask: Task? + private var requests: [String: (tool: String, args: NSDictionary, id: String)] = [:] + private var latestBuildID: String? + private var builds: [String: [String: Any]] = [:] + private var proposals: [String: [String: Any]] = [:] + private var built: (id: String, revision: Int, artifact: AssemblyBuildArtifact)? + private var inspection: MCPDebuggerInspection? + private var runIO: MCPCompiledRunIO? + private var run: (id: String, revision: Int, build: String, machine: VCCMachineSnapshot)? { + willSet { runIO?.invalidate(); runIO = nil } + } + private var runMessage = "No run started." + @Published private(set) var connected = false + @Published private(set) var canRun = false + @Published private(set) var status = "" + @Published private(set) var proposal: Proposal? + + struct Proposal: Identifiable { + enum Content { + case line(path: String, number: Int, before: String, after: String) + case files([AssemblyProjectEdit]) + } + let id: String + let revision: Int + let content: Content + } + private struct AppliedFiles { + let proposal: Proposal + let revision: Int + let removedStops: Set + } + @Published private var appliedFiles: AppliedFiles? + fileprivate var runnableBuildID: String? { canRun ? built?.id : nil } + fileprivate var undoableProposalID: String? { proposal == nil ? appliedFiles?.proposal.id : nil } + + func show(_ model: AssemblyDevelopmentModel, editors: AssemblyEditorPool) { + windowPresentation = UUID() + if self.model !== model { revoke() } + self.model = model + self.editors = editors + let panel = window ?? NSPanel(contentRect: NSRect(x: 0, y: 0, width: 670, height: 460), + styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false) + panel.title = "Assembly Assistant Access" + panel.isReleasedWhenClosed = false + panel.delegate = windowDelegate + panel.contentView = NSHostingView(rootView: AssemblyAccessView(access: self, model: model)) + if window == nil { panel.center() } + window = panel + panel.makeKeyAndOrderFront(nil) + } + + func close(for model: AssemblyDevelopmentModel) { + guard self.model === model else { return } + revoke() + window?.close() + window = nil + } + + fileprivate func choose(_ model: AssemblyDevelopmentModel) { + guard let owner = window, self.model === model, owner.isVisible, + !owner.isMiniaturized, owner.attachedSheet == nil else { return } + let document = model.activeID, generation = scope, presentation = windowPresentation + let panel = NSSavePanel() + panel.title = "Save Assembly Connection" + panel.nameFieldStringValue = "VCC Plus OSS Assembly Connection.json" + panel.beginSheetModal(for: owner) { [weak self, weak owner, weak model] response in + Task { @MainActor [weak self, weak owner, weak model] in + guard let self, let owner, let model else { return } + @MainActor func currentPresentation() -> Bool { + self.windowPresentation == presentation && self.window === owner && self.model === model && owner.isVisible && + !owner.isMiniaturized && model.activeID == document + } + guard currentPresentation(), self.scope == generation else { return } + defer { if currentPresentation() { owner.makeKeyAndOrderFront(nil) } } + guard response == .OK, let url = panel.url else { return } + do { try await self.connect(model, to: url, presentationIsCurrent: currentPresentation) } + catch is CancellationError { } + catch { if currentPresentation() { self.status = error.localizedDescription } } + } + } + } + + func revoke() { + inspection = nil + scope = UUID(); token = ""; connected = false; documentID = nil; selection = nil; editObservation = nil + requests.removeAll(); builds.removeAll(); latestBuildID = nil; proposals.removeAll() + buildTask?.cancel(); buildTask = nil + proposal = nil; appliedFiles = nil; built = nil; last = nil; run = nil; runMessage = "No run started." + canRun = false; status = ""; files.removeAll(); revision = 0 + let old = transport, oldFile = file + transport = nil; file = nil + Task.detached { old?.stop(); oldFile?.remove() } + } + + private static func sourcePaths(_ snapshot: AssemblyProjectSnapshot) throws -> Set { + guard snapshot.settings.makefile == nil, snapshot.settings.linkScript == nil, + (snapshot.settings.modules ?? []).isEmpty else { + throw AssemblyBuildFailure("Share a native direct-assembly project. Linked projects and Make recipes require the local workspace.") + } + let paths = Set(snapshot.files.keys.filter { $0 != AssemblyProjectSnapshot.configurationFilename }) + let extensions = ["asm", "s", "inc", "lwasm", "a09"] + guard paths.contains(snapshot.mainPath), paths.count <= 32, snapshot.files.values.reduce(0, { $0 + $1.count }) <= 512 * 1024, + paths.allSatisfy({ path in + guard extensions.contains((path as NSString).pathExtension.lowercased()), let data = snapshot.files[path] else { return false } + return data.count <= 64 * 1024 && !data.contains(0) && String(data: data, encoding: .utf8) != nil + }) else { throw AssemblyBuildFailure("Share a project containing up to 32 UTF-8 assembly or include files, 64 KiB per file.") } + return paths + } + + func connect(_ model: AssemblyDevelopmentModel, to url: URL, + presentationIsCurrent: (@MainActor () -> Bool)? = nil) async throws { + revoke(); self.model = model + let ticket = scope, doc = model.document, version = model.workspaceRevision + let snapshot = try await Task.detached { try doc.snapshot() }.value + guard scope == ticket, model.activeID == doc.id, model.workspaceRevision == version, + presentationIsCurrent?() != false else { throw CancellationError() } + let paths = try Self.sourcePaths(snapshot) + let key = UUID().uuidString + UUID().uuidString + let handler: MCPTransport.Handler = { [weak self] bytes in + guard let self else { return Data(#"{"error":"access_denied"}"#.utf8) } + return await self.reply(bytes, ticket: ticket) + } + let pair = try await Task.detached { + let server = try MCPTransport(handler: handler) + let info: [String: Any] = ["kind": "assembly", "toolset": 3, "socket": server.unixPath, "port": Int(server.port), "version": 1, "token": key] + return (server, try MCPGrantFile(create: url, data: JSONSerialization.data(withJSONObject: info))) + }.value + guard scope == ticket, model.activeID == doc.id, model.workspaceRevision == version, + presentationIsCurrent?() != false else { + Task.detached { pair.0.stop(); pair.1.remove() } + throw CancellationError() + } + last = snapshot; lastSourceRevision = model.sourceRevision; files = paths; revision = 1 + documentID = doc.id; token = key; transport = pair.0; file = pair.1 + connected = true; status = "Sharing " + doc.title + editObservation = model.$sourceRevision.dropFirst().sink { [weak self] _ in self?.runIO?.invalidate() } + selection = model.$activeID.dropFirst().sink { [weak self] _ in self?.revoke() } + } + + private func snapshot(_ model: AssemblyDevelopmentModel, ticket: UUID, retry: Bool = true) async throws -> AssemblyProjectSnapshot { + let doc = model.document, version = model.workspaceRevision + let value = try await Task.detached { try doc.snapshot() }.value + guard scope == ticket, model.activeID == documentID, doc.id == documentID else { throw AssemblyBuildFailure("access_denied") } + if model.workspaceRevision != version { + guard retry else { throw AssemblyBuildFailure("revision_conflict") } + return try await snapshot(model, ticket: ticket, retry: false) + } + guard try Self.sourcePaths(value) == files else { throw AssemblyBuildFailure("Shared files changed. Export a new connection.") } + if last != value || lastSourceRevision != model.sourceRevision { + lastSourceRevision = model.sourceRevision + revision += 1; last = value; canRun = false; run = nil; runMessage = "No run started." + appliedFiles = nil + if let p = proposal { proposals[p.id]?["status"] = "stale"; proposal = nil } + } + return value + } + + private func reply(_ data: Data, ticket: UUID) async -> Data { + func pack(_ value: [String: Any]) -> Data { (try? JSONSerialization.data(withJSONObject: value)) ?? Data(#"{"error":"encoding_error"}"#.utf8) } + guard connected, ticket == scope, let model, model.activeID == documentID, + let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + let supplied = request["token"] as? String, supplied == token else { return pack(["error": "access_denied"]) } + guard request["version"] as? Int == 1, let args = request["arguments"] as? [String: Any], + let tool = request["tool"] as? String else { return pack(["error": "invalid_arguments"]) } + func currentGrant() -> Bool { + connected && scope == ticket && self.model === model && model.activeID == documentID + } + if tool == "search_help" || tool == "read_topic" { + let reply = await MCPHelpIndex.toolResult(tool, arguments: args) + guard currentGrant() else { return pack(["error": "access_denied"]) } + return pack(reply) + } + do { + let result = try await perform(tool, args, model: model, ticket: ticket) + guard currentGrant() else { return pack(["error": "access_denied"]) } + return pack(["result": result]) + } catch { return pack(["error": currentGrant() ? error.localizedDescription : "access_denied"]) } + } + + private func perform(_ tool: String, _ args: [String: Any], model: AssemblyDevelopmentModel, ticket: UUID) async throws -> [String: Any] { + let snapshot = try await snapshot(model, ticket: ticket) + guard connected, scope == ticket, self.model === model, model.activeID == documentID else { throw AssemblyBuildFailure("access_denied") } + let id = model.activeID.uuidString + if tool == "get_capabilities", args.isEmpty { + return ["version": 1, "input_diagnostics": true, "kind": "assembly", "language": "assembly", "session_id": scope.uuidString, + "project_id": id, "revision": revision, "entry": snapshot.mainPath, "target": snapshot.cpu.rawValue, + "files": files.sorted(), "tools": Self.tools] + } + if tool == "get_machine_status", args.isEmpty { + let observed = await model.machine.mcpReadinessSnapshot() + var build = await MCPMachineStatus.missingToolBlockers(in: model.service.tools.toolchain, requiring: ["lwasm"]) + var run: [String] = [] + if requests.count >= 64 { build.append("Reconnect to start another build.") } + if buildTask != nil || model.working || model.commanding { build.append("Wait for the current build or editor command.") } + if !canRun || built?.artifact.snapshot != snapshot { run.append("Assemble the current project revision.") } + if proposal != nil { run.append("Review the pending assembly edit.") } + if model.machine.busy || model.working || model.commanding { run.append("Wait for the current machine or editor operation.") } + return MCPMachineStatus.result(observed, workspace: .assembly(needs6309: snapshot.cpu == .hd6309), + buildBlockers: build, runBlockers: run, lastBuild: latestBuildID.flatMap(buildRecord), + profile: model.machine.usageProfile, input: model.machine.inputDiagnostics(machine: observed)) + } + if tool == "get_build" { + guard args.count == 1, let key = args["build_id"] as? String else { throw AssemblyBuildFailure("invalid_arguments") } + guard let record = buildRecord(key) else { throw AssemblyBuildFailure("unknown_build") } + return record + } + if tool == "get_proposal" { + guard args.count == 1, let key = args["proposal_id"] as? String else { throw AssemblyBuildFailure("invalid_arguments") } + guard let record = proposals[key] else { throw AssemblyBuildFailure("unknown_proposal") } + return record + } + if tool == "read_screen_text" || tool == "send_keys" { + guard let run, let built, let runIO, run.revision == revision, run.build == built.id, + model.artifact?.id == built.artifact.id else { throw AssemblyBuildFailure("stale_run") } + let epoch = model.workspaceRevision + let result = try await runIO.reply(tool, arguments: args) + guard connected, scope == ticket, self.runIO === runIO, model.activeID == documentID, + model.workspaceRevision == epoch, revision == run.revision, + model.artifact?.id == built.artifact.id else { throw AssemblyBuildFailure("stale_run") } + return result + } + if tool == "get_debug_snapshot" || tool == "read_debug_memory" { + guard let run, let built, run.id == args["run_id"] as? String, run.revision == revision, + run.build == built.id, model.artifact?.id == built.artifact.id else { throw AssemblyBuildFailure("stale_run") } + if tool == "get_debug_snapshot" { + guard args.count == 1 else { throw AssemblyBuildFailure("invalid_arguments") } + return try await runResult(model, ticket: ticket, inspect: true) + } + let epoch = model.workspaceRevision + let now = await model.machine.mcpMachineSnapshot() + guard scope == ticket, self.run?.id == run.id, model.activeID == documentID, model.workspaceRevision == epoch, + revision == run.revision, model.artifact?.id == built.artifact.id, + now.debuggerAssemblyAttached, MCPDebuggerInspection.sameProgram(now, run.machine), + let inspection else { throw AssemblyBuildFailure("stale_snapshot") } + return try inspection.reply(tool: tool, arguments: args) + } + guard args["project_id"] as? String == id else { throw AssemblyBuildFailure("access_denied") } + if tool == "read_project_file" { + guard args.count == 2, let path = args["path"] as? String, files.contains(path), let data = snapshot.files[path] else { + throw AssemblyBuildFailure("path_not_shared") + } + return ["project_id": id, "revision": revision, "path": path, "text": String(decoding: data, as: UTF8.self)] + } + guard let requestedRevision = integer(args["revision"]) else { throw AssemblyBuildFailure("invalid_arguments") } + if tool == "get_run", args.count == 2 { + guard requestedRevision == revision else { throw AssemblyBuildFailure("revision_conflict") } + return try await runResult(model, ticket: ticket) + } + guard ["build_project", "propose_fix", "propose_project_edits"].contains(tool) else { throw AssemblyBuildFailure("invalid_arguments") } + guard let requestID = args["request_id"] as? String, (1...(tool == "propose_project_edits" ? 128 : 64)).contains(requestID.utf8.count) + else { throw AssemblyBuildFailure("invalid_request_id") } + if tool == "propose_fix", integer(args["line_number"]) == nil { throw AssemblyBuildFailure("invalid_arguments") } + if let previous = requests[requestID] { + guard previous.tool == tool, previous.args.isEqual(to: args) else { throw AssemblyBuildFailure("request_conflict") } + if let record = buildRecord(previous.id) ?? proposals[previous.id] { return record } + } + guard requestedRevision == revision else { throw AssemblyBuildFailure("revision_conflict") } + guard requests.count < 64 else { throw AssemblyBuildFailure("session_request_limit") } + let key = UUID().uuidString + if tool == "build_project", args.count == 3 { + guard buildTask == nil, !model.working, !model.commanding else { throw AssemblyBuildFailure("build_busy") } + let number = revision, workspaceRevision = model.workspaceRevision + let record: [String: Any] = ["build_id": key, "project_id": id, "revision": number, "status": "building", "diagnostics": []] + latestBuildID = key + builds[key] = record; requests[requestID] = (tool, NSDictionary(dictionary: args), key) + built = nil; run = nil; canRun = false; runMessage = "No run started." + buildTask = Task { [weak self] in + await self?.build(model, inputs: snapshot, revision: number, id: key, ticket: ticket, workspaceRevision: workspaceRevision) + } + return record + } + if tool == "propose_project_edits" { + guard args.count == 4, proposal == nil else { throw AssemblyBuildFailure("invalid_proposal") } + let edits = try Self.projectEdits(args["edits"], snapshot: snapshot, shared: files) + let record: [String: Any] = ["proposal_id": key, "revision": revision, "status": "pending", + "kind": "project_edits", "files": edits.map(\.path)] + proposals[key] = record; requests[requestID] = (tool, NSDictionary(dictionary: args), key) + proposal = Proposal(id: key, revision: revision, content: .files(edits)) + status = "Review the proposed assembly files." + if let window { + window.makeKeyAndOrderFront(nil) + if !NSApp.isActive { NSApp.requestUserAttention(.informationalRequest) } + } + return record + } + guard tool == "propose_fix", args.count == 6, proposal == nil, let path = args["path"] as? String, files.contains(path), + let line = args["line_number"] as? Int, line > 0, let replacement = args["replacement"] as? String, + replacement.utf8.count <= 1024, !replacement.contains(where: { $0.isNewline || $0 == "\0" }), + let data = snapshot.files[path] else { throw AssemblyBuildFailure("invalid_proposal") } + let source = String(decoding: data, as: UTF8.self) + guard let range = Self.contentRange(line, source), range.length <= 4096 else { throw AssemblyBuildFailure("invalid_line") } + let before = (source as NSString).substring(with: range) + guard before != replacement else { throw AssemblyBuildFailure("unchanged_line") } + let growth = replacement.utf8.count - before.utf8.count + guard data.count + growth <= 64 * 1024, + snapshot.files.values.reduce(0, { $0 + $1.count }) + growth <= 512 * 1024 else { + throw AssemblyBuildFailure("project_too_large") + } + let record: [String: Any] = ["proposal_id": key, "revision": revision, "path": path, "line_number": line, "status": "pending"] + proposals[key] = record; requests[requestID] = (tool, NSDictionary(dictionary: args), key) + proposal = Proposal(id: key, revision: revision, content: .line(path: path, number: line, before: before, after: replacement)) + status = "Review the proposed assembly change." + return record + } + + static func projectEdits(_ value: Any?, snapshot: AssemblyProjectSnapshot, shared: Set) throws -> [AssemblyProjectEdit] { + guard let rows = value as? [[String: Any]], (1...8).contains(rows.count) else { throw AssemblyBuildFailure("invalid_arguments") } + var paths = Set(), edits: [AssemblyProjectEdit] = [] + var bytes = 0, total = snapshot.files.values.reduce(0) { $0 + $1.count } + for row in rows { + guard row.count == 2, let path = row["path"] as? String, let source = row["source"] as? String, + paths.insert(path).inserted, !source.utf8.contains(0) else { throw AssemblyBuildFailure("invalid_arguments") } + guard shared.contains(path), let data = snapshot.files[path], let before = String(data: data, encoding: .utf8) else { + throw AssemblyBuildFailure("access_denied") + } + guard !source.utf8.elementsEqual(before.utf8) else { throw AssemblyBuildFailure("unchanged_file") } + let size = source.utf8.count + bytes += size; total += size - data.count + guard bytes <= 16 * 1024 else { throw AssemblyBuildFailure("patch_too_large") } + edits.append(AssemblyProjectEdit(path: path, before: before, after: source)) + } + guard total <= 512 * 1024 else { throw AssemblyBuildFailure("project_too_large") } + return edits.sorted { $0.path < $1.path } + } + + private func integer(_ value: Any?) -> Int? { + guard let n = value as? NSNumber, CFGetTypeID(n) != CFBooleanGetTypeID(), + !["f", "d"].contains(String(cString: n.objCType)) else { return nil } + return Int(exactly: n) + } + + private func buildRecord(_ id: String) -> [String: Any]? { + guard var record = builds[id] else { return nil } + if record["revision"] as? Int != revision { record["status"] = "stale" } + return record + } + + private func build(_ model: AssemblyDevelopmentModel, inputs: AssemblyProjectSnapshot, revision number: Int, + id: String, ticket: UUID, workspaceRevision: UUID) async { + defer { if ticket == scope { buildTask = nil } } + do { + let artifact = try await model.service.build(inputs) + guard try await snapshot(model, ticket: ticket) == inputs, revision == number, ticket == scope, + workspaceRevision == model.workspaceRevision else { throw AssemblyBuildFailure("revision_conflict") } + builds[id]?["status"] = "succeeded" + builds[id]?["entry"] = Int(artifact.entry) + builds[id]?["target"] = inputs.cpu.rawValue + builds[id]?["instruction_count"] = artifact.instructions.count + builds[id]?["ranges"] = artifact.ranges.map { [Int($0.lowerBound), Int($0.upperBound)] } + built = (id, number, artifact); canRun = true + model.acceptSharedBuild(artifact) + status = "Assembled for " + inputs.cpu.rawValue + ". " + AssemblyDevelopmentModel.summary(artifact) + } catch { + guard scope == ticket else { return } + builds[id]?["status"] = revision == number ? "failed" : "stale" + builds[id]?["diagnostics"] = (error as? AssemblyBuildFailure)?.diagnostics.prefix(32).map { + ["path": $0.path, "line": $0.line, "message": String($0.message.prefix(512))] as [String: Any] + } ?? [] + builds[id]?["message"] = String(error.localizedDescription.prefix(2048)) + status = String(error.localizedDescription.prefix(512)) + } + } + + private static func contentRange(_ line: Int, _ source: String) -> NSRange? { + let text = source as NSString + guard let span = AssemblyDevelopmentModel.lineRange(line, text: source), span.location < text.length else { return nil } + var end = 0 + text.getLineStart(nil, end: nil, contentsEnd: &end, for: NSRange(location: span.location, length: 0)) + return NSRange(location: span.location, length: end - span.location) + } + + func decide(_ id: String, apply: Bool) async { + guard let p = proposal, p.id == id, let model else { return } + if !apply { proposals[p.id]?["status"] = "cancelled"; proposal = nil; return } + do { + let value = try await snapshot(model, ticket: scope) + guard proposal?.id == p.id, revision == p.revision, !model.working, !model.commanding else { throw AssemblyBuildFailure("revision_conflict") } + guard connected, model.activeID == documentID, model.sourceRevision == lastSourceRevision else { throw AssemblyBuildFailure("revision_conflict") } + if case let .files(edits) = p.content { + let removed = try replaceFiles(edits, model: model, value: value) + appliedFiles = AppliedFiles(proposal: p, revision: revision, removedStops: removed) + proposal = nil; proposals[p.id]?["status"] = "applied"; proposals[p.id]?["applied_revision"] = revision + status = "Applied all reviewed files to the assembly draft." + return + } + guard case let .line(path, line, before, after) = p.content else { return } + guard model.buffer.path == path, value.files[path] == Data(model.buffer.text.utf8) else { + model.selectFile(path, line: line) + status = "Review the selected source file, then apply the change." + return + } + guard let range = Self.contentRange(line, model.buffer.text), (model.buffer.text as NSString).substring(with: range) == before else { + throw AssemblyBuildFailure("revision_conflict") + } + let expected = (model.buffer.text as NSString).replacingCharacters(in: range, with: after) + let accepted = editors?.replaceReviewedLine(in: model.buffer, range: range, with: after) ?? false + guard accepted, model.buffer.text == expected else { throw AssemblyBuildFailure("Open the assembly editor before applying the proposal.") } + proposal = nil; proposals[p.id]?["status"] = "applied" + _ = try await snapshot(model, ticket: scope) + proposals[p.id]?["applied_revision"] = revision + status = "Applied the edit. Build the revised assembly source." + } catch { status = error.localizedDescription } + } + + private func replaceFiles(_ edits: [AssemblyProjectEdit], model: AssemblyDevelopmentModel, value: AssemblyProjectSnapshot, + undo: Bool = false, restore: Set = []) throws -> Set { + let paths = Set(edits.map(\.path)) + guard editors?.canReplace(model.document.buffers.filter { paths.contains($0.path) }) != false else { + throw AssemblyBuildFailure("Finish the current editor input before applying this review.") + } + let removed = try model.replaceReviewedFiles(edits, snapshot: value, undo: undo, restoreStops: restore) + var files = value.files + for edit in edits { files[edit.path] = Data((undo ? edit.before : edit.after).utf8) } + last = AssemblyProjectSnapshot(mainPath: value.mainPath, files: files, cpu: value.cpu, settings: value.settings) + lastSourceRevision = model.sourceRevision; revision += 1 + built = nil; canRun = false; run = nil; runMessage = "No run started." + return removed + } + + func undoFiles(_ id: String) async { + guard let applied = appliedFiles, applied.proposal.id == id, let model, case let .files(edits) = applied.proposal.content else { return } + do { + let value = try await snapshot(model, ticket: scope) + guard connected, model.activeID == documentID, appliedFiles?.proposal.id == applied.proposal.id, proposal == nil, + revision == applied.revision, model.sourceRevision == lastSourceRevision else { throw AssemblyBuildFailure("revision_conflict") } + _ = try replaceFiles(edits, model: model, value: value, undo: true, restore: applied.removedStops) + proposals[applied.proposal.id]?["status"] = "undone"; appliedFiles = nil + status = "Undid all reviewed assembly changes." + } catch { status = error.localizedDescription } + } + + func startRun(_ id: String, confirm: ((String) -> Bool)? = nil) async { + guard canRun, proposal == nil, let model, let built, built.id == id, !model.working, !model.commanding else { return } + let ticket = scope + do { + guard try await snapshot(model, ticket: ticket) == built.artifact.snapshot, self.built?.id == built.id, + proposal == nil, revision == built.revision else { throw AssemblyBuildFailure("revision_conflict") } + run = nil; runMessage = "Starting" + let launched = try await model.launchShared(built.artifact, stillGranted: { [weak self] in + self?.scope == ticket && self?.built?.id == built.id && self?.revision == built.revision && + self?.proposal == nil && self?.model?.activeID == self?.documentID + }, confirm: confirm) + guard scope == ticket else { return } + let runID = UUID().uuidString + run = (runID, built.revision, built.id, launched) + runIO = MCPCompiledRunIO(machine: model.machine, runID: runID, expected: launched, assembly: true) + runMessage = "started"; status = "Assembly program loaded." + } catch { if scope == ticket { runMessage = error.localizedDescription; status = runMessage } } + } + + private func runResult(_ model: AssemblyDevelopmentModel, ticket: UUID, inspect: Bool = false) async throws -> [String: Any] { + guard let run, let built, run.revision == revision, run.build == built.id else { + return ["status": runMessage, "revision": revision] + } + let workspaceRevision = model.workspaceRevision + let capture: VCCDebuggerSnapshot? = await withCheckedContinuation { c in + model.machine.readDebugger(address: 0, followPC: true, memoryAddress: 0x0400) { c.resume(returning: $0) } + } + guard let capture, scope == ticket, revision == run.revision, self.run?.id == run.id, + model.activeID == documentID, workspaceRevision == model.workspaceRevision, + model.artifact?.id == built.artifact.id else { throw AssemblyBuildFailure("stale_run") } + let current = capture.machine + guard current.generation == run.machine.generation, current.debuggerProgramRevision == run.machine.debuggerProgramRevision, + current.debuggerMappingFingerprint == run.machine.debuggerMappingFingerprint, current.debuggerAssemblyAttached + else { throw AssemblyBuildFailure("stale_run") } + var result: [String: Any] = ["run_id": run.id, "build_id": built.id, "revision": revision, "target": built.artifact.snapshot.cpu.rawValue, + "processor": current.use6309 ? "HD6309" : "MC6809", "status": current.state == .paused ? "paused" : "running"] + if current.assistantCompiledReturned { + if inspect { throw AssemblyBuildFailure("run_finished") } + result["status"] = "finished" + if let runIO { + if let text = try await runIO.finalScreenText() { result["final_screen_text"] = text } + guard scope == ticket, self.runIO === runIO, self.run?.id == run.id, + model.activeID == documentID, workspaceRevision == model.workspaceRevision else { + throw AssemblyBuildFailure("stale_run") + } + } + return result + } + guard current.state == .paused else { + if inspect { throw AssemblyBuildFailure("pause_required") } + return result + } + let guards = AssemblyDevelopmentModel.codeGuards(built.artifact.instructions) + for (address, bytes) in guards { + let range = Int(address)..<(Int(address) + bytes.count) + guard range.upperBound <= capture.logicalMemory.count, range.upperBound <= capture.logicalMemoryAvailable.count, + capture.logicalMemoryAvailable[range].allSatisfy({ $0 != 0 }), capture.logicalMemory[range].elementsEqual(bytes) + else { throw AssemblyBuildFailure("stale_run") } + } + let pc = current.programCounter + let candidates = built.artifact.instructions.filter { $0.address == pc } + var sourceStop: [String: Any]? + if candidates.count == 1, let mapped = candidates.first, files.contains(mapped.path), + AssemblyDevelopmentModel.location(.init(path: mapped.path, line: mapped.line), in: built.artifact) != nil, + let instruction = capture.instructions.first, instruction.address == pc, Array(instruction.bytes) == mapped.bytes { + sourceStop = ["path": mapped.path, "line": mapped.line, "address": Int(pc), "instruction_bytes": mapped.bytes.map(Int.init)] + } + if inspect { + var ranges = built.artifact.instructions.filter { files.contains($0.path) && guards[$0.address] != nil }.map { + Int($0.address)..<(Int($0.address) + $0.bytes.count) + } + ranges.append(0x0400..<0x0401) + let snapshot = try MCPDebuggerInspection(runID: run.id, capture: capture, + scope: ["project_id": model.activeID.uuidString, "build_id": built.id, "revision": revision], + sourceStop: sourceStop, watches: [], watchStatus: "Assembly has no source-level variable watches.", ranges: ranges) + inspection = snapshot + return snapshot.fields + } + guard let sourceStop else { return result } + result["source_stop"] = sourceStop + var registers = ["pc": Int(pc)] + if let a = capture.registers["A"] { registers["a"] = a.intValue } + if let e = capture.registers["E"] { registers["e"] = e.intValue } + result["registers"] = registers + if capture.logicalMemoryAvailable.count > 0x0400, capture.logicalMemoryAvailable[0x0400] != 0 { + result["text_ram_0400"] = Int(capture.logicalMemory[0x0400]) + } + return result + } + + #if DEBUG + /// A fresh, explicitly isolated synthetic project. Only the regression variant accepts test decisions. + func startFixture(_ model: AssemblyDevelopmentModel, directory: URL, romDirectory: URL) async throws { + guard CommandLine.arguments.contains("--interface-validation"), + try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty + else { throw AssemblyBuildFailure("Use an empty isolated assembly validation directory.") } + try await MCPBASICRun.bootFixture(model.machine, romDirectory: romDirectory) + let project = directory.appendingPathComponent("Assembly") + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: false) + let enhanced = CommandLine.arguments.contains("--mcp-assembly-hd6309") + let source = """ + org $3f00 + include "value.inc" + start \(enhanced ? "lde" : "lda") #VALUE + \(enhanced ? "adde" : "adda") #1 + \(enhanced ? "ste" : "sta") $0400 + done rts + end start + + """ + try Data(source.utf8).write(to: project.appendingPathComponent("main.asm"), options: .withoutOverwriting) + try Data("VALUE equ 1\n".utf8).write(to: project.appendingPathComponent("value.inc"), options: .withoutOverwriting) + model.open(project, folder: true) + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) + while model.document.directory?.lastPathComponent != project.lastPathComponent, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(30)) + } + let physicalProject = try CMOCProject.physicalURL(project) + guard model.document.directory?.path == physicalProject.path else { throw AssemblyBuildFailure("The synthetic assembly workspace failed to open.") } + model.setCPU(enhanced ? .hd6309 : .mc6809) + try await connect(model, to: directory.appendingPathComponent("grant.json")) + guard CommandLine.arguments.contains("--mcp-assembly-regression") else { return } + let editorPool = AssemblyEditorPool() + editors = editorPool + let editorWindow = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 620, height: 320), + styleMask: [.titled], backing: .buffered, defer: false) + editorWindow.title = "Assembly Development — Regression" + let editor = NSHostingView(rootView: AssemblyEditor(finder: SourceFind(), model: model, pool: editorPool, lookup: {})) + editor.sizingOptions = [] + editorWindow.contentView = editor + editorWindow.orderBack(nil) + editor.layoutSubtreeIfNeeded() + try Data().write(to: directory.appendingPathComponent("assembly-regression-fixture"), options: .withoutOverwriting) + let ticket = scope + Task { + defer { editorWindow.orderOut(nil) } + func consume(_ name: String) -> Bool { unlink(directory.appendingPathComponent(name).path) == 0 } + while scope == ticket { + try? await Task.sleep(for: .milliseconds(100)) + if consume("apply"), let id = proposal?.id { await decide(id, apply: true) } + if consume("undo-files"), let id = undoableProposalID { await undoFiles(id) } + if consume("cancel-project-edits"), let id = proposal?.id { await decide(id, apply: false) } + if consume("stale-review-click") { + // A click captured from a retired native review must never operate on its replacement. + await decide("retired-review", apply: true) + await decide("retired-review", apply: false) + await undoFiles("retired-review") + try? Data().write(to: directory.appendingPathComponent("checked-stale-click")) + } + if consume("capture-review"), proposal != nil { + show(model, editors: editorPool) + try? await Task.sleep(for: .milliseconds(250)) + if let panel = window { + let capture = Process() + capture.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture") + capture.arguments = ["-x", "-o", "-l", String(panel.windowNumber), directory.appendingPathComponent("review.png").path] + capture.terminationHandler = { _ in Task { @MainActor in panel.orderOut(nil) } } + do { try capture.run() } catch { panel.orderOut(nil) } + } + } + if consume("stale-run-click") { + await startRun("retired-build", confirm: { _ in true }) + try? Data().write(to: directory.appendingPathComponent("checked-stale-run")) + } + if consume("play"), let id = runnableBuildID { await startRun(id, confirm: { _ in true }) } + if consume("run"), let id = runnableBuildID { + if !model.document.breakpoints.contains(.init(path: "main.asm", line: 6)), + let span = AssemblyDevelopmentModel.lineRange(6, text: model.buffer.text) { + model.moveCursor(span.location); model.toggleBreakpoint() + } + await startRun(id, confirm: { _ in true }) + } + if consume("quit") { + revoke() + NSApp.perform(#selector(NSApplication.terminate(_:)), with: nil, afterDelay: 0) + return + } + } + } + } + #endif +} + +private struct AssemblyAccessView: View { + @ObservedObject var access: MCPAssembly + @ObservedObject var model: AssemblyDevelopmentModel + @State private var expandedFiles = Set() + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 10) { + Label(model.document.title, systemImage: "cpu").font(.headline) + if access.connected { + if let proposal = access.proposal { + switch proposal.content { + case let .line(path, number, before, after): + Text("\(path), line \(number)").bold() + comparison(before: before, after: after) + reviewButtons(proposal.id, multiple: false) + case .files(let edits): + Text(edits.count == 1 ? "Review 1 assembly file" : "Review \(edits.count) assembly files").font(.headline) + reviewButtons(proposal.id, multiple: true) + ForEach(edits, id: \.path) { edit in + DisclosureGroup(edit.path, isExpanded: Binding( + get: { expandedFiles.contains(edit.path) }, + set: { if $0 { expandedFiles.insert(edit.path) } else { expandedFiles.remove(edit.path) } } + )) { + HStack(alignment: .top, spacing: 12) { + sourceColumn("Current", edit.before) + Divider() + sourceColumn("Proposed", edit.after) + }.padding(.vertical, 4) + } + } + .onAppear { if let first = edits.first { expandedFiles = [first.path] } } + .id(proposal.id) + } + } + if let id = access.undoableProposalID { + Button("Undo All Changes") { Task { await access.undoFiles(id) } } + } + if let url = access.grantURL { + MCPChatGPTSetup(grantURL: url, firstPrompt: "Identify my shared VCC Plus assembly project and target processor. Read the entry source file and describe what the CoCo program does.") + } + HStack { + Button("Copy MCP Helper Path") { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/vcc-mcp").path, forType: .string) + } + Button("Revoke Connection") { access.revoke() } + } + let buildID = access.runnableBuildID + Button("Run Shared Build…") { + if let buildID { Task { await access.startRun(buildID) } } + }.disabled(buildID == nil || access.proposal != nil || model.commanding || model.working) + } else { + Text("Share this document’s assembly files with a client that can build them and propose edits. You approve edits and start runs. The client can read the guest text screen and send one letter, digit or space at a time during your run. It can check machine and media status. At a verified source stop it can inspect registers, shared program memory and the text byte at $0400. The client’s model provider may receive those results.") + Button("Save Assembly Connection…") { access.choose(model) } + } + if !access.status.isEmpty { Text(access.status).foregroundStyle(.secondary).textSelection(.enabled) } + }.padding().frame(maxWidth: .infinity, alignment: .leading) + } + } + private func sourceColumn(_ title: String, _ source: String) -> some View { + VStack(alignment: .leading, spacing: 4) { + Text(title).font(.caption).foregroundStyle(.secondary) + ScrollView(.horizontal) { + Text(verbatim: source).font(.callout.monospaced()).textSelection(.enabled) + .fixedSize(horizontal: true, vertical: true) + } + }.frame(maxWidth: .infinity, alignment: .leading) + } + @ViewBuilder private func comparison(before: String, after: String) -> some View { + Text("Current").font(.caption) + Text(before).font(.body.monospaced()).textSelection(.enabled) + Text("Proposed").font(.caption) + Text(after).font(.body.monospaced()).textSelection(.enabled) + } + private func reviewButtons(_ id: String, multiple: Bool) -> some View { + HStack { + Button(multiple ? "Apply All Changes" : "Apply Edit") { Task { await access.decide(id, apply: true) } } + Button(multiple ? "Cancel Changes" : "Cancel Edit") { Task { await access.decide(id, apply: false) } } + } + } + +} diff --git a/platforms/macos/App/MCPBASICRun.swift b/platforms/macos/App/MCPBASICRun.swift new file mode 100644 index 0000000..62116d0 --- /dev/null +++ b/platforms/macos/App/MCPBASICRun.swift @@ -0,0 +1,323 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Combine +import Foundation + +enum MCPGuestKey { + static let limit = 64 + + static func accepts(_ keys: String) -> Bool { + guard keys.utf8.count == 1, let byte = keys.utf8.first else { return false } + return byte == 32 || (48...57).contains(byte) || (65...90).contains(byte) || (97...122).contains(byte) + } +} + +@MainActor +final class MCPBASICRun: ObservableObject { + @Published private(set) var status = "" + @Published private(set) var busy = false + @Published private(set) var runID: String? + @Published private(set) var receipt: [String: Any]? + + private struct Run { + let id: String + let document: UUID + let revision: Int + let snapshot: VCCMachineSnapshot + let guestSource: String + } + private var inspection: MCPDebuggerInspection? + private var run: Run? + private weak var machine: MachineModel? + private var sourceChanges: AnyCancellable? + private var requestedDocument: UUID? + private var requestedRevision: Int? + private var generation = UUID() + private var sending = false + private var sent: [String: String] = [:] + private var verifiedPrompt = false + private var currentApproval: (() -> Bool)? + + func reset() { + if let run { machine?.cancelMCPInput(runID: run.id) } + generation = UUID() + run = nil + inspection = nil + runID = nil + receipt = nil + requestedDocument = nil + requestedRevision = nil + sourceChanges = nil + currentApproval = nil + busy = false + sending = false + verifiedPrompt = false + sent.removeAll() + status = "" + } + + func start(model: BASICDevelopmentModel, bothChoices: Bool, isCurrent: @escaping () -> Bool) async { + guard !busy, !sending, isCurrent() else { return } + reset() + busy = true + machine = model.machine + currentApproval = isCurrent + sourceChanges = model.$source.dropFirst().sink { [weak self] _ in self?.reset() } + let ticket = generation, document = model.documentID, revision = model.sourceRevision + requestedDocument = document + requestedRevision = revision + let current = { self.generation == ticket && document == model.documentID && revision == model.sourceRevision && isCurrent() } + defer { if generation == ticket { busy = false } } + do { + var branches: [[String: Any]] = [] + for key in bothChoices ? ["2", "1"] : [""] { + try require(current(), "The approved revision or connection changed.") + status = "Starting the reviewed BASIC program…" + guard let (snapshot, guestSource) = await model.performTransfer(run: true, reviewIsCurrent: current) else { + throw ProfileFailure.message(model.message ?? "The BASIC workspace could not start this run.") + } + try require(current() && model.machine.basicWorkspaceOwner == model.workspaceID, "The BASIC workspace changed.") + let started = Run(id: UUID().uuidString, document: document, revision: revision, snapshot: snapshot, guestSource: guestSource) + run = started + runID = started.id + sent.removeAll() + verifiedPrompt = false + if bothChoices { + status = key == "2" ? "Checking Mars in the CoCo…" : "Checking Earth in the CoCo…" + branches.append(try await checkChoice(key, model: model, run: started)) + } + } + try require(current(), "The approved revision or connection changed.") + if bothChoices { + let mismatches = branches.filter { $0["color_matches"] as? Bool == false } + receipt = ["document_id": document.uuidString, "revision": revision, "branches": branches, + "verified": mismatches.isEmpty, "behavior_verified": true] + verifiedPrompt = true + if let first = mismatches.first { + status = "Both greetings and PRINT 7 verified. Choice " + (first["key"] as? String ?? "") + + " displayed " + (first["background_rgb"] as? String ?? "") + " instead of the expected " + + (first["expected_color"] as? String ?? "") + " background." + } else { status = "Verified both choices and PRINT 7." } + } else { status = "BASIC started. The client can read the guest screen and send a single letter, digit or space at a time." } + } catch { + if generation == ticket { + status += " " + error.localizedDescription + run = nil + runID = nil + } + } + } + + private func require(_ condition: Bool, _ reason: String) throws { + guard condition else { throw ProfileFailure.message(reason) } + } + + private func validate(_ model: BASICDevelopmentModel, _ expected: Run) throws { + try require(run?.id == expected.id && currentApproval?() == true && model.documentID == expected.document + && model.sourceRevision == expected.revision && model.machine.basicWorkspaceOwner == model.workspaceID, + "The run or reviewed document has changed.") + } + + private func screen(_ model: BASICDevelopmentModel, _ expected: Run) async throws -> [String: Any] { + let deadline = ContinuousClock.now.advanced(by: .seconds(1)) + while true { + try validate(model, expected) + do { + let result = try await model.machine.mcpScreen(expected: expected.snapshot, source: expected.guestSource) + try validate(model, expected) + return result + } catch { + // WIDTH can temporarily switch out BASIC's RAM while redrawing. + guard error.localizedDescription == "Direct BASIC access requires the normal BASIC memory map", + ContinuousClock.now < deadline else { throw error } + try await Task.sleep(for: .milliseconds(45)) + } + } + } + + private func type(_ keys: String, model: BASICDevelopmentModel, run: Run) async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(2)) + while true { + try validate(model, run) + do { + try await model.machine.mcpPaste(keys, runID: run.id, direct: keys == "PRINT 7\n", + expected: run.snapshot, source: run.guestSource) + try validate(model, run) + return + } catch { + // Both refusals occur before the controller queues any keys. A ROM + // interrupt or GIME text update may temporarily obscure direct mode. + let beforeTyping = ["Direct BASIC access requires the normal BASIC memory map", + "The guest is not at the expected BASIC input state."] + guard beforeTyping.contains(error.localizedDescription), ContinuousClock.now < deadline else { throw error } + try await Task.sleep(for: .milliseconds(45)) + } + } + } + + private func wait(_ reason: String, model: BASICDevelopmentModel, run: Run, + until: ([String: Any], [String]) -> Bool) async throws -> [String: Any] { + let clock = ContinuousClock() + let end = clock.now.advanced(by: .seconds(6)) + var last = "" + var state = "" + while clock.now < end { + let result = try await screen(model, run) + last = result["text"] as? String ?? "" + state = "frame \(result["frame"] ?? "?"), paste \(result["paste_remaining"] ?? "?"), direct input \(result["direct_prompt"] ?? "?")" + if until(result, last.components(separatedBy: "\n")) { return result } + try await Task.sleep(for: .milliseconds(75)) + } + throw ProfileFailure.message("Timed out waiting for " + reason + " (" + state + "). Guest screen: " + String(last.suffix(350))) + } + + private static func hasMenu(_ lines: [String]) -> Bool { + let shown = lines.map { $0.trimmingCharacters(in: .whitespaces).lowercased() }.filter { !$0.isEmpty } + guard shown.count >= 2 else { return false } + let first = shown[shown.count - 2], second = shown[shown.count - 1] + return first.hasPrefix("1") && first.contains("earth") && second.hasPrefix("2") && second.contains("mars") + } + + private func checkChoice(_ key: String, model: BASICDevelopmentModel, run: Run) async throws -> [String: Any] { + let menu = try await wait("the 40-column choice menu", model: model, run: run) { s, lines in + s["columns"] as? Int == 40 && Self.hasMenu(lines) && s["direct_prompt"] as? Bool == false + } + try await type("3", model: model, run: run) + let menuFrame = menu["frame"] as? UInt64 ?? 0 + let ignored = try await wait("the menu after the unrelated key", model: model, run: run) { s, _ in + Self.hasMenu((s["text"] as? String ?? "").components(separatedBy: "\n")) && s["direct_prompt"] as? Bool == false && + s["paste_remaining"] as? Int == 0 && (s["frame"] as? UInt64 ?? 0) >= menuFrame + 10 + } + try await type(key, model: model, run: run) + let greeting = key == "1" ? "Hello Nice Blue Dot World!" : "Bring a warm coat!" + let output = try await wait("the greeting and BASIC prompt", model: model, run: run) { s, lines in + s["direct_prompt"] as? Bool == true && s["paste_remaining"] as? Int == 0 && + lines.contains { $0.trimmingCharacters(in: .whitespaces) == "OK" } + } + let text = output["text"] as? String ?? "" + let lines = text.components(separatedBy: "\n") + guard let row = lines.firstIndex(where: { $0.trimmingCharacters(in: .whitespaces) == greeting }) else { + throw ProfileFailure.message("Expected “" + greeting + "â€� for choice " + key + ". Guest screen: " + text) + } + guard let sample = (output["colors"] as? [[String: Int]])?.first(where: { $0["row"] == row }), + let rgb = sample["rgb"] else { + throw ProfileFailure.message("The greeting has no measurable text-cell background.") + } + let red = (rgb >> 16) & 255, green = (rgb >> 8) & 255, blue = rgb & 255 + // Require a strongly dominant primary. Composite palette 37 renders amber + // (#FFBF39); its largest component is red, which alone cannot verify red. + let dominant = key == "1" ? blue : red + let others = key == "1" ? max(red, green) : max(green, blue) + let correct = dominant >= 32 && dominant >= 2 * others + try require(sample["palette_value"] == (key == "1" ? 10 : 37), "The greeting used an unexpected GIME palette value.") + try await type("PRINT 7\n", model: model, run: run) + let prompt = try await wait("the result of PRINT 7", model: model, run: run) { s, rows in + let compact = rows.map { $0.trimmingCharacters(in: .whitespaces).uppercased() }.filter { !$0.isEmpty } + return compact.suffix(3) == ["PRINT 7", "7", "OK"] && s["direct_prompt"] as? Bool == true && s["paste_remaining"] as? Int == 0 + } + return ["key": key, "run_id": run.id, "invalid_key": "3", "invalid_screen": ignored["text"] ?? "", + "screen": text, "greeting": lines[row], "color_matches": correct, "expected_color": key == "1" ? "blue" : "red", "background_rgb": String(format: "#%06X", rgb), "cell": sample, + "frame": output["frame"] ?? 0, "signal": output["signal"] ?? 0, "columns": output["columns"] ?? 0, + "processor": run.snapshot.use6309 ? "HD6309" : "MC6809", "command_screen": prompt["text"] ?? ""] + } + + private func debug(_ tool: String, _ args: [String: Any], model: BASICDevelopmentModel, run: Run) async throws -> [String: Any] { + // The BASIC bridge verifies exact detokenized source plus run identity. + let observed = try await model.machine.checkReviewedBASIC(run.snapshot, source: run.guestSource) + try validate(model, run) + guard MCPDebuggerInspection.sameProgram(observed, run.snapshot) else { throw ProfileFailure.message("stale_run") } + if tool == "get_debug_snapshot" { + guard args.count == 1 else { throw ProfileFailure.message("invalid_arguments") } + let captured = try await MCPDebuggerInspection.capture(model.machine) + let state = captured.machine + guard MCPDebuggerInspection.sameProgram(state, run.snapshot) else { throw ProfileFailure.message("stale_run") } + guard state.state == .paused else { throw ProfileFailure.message("pause_required") } + let stop = model.machine.basicDebug + var watches: [[String: String]] = [], watchStatus = "Pause at a supported BASIC statement to inspect watches." + var mapped: [String: Any]? + if state.basicDebugAttached && !state.basicStepping && state.basicStoppedLine >= 0 { + mapped = ["line": state.basicStoppedLine, "address": Int(state.programCounter)] + let (variables, error) = await model.machine.inspectBASIC(source: model.source, stop: stop) + if let variables { + watches = model.watches.compactMap { name in BASICWatch(name).map { ["name": name, "value": $0.value(in: variables)] } } + watchStatus = "available" + } else { watchStatus = error ?? "BASIC variable memory is unavailable." } + } + let bytes = captured.logicalMemory, available = captured.logicalMemoryAvailable + guard bytes.count >= 0x1d, available.count >= 0x1d, available[0x19..<0x1d].allSatisfy({ $0 != 0 }) else { + throw ProfileFailure.message("memory_unavailable") + } + let start = Int(bytes[0x19]) * 256 + Int(bytes[0x1a]), end = Int(bytes[0x1b]) * 256 + Int(bytes[0x1c]) + // A second source check binds the parsed interpreter pointers and watches to the same paused stop. + let now = try await model.machine.checkReviewedBASIC(run.snapshot, source: run.guestSource) + try validate(model, run) + guard MCPDebuggerInspection.sameProgram(now, state), now.state == .paused, now.cycles == state.cycles, + end >= start else { throw ProfileFailure.message("stale_snapshot") } + inspection = try MCPDebuggerInspection(runID: run.id, capture: captured, + scope: ["document_id": run.document.uuidString, "revision": run.revision], + sourceStop: mapped, watches: watches, watchStatus: watchStatus, ranges: [start.. [String: Any] { + if tool == "get_run" { + guard let requestedDocument, let requestedRevision else { return ["error": "no_run"] } + guard currentApproval?() == true, model.documentID == requestedDocument, model.sourceRevision == requestedRevision, + arguments.count == 2, arguments["document_id"] as? String == requestedDocument.uuidString, + arguments["revision"] as? Int == requestedRevision else { return ["error": "revision_conflict"] } + var result: [String: Any] = ["document_id": requestedDocument.uuidString, "revision": requestedRevision, + "busy": busy, "status": status, "run_id": runID as Any? ?? NSNull()] + if let receipt { result["receipt"] = receipt } + return ["result": result] + } + guard let run else { return ["error": "no_run"] } + do { + try validate(model, run) + guard arguments["run_id"] as? String == run.id else { return ["error": "stale_run"] } + if tool == "get_debug_snapshot" || tool == "read_debug_memory" { + return ["result": try await debug(tool, arguments, model: model, run: run)] + } + if tool == "read_screen_text", arguments.count == 1 { + var observation = try await screen(model, run) + observation["run_id"] = run.id + observation["revision"] = run.revision + return ["result": observation] + } + guard tool == "send_keys", arguments.count == 3, let request = arguments["request_id"] as? String, + (1...64).contains(request.utf8.count), let keys = arguments["keys"] as? String, + MCPGuestKey.accepts(keys) || keys == "PRINT 7\n" + else { return ["error": "invalid_arguments"] } + let accepted = ["result": ["run_id": run.id, "request_id": request, "accepted": true] as [String: Any]] + if let previous = sent[request] { return previous == keys ? accepted : ["error": "request_conflict"] } + guard sent.count < MCPGuestKey.limit else { return ["error": "input_limit_reached"] } + guard !busy, !sending, !verifiedPrompt else { return ["error": "input_unavailable"] } + sending = true + defer { if self.run?.id == run.id { sending = false } } + try await type(keys, model: model, run: run) + sent[request] = keys + verifiedPrompt = keys == "PRINT 7\n" + return accepted + } catch { return ["error": error.localizedDescription] } + } + + #if DEBUG + static func bootFixture(_ machine: MachineModel, romDirectory: URL, + use6309: Bool = CommandLine.arguments.contains("--basic-6309"), + composite: Bool = CommandLine.arguments.contains("--mcp-composite")) async throws { + var profile = ConfigurationProfile(name: "Isolated BASIC review") + profile.systemROM = romDirectory.appendingPathComponent("coco3.rom") + profile.media.rom = romDirectory.appendingPathComponent("disk11.rom") + var layout = CartridgeAssignments() + layout.slots[0].kind = .floppy + profile.media.cartridges = layout + profile.sound = false + profile.videoOutput = composite ? 1 : 0 + profile.machine.use6309 = use6309 + await machine.loadProfile(profile) + if let issue = machine.profileError { throw ProfileFailure.message(issue) } + machine.resume() + try await machine.waitForMCPFixturePrompt() + } + #endif +} diff --git a/platforms/macos/App/MCPCMOC.swift b/platforms/macos/App/MCPCMOC.swift new file mode 100644 index 0000000..7efd70f --- /dev/null +++ b/platforms/macos/App/MCPCMOC.swift @@ -0,0 +1,1952 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import SwiftUI +import Combine +import Darwin + +/// A bounded receipt for one accepted startup. Long preparation and boot work +/// is polled through get_run rather than held inside a transport request. +@MainActor +final class MCPOwnedPlaytestStart { + let identity: String + let requestID: String + let runID: String + let projectID: String + let revision: Int + let artifactID: String + let processor: MCPPlaytestProcessor + private(set) var status = "starting" + private(set) var phase = "preparing_debug_metadata" + private(set) var settled = false + private var task: Task? + private var receipt: [String: Any]? + private var reason: String? + private let redactionRoots: [URL] + + init(identity: String, requestID: String, runID: String = UUID().uuidString, + projectID: String, revision: Int, artifactID: String, processor: MCPPlaytestProcessor = .mc6809, + redactionRoots: [URL] = []) { + self.identity = identity; self.requestID = requestID; self.runID = runID + self.projectID = projectID; self.revision = revision; self.artifactID = artifactID + self.processor = processor + self.redactionRoots = redactionRoots + } + var acceptingResult: Bool { status == "starting" && !Task.isCancelled } + func updatePhase(_ phase: String) { if status == "starting" { self.phase = phase } } + func launch(_ operation: @escaping @MainActor (MCPOwnedPlaytestStart) async throws -> [String: Any]) { + guard task == nil else { return } + task = Task { + defer { settled = true } + do { + var result = try await operation(self) + guard acceptingResult else { status = "cancelled"; return } + result.removeValue(forKey: "png_base64") + receipt = result; status = "ready"; phase = "ready" + } catch { + guard status == "starting", !Task.isCancelled else { status = "cancelled"; return } + reason = CMOCBuildFailureReport.fields(for: error, redacting: redactionRoots)["reason"] as? String + status = "failed" + } + } + } + func cancel() { + guard !settled else { return } + status = "cancelling" + task?.cancel() + } + func waitForCompletion() async { await task?.value } + var fields: [String: Any] { + var value: [String: Any] = ["project_id": projectID, "revision": revision, "artifact_id": artifactID, + "request_id": requestID, "run_id": runID, "owned_playtest": true, "requested_processor": processor.rawValue, + "status": status, "phase": phase, "busy": !settled] + if !settled { value["poll_tool"] = "get_run" } + if let reason { value["error"] = reason } + if let receipt { value["receipt"] = receipt } + return value + } +} + +/// Public refresh receipts expose relative input evidence, never candidate bytes. +struct MCPProjectRefreshRecord { + let id: String + let requestID: String + let expectedRevision: Int + let identity: String + let changes: [CMOCProjectInputManifest.Change] + var status: String + var revision: Int + var reason: String? = nil + var fields: [String: Any] { + let catalog = CMOCSourceMap.boundedJSONCatalog(Array(changes.prefix(64)).map(\.publicFields)) + var value: [String: Any] = ["refresh_id": id, "request_id": requestID, "status": status, + "expected_revision": expectedRevision, "revision": revision, + "changed_inputs": catalog.items, "changed_inputs_total": changes.count, "changed_inputs_truncated": catalog.items.count != changes.count, + "changed_input_paths": Array(changes.prefix(128)).map(\.path), + "changed_input_paths_total": changes.count, "changed_input_paths_truncated": changes.count > 128, + "requires_review": changes.contains(where: \.requiresReview)] + if let reason { value["reason"] = reason } + return value + } + static func inputPage(_ entries: [CMOCProjectInputManifest.Entry], offset: Int, limit: Int) + -> (rows: [[String: Any]], nextOffset: Int?, truncated: Bool) { + let selected = offset < entries.count ? Array(entries.dropFirst(offset).prefix(limit)) : [] + let bounded = CMOCSourceMap.boundedJSONCatalog(selected.map(\.publicFields), maximumBytes: 128 * 1024) + let next = offset + bounded.items.count + return (bounded.items, next < entries.count ? next : nil, bounded.truncated) + } + static let safeTools: Set = ["get_capabilities", "get_machine_status", "get_build", "get_build_log", "get_project_refresh", "read_project_inputs", "refresh_project", "read_project_file", "get_proposal"] +} + +/// The grant binds reviewed drafts and build artifacts to one selected project. +@MainActor +final class MCPCMOC: ObservableObject { + static let shared = MCPCMOC() + private var scope: MCPCMOCProject? + private var approvedInputs: CMOCProjectInputManifest? + private var observedInputChanges: [CMOCProjectInputManifest.Change] = [] + private var lastAcceptedInputChanges: [CMOCProjectInputManifest.Change] = [] + private var refreshRecords: [String: MCPProjectRefreshRecord] = [:] + private var refreshRequests: [String: String] = [:] + private var latestRefreshID: String? + private var refreshCandidate: RefreshCandidate? + private var refreshPanel: NSPanel? + private var refreshProblem: String? + private var refreshApprovingID: String? + private struct CapturedInputs { + let live: [String: String] + let disk: [String: String] + let epoch: Int + let directives: [String: Set] + let make: MCPCMOCMakeInputs? + let manifest: CMOCProjectInputManifest + let scope: MCPCMOCProject + let project: CMOCProject + } + private struct RefreshCandidate { + let refreshID: String + let owner: UUID + let captured: CapturedInputs + } + private static let headers = MCPCMOCProject.libraryHeaders.map { "@toolchain/include/" + $0 } + private static let tools = ["get_capabilities", "refresh_project", "get_project_refresh", "read_project_inputs", "get_machine_status", "get_debug_snapshot", "read_debug_memory", "search_help", "read_topic", "read_project_file", "build_project", "get_build", "get_build_log", "propose_fix", "propose_project_edits", "get_proposal", "get_run", "read_screen_text", "send_keys"] + private weak var model: CMOCDevelopmentModel? + private weak var pendingModel: CMOCDevelopmentModel? + private var projectID: UUID? + private var session = UUID() + private var token = "" + private var server: MCPTransport? + private var file: MCPGrantFile? + fileprivate var grantURL: URL? { file?.url } + private var scratch: URL? + private var service: CMOCBuildService? + private var buildTask: Task? + private var runTask: Task? + private var panel: NSPanel? + private var consentPanel: NSPanel? + private weak var consentModel: CMOCDevelopmentModel? + private var workspaceEpoch = -1 + private var revision = 0 + private var snapshot: [String: String] = [:] + private var diskSnapshot: [String: String] = [:] + private var makeSnapshot: MCPCMOCMakeInputs? + private var approvedRecipeID: String? + @Published var allowProjectMakefile = false + @Published var allowPlaytests = false + fileprivate private(set) var playtestsApproved = false + private var callContextApproved = false + private var playtestMediaApproved = false + #if DEBUG + private var regressionPlaytestHelper: URL? + private var regressionStarterKit: StarterKit? + #endif + private var playtest: MCPPlaytest? + private var playtestStarts: [String: MCPOwnedPlaytestStart] = [:] + private var latestPlaytestStart: MCPOwnedPlaytestStart? + private var playtestStartupCleanup: Task? + private var playtestBusy = false + private var readyDebugMetadata: (artifactID: UUID, map: CMOCProjectSourceMap, variables: CMOCVariableDebug?, variableError: String?)? + private var ownedInspection: (id: String, run: String, clock: Int, memory: Data, ranges: [Range], fields: [String: Any], fingerprint: String, callContext: [String: Any]?)? + private var templateDirectives: [String: Set] = [:] + private var readyArtifact: (revision: Int, value: CMOCBuildArtifact)? + private var buildRequests: [String: String] = [:] + private var latestBuildID: String? + private var builds: [String: [String: Any]] = [:] + private var buildReports: [String: CMOCBuildReport] = [:] + private var proposals: [String: Proposal] = [:] + private var proposalRequests: [String: String] = [:] + private var runID: String? + private var liveIO: MCPCompiledRunIO? + private var inspection: MCPDebuggerInspection? + private var runRevision: Int? + fileprivate private(set) var runReceipt: [String: Any]? + fileprivate var usesDiskRecipe: Bool { scope?.helloDisk == true } + fileprivate var readyToRun: Bool { + readyArtifact?.revision == revision && proposal?.status != "pending" && (!usesDiskRecipe || proposal?.applied == revision) + } + fileprivate struct RunSelection { + let artifactID: UUID + let proposalID: String? + } + fileprivate var runSelection: RunSelection? { + guard readyToRun, let artifact = readyArtifact else { return nil } + return RunSelection(artifactID: artifact.value.id, proposalID: proposal?.id) + } + @Published private(set) var status = "" + @Published private(set) var active = false + @Published private(set) var proposal: Proposal? + @Published private(set) var building = false + @Published private(set) var running = false + @Published private(set) var runStatus = "" + @Published private(set) var buildStatus = "" + private var fixtureLabel: String? + private var regression = false + #if DEBUG + private var fixtureWindow: NSWindow? + private var fixtureRunAlert: NSAlert? + private var fixtureDirectory: URL? + #endif + + struct Proposal { + let id = UUID().uuidString + let request: String, path: String, line: Int, before: String, after: String, revision: Int + var edits: [MCPCMOCEdit]? = nil + var status = "pending" + var applied: Int? + var result: [String: Any] { + var value: [String: Any] = ["proposal_id": id, "path": path, "line_number": line, "before": before, + "after": after, "revision": revision, "status": status] + if let edits { + value = ["proposal_id": id, "revision": revision, "status": status, "files": edits.map(\.path)] + } + if let applied { value["applied_revision"] = applied } + return value + } + } + + private func problem(_ text: String) -> CMOCBuildError { .message(text) } + + private func capture(_ model: CMOCDevelopmentModel, scope: MCPCMOCProject, updatedScope: Bool = false, expandedSupport: Bool = false) async throws -> CapturedInputs { + guard let project = model.project else { throw problem("project_unavailable") } + let template = Bundle.main.resourceURL?.appendingPathComponent("DevelopmentTemplates/HelloDisk") + let workspace = model.assistantProjectID, epoch = model.assistantEditEpoch + let overlays = Dictionary(uniqueKeysWithValues: model.documents.filter { !$0.generated && !$0.reference && $0.dirty }.map { ($0.id, $0.text) }) + let paths = scope.paths + let dirty = model.documents.filter { !$0.generated && !$0.reference && ($0.dirty || $0.conflict) }.map { ($0.id, $0.savedText) } + let result = try await Task.detached(priority: .userInitiated) { + var live: [String: String] = [:], disk: [String: String] = [:] + var directives: [String: Set] = [:] + let manifest = try CMOCProjectInputManifest.capture(project: project, overlays: overlays, + approvedSupportDirectories: expandedSupport ? nil : scope.configuration.buildSupportDirectories) + let capturedProject = CMOCProject(directory: project.directory, configuration: manifest.configuration) + let effectiveScope = updatedScope ? try MCPCMOCProject(project: capturedProject, files: manifest.sharedPaths, customMake: scope.customMake) : scope + if scope.customMake { + for path in effectiveScope.paths { + guard let bytes = manifest.files[path], let text = String(data: bytes, encoding: .utf8), !bytes.contains(0) else { + throw CMOCBuildError.message("unreadable_project_text: " + path) + } + let diskText = try project.readText(relativePath: path) + if let original = dirty.first(where: { $0.0 == path }), original.1 != diskText { + throw CMOCBuildError.message("external_file_change: " + path) + } + try effectiveScope.validate(text, path: path) + live[path] = text; disk[path] = diskText + } + guard live.values.reduce(0, { $0 + $1.utf8.count }) <= 16 * 1024 * 1024 else { + throw CMOCBuildError.message("shared_text_too_large") + } + let make = MCPCMOCMakeInputs(makefile: manifest.configuration.makefile, files: manifest.files, + permissions: manifest.permissions, modificationDates: manifest.modificationDates, + overlayPaths: manifest.overlayPaths, support: manifest.support) + return (live, disk, directives, Optional(make), manifest, effectiveScope, capturedProject) + } + let installed = template.map { CMOCProject(directory: $0) } + let controls = effectiveScope.helloDisk ? MCPCMOCProject.diskControls : [] + for path in (updatedScope ? effectiveScope.paths : paths) + controls { + let diskText = try project.readText(relativePath: path) + guard diskText.utf8.count <= 65536, (overlays[path]?.utf8.count ?? 0) <= 65536 else { + throw CMOCBuildError.message("file_too_large") + } + if let original = dirty.first(where: { $0.0 == path }), original.1 != diskText { + throw CMOCBuildError.message("external_file_change") + } + let text = overlays[path] ?? diskText + let trusted = effectiveScope.helloDisk ? try installed?.readText(relativePath: path) : nil + if controls.contains(path) { + guard text == trusted, diskText == trusted else { throw CMOCBuildError.message("unsupported_project_recipe") } + continue + } + if path.hasSuffix(".c") || path.hasSuffix(".h") { + let allowed = trusted.map { Set($0.components(separatedBy: .newlines).filter { $0.contains("#") }) } + try effectiveScope.validate(text, path: path, trusted: allowed) + directives[path] = allowed + } + live[path] = text + disk[path] = diskText + } + return (live, disk, directives, nil as MCPCMOCMakeInputs?, + manifest.restricting(to: Set(effectiveScope.paths + controls)), effectiveScope, capturedProject) + }.value + guard model.assistantProjectID == workspace, model.assistantEditEpoch == epoch else { throw problem("stale_revision") } + return CapturedInputs(live: result.0, disk: result.1, epoch: epoch, directives: result.2, + make: result.3, manifest: result.4, scope: result.5, project: result.6) + } + + /// Native review already advanced the revision. Keep its frozen Make inputs + /// in step so the next poll does not count that same edit a second time. + private func recordReviewedMakeEdits(_ model: CMOCDevelopmentModel) { + guard let make = makeSnapshot else { return } + var files = make.files + for (path, text) in snapshot { files[path] = Data(text.utf8) } + makeSnapshot = MCPCMOCMakeInputs(makefile: make.makefile, files: files, permissions: make.permissions, + modificationDates: make.modificationDates, overlayPaths: Set(model.overlays.keys), support: make.support) + } + + private func clearBuildAndLiveControls() { + let retiredRun = playtest?.invalidate(); playtest = nil + ownedInspection = nil + let starts = Array(playtestStarts.values), previousCleanup = playtestStartupCleanup + for start in starts { start.cancel() } + playtestStartupCleanup = Task { + await previousCleanup?.value + for start in starts { await start.waitForCompletion() } + await retiredRun?.value + } + playtestStarts.removeAll(); latestPlaytestStart = nil; playtestBusy = false + readyArtifact = nil + readyDebugMetadata = nil + liveIO?.invalidate() + liveIO = nil + } + + private func adoptCaptured(_ captured: CapturedInputs, model: CMOCDevelopmentModel, advanceRevision: Bool) throws { + let diskFiles = captured.manifest.files.merging(captured.disk.mapValues { Data($0.utf8) }) { _, disk in disk } + try model.acceptAssistantProjectRefresh(captured.project, diskFiles: diskFiles, + projectID: model.assistantProjectID, epoch: captured.epoch) + if advanceRevision { revision += 1; clearBuildAndLiveControls() } + if let approvedInputs { + let changes = captured.manifest.changes(from: approvedInputs) + if !changes.isEmpty { lastAcceptedInputChanges = changes } + } + snapshot = captured.live; diskSnapshot = captured.disk; workspaceEpoch = captured.epoch + makeSnapshot = captured.make; templateDirectives = captured.directives + scope = captured.scope; approvedInputs = captured.manifest; approvedRecipeID = captured.make?.recipeID + observedInputChanges = []; refreshProblem = nil + if var p = proposal, p.status == "pending", advanceRevision { p.status = "stale"; update(p) } + } + + private func refresh(_ model: CMOCDevelopmentModel) async throws { + let owner = session + guard active, self.model === model, projectID == model.assistantProjectID else { throw problem("access_denied") } + guard let scope else { throw problem("project_unavailable") } + do { + let captured = try await capture(model, scope: scope, updatedScope: true) + guard session == owner, active, self.model === model, projectID == model.assistantProjectID else { throw problem("access_denied") } + let changes = approvedInputs.map { captured.manifest.changes(from: $0) } ?? [] + if changes.contains(where: \.requiresReview) { + if refreshProblem == nil { clearBuildAndLiveControls() } + if let candidate = refreshCandidate, candidate.captured.manifest != captured.manifest, + var record = refreshRecords[candidate.refreshID] { + record.status = "rejected"; record.reason = "Inputs changed while review was open. Request a new refresh." + refreshRecords[record.id] = record; refreshCandidate = nil + refreshPanel?.close(); refreshPanel = nil; refreshProblem = "project_refresh_required" + } + observedInputChanges = changes + if refreshProblem == nil { refreshProblem = "project_refresh_required" } + return + } + if let candidate = refreshCandidate, candidate.captured.manifest.identity != captured.manifest.identity { + if var record = refreshRecords[candidate.refreshID], record.status == "pending" { + record.status = "rejected"; record.reason = "Inputs changed while review was open. Request a new refresh."; refreshRecords[record.id] = record + } + refreshCandidate = nil; refreshPanel?.close(); refreshPanel = nil + } + let changed = captured.live != snapshot || captured.disk != diskSnapshot || captured.manifest != approvedInputs + if changed { + // A native reviewed edit already moved the revision and updated + // snapshot/epoch; only rebind its canonical manifest here. + let alreadyReviewed = captured.live == snapshot && captured.disk == diskSnapshot && captured.epoch == workspaceEpoch && captured.make == makeSnapshot + try adoptCaptured(captured, model: model, advanceRevision: !alreadyReviewed) + } else { workspaceEpoch = captured.epoch; makeSnapshot = captured.make; observedInputChanges = []; refreshProblem = nil } + } catch { + guard session == owner, active else { throw problem("access_denied") } + if refreshProblem == nil { clearBuildAndLiveControls() } + refreshProblem = sanitized(error.localizedDescription) + } + } + + #if DEBUG + func exportCallContextRegression(_ model: CMOCDevelopmentModel, at destination: URL, playtests: Bool = true, + helperURL: URL? = nil, roms: URL? = nil) async throws { + allowProjectMakefile = true + allowPlaytests = playtests + try await grant(model, at: destination) + regressionPlaytestHelper = helperURL + regressionStarterKit = roms.map { StarterKit(directory: $0) } + } + + func installProjectRefreshRegression(_ model: CMOCDevelopmentModel, artifact: CMOCBuildArtifact) async throws { + guard let project = model.project else { throw problem("project_unavailable") } + let scope = try MCPCMOCProject(project: project, files: model.files.map(\.relativePath), customMake: true) + let captured = try await capture(model, scope: scope, updatedScope: true, expandedSupport: true) + self.model = model; self.scope = captured.scope; self.projectID = model.assistantProjectID; active = true + snapshot = captured.live; diskSnapshot = captured.disk; workspaceEpoch = captured.epoch + approvedInputs = captured.manifest; makeSnapshot = captured.make; approvedRecipeID = captured.make?.recipeID + revision = 0; readyArtifact = (0, artifact) + } + func projectRefreshRegression(_ model: CMOCDevelopmentModel) async throws -> (revision: Int, artifactID: UUID?) { + try await refresh(model) + return (revision, readyArtifact?.value.id) + } + #endif + + private func sanitized(_ text: String) -> String { + var result = text + for root in [scratch, model?.project?.directory].compactMap({ $0 }) { + result = result.replacingOccurrences(of: root.path, with: "") + } + return String(result.prefix(2000)) + } + + private func projectRefreshFields(_ record: MCPProjectRefreshRecord) -> [String: Any] { + var fields = record.fields; fields["project_id"] = projectID?.uuidString + fields["current_revision"] = revision + return fields + } + + private func requestProjectRefresh(_ arguments: [String: Any], model: CMOCDevelopmentModel, owner: UUID) async throws -> [String: Any] { + guard arguments.count == 3, arguments["project_id"] as? String == projectID?.uuidString, + let request = arguments["request_id"] as? String, (1...128).contains(request.utf8.count), + let expected = int(arguments["revision"]), let scope else { throw problem("invalid_arguments") } + if let existing = refreshRequests[request], let record = refreshRecords[existing] { + guard record.expectedRevision == expected else { throw problem("request_id_conflict") } + if record.status == "pending" { showProjectRefresh(record) } + return projectRefreshFields(record) + } + guard expected == revision else { throw problem("stale_revision") } + guard refreshRecords.count < 64, !building, !running, !playtestBusy, + !model.building, !model.commanding, proposal?.status != "pending" else { throw problem("busy_or_review_pending") } + let captured = try await capture(model, scope: scope, updatedScope: true) + guard active, session == owner, self.model === model else { throw problem("access_denied") } + if let existing = refreshRequests[request], let record = refreshRecords[existing] { + guard record.expectedRevision == expected else { throw problem("request_id_conflict") } + return projectRefreshFields(record) + } + guard expected == revision, captured.epoch == model.assistantEditEpoch else { throw problem("stale_revision") } + let changes = approvedInputs.map { captured.manifest.changes(from: $0) } ?? [] + let review = changes.contains(where: \.requiresReview) + let id = UUID().uuidString + var record = MCPProjectRefreshRecord(id: id, requestID: request, expectedRevision: expected, + identity: captured.manifest.identity, changes: changes, status: review ? "pending" : changes.isEmpty ? "unchanged" : "approved", revision: revision) + if review { + clearBuildAndLiveControls(); observedInputChanges = changes; refreshProblem = "project_refresh_pending" + if let old = refreshCandidate, var previous = refreshRecords[old.refreshID], previous.status == "pending" { + previous.status = "rejected"; previous.reason = "Replaced by a newer refresh request."; refreshRecords[previous.id] = previous + } + refreshCandidate = .init(refreshID: id, owner: owner, captured: captured) + } else { + let changed = captured.live != snapshot || captured.disk != diskSnapshot || captured.manifest != approvedInputs + try adoptCaptured(captured, model: model, advanceRevision: changed) + record.revision = revision + } + refreshRecords[id] = record; refreshRequests[request] = id; latestRefreshID = id + if review { showProjectRefresh(record) } + return projectRefreshFields(record) + } + + private func showProjectRefresh(_ record: MCPProjectRefreshRecord) { + guard record.status == "pending" else { return } + refreshPanel?.close() + func describe(_ entry: CMOCProjectInputManifest.Entry?) -> String { + guard let entry else { return "absent" } + return "role=\(entry.role), included=\(entry.included), executable=\(entry.executable), permissions=\(entry.permissions.map { String($0, radix: 8) } ?? "unchanged/non-control"), SHA-256=\(entry.sha256 ?? "none")" + } + func kind(_ entry: CMOCProjectInputManifest.Entry?) -> String { + guard let entry, entry.included else { return "not shared" } + switch entry.role { + case "header": return "shared header" + case "source": return "shared source file" + case "recipe": return "build recipe" + case "project_settings": return "project settings" + case "generator": return "build script" + case "executable": return "build tool" + case "support", "pending_support_root": return entry.role == "pending_support_root" ? "support folder" : "support file" + case "generated_input": return "generated input" + case "resource": return "project resource" + default: return "shared file" + } + } + func capitalized(_ text: String) -> String { text.prefix(1).uppercased() + String(text.dropFirst()) } + func summary(_ change: CMOCProjectInputManifest.Change) -> String { + let old = change.previous, new = change.current + if old?.included != true { return "Added " + kind(new) } + if new?.included != true { return "Removed " + kind(old) } + if old?.role != new?.role { return "Changed from " + kind(old) + " to " + kind(new) } + if old?.permissions != new?.permissions || old?.executable != new?.executable { + return capitalized(kind(new)) + " permissions changed" + } + return capitalized(kind(new)) + " changed" + } + let before = approvedInputs + let after = refreshCandidate?.refreshID == record.id ? refreshCandidate?.captured.manifest : nil + func preview(_ manifest: CMOCProjectInputManifest?, path: String) -> String { + guard let data = manifest?.files[path] ?? manifest?.support.files[path] else { return "Absent" } + guard data.count <= 64 * 1024, !data.contains(0), let text = String(data: data, encoding: .utf8) else { + return "\(data.count) bytes. Review this file locally; its exact contents are identified under Verification Details." + } + return text + } + let view = VStack(alignment: .leading, spacing: 14) { + Text("Review Project Input Changes").font(.title2.bold()) + Text("Approve \(record.changes.count == 1 ? "this 1 change" : "these \(record.changes.count) changes") to the shared files, build recipe and support files. Approval updates what the assistant can use and does not run the project. Your unsaved edits are kept.") + if record.changes.contains(where: { $0.current?.role == "pending_support_root" }) { + Text("New support folders have not been opened. Approving gives the assistant access to the entire named folder; its contents will be read after approval.") + .font(.callout).foregroundStyle(.secondary) + } + ScrollView { + LazyVStack(alignment: .leading, spacing: 16) { + ForEach(record.changes, id: \.path) { change in + VStack(alignment: .leading, spacing: 4) { + Text(change.path).font(.system(.body, design: .monospaced)).fontWeight(.semibold) + Text(summary(change)).font(.callout) + Text("Before: " + capitalized(kind(change.previous)) + " · After: " + capitalized(kind(change.current))) + .font(.caption).foregroundStyle(.secondary) + DisclosureGroup("Verification Details") { + Text("Before: " + describe(change.previous)) + Text("After: " + describe(change.current)) + }.font(.system(.caption, design: .monospaced)) + DisclosureGroup("Compare File Contents") { + Text("Before").fontWeight(.semibold) + Text(preview(before, path: change.path)) + Text("After").fontWeight(.semibold) + Text(preview(after, path: change.path)) + }.font(.system(.caption, design: .monospaced)) + }.textSelection(.enabled) + } + }.frame(maxWidth: .infinity, alignment: .leading) + }.frame(maxWidth: .infinity, maxHeight: .infinity) + HStack { + Button("Reject") { self.decideProjectRefresh(record.id, approve: false) } + Spacer() + Button("Approve Refresh") { self.decideProjectRefresh(record.id, approve: true) }.keyboardShortcut(.defaultAction) + } + }.padding(20) + let panel = window("Review Project Refresh", width: 760, height: 520, scrolls: false, view: view) + refreshPanel = panel; panel.makeKeyAndOrderFront(nil) + } + + private func decideProjectRefresh(_ id: String, approve: Bool) { + guard let candidate = refreshCandidate, candidate.refreshID == id, + var record = refreshRecords[id], record.status == "pending" else { return } + if !approve { + record.status = "rejected"; record.reason = "The project input changes were rejected locally." + refreshRecords[id] = record; refreshProblem = "project_refresh_rejected" + refreshCandidate = nil; refreshPanel?.close(); refreshPanel = nil + return + } + guard refreshApprovingID != id else { return } + refreshApprovingID = id + Task { + defer { if refreshApprovingID == id { refreshApprovingID = nil } } + do { + guard let model, active, session == candidate.owner, let scope, + revision == record.expectedRevision else { throw problem("stale_revision") } + let fresh = try await capture(model, scope: scope, updatedScope: true) + guard active, session == candidate.owner, self.model === model, + refreshCandidate?.refreshID == id, fresh.manifest == candidate.captured.manifest, + fresh.epoch == candidate.captured.epoch, fresh.epoch == model.assistantEditEpoch, + revision == record.expectedRevision else { throw problem("stale_revision") } + // Only this explicit native action authorizes reading newly + // named support roots. Recheck the limited review basis both + // before and after that read; no unapproved member names/hash + // are included in pending public receipts. + let authorized = try await capture(model, scope: scope, updatedScope: true, expandedSupport: true) + guard authorized.manifest.files == fresh.manifest.files, + authorized.manifest.permissions == fresh.manifest.permissions, + authorized.manifest.configuration == fresh.manifest.configuration, + fresh.manifest.support.files.allSatisfy({ authorized.manifest.support.files[$0.key] == $0.value }), + fresh.manifest.support.permissions.allSatisfy({ authorized.manifest.support.permissions[$0.key] == $0.value }) else { + throw problem("stale_revision") + } + let finalBasis = try await capture(model, scope: scope, updatedScope: true) + guard active, session == candidate.owner, self.model === model, + refreshCandidate?.refreshID == id, finalBasis.manifest == candidate.captured.manifest, + finalBasis.epoch == candidate.captured.epoch, authorized.epoch == finalBasis.epoch, + finalBasis.epoch == model.assistantEditEpoch, revision == record.expectedRevision else { throw problem("stale_revision") } + try adoptCaptured(authorized, model: model, advanceRevision: true) + record.status = "approved"; record.revision = revision + } catch { + guard active, session == candidate.owner, refreshCandidate?.refreshID == id else { return } + record.status = "rejected"; record.reason = sanitized(error.localizedDescription); refreshProblem = "project_refresh_rejected" + } + guard active, session == candidate.owner, refreshCandidate?.refreshID == id else { return } + refreshRecords[id] = record; refreshCandidate = nil + refreshPanel?.close(); refreshPanel = nil + } + } + + private func grant(_ model: CMOCDevelopmentModel, at destination: URL, + presentationIsCurrent: (@MainActor () -> Bool)? = nil) async throws { + let id = model.assistantProjectID, ticket = UUID(), secret = UUID().uuidString + UUID().uuidString + let approvedPlaytests = allowPlaytests + let cleanup = revoke() + session = ticket + pendingModel = model + defer { if session == ticket { pendingModel = nil } } + await cleanup.value + guard session == ticket, model.assistantProjectID == id, presentationIsCurrent?() != false else { throw problem("access_denied") } + guard let project = model.project else { throw problem("project_unavailable") } + let scope = try MCPCMOCProject(project: project, files: model.files.map(\.relativePath), customMake: allowProjectMakefile) + let captured = try await capture(model, scope: scope, updatedScope: true, expandedSupport: true) + guard session == ticket, model.assistantProjectID == id, presentationIsCurrent?() != false else { throw problem("stale_revision") } + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("vcc-c-project-" + UUID().uuidString) + let handler: MCPTransport.Handler = { [weak self] data in + guard let self else { return Data(#"{"error":"access_denied"}"#.utf8) } + return await self.reply(data, owner: ticket) + } + let (server, file) = try await Task.detached { + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + do { + let server = try MCPTransport(handler: handler) + let bytes = try JSONSerialization.data(withJSONObject: ["token": secret, "kind": "cmoc", "toolset": 11, "playtestMedia": approvedPlaytests, "playtestCallContext": approvedPlaytests, "projectRefresh": true, "projectDiagnostics": true, "playtestAudio": approvedPlaytests, "playtestProcessors": approvedPlaytests, "playtestJoysticks": approvedPlaytests, "customMake": scope.customMake, "playtest": approvedPlaytests, "canPropose": true, + "socket": server.unixPath, "port": Int(server.port), "version": 1]) + return (server, try MCPGrantFile(create: destination, data: bytes)) + } catch { try? FileManager.default.removeItem(at: dir); throw error } + }.value + guard session == ticket, model.assistantProjectID == id, presentationIsCurrent?() != false else { + Task.detached { server.stop(); file.remove(); try? FileManager.default.removeItem(at: dir) } + throw problem("stale_revision") + } + self.server = server; self.file = file; token = secret; projectID = id; self.model = model + scratch = dir; service = CMOCBuildService(toolchain: model.service.toolchain, buildRoot: dir.appendingPathComponent("Builds")) + snapshot = captured.live; diskSnapshot = captured.disk; workspaceEpoch = captured.epoch; makeSnapshot = captured.make; approvedInputs = captured.manifest; revision = 0 + self.playtestsApproved = approvedPlaytests + self.callContextApproved = approvedPlaytests + self.playtestMediaApproved = approvedPlaytests + self.scope = captured.scope; templateDirectives = captured.directives; approvedRecipeID = captured.make?.recipeID + active = true; status = "Connected to " + (model.project?.directory.lastPathComponent ?? "Hello Disk") + } + + @discardableResult func revoke() -> Task { + let playtestCleanup = playtest?.invalidate() + let old = server, grant = file, dir = scratch, work = buildTask, guest = runTask + session = UUID(); token = ""; projectID = nil; active = false; model = nil; pendingModel = nil + callContextApproved = false; playtestMediaApproved = false + #if DEBUG + regressionPlaytestHelper = nil; regressionStarterKit = nil + #endif + server = nil; file = nil; scratch = nil; service = nil; scope = nil + snapshot.removeAll(); diskSnapshot.removeAll(); templateDirectives.removeAll(); makeSnapshot = nil; approvedRecipeID = nil + approvedInputs = nil; observedInputChanges = []; lastAcceptedInputChanges = []; refreshRecords.removeAll(); refreshRequests.removeAll(); latestRefreshID = nil + refreshCandidate = nil; refreshProblem = nil; refreshApprovingID = nil; refreshPanel?.close(); refreshPanel = nil + work?.cancel(); guest?.cancel(); buildTask = nil; runTask = nil + builds.removeAll(); buildReports.removeAll(); latestBuildID = nil; buildRequests.removeAll(); clearBuildAndLiveControls(); building = false + proposals.removeAll(); proposalRequests.removeAll(); proposal = nil; status = "" + runID = nil; inspection = nil + runRevision = nil; runReceipt = nil; running = false; runStatus = ""; buildStatus = "" + panel?.close(); panel = nil + let startupCleanup = playtestStartupCleanup + return Task.detached { + await startupCleanup?.value + await playtestCleanup?.value + old?.stop(); grant?.remove() + await work?.value; await guest?.value + if let dir { try? FileManager.default.removeItem(at: dir) } + } + } + func closing(_ model: CMOCDevelopmentModel) { + if self.model === model || pendingModel === model { revoke() } + if consentModel === model { consentPanel?.close(); consentPanel = nil; consentModel = nil } + } + + private func reply(_ data: Data, owner: UUID) async -> Data { + func pack(_ value: [String: Any]) -> Data { (try? JSONSerialization.data(withJSONObject: value)) ?? Data() } + guard active, session == owner, let model, scope != nil, model.assistantProjectID == projectID, let id = projectID?.uuidString, + let r = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], r["token"] as? String == token, + r["version"] as? Int == 1, let tool = r["tool"] as? String, let args = r["arguments"] as? [String: Any] + else { return pack(["error": "access_denied"]) } + func currentGrant() -> Bool { + active && session == owner && self.model === model && model.assistantProjectID == projectID + } + if tool == "search_help" || tool == "read_topic" { + let reply = await MCPHelpIndex.toolResult(tool, arguments: args) + guard currentGrant() else { return pack(["error": "access_denied"]) } + return pack(reply) + } + do { + if tool != "refresh_project" { try await refresh(model) } + guard currentGrant(), let scope else { return pack(["error": "access_denied"]) } + if let refreshProblem, !MCPProjectRefreshRecord.safeTools.contains(tool) { throw problem(refreshProblem) } + let result: [String: Any] + switch tool { + case "refresh_project": + result = try await requestProjectRefresh(args, model: model, owner: owner) + case "get_project_refresh" where args.count == 2: + guard args["project_id"] as? String == id, let refreshID = args["refresh_id"] as? String, + let record = refreshRecords[refreshID] else { throw problem("unknown_project_refresh") } + result = projectRefreshFields(record) + case "read_project_inputs": + guard Set(args.keys).isSubset(of: ["project_id", "offset", "limit"]), args["project_id"] as? String == id, + let manifest = approvedInputs else { throw problem("invalid_arguments") } + let offset = args["offset"] == nil ? 0 : int(args["offset"]) + let limit = args["limit"] == nil ? 128 : int(args["limit"]) + guard let offset, let limit, offset >= 0, (1...256).contains(limit) else { throw problem("invalid_arguments") } + let page = MCPProjectRefreshRecord.inputPage(manifest.entries, offset: offset, limit: limit) + var fields: [String: Any] = ["project_id": id, "revision": revision, "input_identity": manifest.identity, + "entries": page.rows, "offset": offset, "total": manifest.entries.count, + "next_offset": page.nextOffset as Any? ?? NSNull(), "page_truncated": page.truncated, + "status": refreshProblem ?? "approved"] + if let latestRefreshID, let record = refreshRecords[latestRefreshID] { fields["refresh"] = projectRefreshFields(record) } + result = fields + case "get_capabilities" where args.isEmpty: + result = ["tools": Self.tools + (callContextApproved ? ["get_call_context"] : []) + (playtestMediaApproved ? ["list_playtest_media", "exchange_playtest_media"] : []) + (playtestsApproved ? ["list_playtest_disks", "start_playtest", "playtest_input", "get_playtest_input", "playtest_debug", "capture_playtest", "capture_playtest_graphics", "capture_playtest_audio", "restart_playtest", "stop_playtest"] : []), "playtest_media_exchange": playtestMediaApproved, "playtest_media_drive": "FD0", "playtest_media_maximum_disks": 9, "playtest_media_maximum_disk_bytes": 512 * 1024, "call_context": callContextApproved, "call_context_maximum_stack_bytes": 64, "input_diagnostics": true, "playtest_joystick_input": playtestsApproved, "playtest_joystick_interfaces": playtestsApproved ? ["standard"] : [], "playtest_joystick_axis_min": 0, "playtest_joystick_axis_max": 16383, "playtest_joystick_axis_center": 8191, "owned_playtests": playtestsApproved, "async_playtest_start": playtestsApproved, "retained_playtest_disks": playtestsApproved, "period_key": playtestsApproved, "graphics_buffer_capture": playtestsApproved, "custom_gime_canvases": playtestsApproved, "source_only_debugging": playtestsApproved, "verified_flat_debugging": playtestsApproved, "audio_capture": playtestsApproved, "audio_capture_maximum_fields": 120, "audio_capture_maximum_clips": 16, "audio_capture_maximum_bytes": 4 * 1024 * 1024, "build_diagnostics": true, "project_refresh": true, "input_status": refreshProblem ?? "approved", "changed_input_paths": Array(observedInputChanges.prefix(128)).map(\.path), "changed_input_paths_total": observedInputChanges.count, "changed_input_paths_truncated": observedInputChanges.count > 128, "kind": "cmoc", "app": "VCC Plus OSS", + "mutation_request_limit": MCPPlaytest.mutationRequestLimit, "stop_retention_exempt": true, + "playtest_processors": playtestsApproved ? ["MC6809", "HD6309"] : [], + "playtest_default_processor": "MC6809", "playtest_processor_selection": playtestsApproved, + "app_version": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown", + "app_build": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown", "project_id": id, "revision": revision, + "entry": scope.entry, "target": "CoCo Disk BASIC", "build_recipe": scope.customMake ? "approved_make" : scope.helloDisk ? "installed_hello_disk" : "bundled_cmoc", "files": scope.paths, "headers": Self.headers, "session_id": owner.uuidString, "version": 1] + if scope.customMake { + var facts = result + facts["recipe_id"] = approvedRecipeID + facts["build_actions"] = scope.configuration.diskTarget == nil ? ["build"] : ["build", "disk"] + facts["configurations"] = scope.configuration.configurations.map(\.name) + facts["configuration"] = model.configurationName + facts["targets"] = ["build": scope.configuration.buildTarget, "disk": scope.configuration.diskTarget ?? ""] + facts["build_support_directories"] = scope.configuration.buildSupportDirectories + facts["playtest_disk_products"] = scope.configuration.playtestDisks + facts["function_entry_stops"] = playtestsApproved + facts["launch_mode"] = scope.configuration.launchMode.rawValue + facts["launch_commands"] = scope.configuration.launchCommands + facts["run_requirement"] = playtestsApproved ? "Owned playtests may cold-boot a copy of the current artifact disk or a selected retained test disk in an isolated 512 KB MC6809 or HD6309 worker. MC6809 is the default; the guest controls HD6309 execution mode. Debug evidence stays bound to the current artifact and is checked against runtime bytes." : "Start in VCC Plus; source debugging requires a verified map matching the delivered binary." + return pack(["result": facts]) + } + case "get_machine_status" where args.isEmpty: + let observed = await model.machine.mcpReadinessSnapshot() + let tools = CMOCBuildService.requiredExecutables + ["mcpp"] + + (scope.helloDisk ? ["perl", "writecocofile", "install-coco-boot-loader"] : []) + var build = await MCPMachineStatus.missingToolBlockers(in: model.service.toolchain, requiring: tools) + var run: [String] = [] + if refreshProblem != nil { + build.append("Refresh the changed project inputs and complete native review before building.") + run.append("Project inputs changed; refresh and rebuild before running.") + } + if builds.count >= 32 { build.append("Reconnect to start another build.") } + if building || running || model.building || model.commanding { build.append("Wait for the current operation to finish.") } + if readyArtifact?.revision != revision { run.append("Build the current project revision successfully.") } + if proposal?.status == "pending" { run.append("Review the pending C source change.") } + else if !readyToRun && readyArtifact?.revision == revision { run.append("Apply a source change to run the reviewed Hello Disk build.") } + if model.machine.busy || building || running || model.commanding { run.append("Wait for the current operation to finish.") } + result = MCPMachineStatus.result(observed, workspace: .cmoc(needsFloppy: scope.helloDisk), + buildBlockers: build, runBlockers: run, lastBuild: latestBuildID.flatMap(buildRecord), + profile: model.machine.usageProfile, input: model.machine.inputDiagnostics(machine: observed)) + case "read_project_file" where args.count == 2: + guard args["project_id"] as? String == id, let path = args["path"] as? String else { throw problem("access_denied") } + let text: String + if Self.headers.contains(path) { + let url = model.service.toolchain.appendingPathComponent("share/cmoc/include").appendingPathComponent((path as NSString).lastPathComponent) + text = try await Task.detached { try CMOCProject.readText(url, maximumBytes: 65536) }.value + guard active, session == owner, model.assistantProjectID == projectID else { throw problem("access_denied") } + } else { text = try read(path) } + result = ["project_id": id, "revision": revision, "path": path, "text": text] + case "build_project" where args.count >= 3 && args.count <= 5: + guard args["project_id"] as? String == id else { throw problem("access_denied") } + guard Set(args.keys).isSubset(of: ["project_id", "revision", "request_id", "action", "configuration"]), + scope.customMake || args.count == 3, + args["action"] == nil || args["action"] is String, + args["configuration"] == nil || args["configuration"] is String else { throw problem("invalid_arguments") } + result = try startBuild(request: args["request_id"] as? String, revision: int(args["revision"]), model: model, + action: args["action"] as? String, configuration: args["configuration"] as? String) + case "get_build" where args.count == 1: + guard let id = args["build_id"] as? String, let build = buildRecord(id) else { throw problem("unknown_build") } + result = build + case "get_build_log": + guard Set(args.keys).isSubset(of: ["build_id", "offset", "limit"]), + let buildID = args["build_id"] as? String, let build = buildRecord(buildID) else { throw problem("unknown_build") } + guard let report = buildReports[buildID] else { throw problem("build_log_pending") } + let offset = args["offset"] == nil ? 0 : int(args["offset"]) + let limit = args["limit"] == nil ? 16_384 : int(args["limit"]) + guard let offset, let limit else { throw problem("invalid_arguments") } + var page = try report.logPage(offset: offset, limit: limit) + for key in ["build_id", "project_id", "revision", "action", "configuration", "status"] { page[key] = build[key] } + result = page + case "propose_fix" where args.count == 6: + guard args["project_id"] as? String == id else { throw problem("access_denied") } + result = try propose(args) + case "propose_project_edits" where args.count == 4: + guard args["project_id"] as? String == id else { throw problem("access_denied") } + result = try proposeEdits(args, scope: scope) + case "get_proposal" where args.count == 1: + guard let id = args["proposal_id"] as? String, let p = proposals[id] else { throw problem("unknown_proposal") } + result = p.result + case "list_playtest_media": + guard playtestMediaApproved, + Set(args.keys).isSubset(of: ["project_id", "revision", "artifact_id", "run_id"]), + (3...4).contains(args.count), args["project_id"] as? String == id, + int(args["revision"]) == revision, let ready = readyArtifact, ready.revision == revision, + args["artifact_id"] as? String == ready.value.id.uuidString else { throw problem("invalid_playtest_selection") } + let storage = try retainedDiskContext(model) + let products = try await artifactMedia(ready.value, projectKey: storage.key) + guard currentGrant(), readyArtifact?.value.id == ready.value.id, + workspaceEpoch == model.assistantEditEpoch else { throw problem("stale_run") } + let retained = try await MCPPlaytestDiskStore.list(directory: storage.directory, projectKey: storage.key) + guard currentGrant(), readyArtifact?.value.id == ready.value.id, + workspaceEpoch == model.assistantEditEpoch else { throw problem("stale_run") } + var state: [String: Any] = [:] + if let supplied = args["run_id"] { + guard let run = supplied as? String, let owned = playtest, owned.runID == run, + ownsPlaytest(owned, artifact: ready.value, owner: owner), !playtestBusy else { throw problem("stale_run") } + playtestBusy = true + do { + state = try await owned.reply("list_playtest_media", arguments: ["run_id": run]) + playtestBusy = false + } catch { playtestBusy = false; throw error } + guard ownsPlaytest(owned, artifact: ready.value, owner: owner) else { throw problem("stale_run") } + } + var rows = state["media"] as? [[String: Any]] ?? products.map { item in + ["media_id": item.id, "name": item.name, "media_key": item.key, "base_sha256": item.baseSHA256, + "media_sha256": item.baseSHA256, "byte_count": item.data.count, "inserted": false, "dirty": false, "retained": false] + } + for index in rows.indices { + guard let key = rows[index]["media_key"] as? String, + let product = products.first(where: { $0.key == key }) else { continue } + let choices = retained.filter { + $0.provenance.artifactDiskSHA256 == ready.value.diskSHA256 && + ($0.provenance.mediaKey ?? "primary") == key && + ($0.provenance.mediaBaseSHA256 ?? $0.provenance.artifactDiskSHA256) == product.baseSHA256 + } + rows[index]["retained_disks"] = Array(choices.prefix(16)).map(\.publicFields) + rows[index]["retained_disk_count"] = choices.count + rows[index]["retained_disks_truncated"] = choices.count > 16 + } + state["media"] = rows; state["project_id"] = id; state["revision"] = revision + state["artifact_id"] = ready.value.id.uuidString; state["drive"] = "FD0" + result = state + case "list_playtest_disks": + guard playtestsApproved, args.count == 1, args["project_id"] as? String == id else { throw problem("access_denied") } + let storage = try retainedDiskContext(model) + let records = try await MCPPlaytestDiskStore.list(directory: storage.directory, projectKey: storage.key) + guard currentGrant(), workspaceEpoch == model.assistantEditEpoch else { throw problem("stale_run") } + // The legacy endpoint selects only the primary boot disk. + // Additional media histories belong to list_playtest_media. + result = ["project_id": id, "disks": records.filter { ($0.provenance.mediaKey ?? "primary") == "primary" }.map(\.publicFields)] + case "start_playtest": + guard playtestsApproved else { throw problem("access_denied") } + result = try await startPlaytest(args, model: model, owner: owner) + case "playtest_input", "get_playtest_input", "playtest_debug", "capture_playtest", "capture_playtest_graphics", "capture_playtest_audio", "restart_playtest", "stop_playtest", "exchange_playtest_media": + if tool == "stop_playtest", playtestsApproved, args.count == 2, + let runID = args["run_id"] as? String, let request = args["request_id"] as? String, + (1...128).contains(request.utf8.count), + let start = playtestStarts.values.first(where: { $0.runID == runID }), start.status != "ready" { + guard start.revision == revision, start.artifactID == readyArtifact?.value.id.uuidString else { throw problem("stale_run") } + start.cancel() + result = start.fields + break + } + guard tool != "exchange_playtest_media" || playtestMediaApproved else { throw problem("access_denied") } + guard playtestsApproved, let owned = playtest, args["run_id"] as? String == owned.runID, + let artifact = readyArtifact, artifact.revision == revision, + owned.artifactID == artifact.value.id.uuidString, !playtestBusy else { throw problem("stale_run") } + playtestBusy = true + defer { playtestBusy = false } + if !["capture_playtest", "capture_playtest_graphics", "get_playtest_input"].contains(tool) { ownedInspection = nil } + var request = args + if tool == "playtest_debug" { + guard Set(args.keys).isSubset(of: ["run_id", "request_id", "action", "function", "stop_kind"]), let action = args["action"] as? String else { throw problem("invalid_arguments") } + if action == "stop_at" { + guard (4...5).contains(args.count), let function = args["function"] as? String else { throw problem("invalid_arguments") } + let kind = try functionStopKind(args["stop_kind"]) + request.removeValue(forKey: "function"); request.removeValue(forKey: "stop_kind") + request["selection"] = kind + ":" + function + let point = try await verifiedFunction(function, artifact: artifact.value, kind: kind) + request["address"] = Int(point.address) + if let module = point.moduleID { request["module_id"] = module } + } else if args.count != 3 { throw problem("invalid_arguments") } + } + guard ownsPlaytest(owned, artifact: artifact.value, owner: owner) else { throw problem("stale_run") } + result = try await owned.reply(tool, arguments: request, isCurrent: { self.ownsPlaytest(owned, artifact: artifact.value, owner: owner) }) + guard ownsPlaytest(owned, artifact: artifact.value, owner: owner) else { throw problem("stale_run") } + case "read_screen_text", "send_keys": + guard let io = liveIO, let runID, args["run_id"] as? String == runID, + let artifact = readyArtifact, artifact.revision == revision, runRevision == revision, + inspection?.fields["artifact_id"] as? String == artifact.value.id.uuidString else { throw problem("stale_run") } + result = try await io.reply(tool, arguments: args) + guard currentGrant(), liveIO === io, self.runID == runID, runRevision == revision, + model.assistantEditEpoch == workspaceEpoch, readyArtifact?.value.id == artifact.value.id else { + throw problem("stale_run") + } + case "get_call_context": + guard callContextApproved, playtestsApproved, + Set(args.keys) == ["run_id", "snapshot_id"], + let owned = playtest, args["run_id"] as? String == owned.runID, + !playtestBusy, let artifact = readyArtifact, artifact.revision == revision, + artifact.value.id.uuidString == owned.artifactID else { throw problem("access_denied") } + playtestBusy = true; defer { playtestBusy = false } + result = try await ownedDebugReply(tool, arguments: args, owned: owned, artifact: artifact.value, owner: owner) + case "get_debug_snapshot", "read_debug_memory": + if let owned = playtest, args["run_id"] as? String == owned.runID { + guard playtestsApproved, !playtestBusy, let artifact = readyArtifact, artifact.revision == revision, + artifact.value.id.uuidString == owned.artifactID else { throw problem("stale_run") } + playtestBusy = true; defer { playtestBusy = false } + result = try await ownedDebugReply(tool, arguments: args, owned: owned, artifact: artifact.value, owner: owner) + break + } + guard let runID, args["run_id"] as? String == runID, runRevision == revision, + let artifact = readyArtifact, let inspection, inspection.runID == runID, + inspection.fields["artifact_id"] as? String == artifact.value.id.uuidString else { throw problem("stale_run") } + let now = await model.machine.mcpMachineSnapshot() + guard currentGrant(), self.runID == runID, runRevision == revision, workspaceEpoch == model.assistantEditEpoch, + readyArtifact?.value.id == artifact.value.id, + MCPDebuggerInspection.sameProgram(now, inspection.machine) else { throw problem("stale_run") } + result = try inspection.reply(tool: tool, arguments: args) + case "get_run" where args.count == 2: + guard args["project_id"] as? String == id else { throw problem("access_denied") } + if let start = latestPlaytestStart, start.status != "ready" { + guard int(args["revision"]) == revision, start.revision == revision, + start.artifactID == readyArtifact?.value.id.uuidString else { throw problem("stale_revision") } + result = start.fields + break + } + if let owned = playtest, int(args["revision"]) == owned.revision, let artifact = readyArtifact { + guard ownsPlaytest(owned, artifact: artifact.value, owner: owner), !playtestBusy else { throw problem("stale_run") } + playtestBusy = true; defer { playtestBusy = false } + var receipt = try await owned.capture() + receipt.removeValue(forKey: "png_base64") + guard ownsPlaytest(owned, artifact: artifact.value, owner: owner) else { throw problem("stale_run") } + result = ["project_id": id, "revision": revision, "run_id": owned.runID, "artifact_id": artifact.value.id.uuidString, + "owned_playtest": true, "requested_processor": owned.processor.rawValue, + "status": "ready", "phase": "ready", "busy": false, "receipt": receipt] + break + } + guard runRevision != nil else { throw problem("no_run") } + guard int(args["revision"]) == revision, runRevision == revision else { throw problem("stale_revision") } + var state: [String: Any] = ["project_id": id, "revision": revision, "busy": running, "status": runStatus] + state["run_id"] = runID as Any? ?? NSNull() + if let runReceipt { state["receipt"] = runReceipt } + if let io = liveIO, let inspection, let runID { + let observed = await model.machine.mcpMachineSnapshot() + guard currentGrant(), liveIO === io, self.runID == runID, runRevision == revision, + workspaceEpoch == model.assistantEditEpoch, + MCPDebuggerInspection.sameProgram(observed, inspection.machine), + observed.debuggerDevelopmentAttached else { throw problem("stale_run") } + if observed.assistantCompiledReturned { + let text = try await io.finalScreenText() + guard currentGrant(), liveIO === io, self.runID == runID, runRevision == revision, + workspaceEpoch == model.assistantEditEpoch else { throw problem("stale_run") } + if let text { state["final_screen_text"] = text } + state["status"] = "finished" + runStatus = "The C program returned to BASIC." + } else { + state["status"] = observed.state == .paused ? "paused" : "running" + } + } + result = state + default: throw problem("invalid_arguments") + } + guard currentGrant() else { return pack(["error": "access_denied"]) } + return pack(["result": result]) + } catch { + guard currentGrant() else { return pack(["error": "access_denied"]) } + let message = sanitized(error.localizedDescription) + let stale = message.contains("stale") || refreshProblem != nil || message.contains("external_file_change") + if stale { + let changes = observedInputChanges.isEmpty ? lastAcceptedInputChanges : observedInputChanges + var details: [String: Any] = ["error": message, "current_revision": revision, + "current_artifact_id": readyArtifact?.value.id.uuidString as Any? ?? NSNull(), + "changed_input_paths": Array(changes.prefix(128)).map(\.path), + "changed_input_paths_total": changes.count, "changed_input_paths_truncated": changes.count > 128, "input_status": refreshProblem ?? "approved"] + if let expected = int(args["revision"]) { details["expected_revision"] = expected } + if let expected = args["artifact_id"] as? String { details["expected_artifact_id"] = expected } + if let latestRefreshID { details["refresh_id"] = latestRefreshID } + return pack(["error": message, "error_details": details]) + } + return pack(["error": message]) + } + } + + private func ownsPlaytest(_ owned: MCPPlaytest, artifact: CMOCBuildArtifact, owner: UUID) -> Bool { + active && session == owner && playtest === owned && readyArtifact?.value.id == artifact.id && + readyArtifact?.revision == revision && owned.revision == revision && + workspaceEpoch == model?.assistantEditEpoch && projectID == model?.assistantProjectID + } + + private func retainedDiskContext(_ model: CMOCDevelopmentModel) throws -> (directory: URL, key: String) { + guard let project = model.project else { throw problem("project_unavailable") } + let identity = project.directory.standardizedFileURL.resolvingSymlinksInPath().path + return (model.machine.developmentRunDirectory.appendingPathComponent("Assistant Playtests"), + CMOCProject.sha256(Data(identity.utf8))) + } + + private func startPlaytest(_ arguments: [String: Any], model: CMOCDevelopmentModel, owner: UUID) async throws -> [String: Any] { + guard Set(arguments.keys).isSubset(of: ["project_id", "revision", "artifact_id", "request_id", "stop_function", "stop_kind", "retained_disk_id", "retained_disk_sha256", "processor", "retained_media"]), + (4...10).contains(arguments.count), arguments["project_id"] as? String == projectID?.uuidString, + int(arguments["revision"]) == revision, let request = arguments["request_id"] as? String, + (1...128).contains(request.utf8.count), let ready = readyArtifact, ready.revision == revision, + arguments["artifact_id"] as? String == ready.value.id.uuidString, + !building, !running, proposal?.status != "pending", let scope else { throw problem("invalid_playtest_selection") } + let artifact = ready.value + let processor = try MCPPlaytestProcessor.selected(arguments["processor"]) + let function = arguments["stop_function"] as? String + let kind = try functionStopKind(arguments["stop_kind"]) + guard arguments["stop_kind"] == nil || function != nil else { throw problem("invalid_arguments") } + guard arguments["stop_function"] == nil || (function != nil && !(function?.isEmpty ?? true)) else { throw problem("invalid_arguments") } + let retainedID = arguments["retained_disk_id"] as? String + let retainedSHA = arguments["retained_disk_sha256"] as? String + var retainedMedia: [[String: String]] = [] + if let value = arguments["retained_media"] { + guard playtestMediaApproved, let records = value as? [[String: String]], (1...8).contains(records.count), + Set(records.compactMap { $0["media_id"] }).count == records.count, + records.allSatisfy({ Set($0.keys) == ["media_id", "retained_disk_id", "retained_disk_sha256"] }) else { + throw problem("invalid_retained_media_selection") + } + let allowed = Set(artifact.playtestDiskProducts.map { + MCPPlaytestMedium.identifier(artifactID: artifact.id.uuidString, key: "disk:" + $0.relativePath) + }) + guard records.allSatisfy({ allowed.contains($0["media_id"] ?? "") }) else { throw problem("invalid_retained_media_selection") } + retainedMedia = records + } + guard (arguments["retained_disk_id"] == nil && arguments["retained_disk_sha256"] == nil) || + (retainedID != nil && retainedSHA != nil) else { throw problem("invalid_retained_disk_selection") } + let selection: [String: Any] = ["artifact": artifact.id.uuidString, "revision": revision, "stop_kind": kind, "processor": processor.rawValue, + "function": function as Any? ?? NSNull(), "retained_media": retainedMedia, "retained_disk_id": retainedID as Any? ?? NSNull(), + "retained_disk_sha256": retainedSHA as Any? ?? NSNull()] + let identity = CMOCProject.sha256(try JSONSerialization.data(withJSONObject: selection, options: [.sortedKeys])) + if let existing = playtestStarts[request] { + guard existing.identity == identity, + existing.status != "ready" || playtest?.runID == existing.runID else { throw problem("request_id_conflict") } + return existing.fields + } + guard !playtestBusy else { throw problem("playtest_busy") } + #if DEBUG + let selectedKit = regressionStarterKit ?? StarterKit.bundled + #else + let selectedKit = StarterKit.bundled + #endif + guard playtestStarts.count < 16, let diskURL = artifact.diskURL, let kit = selectedKit else { throw problem("disk_playtest_unavailable") } + let start = MCPOwnedPlaytestStart(identity: identity, requestID: request, projectID: projectID!.uuidString, + revision: revision, artifactID: artifact.id.uuidString, processor: processor, + redactionRoots: [scratch, artifact.directory, artifact.compilationDirectory].compactMap { $0 }) + let priorCleanup = playtestStartupCleanup + playtestStarts[request] = start; latestPlaytestStart = start; playtestBusy = true + start.launch { [self] start in + defer { if latestPlaytestStart === start { playtestBusy = false } } + return try await preparePlaytest(start, artifact: artifact, diskURL: diskURL, kit: kit, + function: function, kind: kind, retainedID: retainedID, retainedSHA: retainedSHA, retainedMedia: retainedMedia, processor: processor, + model: model, owner: owner, scope: scope, priorCleanup: priorCleanup) + } + return start.fields + } + + private func preparePlaytest(_ start: MCPOwnedPlaytestStart, artifact: CMOCBuildArtifact, diskURL: URL, + kit: StarterKit, function: String?, kind: String, retainedID: String?, retainedSHA: String?, retainedMedia: [[String: String]], processor: MCPPlaytestProcessor, + model: CMOCDevelopmentModel, owner: UUID, scope: MCPCMOCProject, + priorCleanup: Task?) async throws -> [String: Any] { + func current() -> Bool { + start.acceptingResult && latestPlaytestStart === start && active && session == owner && + self.model === model && readyArtifact?.value.id == artifact.id && readyArtifact?.revision == revision && + start.revision == revision && workspaceEpoch == model.assistantEditEpoch && projectID == model.assistantProjectID + } + guard current() else { throw problem("stale_run") } + start.updatePhase("waiting_for_previous_startup_cleanup") + await priorCleanup?.value + guard current() else { throw problem("stale_run") } + start.updatePhase("preparing_debug_metadata") + var modules: [[String: Any]] = [], flatGuards: [[String: Any]] = [], stop: UInt16?, stopModule: String? + var graphicsBuffers: [[String: Any]] = [] + let evidence: (map: CMOCProjectSourceMap, variables: CMOCVariableDebug?, variableError: String?)? + do { evidence = try await debugMetadata(artifact) } + catch { + if artifact.debugManifestRelativePath != nil || function != nil { throw error } + evidence = nil // A playable build need not have source debug evidence. + } + if let evidence { + let map = evidence.map + guard current() else { throw problem("stale_run") } + if let function { + let point = try await verifiedFunction(function, artifact: artifact, kind: kind) + stop = point.address; stopModule = point.moduleID + } + if let layout = map.bankedLayout { + graphicsBuffers = layout.framebuffers.map(\.workerFields) + modules = layout.modules.compactMap { module in + let code = module.codeGuards + guard !code.isEmpty else { return nil } + return ["id": module.id, "pages": module.pages.map { ["logical_page": $0.logicalPage, "physical_page": $0.physicalPage] }, + "guards": code.map { ["address": Int($0.address), "bytes_base64": Data($0.bytes).base64EncodedString()] }] + } + } else { + flatGuards = map.flatCodeGuards.map(\.workerFields) + guard !flatGuards.isEmpty else { throw problem("verified_flat_code_unavailable") } + } + } + guard current() else { throw problem("stale_run") } + start.updatePhase("reading_artifact") + let payload = try await Task.detached { + (try ROMImage.read(kit.directory.appendingPathComponent("coco3.rom")), + try DiskFiles.readROM(kit.directory.appendingPathComponent("disk11.rom")), + try artifact.playtestPrimaryDiskData()) + }.value + guard current() else { throw problem("stale_run") } + guard let expectedDisk = artifact.diskSHA256, CMOCProject.sha256(payload.2) == expectedDisk else { throw problem("artifact_disk_changed") } + let storage = try retainedDiskContext(model) + var selectedDisk = payload.2 + var origin = "verified_artifact" + var originArtifactID: String? = artifact.id.uuidString + var originArtifactDiskSHA256: String? = expectedDisk + if let retainedID, let retainedSHA { + start.updatePhase("reading_retained_disk") + let saved = try await MCPPlaytestDiskStore.load(directory: storage.directory, id: retainedID, + expectedSHA256: retainedSHA, projectKey: storage.key, artifactDiskSHA256: expectedDisk) + selectedDisk = saved.data; origin = saved.record.provenance.origin + originArtifactID = saved.record.provenance.originArtifactID + originArtifactDiskSHA256 = saved.record.provenance.originArtifactDiskSHA256 + } + guard current() else { throw problem("stale_run") } + let provenance = MCPPlaytestDiskStore.Provenance(projectKey: storage.key, artifactID: artifact.id.uuidString, + artifactDiskSHA256: expectedDisk, parentDiskID: retainedID, origin: origin, + originArtifactID: originArtifactID, originArtifactDiskSHA256: originArtifactDiskSHA256, + mediaKey: playtestMediaApproved ? "primary" : nil, mediaBaseSHA256: playtestMediaApproved ? expectedDisk : nil) + var media: [MCPPlaytestMedium]? + if playtestMediaApproved { + var selected = try await artifactMedia(artifact, projectKey: storage.key, primaryData: payload.2) + guard current(), let primary = selected.first else { throw problem("stale_run") } + selected[0] = MCPPlaytestMedium(id: primary.id, name: primary.name, key: primary.key, + baseSHA256: primary.baseSHA256, data: selectedDisk, provenance: provenance) + for saved in retainedMedia { + guard let id = saved["media_id"], let index = selected.firstIndex(where: { $0.id == id }), index > 0, + let diskID = saved["retained_disk_id"], let hash = saved["retained_disk_sha256"] else { throw problem("invalid_retained_media_selection") } + let item = selected[index] + let copy = try await MCPPlaytestDiskStore.load(directory: storage.directory, id: diskID, expectedSHA256: hash, + projectKey: storage.key, artifactDiskSHA256: expectedDisk, mediaKey: item.key, mediaBaseSHA256: item.baseSHA256) + guard current() else { throw problem("stale_run") } + let prior = copy.record.provenance + let origin = MCPPlaytestDiskStore.Provenance(projectKey: storage.key, artifactID: artifact.id.uuidString, + artifactDiskSHA256: expectedDisk, parentDiskID: diskID, origin: prior.origin, + originArtifactID: prior.originArtifactID, originArtifactDiskSHA256: prior.originArtifactDiskSHA256, + mediaKey: item.key, mediaBaseSHA256: item.baseSHA256) + selected[index] = MCPPlaytestMedium(id: item.id, name: item.name, key: item.key, + baseSHA256: item.baseSHA256, data: copy.data, provenance: origin) + } + media = selected + } + if let previous = playtest { + start.updatePhase("retaining_previous_run") + try await previous.retainForReplacement() + guard playtest === previous else { throw problem("stale_run") } + playtest = nil + } + ownedInspection = nil + guard current() else { throw problem("stale_run") } + start.updatePhase("booting") + var helperURL: URL? + #if DEBUG + helperURL = regressionPlaytestHelper + #endif + let owned = try await MCPPlaytest.start(systemROM: payload.0, diskROM: payload.1, disk: selectedDisk, + bootCommands: scope.configuration.launchCommands.joined(separator: "\n") + "\n", + projectID: projectID!.uuidString, revision: revision, artifactID: artifact.id.uuidString, modules: modules, stopAt: stop, stopModule: stopModule, flatGuards: flatGuards, cpu: processor.workerCPU, helperURL: helperURL, + retentionDirectory: storage.directory, diskProvenance: provenance, resumedDiskID: retainedID, + graphicsBuffers: graphicsBuffers, runID: start.runID, media: media) + guard current() else { await owned.invalidate().value; throw problem("stale_run") } + playtest = owned + start.updatePhase("capturing_initial_state") + do { + let result = try await owned.capture() + guard current(), ownsPlaytest(owned, artifact: artifact, owner: owner) else { throw problem("stale_run") } + return result + } catch { + await owned.invalidate().value + if playtest === owned { playtest = nil } + throw error + } + } + + private func artifactMedia(_ artifact: CMOCBuildArtifact, projectKey: String, primaryData: Data? = nil) async throws -> [MCPPlaytestMedium] { + try await Task.detached { + let primary = try primaryData ?? artifact.playtestPrimaryDiskData() + guard let base = artifact.diskSHA256, CMOCProject.sha256(primary) == base else { throw ProfileFailure.message("artifact_disk_changed") } + func medium(key: String, name: String, hash: String, bytes: Data) -> MCPPlaytestMedium { + let origin = MCPPlaytestDiskStore.Provenance(projectKey: projectKey, artifactID: artifact.id.uuidString, + artifactDiskSHA256: base, mediaKey: key, mediaBaseSHA256: hash) + return MCPPlaytestMedium(id: MCPPlaytestMedium.identifier(artifactID: artifact.id.uuidString, key: key), + name: name, key: key, baseSHA256: hash, data: bytes, provenance: origin) + } + var result = [medium(key: "primary", name: artifact.diskRelativePath ?? "Boot disk", hash: base, bytes: primary)] + for product in artifact.playtestDiskProducts { + let bytes = try artifact.playtestDiskData(for: product) + result.append(medium(key: "disk:" + product.relativePath, name: product.relativePath, hash: product.sha256, bytes: bytes)) + } + return result + }.value + } + + private func debugMetadata(_ artifact: CMOCBuildArtifact) async throws -> (map: CMOCProjectSourceMap, variables: CMOCVariableDebug?, variableError: String?) { + if let cached = readyDebugMetadata, cached.artifactID == artifact.id { return (cached.map, cached.variables, cached.variableError) } + let owner = session + let verified = try await Task.detached { + let map = try CMOCProjectSourceMap.parse(artifact: artifact) + do { return (map, Optional(try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map)), Optional.none) } + catch { return (map, Optional.none, Optional(error.localizedDescription)) } + }.value + guard active, session == owner, readyArtifact?.value.id == artifact.id, readyArtifact?.revision == revision, + workspaceEpoch == model?.assistantEditEpoch, projectID == model?.assistantProjectID else { throw problem("stale_run") } + readyDebugMetadata = (artifact.id, verified.0, verified.1, verified.2) + return verified + } + + private func functionStopKind(_ value: Any?) throws -> String { + guard value != nil else { return "c_line" } + guard let kind = value as? String, ["c_line", "function_entry"].contains(kind) else { throw problem("invalid_arguments") } + return kind + } + + private func verifiedFunction(_ name: String, artifact: CMOCBuildArtifact, kind: String = "c_line") async throws -> (address: UInt16, moduleID: String?) { + let (map, metadata, _) = try await debugMetadata(artifact) + if kind == "function_entry", let function = metadata?.entryFunction(named: name), let address = UInt16(exactly: function.entry) { + return (address, function.moduleID) + } + if kind == "function_entry", let symbol = map.executableSymbol(named: name) { return (symbol.address, symbol.moduleID) } + if kind == "c_line", let point = metadata?.breakpointInstruction(named: name) { return (point.address, point.moduleID) } + throw problem("verified_function_unavailable: Choose a function from the build receipt's functions or function_entries list for the selected stop kind.") + } + + private func ownedDebugReply(_ tool: String, arguments: [String: Any], owned: MCPPlaytest, + artifact: CMOCBuildArtifact, owner: UUID) async throws -> [String: Any] { + let capture = try await owned.debugCapture() + guard ownsPlaytest(owned, artifact: artifact, owner: owner), + capture["processor"] as? String == owned.processor.rawValue, + capture["paused"] as? Bool == true, capture["attached"] as? Bool == true, + let clock = capture["field_clock"] as? Int else { throw problem("verified_pause_required") } + if tool == "get_call_context" { + guard callContextApproved, Set(arguments.keys) == ["run_id", "snapshot_id"], + let previous = ownedInspection, previous.run == owned.runID, + arguments["snapshot_id"] as? String == previous.id, + previous.clock == clock, previous.fingerprint == Self.ownedCaptureFingerprint(capture), + var context = previous.callContext else { throw problem("stale_or_unavailable_call_context") } + for key in ["run_id", "snapshot_id", "artifact_id", "project_id", "revision", "processor", "requested_processor", + "execution_mode", "md_register", "field_clock", "boot", "stop_kind", "mapping_fingerprint", "program_revision"] { + context[key] = previous.fields[key] ?? NSNull() + } + return context + } + if tool == "read_debug_memory" { + guard arguments.count == 4, let previous = ownedInspection, previous.run == owned.runID, + previous.clock == clock, arguments["snapshot_id"] as? String == previous.id, + let address = int(arguments["address"]), let count = int(arguments["count"]), + (1...256).contains(count), address >= 0, address <= 0xff00 - count, + previous.ranges.contains(where: { $0.contains(address) && address + count <= $0.upperBound }) else { throw problem("stale_or_unavailable_memory") } + return ["run_id": owned.runID, "snapshot_id": previous.id, "address": address, "count": count, + "bytes": Array(previous.memory[address..<(address + count)]).map(Int.init)] + } + guard arguments.count == 1, let encoded = capture["logical_memory"] as? String, + let memory = Data(base64Encoded: encoded), memory.count == 65536, + let encodedAvailable = capture["available"] as? String, let available = Data(base64Encoded: encodedAvailable), available.count == memory.count, + let pc = capture["pc"] as? Int, let address = UInt16(exactly: pc), + let registers = capture["registers"] as? [String: Int], + let stackPointer = registers["S"].flatMap({ UInt16(exactly: $0) }), + let framePointer = registers["U"].flatMap({ UInt16(exactly: $0) }), + let rawPages = capture["physical_pages"] as? [String: Int] else { throw problem("invalid_worker_capture") } + let pages = Dictionary(uniqueKeysWithValues: rawPages.compactMap { key, value in Int(key).map { ($0, value) } }) + let (verifiedMap, verifiedMetadata, variableError) = try await debugMetadata(artifact) + guard ownsPlaytest(owned, artifact: artifact, owner: owner) else { throw problem("stale_run") } + let map = verifiedMap.projected(physicalPages: pages, memory: memory, available: available) + let metadata = verifiedMetadata?.projected(physicalPages: pages, memory: memory, available: available) + let shared = Set(scope?.paths ?? []) + let point = map.instruction(at: address).flatMap { shared.contains($0.sourcePath) ? $0 : nil } + let function = metadata?.entryFunction(containing: address).flatMap { shared.contains($0.sourcePath) ? $0 : nil } + let executable = map.executableLocation(at: address, memory: memory, available: available, sharedPaths: shared) + guard point != nil || function != nil || executable != nil, + map.verifiesRuntime(memory: memory, available: available) else { throw problem("stale_program_bytes") } + if let point { + guard pc + point.bytes.count <= memory.count, point.bytes == Array(memory[pc..<(pc + point.bytes.count)]) else { throw problem("stale_program_bytes") } + } + let evaluator = metadata.map { CMOCWatchEvaluator(metadata: $0, context: .init(pc: address, u: UInt16(registers["U"] ?? 0), memory: memory, available: available), frameLocalsAvailable: false) } + var ranges = map.instructions.filter { shared.contains($0.sourcePath) }.map { Int($0.address)..<(Int($0.address) + $0.bytes.count) } + ranges += map.executableCodeRanges(sharedPaths: shared) + ranges += (metadata?.functions ?? []).compactMap { function -> Range? in + guard shared.contains(function.sourcePath), metadata?.entryFunction(named: function.name) != nil else { return nil } + return function.entry.. 0, + start >= 0, start + variable.type.size <= 0xfe00 else { return nil } + return start..<(start + variable.type.size) + } + var permitted = IndexSet() + for range in ranges where available[range].allSatisfy({ $0 != 0 }) { permitted.insert(integersIn: range) } + ranges = Array(permitted.rangeView) + let watches: [[String: Any]] = evaluator == nil ? [] : (model?.watches.map { name in + guard name.range(of: #"^[A-Za-z_][A-Za-z_0-9]*$"#, options: .regularExpression) != nil else { + return ["name": name, "unavailable": "Only locally configured named variables are shared."] + } + let value = evaluator!.evaluate(name) + if let error = value.error { return ["name": name, "unavailable": error] } + var row: [String: Any] = ["name": name, "type": value.typeName, "value": value.value] + if let address = value.address, let variable = metadata?.variables.first(where: { $0.name == name && $0.address == Int(address) }), + ranges.contains(where: { $0.contains(Int(address)) && Int(address) + variable.type.size <= $0.upperBound }) { + row["address"] = Int(address); row["byte_count"] = variable.type.size + if let moduleID = variable.moduleID { row["module_id"] = moduleID } + if let page = pages[Int(address) / 8192] { row["physical_address"] = page * 8192 + Int(address) % 8192 } + } + return row + } ?? []) + let globals = CMOCPublicDebugEvidence.globals(metadata: metadata, sharedPaths: shared, + context: .init(pc: address, u: UInt16(registers["U"] ?? 0), memory: memory, available: available), + permittedRanges: ranges, physicalPages: pages) + let snapshot = UUID().uuidString + let sourceStop: [String: Any]? = point.map { point in + let physical: Int? = point.physicalAddress.map { Int($0) } + ?? pages[pc / 8192].map { $0 * 8192 + pc % 8192 } + return ["path": point.sourcePath, "line": point.sourceLine, "address": pc, + "module_id": point.moduleID as Any? ?? NSNull(), "physical_address": physical as Any? ?? NSNull()] + } + let functionStop: [String: Any]? = function.map { function in + var declaration: [String: Any] = ["path": function.sourcePath] + if let line = function.sourceLine { declaration["line"] = line } + let physical = function.moduleID.flatMap { map.bankedLayout?.module(id: $0)?.physicalAddress(pc) }.map { Int($0) } + ?? pages[pc / 8192].map { $0 * 8192 + pc % 8192 } + return ["name": function.name, "entry_address": function.entry, "address": pc, "at_entry": pc == function.entry, + "instruction_offset": pc - function.entry, "module_id": function.moduleID as Any? ?? NSNull(), + "physical_address": physical as Any? ?? NSNull(), "declaration": declaration] + } + let sharedModules = map.sharedExecutableModuleIDs(paths: shared) + let symbols = map.executableSymbols.filter { $0.address == address && sharedModules.contains($0.moduleID) }.map { symbol in + ["name": symbol.name, "address": Int(symbol.address), "module_id": symbol.moduleID, + "physical_address": symbol.physicalAddress, "object_path": symbol.objectPath, "section": symbol.sectionName] as [String: Any] + } + let symbolCatalog = CMOCSourceMap.boundedJSONCatalog(symbols) + let executableStop: [String: Any]? = executable.map { location in + ["address": pc, "module_id": location.moduleID, "physical_address": location.physicalAddress, + "code_range": ["address": location.codeRange.lowerBound, "count": location.codeRange.count]] + } + let stopKind = function?.entry == pc ? "function_entry" : point != nil ? "c_line" : !symbols.isEmpty ? "symbol_entry" : "assembly_instruction" + let fields: [String: Any] = ["run_id": owned.runID, "snapshot_id": snapshot, "artifact_id": artifact.id.uuidString, + "project_id": owned.projectID, "revision": owned.revision, "status": "paused", "processor": capture["processor"] as Any? ?? NSNull(), + "requested_processor": owned.processor.rawValue, "execution_mode": capture["execution_mode"] as Any? ?? NSNull(), + "md_register": capture["md_register"] as Any? ?? NSNull(), "field_clock": clock, "boot": capture["boot"] as Any? ?? NSNull(), + "registers": registers, "stop_kind": stopKind, "source_stop": sourceStop as Any? ?? NSNull(), + "function_stop": functionStop as Any? ?? NSNull(), "watches": watches, + "globals": globals.items, "globals_total": globals.total, "globals_truncated": globals.truncated, + "mapping_fingerprint": capture["mapping_fingerprint"] as Any? ?? NSNull(), + "program_revision": capture["program_revision"] as Any? ?? NSNull(), + "physical_pages": rawPages, + "symbol_stop": symbols.count == 1 ? symbolCatalog.items.first as Any? ?? NSNull() : NSNull(), + "symbols_at_pc": symbolCatalog.items, "symbols_at_pc_total": symbolCatalog.total, "symbols_at_pc_truncated": symbolCatalog.truncated, + "executable_stop": executableStop as Any? ?? NSNull(), + "source_debugging": ["status": metadata == nil ? "source_only" : "verified", "source_map": "verified", "variables": metadata == nil ? "unavailable" : "verified"], + "watch_status": metadata == nil ? String((variableError ?? "Typed C metadata is unavailable; verified code inspection remains available.").prefix(2000)) : "Verified globals; C frame locals are unavailable for owned entry and instruction stops.", + "memory_ranges": ranges.map { ["address": $0.lowerBound, "count": $0.count] }] + guard let fingerprint = Self.ownedCaptureFingerprint(capture) else { throw problem("invalid_worker_capture") } + let context = callContextApproved ? CMOCOwnedCallContext.capture(map: map, metadata: metadata, pc: address, + s: stackPointer, u: framePointer, memory: memory, available: available, + physicalPages: pages, sharedPaths: shared) : nil + ownedInspection = (snapshot, owned.runID, clock, memory, ranges, fields, fingerprint, context) + return fields + } + + /// Guest identity only: request budgets may change while a nonadvancing read is serviced. + /// Boot/mapping/register/memory changes invalidate a call context even at the same field clock. + static func ownedCaptureFingerprint(_ capture: [String: Any]) -> String? { + let keys = ["boot", "field_clock", "machine_frame", "cycles", "generation", "pc", "registers", "processor", "execution_mode", + "mapping_fingerprint", "program_revision", "physical_pages", "logical_memory", "available"] + guard keys.allSatisfy({ capture[$0] != nil }) else { return nil } + var state = Dictionary(uniqueKeysWithValues: keys.map { ($0, capture[$0]!) }) + state["md_register"] = capture["md_register"] ?? NSNull() + guard JSONSerialization.isValidJSONObject(state), + let bytes = try? JSONSerialization.data(withJSONObject: state, options: [.sortedKeys]) else { return nil } + return CMOCSourceMap.sha256(bytes) + } + + private func read(_ path: String) throws -> String { + if let text = snapshot[path] { return text } + throw problem("access_denied") + } + private func int(_ value: Any?) -> Int? { + guard let n = value as? NSNumber, CFGetTypeID(n) != CFBooleanGetTypeID(), !["f","d"].contains(String(cString: n.objCType)) else { return nil } + return Int(exactly: n) + } + + private func buildRecord(_ id: String) -> [String: Any]? { + guard var record = builds[id] else { return nil } + if record["revision"] as? Int != revision || refreshProblem != nil { record["status"] = "stale" } + return record + } + + private func startBuild(request: String?, revision expected: Int?, model: CMOCDevelopmentModel, action requestedAction: String? = nil, configuration requestedConfiguration: String? = nil) throws -> [String: Any] { + guard refreshProblem == nil, let request, (1...128).contains(request.utf8.count), let expected, let scratch, let service, let scope else { throw problem("invalid_arguments") } + let action: CMOCBuildAction = scope.customMake ? (CMOCBuildAction(rawValue: requestedAction ?? "build") ?? .custom) : (scope.helloDisk ? .disk : .build) + let configuration = scope.customMake ? (requestedConfiguration ?? model.configurationName) : "Debug" + guard [.build, .disk].contains(action), action != .disk || scope.helloDisk || scope.configuration.diskTarget != nil, + !scope.customMake || scope.configuration.configurations.contains(where: { $0.name == configuration }) else { + throw problem("unsupported_build_selection: Choose a declared build/disk action and configuration from get_capabilities.") + } + guard proposalRequests[request] == nil else { throw problem("request_id_conflict") } + if let id = buildRequests[request], let old = buildRecord(id) { + guard old["revision"] as? Int == expected, old["action"] as? String == action.rawValue, old["configuration"] as? String == configuration else { throw problem("request_id_conflict") } + return old + } + guard revision == expected else { throw problem("stale_revision") } + guard !building, !running, !model.building, !model.commanding else { throw problem("busy") } + guard builds.count < 32 else { throw problem("session_build_limit") } + let id = UUID().uuidString, owner = session, inputs = snapshot, make = makeSnapshot + let base: [String: Any] = ["build_id": id, "project_id": model.assistantProjectID.uuidString, "revision": expected, "action": action.rawValue, "configuration": configuration, "recipe_id": approvedRecipeID as Any? ?? NSNull()] + var initial = base; initial["status"] = "building" + latestBuildID = id + builds[id] = initial; buildRequests[request] = id + clearBuildAndLiveControls() + building = true; buildStatus = scope.customMake ? "Building the approved Make project…" : "Building the captured C sources…" + buildTask = Task { + var result = base + do { + let project = try await Task.detached { try scope.snapshotProject(at: scope.customMake ? scratch.appendingPathComponent("Source-" + id).appendingPathComponent("project") : scratch.appendingPathComponent("Source-" + id), inputs: inputs, + buildInputs: make?.files, support: make?.support, permissions: make?.permissions ?? [:], + modificationDates: make?.modificationDates ?? [:], overlayPaths: make?.overlayPaths ?? []) }.value + try Task.checkCancellation() + let artifact = try await service.build(project: project, overlays: inputs, action: action, configuration: configuration) + try Task.checkCancellation() + try await refresh(model) + guard session == owner, revision == expected, refreshProblem == nil else { throw problem("stale_revision") } + readyArtifact = (expected, artifact) + result["status"] = "succeeded"; result["artifact_id"] = artifact.id.uuidString + result["diagnostics"] = [] + if scope.customMake { + result["log"] = String(artifact.buildLog.suffix(32_000)).replacingOccurrences(of: scratch.path, with: "") + result["outputs"] = try await Task.detached { + try [artifact.binaryRelativePath, artifact.diskRelativePath, artifact.debugManifestRelativePath].compactMap { path -> [String: Any]? in + guard let path else { return nil } + let bytes = try Data(contentsOf: artifact.fileURL(path)) + return ["path": path, "bytes": bytes.count, "sha256": CMOCProject.sha256(bytes)] + } + }.value + } else { result["log"] = scope.helloDisk ? "Bundled CMOC compiled and linked HELLO.BIN and built HELLO.DSK." : "Bundled CMOC compiled and linked main.bin." } + let evidence = await Task.detached { + CMOCPublicDebugEvidence.fields(artifact: artifact, sharedPaths: Set(scope.paths)) + }.value + guard session == owner, revision == expected, refreshProblem == nil, readyArtifact?.value.id == artifact.id else { throw problem("stale_revision") } + result["source_debugging"] = evidence + result["playtest_disk_products"] = artifact.playtestDiskProducts.map { + ["media_id": MCPPlaytestMedium.identifier(artifactID: artifact.id.uuidString, key: "disk:" + $0.relativePath), + "path": $0.relativePath, "bytes": $0.byteCount, "sha256": $0.sha256] as [String: Any] + } + if let manifestPath = artifact.debugManifestRelativePath { + result["debug_manifest"] = await Task.detached { () -> [String: Any] in + var fields: [String: Any] = ["path": manifestPath] + if let bytes = try? Data(contentsOf: artifact.fileURL(manifestPath)), bytes.count <= 1024 * 1024 { + fields["sha256"] = CMOCProject.sha256(bytes); fields["bytes"] = bytes.count + if bytes.count <= 128 * 1024, let text = String(data: bytes, encoding: .utf8) { fields["text"] = text } + } + return fields + }.value + } + let report = CMOCBuildReport(artifact: artifact, redacting: [scratch], visiblePaths: Set(scope.paths)) + buildReports[id] = report + for (key, value) in report.fields() { result[key] = value } + } catch { + guard session == owner else { return } + result["status"] = "failed" + let report = CMOCBuildReport(error: error, redacting: [scratch], visiblePaths: Set(scope.paths)) + buildReports[id] = report + for (key, value) in report.fields() { result[key] = value } + } + guard session == owner else { return } + builds[id] = result; building = false; buildStatus = result["log"] as? String ?? "" + } + return initial + } + + private func propose(_ args: [String: Any]) throws -> [String: Any] { + guard let path = args["path"] as? String, let number = int(args["line_number"]), number > 0, + let expected = int(args["revision"]), let replacement = args["replacement"] as? String, + let request = args["request_id"] as? String, (1...128).contains(request.utf8.count), + (1...512).contains(replacement.utf8.count), replacement.utf8.allSatisfy({ $0 == 9 || (32...126).contains($0) }) + else { throw problem("invalid_arguments") } + guard buildRequests[request] == nil else { throw problem("request_id_conflict") } + if let id = proposalRequests[request], let old = proposals[id] { + guard old.edits == nil, old.revision == expected, old.path == path, old.line == number, old.after == replacement else { throw problem("request_id_conflict") } + return old.result + } + guard expected == revision else { throw problem("stale_revision") } + guard !running, proposal?.status != "pending", proposals.count < 64 else { throw problem("review_pending_or_limit") } + guard path.hasSuffix(".c") || path.hasSuffix(".h"), let text = snapshot[path] else { throw problem("access_denied") } + let reported = builds.values.contains { build in + guard build["status"] as? String == "failed", build["revision"] as? Int == expected, + let rows = build["diagnostics"] as? [[String: Any]] else { return false } + return rows.contains { $0["path"] as? String == path && $0["line"] as? Int == number } + } + guard reported else { throw problem("missing_compiler_diagnostic") } + guard let range = line(number, in: text) else { throw problem("line_not_found") } + let before = (text as NSString).substring(with: range) + guard before != replacement else { throw problem("unchanged_line") } + guard let scope else { throw problem("access_denied") } + try scope.validate((text as NSString).replacingCharacters(in: range, with: replacement), path: path, trusted: templateDirectives[path]) + let p = Proposal(request: request, path: path, line: number, before: before, after: replacement, revision: expected) + proposalRequests[request] = p.id; update(p) + if let model { showReview(model) } + return p.result + } + private func proposeEdits(_ args: [String: Any], scope: MCPCMOCProject) throws -> [String: Any] { + guard let request = args["request_id"] as? String, (1...128).contains(request.utf8.count), + let expected = int(args["revision"]), let rows = args["edits"] as? [[String: Any]], (1...8).contains(rows.count) else { + throw problem("invalid_arguments") + } + var replacements: [String: String] = [:] + var size = 0 + for row in rows { + guard row.count == 2, let path = row["path"] as? String, let text = row["source"] as? String, + replacements[path] == nil, text.utf8.allSatisfy({ $0 == 9 || $0 == 10 || $0 == 13 || (32...126).contains($0) }) + else { throw problem("invalid_arguments") } + size += text.utf8.count + guard size <= 16384 else { throw problem("patch_too_large") } + replacements[path] = text + } + guard buildRequests[request] == nil else { throw problem("request_id_conflict") } + if let id = proposalRequests[request], let old = proposals[id] { + guard let edits = old.edits, old.revision == expected, + Dictionary(uniqueKeysWithValues: edits.map { ($0.path, $0.after) }) == replacements else { throw problem("request_id_conflict") } + return old.result + } + guard expected == revision else { throw problem("stale_revision") } + guard !running, proposal?.status != "pending", proposals.count < 64 else { throw problem("review_pending_or_limit") } + let edits = try replacements.keys.sorted().map { path -> MCPCMOCEdit in + guard path.hasSuffix(".c") || path.hasSuffix(".h"), let before = snapshot[path], let after = replacements[path] else { throw problem("access_denied") } + guard !before.utf8.elementsEqual(after.utf8) else { throw problem("unchanged_file") } + try scope.validate(after, path: path, trusted: templateDirectives[path]) + return MCPCMOCEdit(path: path, before: before, after: after) + } + let p = Proposal(request: request, path: "", line: 0, before: "", after: "", revision: expected, edits: edits) + proposalRequests[request] = p.id; update(p) + if let model { showReview(model) } + return p.result + } + + private func update(_ p: Proposal) { proposal = p; proposals[p.id] = p } + private func line(_ number: Int, in source: String) -> NSRange? { + guard number > 0 else { return nil } + let value = source as NSString + var at = 0, row = 1 + while at < value.length { + var start = 0, end = 0, contents = 0 + value.getLineStart(&start, end: &end, contentsEnd: &contents, for: NSRange(location: at, length: 0)) + if row == number { return NSRange(location: start, length: contents - start) } + at = end; row += 1 + } + return nil + } + + fileprivate func decide(_ id: String, apply: Bool) async { + guard let model, var p = proposal, p.id == id, p.status == "pending" else { return } + if !apply { p.status = "cancelled"; update(p); return } + do { + try await refresh(model) + guard refreshProblem == nil, proposal?.id == id, proposal?.status == "pending", p.revision == revision else { return } + guard !model.building, !model.commanding, !running else { throw problem("The workspace is busy.") } + if let edits = p.edits { + try model.applyAssistantEdits(edits, disk: diskSnapshot, projectID: model.assistantProjectID, epoch: workspaceEpoch) + for edit in edits { snapshot[edit.path] = edit.after } + revision += 1; workspaceEpoch = model.assistantEditEpoch; recordReviewedMakeEdits(model); clearBuildAndLiveControls() + p.status = "applied"; p.applied = revision; update(p) + buildStatus = "Changes applied to the open project drafts. Rebuild to check them." + return + } + model.openFile(p.path, line: p.line) + // A tab switch installs that document's NSTextView on SwiftUI's next update. + for _ in 0..<20 where model.assistantEditorFile != p.path { try await Task.sleep(for: .milliseconds(20)) } + try await refresh(model) + guard active, refreshProblem == nil, projectID == model.assistantProjectID, proposal?.id == id, proposal?.status == "pending", + revision == p.revision, workspaceEpoch == model.assistantEditEpoch, + model.selectedFile == p.path, let editor = model.assistantEditor, editor.window != nil, + editor.isEditable, !editor.hasMarkedText(), editor.undoManager != nil, + editor.string == snapshot[p.path], let range = line(p.line, in: editor.string), + (editor.string as NSString).substring(with: range) == p.before else { throw problem("stale_revision") } + editor.breakUndoCoalescing() + editor.insertText(p.after, replacementRange: range) + editor.breakUndoCoalescing() + guard model.source == (snapshot[p.path]! as NSString).replacingCharacters(in: range, with: p.after) else { + throw problem("The editor could not apply this repair.") + } + editor.undoManager?.setActionName("Assistant C Repair") + revision += 1; workspaceEpoch = model.assistantEditEpoch; snapshot[p.path] = model.source; recordReviewedMakeEdits(model); clearBuildAndLiveControls() + p.status = "applied"; p.applied = revision; update(p) + buildStatus = "Rebuild the repaired revision to check the compiler result." + } catch { status = error.localizedDescription } + } + fileprivate func undo(_ id: String) async { + guard let model, var p = proposal, p.id == id, p.status == "applied", !running, !building else { return } + do { + try await refresh(model) + guard proposal?.id == id, proposal?.status == "applied", p.applied == revision, + !running, !building, !model.commanding, !model.building else { return } + if let edits = p.edits { + let reverse = edits.map { MCPCMOCEdit(path: $0.path, before: $0.after, after: $0.before) } + try model.applyAssistantEdits(reverse, disk: diskSnapshot, projectID: model.assistantProjectID, epoch: workspaceEpoch, undoing: true) + for edit in reverse { snapshot[edit.path] = edit.after } + revision += 1; workspaceEpoch = model.assistantEditEpoch; recordReviewedMakeEdits(model); clearBuildAndLiveControls() + p.status = "undone"; update(p); buildStatus = "All reviewed file changes were undone." + return + } + guard model.assistantEditorFile == p.path, model.selectedFile == p.path, + let manager = model.assistantEditor?.undoManager, manager.undoActionName == "Assistant C Repair", manager.canUndo, + let changed = line(p.line, in: model.source), (model.source as NSString).substring(with: changed) == p.after else { return } + let restored = (model.source as NSString).replacingCharacters(in: changed, with: p.before) + manager.undo() + let restoredEpoch = model.assistantEditEpoch + try await refresh(model) + guard proposal?.id == id, proposal?.status == "applied", workspaceEpoch == restoredEpoch, + revision == (p.applied ?? -1) + 1, snapshot[p.path]?.utf8.elementsEqual(restored.utf8) == true else { return } + p.status = "undone"; update(p); buildStatus = "Edit undone." + } catch { status = error.localizedDescription } + } + fileprivate func rebuild(_ proposalID: String) async { + guard let model, let selected = proposal, selected.id == proposalID, let expected = selected.applied else { return } + do { + try await refresh(model) + guard proposal?.id == proposalID, proposal?.status == "applied", revision == expected else { return } + _ = try startBuild(request: UUID().uuidString, revision: expected, model: model) + } catch { status = error.localizedDescription } + } + private func runAlert() -> NSAlert { + let alert = NSAlert() + alert.messageText = "Run this C build in the CoCo?" + alert.informativeText = "Inspect at main pauses at the first verified C statement. Play in CoCo continues from that statement and lets the connected assistant read the game screen and send keys during this run." + let cancel = alert.addButton(withTitle: "Cancel") + cancel.keyEquivalent = "\u{1b}" + alert.addButton(withTitle: "Play in CoCo") + alert.addButton(withTitle: "Inspect at main") + return alert + } + + fileprivate func run(_ selected: RunSelection?, fixturePlay: Bool = false) async { + guard let selected, !running, !building, let model, let scope, + proposal?.id == selected.proposalID, readyArtifact?.value.id == selected.artifactID else { return } + let proposalID = selected.proposalID + do { + try await refresh(model) + guard refreshProblem == nil, !running, !building, proposal?.id == proposalID, readyToRun, let artifact = readyArtifact, + artifact.value.id == selected.artifactID else { + throw problem("Rebuild this revision successfully before running.") + } + let owner = session, epoch = workspaceEpoch, expected = revision + guard !model.commanding, !model.building else { throw problem("The C workbench is busy.") } + var play = regression && fixturePlay && !scope.helloDisk + if !scope.helloDisk && !regression { + let readiness = await model.machine.mcpReadinessSnapshot() + guard session == owner, self.model === model, workspaceEpoch == model.assistantEditEpoch, + readyArtifact?.value.id == artifact.value.id else { throw problem("stale_revision") } + if readiness.assistantEmptyBASIC?.boolValue == false { throw problem(MCPMachineStatus.occupiedBASICGuidance) } + let alert = runAlert() + switch alert.runModal() { + case .alertSecondButtonReturn: play = true + case .alertThirdButtonReturn: play = false + default: return + } + try await refresh(model) + guard session == owner, revision == expected, refreshProblem == nil, readyArtifact?.value.id == artifact.value.id, + proposal?.id == proposalID, !building, !running, !model.commanding, !model.building else { throw problem("stale_revision") } + } + let id = UUID().uuidString + liveIO?.invalidate(); liveIO = nil + runID = id; inspection = nil + runRevision = revision; running = true; runReceipt = nil; runStatus = "Running the reviewed binary in the CoCo…" + let current: @MainActor () -> Bool = { [weak self, weak model] in + guard let self, let model else { return false } + return self.active && self.refreshProblem == nil && self.session == owner && self.projectID == model.assistantProjectID && + self.revision == expected && model.assistantEditEpoch == epoch && self.proposal?.id == proposalID + } + runTask = Task { + do { + let saveStop: MCPCMOCGuest.SaveStop = { capture, info, point in + guard current(), self.runID == id, let project = self.projectID else { throw CancellationError() } + self.inspection = try MCPCMOCGuest.inspection(runID: id, revision: expected, projectID: project.uuidString, + build: artifact.value, capture: capture, info: info, point: point, watches: model.watches, sharedPaths: Set(scope.paths)) + } + let receipt: [String: Any] + if scope.helloDisk { + receipt = try await MCPCMOCGuest.run(model: model, build: artifact.value, isCurrent: current, saveStop: saveStop) + } else { + receipt = try await MCPCMOCGuest.runOrdinary(model: model, build: artifact.value, play: play, isCurrent: current, saveStop: saveStop) + } + try await refresh(model) + guard current() else { throw problem("stale_revision") } + runReceipt = receipt + if play, let stop = inspection { + liveIO = MCPCompiledRunIO(machine: model.machine, runID: id, expected: stop.machine, assembly: false) + runStatus = "Continued from main. Your assistant can read the CoCo screen and send game keys through MCP. To play yourself, choose Input → Focus CoCo Display." + } else { + runStatus = scope.helloDisk ? "Finished guest verification." : "Paused at a C source statement." + } + if let panel { + let visible = (panel.screen ?? NSScreen.main)?.visibleFrame.height ?? 800 + let height = min(max(480, visible - 100), 760) + panel.setContentSize(NSSize(width: max(panel.frame.width, 645), height: height)) + } + } catch { if session == owner { runStatus = error.localizedDescription } } + if session == owner { running = false } + } + } catch { status = error.localizedDescription } + } + + func showAccess(_ model: CMOCDevelopmentModel) { + consentPanel?.close() + let w = window("C Project Assistant Access", width: 560, height: 380, + view: MCPCMOCConsent(host: self, model: model)) + consentPanel = w; consentModel = model; w.makeKeyAndOrderFront(nil) + } + fileprivate func exportGrant(_ model: CMOCDevelopmentModel) { + guard let owner = consentPanel, consentModel === model, owner.isVisible, + !owner.isMiniaturized, owner.attachedSheet == nil else { return } + let project = model.assistantProjectID, generation = session + let approvedMake = allowProjectMakefile, approvedPlaytests = allowPlaytests + let picker = NSSavePanel(); picker.title = "Share C Project for Reviewed Changes" + picker.message = "Choose a new private connection file for the local assistant." + picker.nameFieldStringValue = "VCC Plus OSS C Connection.json" + picker.beginSheetModal(for: owner) { [weak self, weak owner, weak model] response in + Task { @MainActor [weak self, weak owner, weak model] in + guard let self, let owner, let model else { return } + @MainActor func currentPresentation() -> Bool { + self.consentPanel === owner && self.consentModel === model && owner.isVisible && + !owner.isMiniaturized && model.assistantProjectID == project && + self.allowProjectMakefile == approvedMake && self.allowPlaytests == approvedPlaytests + } + guard currentPresentation(), self.session == generation else { return } + defer { if currentPresentation() { owner.makeKeyAndOrderFront(nil) } } + guard response == .OK, let url = picker.url else { return } + do { try await self.grant(model, at: url, presentationIsCurrent: currentPresentation) } + catch { if currentPresentation() { self.status = error.localizedDescription } } + } + } + } + private func window(_ title: String, width: CGFloat, height: CGFloat, scrolls: Bool = true, view: V) -> NSPanel { + let w = NSPanel(contentRect: NSRect(x: 0, y: 0, width: width, height: height), + styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false) + w.title = title; w.isReleasedWhenClosed = false; w.contentMinSize = NSSize(width: 405, height: 220) + let content = NSHostingView(rootView: Group { if scrolls { ScrollView { view } } else { view } }) + content.sizingOptions = []; w.contentView = content; w.center() + return w + } + fileprivate func showReview(_ model: CMOCDevelopmentModel) { + guard self.model === model else { return } + if panel == nil { + let title = "Review C Changes" + (fixtureLabel.map { " — " + $0 } ?? "") + panel = window(title, width: 645, height: 435, scrolls: false, view: MCPCMOCReview(host: self)) + #if DEBUG + if let fixtureLabel, let w = panel, let screen = w.screen?.visibleFrame { + let offset = min(screen.width / 4, max(0, (screen.width - w.frame.width) / 2)) + w.setFrameOrigin(NSPoint(x: screen.midX - w.frame.width / 2 + (fixtureLabel.lowercased().contains("ollama") ? offset : -offset), y: w.frame.minY)) + } + #endif + } + if !regression { panel?.makeKeyAndOrderFront(nil); NSApp.requestUserAttention(.informationalRequest) } + #if DEBUG + if let fixtureDirectory, let panel { try? Data(String(panel.windowNumber).utf8).write(to: fixtureDirectory.appendingPathComponent("review-window-id")) } + #endif + } + + #if DEBUG + func fixture(_ model: CMOCDevelopmentModel, directory: URL, roms: URL) async throws { + var info = stat() + guard lstat(directory.path, &info) == 0, info.st_mode & S_IFMT == S_IFDIR, info.st_uid == geteuid(), info.st_mode & 0o077 == 0 else { throw POSIXError(.EACCES) } + fixtureDirectory = directory + let args = CommandLine.arguments + regression = args.contains("--mcp-c-regression") + if let i = args.firstIndex(of: "--mcp-c-label"), args.indices.contains(i + 1) { fixtureLabel = args[i + 1] } + try await MCPBASICRun.bootFixture(model.machine, romDirectory: roms) + if regression, let i = args.firstIndex(of: "--mcp-c-make-project"), args.indices.contains(i + 1) { + allowProjectMakefile = true + try model.adopt(CMOCProject.open(at: URL(fileURLWithPath: args[i + 1]))) + } else if regression && args.contains("--mcp-c-ordinary") { + let project = try CMOCProject.create(at: directory.appendingPathComponent("C Project")) + try Data("#include \n#include \"value.h\"\nint main(void) { printf(\"VALUE %d\\n\", value()); return 0; }\n".utf8).write(to: project.sourceURL) + try Data("int value(void);\n".utf8).write(to: project.directory.appendingPathComponent("value.h")) + try Data("#include \"value.h\"\nint value(void) { return 6; }\n".utf8).write(to: project.directory.appendingPathComponent("value.c")) + try Data("$(error The personal Makefile must never run under the assistant grant)\n".utf8).write(to: project.makefileURL) + try model.adopt(project) + } else { + let project = try CMOCProject.createHelloDisk(at: directory.appendingPathComponent("Hello Disk")) + try model.adopt(project) + let good = "printf(\"GENERATED WORD COUNT: %u\\n\", generatedWordCount);" + guard model.source.contains(good) else { throw problem("The installed example did not match the diagnostic fixture.") } + model.source = model.source.replacingOccurrences(of: good, with: good.replacingOccurrences(of: "generatedWordCount", with: "generatedWordCounts")) + // Persist the authored broken training input, so a cancelled review can be closed normally. + guard model.save() else { throw problem("Could not create the disposable fixture source.") } + } + let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1100, height: 755), styleMask: [.titled, .resizable, .miniaturizable], backing: .buffered, defer: false) + w.title = "C Development — " + (fixtureLabel ?? "Compiler Repair") + let view = NSHostingView(rootView: CMOCDevelopmentView(model: model)) + view.sizingOptions = []; w.contentView = view; w.center(); fixtureWindow = w + if regression { w.orderBack(nil) } else { w.orderFront(nil) } + view.layoutSubtreeIfNeeded() + let pairing = directory.appendingPathComponent("grant.json") + try await grant(model, at: pairing) + guard regression else { return } + try Data().write(to: directory.appendingPathComponent("regression-fixture"), options: .withoutOverwriting) + Task { @MainActor in + func take(_ name: String) -> Bool { unlink(directory.appendingPathComponent(name).path) == 0 } + func mark(_ name: String) { try? Data().write(to: directory.appendingPathComponent(name)) } + while true { + try? await Task.sleep(for: .milliseconds(150)) + if take("show-access") { showAccess(model); mark("access-shown") } + if take("show-review"), let panel { + panel.orderBack(nil) + try? await Task.sleep(for: .milliseconds(250)) + mark("review-shown") + } + if take("apply"), let p = proposal { await decide(p.id, apply: true); mark("applied") } + if take("cancel"), let p = proposal { await decide(p.id, apply: false); mark("cancelled") } + if take("undo"), let p = proposal { await undo(p.id); mark("undone") } + if take("edit") { model.source += "\n/* Independent native edit */\n"; mark("edited") } + if take("run") { await run(runSelection); mark("run-started") } + if take("play") { await run(runSelection, fixturePlay: true); mark("play-started") } + if take("show-run-options"), runSelection != nil, !usesDiskRecipe { + let alert = runAlert() + alert.layout() + fixtureRunAlert = alert + let w = alert.window + w.center(); w.alphaValue = 1; w.orderFront(nil) + try? await Task.sleep(for: .milliseconds(350)) + w.contentView?.layoutSubtreeIfNeeded() + w.displayIfNeeded() + if let content = w.contentView, let bitmap = content.bitmapImageRepForCachingDisplay(in: content.bounds) { + content.cacheDisplay(in: content.bounds, to: bitmap) + try? bitmap.representation(using: .png, properties: [:])?.write(to: directory.appendingPathComponent("run-options-content.png")) + } + try? Data(String(w.windowNumber).utf8).write(to: directory.appendingPathComponent("run-options-window-id")) + mark("run-options-shown") + } + if take("hide-run-options") { fixtureRunAlert?.window.orderOut(nil); fixtureRunAlert = nil; mark("run-options-hidden") } + if take("replay-stale-review"), let selected = runSelection, let prior = proposals.keys.first(where: { $0 != selected.proposalID }) { + await undo(prior) + await rebuild(prior) + await run(RunSelection(artifactID: UUID(), proposalID: selected.proposalID)) + mark("stale-review-replayed") + } + if take("revoke") { await revoke().value; mark("revoked") } + if take("reconnect") { try? await grant(model, at: pairing); if active { mark("reconnected") } } + if take("capture-result"), let panel, runReceipt != nil { + panel.orderFront(nil); try? await Task.sleep(for: .milliseconds(300)) + let tool = Process(); tool.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture") + tool.arguments = ["-x", "-o", "-l", String(panel.windowNumber), directory.appendingPathComponent("verified.png").path] + tool.terminationHandler = { _ in Task { @MainActor in panel.orderOut(nil) } } + do { try tool.run() } catch { panel.orderOut(nil) } + } + if take("quit") { + await revoke().value + _ = model.save() + NSApp.perform(#selector(NSApplication.terminate(_:)), with: nil, afterDelay: 0) + return + } + } + } + } + #endif +} + +private struct MCPCMOCConsent: View { + @ObservedObject var host: MCPCMOC + let model: CMOCDevelopmentModel + var body: some View { + let selectedRun = host.runSelection + VStack(alignment: .leading, spacing: 12) { + Text(model.project?.directory.lastPathComponent ?? "C Development").font(.headline) + Text("Share this project’s C sources and headers, or the installed Hello Disk example with its word list. The assistant can read machine and build status, compile shared drafts, and propose changes. Review and apply edits here. Start guest execution from VCC Plus.") + if !host.active { + Toggle("Allow Disposable Playtests", isOn: $host.allowPlaytests) + if host.allowPlaytests { + Text("Allow the assistant to launch this project's built disk or resume a retained test disk in a separate 512 KB 6809 or 6309 CoCo, hold key combinations and standard joystick axes and buttons, read input diagnostics, capture its screen, declared graphics buffers and guest audio, inspect verified program stops and shared data, read up to 64 bytes at the paused test guest’s stack pointer with caller and argument interpretations only when verified, and restart its own writable test disks. Reviewed additional disk products can be inserted or ejected in the paused, idle test drive without a reset or advancing time; each private writable copy is retained. The guest controls 6309 execution mode. Audio capture advances the test guest and uses no microphone. Retained originals and your current CoCo and media are preserved. Access ends when this connection or build changes.").font(.callout) + } + if host.allowPlaytests, let media = model.project?.configuration.playtestDisks, !media.isEmpty { + Text("Additional playtest disks: " + media.joined(separator: ", ")).font(.callout).textSelection(.enabled) + } + Toggle("Use Project Makefile", isOn: $host.allowProjectMakefile) + if host.allowProjectMakefile { + Text("Allow builds using this project's existing Makefile and declared configurations. Make recipes and compiler inputs can execute local commands, just as Build does. Recipe or support-file changes require native review through project refresh.").font(.callout) + if let paths = model.project?.configuration.buildSupportDirectories, !paths.isEmpty { + Text("Build support: " + paths.joined(separator: ", ")).font(.callout).textSelection(.enabled) + } + } + } + if let project = model.project, let shared = try? MCPCMOCProject(project: project, files: model.files.map(\.relativePath), customMake: host.allowProjectMakefile) { + DisclosureGroup("Files shared (\(shared.paths.count))") { + Text(shared.paths.joined(separator: "\n")).font(.system(.caption, design: .monospaced)).textSelection(.enabled) + } + } + Text("The assistant's model provider may receive the shared files and diagnostics.").font(.callout) + if host.active { + if host.playtestsApproved { Text("Disposable playtests and bounded read-only call context are enabled for this connection. Each test uses a separate CoCo and its own disk copies. Paused-drive media exchange is available for this connection's reviewed disk products.").font(.callout) } + if let url = host.grantURL { + MCPChatGPTSetup(grantURL: url, firstPrompt: "Identify my shared VCC Plus C project and read its entry source. Describe its target and what the CoCo program does.") + } + HStack { + Button("Revoke Access") { host.revoke() } + if host.proposal != nil { Button("Review Changes…") { host.showReview(model) } } + if !host.usesDiskRecipe { + Button("Run C Build…") { Task { await host.run(selectedRun) } }.disabled(selectedRun == nil || host.running || host.building) + } + } + } else { Button("Save Private Connection…") { host.exportGrant(model) } } + if !host.runStatus.isEmpty { Text(host.runStatus).font(.callout).textSelection(.enabled) } + Text(host.status).font(.callout).textSelection(.enabled) + }.padding(18).frame(maxWidth: .infinity, alignment: .leading) + } +} + +private struct MCPCMOCReview: View { + @ObservedObject var host: MCPCMOC + @State private var selectedPath: String? + var body: some View { + let selectedRun = host.runSelection + if let p = host.proposal { + GeometryReader { geometry in + ScrollView { + VStack(alignment: .leading, spacing: 12) { + Label(p.edits.map { "Review \($0.count) C project \($0.count == 1 ? "file" : "files")" } ?? "\(p.path) · line \(p.line)", systemImage: "curlybraces").font(.headline) + Text(p.applied.map { "Reviewed revision \(p.revision) → applied revision \($0)" } ?? "Draft revision \(p.revision)").foregroundStyle(.secondary) + if let edits = p.edits, let file = edits.first(where: { $0.path == selectedPath }) ?? edits.first { + Picker("File", selection: Binding(get: { file.path }, set: { selectedPath = $0 })) { + ForEach(edits, id: \.path) { Text($0.path).tag($0.path) } + }.accessibilityLabel("Changed project file") + ScrollView { + VStack(alignment: .leading, spacing: 8) { + code("Before", file.before, .red) + code(p.applied == nil ? "Proposed" : "Applied", file.after, .green) + } + }.frame(height: max(90, geometry.size.height - (p.status == "pending" ? 185 : 280))) + } else { + code(p.applied == nil ? "Current" : "Before", p.before, .red) + code(p.applied == nil ? "Proposed" : "Applied", p.after, .green) + } + if p.status == "pending" { + HStack { + Button(p.edits == nil ? "Cancel Repair" : "Cancel Changes") { Task { await host.decide(p.id, apply: false) } } + Button(p.edits == nil ? "Apply Repair" : "Apply All Changes") { Task { await host.decide(p.id, apply: true) } }.buttonStyle(.borderedProminent) + } + } else if p.status == "applied" { + HStack { + Button(p.edits == nil ? "Undo Repair" : "Undo All Changes") { Task { await host.undo(p.id) } } + Button("Rebuild") { Task { await host.rebuild(p.id) } } + Button(host.usesDiskRecipe ? "Run and Verify" : "Run C Build…") { Task { await host.run(selectedRun) } } + .disabled(selectedRun == nil) + .help("Run the current compiled program in the CoCo.") + }.disabled(host.building || host.running) + if host.usesDiskRecipe { Text("Run temporarily mounts the built disk in an empty FD0 and starts the compiled program at a blank Disk BASIC prompt.").font(.caption) } + } else { Text(p.status == "stale" ? "The project changed. Read the new revision before proposing a repair." : p.status.capitalized) } + if !host.buildStatus.isEmpty { Text(host.buildStatus).font(.callout).textSelection(.enabled) } + if !host.runStatus.isEmpty { Text(host.runStatus).font(.headline) } + if let receipt = host.runReceipt, let point = receipt["source_stop"] as? [String: Any], + let path = point["path"] as? String, let line = point["line"] as? Int, let address = point["address"] as? Int { + Text(String(format: "Source stop · %@:%d at $%04X", path, line, address)) + if let screen = receipt["screen"] as? String { + Text(screen.trimmingCharacters(in: .whitespacesAndNewlines)) + .font(.system(.caption, design: .monospaced)).textSelection(.enabled) + } + } + if !host.status.isEmpty { Text(host.status).font(.caption).foregroundStyle(.secondary).textSelection(.enabled) } + }.padding(18).frame(maxWidth: .infinity, alignment: .leading) + } + } + } + } + private func code(_ label: String, _ text: String, _ color: Color) -> some View { + VStack(alignment: .leading, spacing: 4) { + Text(label).font(.caption.weight(.semibold)); Text(text).font(.system(.body, design: .monospaced)).textSelection(.enabled) + }.padding(10).frame(maxWidth: .infinity, alignment: .leading).background(color.opacity(0.1), in: RoundedRectangle(cornerRadius: 5)) + } +} diff --git a/platforms/macos/App/MCPCMOCGuest.swift b/platforms/macos/App/MCPCMOCGuest.swift new file mode 100644 index 0000000..f73dc03 --- /dev/null +++ b/platforms/macos/App/MCPCMOCGuest.swift @@ -0,0 +1,167 @@ +import Foundation + +@MainActor +enum MCPCMOCGuest { + struct DebugInfo { + let map: CMOCProjectSourceMap + let variables: CMOCVariableDebug? + + init(_ build: CMOCBuildArtifact) throws { + map = try CMOCProjectSourceMap.parse(artifact: build) + guard map.matches(sources: build.sources, binary: build.binaryData) else { + throw ProfileFailure.message("The C source and binary differ from their source map.") + } + variables = try? CMOCVariableDebug.parse(artifact: build, verifiedMap: map) + } + } + + typealias SaveStop = @MainActor (VCCDebuggerSnapshot, DebugInfo, CMOCProjectSourceMap.Instruction) throws -> Void + + static func run(model: CMOCDevelopmentModel, build: CMOCBuildArtifact, + isCurrent: @escaping @MainActor () -> Bool, saveStop: SaveStop) async throws -> [String: Any] { + let (info, point, disk, expectedOutput) = try await Task.detached { + let info = try DebugInfo(build) + guard let disk = build.diskURL, + let entry = build.sources["main.c"].flatMap({ String(data: $0, encoding: .utf8) }), + let line = entry.components(separatedBy: "\n").firstIndex(where: { $0.contains("printf(\"DISK RESULT:") }), + let point = info.map.instructions.first(where: { $0.sourcePath == "main.c" && $0.sourceLine == line + 1 }) else { + throw ProfileFailure.message("The Hello Disk source stop could not be matched to this binary.") + } + let wordPath = "assets/words.txt" + let wordData = try Data(contentsOf: build.fileURL(wordPath)) + guard CMOCProject.sha256(wordData) == build.fileHashes[wordPath], + let words = String(data: wordData, encoding: .utf8)?.split(whereSeparator: \.isNewline) else { + throw ProfileFailure.message("The word list changed after this disk was built.") + } + let lines = ["HELLO FROM A MULTI-FILE PROJECT", "WORDS READ FROM THE FLOPPY:"] + words.map(String.init) + + ["", "DISK RESULT: 0", "GENERATED WORD COUNT: \(words.count)"] + return (info, point, try Data(contentsOf: disk), lines.joined(separator: "\n")) + }.value + let machine = model.machine + let initial = await machine.mcpMachineSnapshot() + let name = "Hello Disk " + UUID().uuidString + ".dsk" + let deadline = ContinuousClock.now.advanced(by: .seconds(25)) + do { + let launched = try await launchAtStop(model, build: build, info: info, point: point, disk: disk, name: name, + initial: initial, deadline: deadline, isCurrent: isCurrent, saveStop: saveStop) + let continued = await machine.continueReviewedC(launched, name: name, stop: point.address, bytes: Data(point.bytes)) + if let error = continued.errorMessage { throw ProfileFailure.message(error) } + while ContinuousClock.now < deadline { + let (screen, now) = await machine.reviewedCOutput() + guard isCurrent(), now.generation == launched.generation, now.debuggerProgramRevision == launched.debuggerProgramRevision, + now.disks.first?.name == name else { throw CancellationError() } + if let screen, let output = screen.range(of: expectedOutput + "\n", options: .backwards), + now.disks[0].readEvents > initial.disks[0].readEvents { + let receipt: [String: Any] = ["screen": String(screen[output]).trimmingCharacters(in: .newlines), "cpu": now.use6309 ? "6309" : "6809", + "source_stop": ["path": point.sourcePath, "line": point.sourceLine, "address": Int(point.address), + "bytes": point.bytes.map { Int($0) }], + "disk_read_events": now.disks[0].readEvents - initial.disks[0].readEvents, + "disk_write_protected": now.disks[0].writeProtected, "artifact_id": build.id.uuidString] + await machine.ejectReviewedCDisk(name) + return receipt + } + try await Task.sleep(for: .milliseconds(50)) + } + throw ProfileFailure.message("Hello Disk did not display its successful disk result and generated word count.") + } catch { + await machine.ejectReviewedCDisk(name) + throw error + } + } + + static func runOrdinary(model: CMOCDevelopmentModel, build: CMOCBuildArtifact, play: Bool = false, + isCurrent: @escaping @MainActor () -> Bool, saveStop: SaveStop) async throws -> [String: Any] { + let (info, point) = try await Task.detached { + let info = try DebugInfo(build) + guard info.map.bankedLayout == nil else { + throw ProfileFailure.message("This packed build requires its declared disk launch. Use the C workspace's Disk & Run, or grant disposable playtests for assistant execution.") + } + guard let main = info.variables?.functions.first(where: { $0.name == "main" && $0.sourcePath == build.entrySourcePath }), + let point = info.map.instructions.first(where: { + $0.sourcePath == main.sourcePath && main.body <= Int($0.address) && Int($0.address) < main.end + }) else { throw ProfileFailure.message("Build the Debug configuration with a mapped main function to run this shared project.") } + return (info, point) + }.value + let initial = await model.machine.mcpMachineSnapshot() + let state = try await launchAtStop(model, build: build, info: info, point: point, disk: nil, name: "", + initial: initial, deadline: .now.advanced(by: .seconds(25)), + isCurrent: isCurrent, saveStop: saveStop) + if play { + guard isCurrent() else { throw CancellationError() } + let continued = await model.machine.continueReviewedC(state, name: "", stop: point.address, bytes: Data(point.bytes)) + if let error = continued.errorMessage { throw ProfileFailure.message(error) } + } + return ["artifact_id": build.id.uuidString, "status": play ? "continued_from_main" : "paused", "cpu": state.use6309 ? "6309" : "6809", + "source_stop": ["path": point.sourcePath, "line": point.sourceLine, "address": Int(point.address), + "bytes": point.bytes.map(Int.init)] as [String: Any]] + } + + private static func launchAtStop(_ model: CMOCDevelopmentModel, build: CMOCBuildArtifact, info: DebugInfo, + point: CMOCProjectSourceMap.Instruction, disk: Data?, name: String, + initial: VCCMachineSnapshot, deadline: ContinuousClock.Instant, + isCurrent: @escaping @MainActor () -> Bool, saveStop: SaveStop) async throws -> VCCMachineSnapshot { + let machine = model.machine + var launched: VCCMachineSnapshot + repeat { + guard isCurrent() else { throw CancellationError() } + launched = await machine.startReviewedC(build.binaryData, disk: disk, name: name, stop: point.address, expected: initial) + if launched.errorMessage == nil { break } + if launched.errorMessage == "occupied_basic_program" { throw ProfileFailure.message(MCPMachineStatus.occupiedBASICGuidance) } + guard launched.errorMessage == "Waiting for an empty Disk BASIC prompt.", ContinuousClock.now < deadline else { + throw ProfileFailure.message(launched.errorMessage ?? "The CoCo could not start the reviewed binary.") + } + try await Task.sleep(for: .milliseconds(60)) + } while true + var stopped = launched + while stopped.state != .paused && ContinuousClock.now < deadline { + guard isCurrent(), stopped.generation == launched.generation, + stopped.debuggerProgramRevision == launched.debuggerProgramRevision else { throw CancellationError() } + try await Task.sleep(for: .milliseconds(50)) + stopped = await machine.mcpMachineSnapshot() + } + let capture = try await MCPDebuggerInspection.capture(machine) + guard isCurrent(), MCPDebuggerInspection.sameProgram(capture.machine, launched), + capture.machine.state == .paused, capture.machine.programCounter == point.address, + capture.machine.debuggerDevelopmentAttached, disk == nil || capture.machine.disks.first?.name == name, + capture.instructions.first?.bytes == Data(point.bytes) else { + throw ProfileFailure.message("The reviewed binary did not reach its verified C source stop.") + } + try saveStop(capture, info, point) + return capture.machine + } + + static func inspection(runID: String, revision: Int, projectID: String, build: CMOCBuildArtifact, + capture: VCCDebuggerSnapshot, info: DebugInfo, point: CMOCProjectSourceMap.Instruction, + watches: [String], sharedPaths: Set) throws -> MCPDebuggerInspection { + guard sharedPaths.contains(point.sourcePath) else { throw ProfileFailure.message("path_not_shared") } + let memory = capture.logicalMemory, available = capture.logicalMemoryAvailable + let ranges: [Range] = try info.map.instructions.compactMap { instruction in + let range = Int(instruction.address)..<(Int(instruction.address) + instruction.bytes.count) + guard range.upperBound <= min(memory.count, available.count), available[range].allSatisfy({ $0 != 0 }), + memory[range].elementsEqual(instruction.bytes) else { throw ProfileFailure.message("stale_run") } + return sharedPaths.contains(instruction.sourcePath) ? range : nil + } + var rows: [[String: String]] = [], status = "C watch metadata is unavailable for this build." + if let metadata = info.variables, let u = capture.registers["U"]?.uint16Value, let s = capture.registers["S"]?.uint16Value { + status = "available" + let frame = CMOCCallStack.capture(metadata: metadata, pc: point.address, u: u, s: s, memory: memory, + available: available, maximumFrames: 1).frames.first + let evaluator = CMOCWatchEvaluator(metadata: metadata, context: .init(pc: point.address, u: u, memory: memory, available: available), + frameLocalsAvailable: frame?.localsInspectable == true) + rows = watches.map { name in + // Only a locally configured named variable can cross the grant. Arbitrary dereferences can name unrelated memory. + guard name.range(of: #"^[A-Za-z_][A-Za-z_0-9]*$"#, options: .regularExpression) != nil else { + return ["name": name, "unavailable": "Only named C variables are shared."] + } + let value = evaluator.evaluate(name) + if let error = value.error { return ["name": name, "unavailable": error] } + return ["name": name, "type": value.typeName, "value": value.value] + } + } + return try MCPDebuggerInspection(runID: runID, capture: capture, + scope: ["project_id": projectID, "revision": revision, "artifact_id": build.id.uuidString, "observation": "captured_source_stop"], + sourceStop: ["path": point.sourcePath, "line": point.sourceLine, "address": Int(point.address), "instruction_bytes": point.bytes.map(Int.init)], + watches: rows, watchStatus: status, ranges: ranges) + } + +} diff --git a/platforms/macos/App/MCPCMOCProject.swift b/platforms/macos/App/MCPCMOCProject.swift new file mode 100644 index 0000000..00721ee --- /dev/null +++ b/platforms/macos/App/MCPCMOCProject.swift @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// A grant fixes the input names and build recipe at consent time. An ordinary +/// project contributes C and headers only; its Make recipes and options never run. +struct MCPCMOCProject: Equatable, Sendable { + static let diskPaths = ["assets/words.txt", "include/hello.h", "main.c", "src/disk.c", "src/display.c"] + static let diskControls = ["Makefile", "tools/build-data.pl", CMOCProject.configurationFilename] + static let libraryHeaders = ["cmoc.h", "coco.h", "decbfile.h", "stdarg.h", "assert.h", "setjmp.h", "disk.h", "lores.h", "gimeterm.h"] + let paths: [String] + let entry: String + let helloDisk: Bool + let customMake: Bool + let configuration: CMOCProjectConfiguration + + init(project: CMOCProject, files: [String], customMake: Bool = false) throws { + self.customMake = customMake + configuration = try project.configuration.validated() + let available = Set(files) + helloDisk = !customMake && Set(Self.diskPaths + Self.diskControls).isSubset(of: available) + if customMake { + entry = project.configuration.entrySource + paths = available.filter { CMOCProject.isEditable($0) }.sorted() + guard paths.contains(entry), paths.contains(configuration.makefile), paths.count <= 1024, + Set(paths.map { $0.lowercased() }).count == paths.count else { + throw CMOCBuildError.message("unsupported_project_sources: choose a project with at most 1,024 distinct shared text files") + } + for path in paths { try CMOCProject.validateRelativePath(path) } + } else if helloDisk { + paths = Self.diskPaths + entry = "main.c" + } else { + entry = project.configuration.entrySource + paths = available.filter { $0.hasSuffix(".c") || $0.hasSuffix(".h") }.sorted() + guard paths.contains(entry), entry.hasSuffix(".c"), paths.count <= 64, + Set(paths.map { $0.lowercased() }).count == paths.count, + paths.allSatisfy(Self.validPath) else { throw CMOCBuildError.message("unsupported_project_sources") } + } + } + + private static func validPath(_ path: String) -> Bool { + guard path.utf8.count <= 200, !path.hasPrefix("obj/"), !path.hasPrefix("generated/") else { return false } + return path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { part in + guard let first = part.first, first.isASCII, first.isLetter || first == "_" || first.isNumber else { return false } + return part.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || "_.-".contains($0)) } + } + } + + // Remove C comments before classifying directives. Quoted strings and + // character literals stay intact; comments cannot hide a leading #include. + private static let lexicalTokens = try! NSRegularExpression(pattern: ##"(?s)/\*.*?(?:\*/|\z)|//[^\r\n]*|"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'"##) + private static func uncomment(_ source: String) -> String { + let text = source as NSString + let result = NSMutableString(capacity: text.length) + var start = 0 + for token in lexicalTokens.matches(in: source, range: NSRange(location: 0, length: text.length)) { + let value = text.substring(with: token.range) + guard value.hasPrefix("/") else { continue } + result.append(text.substring(with: NSRange(location: start, length: token.range.location - start))) + result.append(" " + String(value.filter { $0.isNewline })) + start = NSMaxRange(token.range) + } + result.append(text.substring(from: start)) + return result as String + } + + func validate(_ source: String, path: String, trusted: Set? = nil) throws { + guard source.utf8.count <= (customMake ? CMOCProject.maximumSourceBytes : 65536), !source.utf8.contains(0) else { + throw CMOCBuildError.message("file_too_large: " + path) + } + if customMake { return } // The user explicitly approved this project's Make recipe and compiler inputs. + var rejectedLine = 1 + // Locate the first construct outside the restricted C-source mode. + if let range = source.range(of: #"(?m)^.*(?:\basm\b|__asm|_Pragma|__has_include|_CMOC_CONCAT|%:|\?\?|##|#\s*(?:pragma|line|error|warning)).*$"#, options: .regularExpression) { + rejectedLine = source[.. CMOCBuildError { + .message("unsupported_source_directive: \(path):\(line): This construct is outside the restricted C connection. For your own Make project, select Use Project Makefile in Assistant Access.") + } + let denied = rejection(rejectedLine) + guard !source.contains("%:"), !source.contains("??"), !source.contains("##"), + source.utf8.allSatisfy({ $0 == 9 || $0 == 10 || $0 == 13 || $0 >= 32 }), + source.range(of: #"\\[ \t]*(?:\r|\n|$)|\\[uU][0-9a-fA-F]"#, options: .regularExpression) == nil, + source.range(of: #"\b(asm|__asm_?_?|_Pragma|__has_include(?:_next)?|_CMOC_CONCAT2?)\b"#, options: .regularExpression) == nil else { throw denied } + if let trusted { + guard source.components(separatedBy: .newlines).allSatisfy({ !$0.contains("#") || trusted.contains($0) }) else { throw denied } + return + } + for (index, line) in Self.uncomment(source).components(separatedBy: .newlines).enumerated() { + let denied = rejection(index + 1) + let directive = line.trimmingCharacters(in: .whitespaces) + guard directive.hasPrefix("#") else { continue } + let body = directive.dropFirst().trimmingCharacters(in: .whitespaces) + let nameEnd = body.firstIndex(where: { !$0.isLetter && $0 != "_" }) ?? body.endIndex + let keyword = String(body[..= 3, let first = arg.first, let last = arg.last else { throw denied } + let name = String(arg.dropFirst().dropLast()) + if first == "<", last == ">", Self.libraryHeaders.contains(name) { continue } + let parent = (path as NSString).deletingLastPathComponent + guard first == "\"", last == "\"", Self.validPath(name), name.hasSuffix(".h"), + paths.contains(name) || paths.contains("include/" + name) || paths.contains(parent + "/" + name) else { throw denied } + } + } + + func snapshotProject(at directory: URL, inputs: [String: String], buildInputs: [String: Data]? = nil, + support: CMOCBuildSupportSnapshot? = nil, permissions: [String: Int] = [:], + modificationDates: [String: Date] = [:], overlayPaths: Set = []) throws -> CMOCProject { + if customMake { + guard var files = buildInputs else { throw CMOCBuildError.message("missing_project_source") } + for (path, text) in inputs { files[path] = try CMOCProject.sourceBytes(text) } + let fm = FileManager.default + try fm.createDirectory(at: directory, withIntermediateDirectories: true) + for (path, bytes) in files { + try CMOCProject.validateRelativePath(path) + let url = directory.appendingPathComponent(path) + try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try bytes.write(to: url, options: .withoutOverwriting) + if let mode = permissions[path] { try fm.setAttributes([.posixPermissions: mode], ofItemAtPath: url.path) } + if !overlayPaths.contains(path), let date = modificationDates[path] { + try fm.setAttributes([.modificationDate: date], ofItemAtPath: url.path) + } + } + for relative in configuration.buildSupportDirectories { + try fm.createDirectory(at: directory.appendingPathComponent(relative).standardizedFileURL, withIntermediateDirectories: true) + } + if let support { + for (path, bytes) in support.files { + guard configuration.buildSupportDirectories.contains(where: { path.hasPrefix($0 + "/") }) else { + throw CMOCBuildError.message("unapproved_build_support") + } + let url = directory.appendingPathComponent(path).standardizedFileURL + try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try bytes.write(to: url, options: .withoutOverwriting) + if let mode = support.permissions[path] { try fm.setAttributes([.posixPermissions: mode], ofItemAtPath: url.path) } + } + } + return try CMOCProject.open(at: directory) + } + if helloDisk { return try CMOCProject.createHelloDisk(at: directory) } + var recipe = CMOCMakefileSettings() + recipe.sources = paths.filter { $0.hasSuffix(".c") } + recipe.compilerOptions = ["-I."] // Allow a nested source to include a shared header at the project root. + recipe.includePaths = paths.contains(where: { $0.hasPrefix("include/") }) ? ["include"] : [] + var configuration = CMOCProjectConfiguration() + configuration.entrySource = entry + configuration.makefileSettings = recipe + configuration.buildTarget = "build" + let fm = FileManager.default + try fm.createDirectory(at: directory, withIntermediateDirectories: false) + for path in paths { + guard let source = inputs[path] else { throw CMOCBuildError.message("missing_project_source") } + let url = directory.appendingPathComponent(path) + try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(source.utf8).write(to: url, options: .withoutOverwriting) + } + try Data(recipe.generateMakefile().utf8).write(to: directory.appendingPathComponent("Makefile")) + try JSONEncoder().encode(configuration).write(to: directory.appendingPathComponent(CMOCProject.configurationFilename)) + return try CMOCProject.open(at: directory) + } +} + +struct MCPCMOCEdit: Equatable { + let path: String + let before: String + let after: String +} + +/// Frozen inputs for an explicitly approved Make build. Binary resources are +/// build inputs but are not exposed as assistant-readable text. +struct MCPCMOCMakeInputs: Equatable, Sendable { + let makefile: String + let files: [String: Data] + let permissions: [String: Int] + var modificationDates: [String: Date] = [:] + var overlayPaths: Set = [] + let support: CMOCBuildSupportSnapshot + + static func == (lhs: Self, rhs: Self) -> Bool { + // Modification times are Make scheduling hints, not source revisions. + // Overlay membership can change on Save without changing any bytes. + lhs.makefile == rhs.makefile && lhs.files == rhs.files && lhs.permissions == rhs.permissions && lhs.support == rhs.support + } + + var recipeID: String { + let controls = files.filter { path, _ in + let name = (path as NSString).lastPathComponent + return path == makefile || (permissions[path] ?? 0) & 0o111 != 0 + || ["Makefile", "makefile", "GNUmakefile", CMOCProject.configurationFilename].contains(name) + || ["mk", "pl", "py", "sh", "rb"].contains((path as NSString).pathExtension.lowercased()) + }.mapValues(CMOCProject.sha256) + let rows = controls.merging(support.hashes) { first, _ in first }.sorted { $0.key < $1.key } + return CMOCProject.sha256(Data(rows.map { "\($0.key):\($0.value):\(permissions[$0.key] ?? 0)" }.joined(separator: "\n").utf8)) + } +} diff --git a/platforms/macos/App/MCPChatGPTSetup.swift b/platforms/macos/App/MCPChatGPTSetup.swift new file mode 100644 index 0000000..7aabd14 --- /dev/null +++ b/platforms/macos/App/MCPChatGPTSetup.swift @@ -0,0 +1,307 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import CryptoKit +import Foundation +import Security +import SwiftUI + +/// Only the helper path and the grant filename go into the desktop client's configuration. +struct MCPChatGPTConnection { + let grantURL: URL + let helper: URL + let name: String + + init(grantURL: URL, helper: URL = Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/vcc-mcp")) { + self.grantURL = grantURL + self.helper = helper + // Per-file names let BASIC, C and assembly grants coexist. Re-exporting to the same path reuses the entry. + let suffix = SHA256.hash(data: Data(grantURL.path.utf8)).prefix(6).map { String(format: "%02x", $0) }.joined() + name = "vcc-plus-oss-" + suffix + } + + var arguments: [String] { ["--grant", grantURL.path] } + + enum Registration { case missing, matches, disabled, conflict } + + enum SetupError: LocalizedError { + case manualSetup, installApp, grantUnavailable, cliFailed, timeout + var errorDescription: String? { + switch self { + case .manualSetup: return "Use the manual steps for this version of ChatGPT." + case .installApp: return "Copy VCC Plus OSS into Applications and open that copy before adding it to ChatGPT." + case .grantUnavailable: return "Save a new connection file in VCC Plus before connecting." + case .cliFailed: return "ChatGPT could not confirm its MCP settings. Check the entry in Settings → MCP servers." + case .timeout: return "ChatGPT took too long to respond. Check the entry in Settings → MCP servers." + } + } + } + + static func cli(in app: URL?) throws -> URL { + guard let app else { throw SetupError.manualSetup } + let cli = app.appendingPathComponent("Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex") + var code: SecStaticCode? + var requirement: SecRequirement? + guard FileManager.default.isExecutableFile(atPath: cli.path), + SecStaticCodeCreateWithPath(cli as CFURL, [], &code) == errSecSuccess, let code, + SecRequirementCreateWithString(#"anchor apple generic and identifier "codex" and certificate leaf[subject.OU] = "2DC432GLL2""# as CFString, [], &requirement) == errSecSuccess, + let requirement, SecStaticCodeCheckValidity(code, [], requirement) == errSecSuccess else { throw SetupError.manualSetup } + return cli + } + + private func command(_ cli: URL, _ args: [String]) throws -> (Int32, Data) { + let process = Process() + let pipe = Pipe() + process.executableURL = cli + process.arguments = args + // Resolve user-level ChatGPT settings, independent of any trusted project in the app launch directory. + process.currentDirectoryURL = URL(fileURLWithPath: "/", isDirectory: true) + process.standardInput = FileHandle.nullDevice + process.standardOutput = pipe + process.standardError = pipe + try process.run() + let terminate = DispatchWorkItem { if process.isRunning { process.terminate() } } + let forceStop = DispatchWorkItem { if process.isRunning { kill(process.processIdentifier, SIGKILL) } } + DispatchQueue.global().asyncAfter(deadline: .now() + 10, execute: terminate) + DispatchQueue.global().asyncAfter(deadline: .now() + 12, execute: forceStop) + defer { terminate.cancel(); forceStop.cancel() } + let output = pipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationReason == .exit else { throw SetupError.timeout } + return (process.terminationStatus, output) + } + + func registration(cli: URL) throws -> Registration { + let (status, bytes) = try command(cli, ["mcp", "get", "--json", name]) + let lines = String(decoding: bytes, as: UTF8.self).components(separatedBy: .newlines) + if status != 0 { + guard lines.contains("Error: No MCP server named '\(name)' found.") else { throw SetupError.cliFailed } + return .missing + } + // The CLI can emit a startup warning on stderr before printing its JSON record. + guard let start = lines.firstIndex(where: { $0.first == "{" }), + let entry = (try? JSONSerialization.jsonObject(with: Data(lines[start...].joined(separator: "\n").utf8))) as? [String: Any], + entry["name"] as? String == name, let transport = entry["transport"] as? [String: Any] else { throw SetupError.cliFailed } + guard transport["type"] as? String == "stdio", transport["command"] as? String == helper.path, + transport["args"] as? [String] == arguments else { return .conflict } + return entry["enabled"] as? Bool == true ? .matches : .disabled + } + + func configure(app: URL?, add: Bool) throws -> String { + let cli = try Self.cli(in: app) + guard FileManager.default.isReadableFile(atPath: grantURL.path) else { throw SetupError.grantUnavailable } + let volume = try helper.resourceValues(forKeys: [.volumeIsReadOnlyKey]) + guard FileManager.default.isExecutableFile(atPath: helper.path), + !(helper.path.hasPrefix("/Volumes/") && volume.volumeIsReadOnly == true), !helper.path.contains("/AppTranslocation/") else { throw SetupError.installApp } + switch try registration(cli: cli) { + case .matches: return "This connection is saved in ChatGPT. Restart ChatGPT if needed, then type /mcp to check the live connection." + case .disabled: return "This connection is saved but disabled. Enable it in ChatGPT Settings → MCP servers." + case .conflict: return "ChatGPT already uses this server name for another connection. Choose a different name in manual setup." + case .missing: + guard add else { return "This connection has not been added to ChatGPT yet." } + } + let (status, _) = try command(cli, ["mcp", "add", name, "--", helper.path] + arguments) + guard status == 0, try registration(cli: cli) == .matches else { throw SetupError.cliFailed } + return "Added to ChatGPT. In Settings → MCP servers, select Restart. Start a local chat and type /mcp to check the live connection." + } +} + +/// The editable starter is a runtime resource also used by Book 12. Connection details are composed at +/// copy time so an edited draft cannot retain a previous connection's grant path. +struct MCPProjectSetupPrompt { + static let resourcePath = "PROJECT_SETUP_PREAMBLE.txt" + let starter: String + var text: String + + enum PromptError: LocalizedError { + case unavailable, empty + + var errorDescription: String? { + switch self { + case .unavailable: return "The project setup starter could not be read from this app’s runtime resources." + case .empty: return "The project setup prompt is empty. Enter your instructions or reset to the starter." + } + } + } + + init(starter: String) throws { + guard !starter.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw PromptError.empty } + self.starter = starter + text = starter + } + + static func load(runtimeTemplates: URL?) throws -> Self { + guard let runtimeTemplates, + let text = try? String(contentsOf: runtimeTemplates.appendingPathComponent(resourcePath), encoding: .utf8) else { + throw PromptError.unavailable + } + return try Self(starter: text) + } + + var canCopy: Bool { !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } + + mutating func reset() { text = starter } + + func connectionDetails(_ connection: MCPChatGPTConnection) throws -> String { + // Encode paths as data, including any embedded whitespace or quotation marks. + // Never open the grant file: its token and other contents stay on this Mac. + let details: [String: Any] = ["name": connection.name, "command": connection.helper.path, + "arguments": connection.arguments] + let bytes = try JSONSerialization.data(withJSONObject: details, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) + return String(decoding: bytes, as: UTF8.self) + } + + func rendered(connection: MCPChatGPTConnection, firstPrompt: String) throws -> String { + guard canCopy else { throw PromptError.empty } + return """ + \(text.trimmingCharacters(in: .whitespacesAndNewlines)) + + VCC Plus connection details (configuration only; verify tool discovery and a successful request separately): + \(try connectionDetails(connection)) + + First read-only check after discovering this connection’s tools: + \(firstPrompt) + """ + } +} + +struct MCPChatGPTSetup: View { + let grantURL: URL + let firstPrompt: String + @State private var message = "" + @State private var working = false + @State private var expanded = false + @State private var projectPrompt: MCPProjectSetupPrompt? + @State private var promptMessage = "" + @State private var editingPrompt = false + + private func configure(add: Bool) { + guard !working else { return } + let setup = MCPChatGPTConnection(grantURL: grantURL) + let app = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.openai.codex") + working = true + Task { @MainActor in + let result = await Task.detached(priority: .userInitiated) { + do { return try setup.configure(app: app, add: add) } + catch { return error.localizedDescription } + }.value + message = result + working = false + } + } + + private func copy(_ value: String) { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(value, forType: .string) + } + + private func copyProjectPrompt() { + guard let projectPrompt else { return } + do { + let value = try projectPrompt.rendered(connection: MCPChatGPTConnection(grantURL: grantURL), firstPrompt: firstPrompt) + copy(value) + promptMessage = "Project setup prompt copied." + } catch { + promptMessage = error.localizedDescription + } + } + + @MainActor private func loadProjectPrompt() async { + guard projectPrompt == nil else { return } + let templates = Bundle.main.url(forResource: "RuntimeTemplates", withExtension: nil) + let result = await Task.detached(priority: .userInitiated) { + Result { try MCPProjectSetupPrompt.load(runtimeTemplates: templates) } + }.value + guard !Task.isCancelled, projectPrompt == nil else { return } + switch result { + case .success(let prompt): projectPrompt = prompt + case .failure(let error): promptMessage = error.localizedDescription + } + } + + private var projectPromptEditor: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Project Setup Prompt").font(.title2) + Text("Edit the starter for your project. It authorizes setup only within the permissions you exported. Copying does not change your connections.") + .foregroundStyle(.secondary) + TextEditor(text: Binding(get: { projectPrompt?.text ?? "" }, set: { projectPrompt?.text = $0; promptMessage = "" })) + .font(.body.monospaced()) + .scrollContentBackground(.hidden) + .padding(6) + .background(.background, in: RoundedRectangle(cornerRadius: 6)) + .overlay(RoundedRectangle(cornerRadius: 6).stroke(.quaternary)) + .accessibilityLabel("Project setup instructions") + .accessibilityIdentifier("mcp.projectSetup.instructions") + Text("The current connection name, helper path and saved connection path are appended when you copy. Connection file contents are never included.") + .font(.callout).foregroundStyle(.secondary) + if let projectPrompt, + let details = try? projectPrompt.connectionDetails(MCPChatGPTConnection(grantURL: grantURL)) { + DisclosureGroup("Included connection details") { + ScrollView { + Text(details).font(.callout.monospaced()).textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + }.frame(maxHeight: 100) + } + } + if !promptMessage.isEmpty { Text(promptMessage).font(.callout).textSelection(.enabled) } + HStack { + Button("Reset to Starter") { projectPrompt?.reset(); promptMessage = "" } + .accessibilityIdentifier("mcp.projectSetup.reset") + Spacer() + Button("Done") { editingPrompt = false }.keyboardShortcut(.cancelAction) + Button("Copy Project Setup Prompt") { copyProjectPrompt() } + .disabled(projectPrompt?.canCopy != true) + .keyboardShortcut(.defaultAction) + .accessibilityIdentifier("mcp.projectSetup.editorCopy") + } + } + .padding(20) + .frame(minWidth: 520, idealWidth: 640, minHeight: 400, idealHeight: 540) + } + + private func field(_ label: String, _ value: String) -> some View { + HStack(alignment: .firstTextBaseline) { + Text(label).frame(width: 85, alignment: .leading) + Text(value).font(.callout.monospaced()).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) + Button { copy(value) } label: { Image(systemName: "doc.on.doc") }.accessibilityLabel("Copy " + label) + } + } + + var body: some View { + let setup = MCPChatGPTConnection(grantURL: grantURL) + VStack(alignment: .leading, spacing: 8) { + Text("ChatGPT for Mac").font(.headline) + HStack { + Button("Add to ChatGPT") { configure(add: true) } + Button("Check Setup") { configure(add: false) } + Button("Copy First Prompt") { copy(firstPrompt) } + }.disabled(working) + HStack { + Button("Copy Project Setup Prompt") { copyProjectPrompt() } + .disabled(projectPrompt?.canCopy != true) + .accessibilityIdentifier("mcp.projectSetup.copy") + Button("Edit…") { editingPrompt = true } + .disabled(projectPrompt == nil) + .accessibilityLabel("Edit project setup prompt") + .accessibilityIdentifier("mcp.projectSetup.edit") + } + Text("An editable starter that authorizes setup within your exported permissions. Copying does not change your connections.") + .font(.callout).foregroundStyle(.secondary) + if !promptMessage.isEmpty { Text(promptMessage).font(.callout).textSelection(.enabled) } + if working { ProgressView().controlSize(.small) } + if !message.isEmpty { Text(message).font(.callout).textSelection(.enabled) } + DisclosureGroup("Manual setup", isExpanded: $expanded) { + VStack(alignment: .leading, spacing: 6) { + Text("In ChatGPT Settings → MCP servers, choose Add server and select STDIO. Enter each argument separately.") + field("Name", setup.name) + field("Command", setup.helper.path) + field("Argument 1", setup.arguments[0]) + field("Argument 2", setup.arguments[1]) + Text("Save, select Restart in ChatGPT, and type /mcp in a local chat. Paste the first prompt to try VCC Plus.") + Link("ChatGPT MCP instructions", destination: URL(string: "https://learn.chatgpt.com/docs/extend/mcp")!) + }.padding(.top, 4) + } + } + .task { await loadProjectPrompt() } + .sheet(isPresented: $editingPrompt) { projectPromptEditor } + } +} diff --git a/platforms/macos/App/MCPCompiledRunIO.swift b/platforms/macos/App/MCPCompiledRunIO.swift new file mode 100644 index 0000000..54c7650 --- /dev/null +++ b/platforms/macos/App/MCPCompiledRunIO.swift @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// Input receipts belong to one native launch and cannot be reused after its grant is retired. +@MainActor +final class MCPCompiledRunIO { + private let machine: MachineModel + private let runID: String + private let expected: VCCMachineSnapshot + private let assembly: Bool + private let lease = VCCCompiledRunLease() + private var accepted: [String: String] = [:] + private var sending = false + + init(machine: MachineModel, runID: String, expected: VCCMachineSnapshot, assembly: Bool) { + self.machine = machine + self.runID = runID + self.expected = expected + self.assembly = assembly + } + + func invalidate() { + lease.invalidate() + machine.cancelMCPInput(runID: runID) + } + + func finalScreenText() async throws -> String? { + let result = try await machine.mcpCompiledGuest(lease: lease, runID: runID, expected: expected, + assembly: assembly, key: nil, readScreen: false, finalScreen: true) + guard lease.isValid else { throw ProfileFailure.message("stale_run") } + return result["text"] as? String + } + + func reply(_ tool: String, arguments: [String: Any]) async throws -> [String: Any] { + guard lease.isValid, arguments["run_id"] as? String == runID else { throw ProfileFailure.message("stale_run") } + if tool == "read_screen_text", arguments.count == 1 { + let result = try await machine.mcpCompiledGuest(lease: lease, runID: runID, expected: expected, + assembly: assembly, key: nil, readScreen: true) + guard lease.isValid else { throw ProfileFailure.message("stale_run") } + return result + } + guard tool == "send_keys", arguments.count == 3, + let request = arguments["request_id"] as? String, (1...64).contains(request.utf8.count), + let keys = arguments["keys"] as? String, MCPGuestKey.accepts(keys), + let chord = CocoKeyboard.chord(for: keys) else { throw ProfileFailure.message("invalid_arguments") } + let prior = accepted[request] + if let prior, prior != keys { throw ProfileFailure.message("request_conflict") } + guard !sending else { throw ProfileFailure.message("input_busy") } + guard prior != nil || accepted.count < MCPGuestKey.limit else { throw ProfileFailure.message("input_limit_reached") } + sending = true + defer { sending = false } + // Revalidate even cached receipts. Only the first accepted request submits a chord. + _ = try await machine.mcpCompiledGuest(lease: lease, runID: runID, expected: expected, assembly: assembly, + key: prior == nil ? NSNumber(value: chord) : nil, readScreen: false) + guard lease.isValid else { throw ProfileFailure.message("stale_run") } + accepted[request] = keys + return ["run_id": runID, "request_id": request, "accepted": true] + } +} diff --git a/platforms/macos/App/MCPDebuggerInspection.swift b/platforms/macos/App/MCPDebuggerInspection.swift new file mode 100644 index 0000000..962f869 --- /dev/null +++ b/platforms/macos/App/MCPDebuggerInspection.swift @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// One immutable observation of an explicitly shared program. Only the permitted +/// ranges are retained. Memory requests never perform another guest bus read. +struct MCPDebuggerInspection { + let runID: String + let id = UUID().uuidString + let machine: VCCMachineSnapshot + private let memory: [(range: Range, bytes: Data)] + let fields: [String: Any] + + init(runID: String, capture: VCCDebuggerSnapshot, scope: [String: Any], + sourceStop: [String: Any]?, watches: [[String: String]], watchStatus: String, + ranges: [Range]) throws { + let state = capture.machine + guard state.state == .paused, state.assistantDeviceBlockers.isEmpty else { + throw ProfileFailure.message("pause_required") + } + self.runID = runID + machine = state + let data = capture.logicalMemory, available = capture.logicalMemoryAvailable + var permitted = IndexSet() + for range in ranges where range.lowerBound >= 0 && range.upperBound <= min(0xff00, data.count, available.count) { + permitted.insert(integersIn: range) + } + for address in Array(permitted) where available[address] == 0 { permitted.remove(address) } + memory = permitted.rangeView.map { ($0, data.subdata(in: $0)) } + var fields = scope + fields["run_id"] = runID + fields["snapshot_id"] = id + fields["status"] = "paused" + fields["processor"] = state.use6309 ? "HD6309" : "MC6809" + fields["registers"] = capture.registers.reduce(into: [String: Int]()) { $0[$1.key.lowercased()] = $1.value.intValue } + fields["source_stop"] = sourceStop as Any? ?? NSNull() + fields["watches"] = watches + fields["watch_status"] = watchStatus + fields["memory_ranges"] = memory.map { ["address": $0.range.lowerBound, "count": $0.range.count] } + self.fields = fields + } + + static func sameProgram(_ state: VCCMachineSnapshot, _ expected: VCCMachineSnapshot) -> Bool { + state.assistantDeviceBlockers.isEmpty && state.generation == expected.generation && + state.debuggerProgramRevision == expected.debuggerProgramRevision && + state.debuggerMappingFingerprint == expected.debuggerMappingFingerprint && state.use6309 == expected.use6309 + } + + func reply(tool: String, arguments: [String: Any]) throws -> [String: Any] { + guard arguments["run_id"] as? String == runID else { throw ProfileFailure.message("stale_run") } + if tool == "get_debug_snapshot", arguments.count == 1 { return fields } + guard tool == "read_debug_memory", arguments.count == 4, + let requested = arguments["snapshot_id"] as? String, let address = Self.integer(arguments["address"]), + let count = Self.integer(arguments["count"]), (0...65535).contains(address), (1...256).contains(count), + address + count <= 65536 else { throw ProfileFailure.message("invalid_arguments") } + guard requested == id else { throw ProfileFailure.message("stale_snapshot") } + guard let block = memory.first(where: { $0.range.contains(address) && address + count <= $0.range.upperBound }) else { + throw ProfileFailure.message("memory_unavailable") + } + let offset = address - block.range.lowerBound + return ["run_id": runID, "snapshot_id": id, "address": address, "count": count, + "bytes": block.bytes[offset..<(offset + count)].map(Int.init)] + } + + private static func integer(_ value: Any?) -> Int? { + guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), + !["f", "d"].contains(String(cString: number.objCType)) else { return nil } + return Int(exactly: number) + } + + @MainActor static func capture(_ machine: MachineModel) async throws -> VCCDebuggerSnapshot { + let snapshot: VCCDebuggerSnapshot? = await withCheckedContinuation { continuation in + machine.readDebugger(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) } + } + guard let snapshot else { throw ProfileFailure.message("debugger_busy") } + return snapshot + } +} diff --git a/platforms/macos/App/MCPHelpIndex.swift b/platforms/macos/App/MCPHelpIndex.swift new file mode 100644 index 0000000..1bad730 --- /dev/null +++ b/platforms/macos/App/MCPHelpIndex.swift @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +// Decode the installed reader's generated JSON payload as data, never executable JavaScript. +actor MCPHelpIndex { + static let shared = MCPHelpIndex() + struct Topic { + let id, title, text: String + } + private struct Book: Decodable { + struct Chapter: Decodable { + struct Section: Decodable { let id, title: String; let passages: [String] } + let page: String + let sections: [Section] + } + let directory: String + let chapters: [Chapter] + } + private let root: URL? + private var cached: [Topic]? + + init(root: URL? = Bundle.main.url(forResource: "ManualLibrary", withExtension: nil)) { + self.root = root + } + + private func topics() throws -> [Topic] { + if let cached { return cached } + guard let root else { throw CocoaError(.fileNoSuchFile) } + let contents = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil) + let books = [root.appendingPathComponent("book-index.js")] + contents.map { $0.appendingPathComponent("book-index.js") }.filter { FileManager.default.fileExists(atPath: $0.path) } + var topics: [Topic] = [] + for file in books { + let index = try String(contentsOf: file, encoding: .utf8).trimmingCharacters(in: .whitespacesAndNewlines) + let prefix = "(globalThis.manualBooks ??= []).push(" + guard index.hasPrefix(prefix), index.hasSuffix(");") else { throw CocoaError(.fileReadCorruptFile) } + let payload = index.dropFirst(prefix.count).dropLast(2) + let book = try JSONDecoder().decode(Book.self, from: Data(payload.utf8)) + for chapter in book.chapters { + for section in chapter.sections { + topics.append(Topic(id: "\(book.directory)/\(chapter.page)#\(section.id)", + title: section.title, text: section.passages.joined(separator: "\n\n"))) + } + } + } + cached = topics.sorted { $0.id < $1.id } + return cached! + } + + func search(_ query: String) throws -> [Topic] { + let words = query.lowercased().split(whereSeparator: \.isWhitespace).map(String.init) + guard !words.isEmpty else { return [] } + return try topics().compactMap { t -> (Int, Topic)? in + let title = t.title.lowercased(), body = t.text.lowercased() + guard words.allSatisfy({ title.contains($0) || body.contains($0) }) else { return nil } + return (words.filter { title.contains($0) }.count + (title == query.lowercased() ? 10 : 0), t) + }.sorted { lhs, rhs in + lhs.0 == rhs.0 ? lhs.1.id < rhs.1.id : lhs.0 > rhs.0 + }.prefix(8).map { $0.1 } + } + func read(_ id: String) throws -> Topic? { try topics().first { $0.id == id } } + + @MainActor + static func toolResult(_ name: String, arguments args: [String: Any]) async -> [String: Any] { + do { + switch name { + case "search_help": + guard args.count == 1, let query = args["query"] as? String, (1...160).contains(query.utf8.count), + !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return ["error": "invalid_arguments"] } + let topics = try await shared.search(query) + return ["result": ["hits": topics.map { ["topic_id": $0.id, "title": $0.title, "excerpt": String($0.text.prefix(240))] }]] + case "read_topic": + guard args.count == 1, let id = args["topic_id"] as? String, (1...512).contains(id.utf8.count) + else { return ["error": "invalid_arguments"] } + guard let topic = try await shared.read(id) else { return ["error": "not_found"] } + var text = String(decoding: topic.text.utf8.prefix(12 * 1024), as: UTF8.self) + while text.utf8.count > 12 * 1024 { text.removeLast() } + return ["result": ["topic_id": id, "title": topic.title, "text": text, "truncated": text != topic.text]] + default: return ["error": "invalid_arguments"] + } + } catch { return ["error": "manual_unavailable"] } + } +} diff --git a/platforms/macos/App/MCPMachineStatus.swift b/platforms/macos/App/MCPMachineStatus.swift new file mode 100644 index 0000000..5cd8b4b --- /dev/null +++ b/platforms/macos/App/MCPMachineStatus.swift @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// Read-only observations of the shared development setup; host paths and guest contents stay private. +enum MCPMachineStatus { + enum Workspace { case basic, cmoc(needsFloppy: Bool), assembly(needs6309: Bool) } + static let occupiedBASICGuidance = "A program is in CoCo BASIC memory. In BASIC Development, save any open draft, choose Read from CoCo, then Save As… to keep the guest listing. When you are ready to clear its program and variables, type NEW at the CoCo’s OK prompt and retry the C run." + + static func missingToolBlockers(in toolchain: URL, requiring names: [String]) async -> [String] { + await Task.detached { + let bin = toolchain.appendingPathComponent("bin") + return names.filter { !FileManager.default.isExecutableFile(atPath: bin.appendingPathComponent($0).path) } + .map { "Install the bundled development tool " + $0 + "." } + }.value + } + + static func result(_ machine: VCCMachineSnapshot, workspace: Workspace, + buildBlockers: [String]?, runBlockers: [String], + lastBuild: [String: Any]? = nil, profile: SystemProfile? = nil, input: [String: Any]? = nil) -> [String: Any] { + var reasons = runBlockers + machine.assistantDeviceBlockers + let state: String + switch machine.state { + case .running: state = "running" + case .paused: state = "paused" + case .empty: state = "empty" + case .closed: state = "closed" + @unknown default: state = "unknown" + } + if machine.state != .running && machine.state != .paused { + reasons.append("Start the CoCo before running the shared program.") + } + switch workspace { + case .assembly(let needs6309): + if needs6309 && !machine.use6309 { reasons.append("Use an HD6309 guest or assemble for MC6809.") } + case .cmoc(let needsFloppy): + if needsFloppy && machine.disks.first?.mounted != false { reasons.append("Use an empty floppy drive 0 before starting Hello Disk.") } + if machine.basicDebugAttached || (machine.debuggerDevelopmentAttached && !machine.assistantCompiledReturned) || machine.debuggerAssemblyAttached || machine.pasteRemaining > 0 { + reasons.append("Finish the active debugging or paste session.") + } + if machine.assistantEmptyBASIC?.boolValue == false { reasons.append(occupiedBASICGuidance) } + fallthrough + case .basic: + if machine.assistantDirectPrompt?.boolValue != true { + reasons.append(machine.assistantDirectPrompt == nil ? "Use a supported BASIC system and memory map." : "Wait at the BASIC OK prompt.") + } + } + func drives(_ disks: [VCCDiskSnapshot]) -> [[String: Any]] { + disks.enumerated().map { index, disk in + ["drive": index, "mounted": disk.mounted, "write_protected": disk.writeProtected] + } + } + var build: [String: Any] = ["applicable": false] + if let buildBlockers { + build = ["applicable": true, "available": buildBlockers.isEmpty, "blockers": buildBlockers] + if let lastBuild { + build["last_build"] = lastBuild.filter { ["build_id", "revision", "status"].contains($0.key) } + } + } + var result: [String: Any] = [ + "processor": machine.use6309 ? "HD6309" : "MC6809", "state": state, + "system_profile": (profile?.name as Any?) ?? NSNull(), + "video_output": DisplayOutput(rawValue: machine.videoOutput)?.label ?? "unknown", + "memory": MachineSettings.memoryLabels.indices.contains(Int(machine.ramConfiguration)) + ? MachineSettings.memoryLabels[Int(machine.ramConfiguration)] : "unknown", + "floppy_drives": drives(machine.disks), "hard_drives": drives(machine.hardDisks), + "cassette_mounted": machine.tapeMounted, "cassette_recording": machine.tapeMode == 2, + "drivewire_enabled": machine.driveWireEnabled, + "basic_direct_prompt": (machine.assistantDirectPrompt as Any?) ?? NSNull(), + "basic_program_loaded": (machine.assistantEmptyBASIC.map { !$0.boolValue } as Any?) ?? NSNull(), + "build": build, + "run": ["blockers": reasons, "ready_for_native_run": reasons.isEmpty] as [String: Any] + ] + if let input { result["input"] = input } + return result + } +} diff --git a/platforms/macos/App/MCPPlaytest.swift b/platforms/macos/App/MCPPlaytest.swift new file mode 100644 index 0000000..e3b8853 --- /dev/null +++ b/platforms/macos/App/MCPPlaytest.swift @@ -0,0 +1,1083 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import Darwin + +/// Public processor choices are guest CPUs, independent of the Mac's host +/// architecture. Selection never sets the HD6309 MD register for the guest. +enum MCPPlaytestProcessor: String, Sendable { + case mc6809 = "MC6809" + case hd6309 = "HD6309" + var workerCPU: String { self == .hd6309 ? "6309" : "6809" } + static func selected(_ value: Any?) throws -> Self { + guard let value else { return .mc6809 } + guard let name = value as? String, let processor = Self(rawValue: name) else { + throw ProfileFailure.message("invalid_playtest_processor") + } + return processor + } +} + +/// Validated complete standard-joystick snapshots. Coordinates use the same +/// 14-bit input range as the native host; they never address guest memory. +enum MCPPlaytestJoystick { + static func snapshots(_ value: Any) throws -> [[String: Any]] { + guard let values = value as? [[String: Any]], values.count <= 2 else { + throw ProfileFailure.message("invalid_playtest_joystick") + } + var seen = Set() + return try values.map { item in + guard Set(item.keys) == ["port", "x", "y", "buttons"], + let port = item["port"] as? String, ["right", "left"].contains(port), + seen.insert(port).inserted, let x = axis(item["x"]), let y = axis(item["y"]), + let buttons = item["buttons"] as? [String], buttons.count <= 2, + Set(buttons).count == buttons.count, + buttons.allSatisfy({ ["fire1", "fire2"].contains($0) }) else { + throw ProfileFailure.message("invalid_playtest_joystick") + } + return ["port": port, "x": x, "y": y, "buttons": buttons] + } + } + private static func axis(_ value: Any?) -> Int? { + guard let value = value as? NSNumber, CFGetTypeID(value) != CFBooleanGetTypeID(), + value.doubleValue.isFinite, (0...16383).contains(value.doubleValue), + value.doubleValue.rounded(.towardZero) == value.doubleValue else { return nil } + return value.intValue + } +} + +/// Durable app-owned playtest disks. A UUID directory is published in one rename +/// only after its immutable disk and provenance sidecar have both been synced. +/// Legacy flat UUID.dsk files require an exact prior receipt and are never listed. +struct MCPPlaytestDiskStore: Sendable { + struct Provenance: Codable, Equatable, Sendable { + let projectKey: String? + let artifactID: String? + let artifactDiskSHA256: String? + let parentDiskID: String? + let origin: String + let originArtifactID: String? + let originArtifactDiskSHA256: String? + let mediaKey: String? + let mediaBaseSHA256: String? + + init(projectKey: String?, artifactID: String?, artifactDiskSHA256: String?, parentDiskID: String? = nil, + origin: String = "verified_artifact", originArtifactID: String? = nil, originArtifactDiskSHA256: String? = nil, + mediaKey: String? = nil, mediaBaseSHA256: String? = nil) { + self.projectKey = projectKey; self.artifactID = artifactID; self.artifactDiskSHA256 = artifactDiskSHA256 + self.parentDiskID = parentDiskID; self.origin = origin + self.originArtifactID = originArtifactID ?? (origin == "verified_artifact" ? artifactID : nil) + self.originArtifactDiskSHA256 = originArtifactDiskSHA256 ?? (origin == "verified_artifact" ? artifactDiskSHA256 : nil) + self.mediaKey = mediaKey; self.mediaBaseSHA256 = mediaBaseSHA256 + } + + var publicFields: [String: Any] { + var fields: [String: Any] = ["artifact_id": artifactID as Any? ?? NSNull(), + "artifact_disk_sha256": artifactDiskSHA256 as Any? ?? NSNull(), "origin": origin, + "origin_artifact_id": originArtifactID as Any? ?? NSNull(), + "origin_artifact_disk_sha256": originArtifactDiskSHA256 as Any? ?? NSNull()] + if let parentDiskID { fields["parent_disk_id"] = parentDiskID } + fields["media_key"] = mediaKey ?? "primary" + fields["media_base_sha256"] = (mediaBaseSHA256 ?? artifactDiskSHA256) as Any? ?? NSNull() + return fields + } + } + + struct Record: Codable, Equatable, Sendable { + let version: Int + let id: String + let runID: String + let diskSHA256: String + let provenance: Provenance + let createdAt: Date? + let byteCount: Int + + var publicFields: [String: Any] { + var fields = provenance.publicFields + fields["retained_disk_id"] = id; fields["run_id"] = runID + fields["disk_sha256"] = diskSHA256; fields["byte_count"] = byteCount + fields["created_at"] = createdAt.map { ISO8601DateFormatter().string(from: $0) } as Any? ?? NSNull() + return fields + } + } + + private static let maximumDiskBytes = 512 * 1024 + private static let maximumSidecarBytes = 16 * 1024 + private static func failure(_ value: String) -> ProfileFailure { .message(value) } + private static func identifier(_ value: String) throws -> String { + guard value.utf8.count == 36, let uuid = UUID(uuidString: value), uuid.uuidString.lowercased() == value.lowercased() else { + throw failure("invalid_retained_disk_id") + } + return uuid.uuidString + } + private static func digest(_ value: String) -> Bool { + value.utf8.count == 64 && value.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) } + } + static func validate(_ provenance: Provenance) throws { + guard let key = provenance.projectKey, digest(key), let artifact = provenance.artifactID, + (try? identifier(artifact)) != nil, let artifactSHA = provenance.artifactDiskSHA256, digest(artifactSHA), + ["verified_artifact", "legacy_receipt"].contains(provenance.origin) else { throw failure("invalid_playtest_disk_provenance") } + if let parent = provenance.parentDiskID { _ = try identifier(parent) } + if let key = provenance.mediaKey { + guard !key.isEmpty, key.utf8.count <= 4096, let base = provenance.mediaBaseSHA256, digest(base) else { + throw failure("invalid_playtest_media_provenance") + } + if key != "primary" { + guard key.hasPrefix("disk:") else { throw failure("invalid_playtest_media_provenance") } + try CMOCProject.validateRelativePath(String(key.dropFirst(5))) + } + } else if provenance.mediaBaseSHA256 != nil { throw failure("invalid_playtest_media_provenance") } + if provenance.origin == "verified_artifact" { + guard let original = provenance.originArtifactID, (try? identifier(original)) != nil, + provenance.originArtifactDiskSHA256 == artifactSHA else { throw failure("invalid_playtest_disk_provenance") } + } else { + guard provenance.originArtifactID == nil, provenance.originArtifactDiskSHA256 == nil else { + throw failure("invalid_legacy_disk_origin") + } + } + } + + private static func canonicalDirectory(_ directory: URL) throws -> URL { + let path = directory.standardizedFileURL.path + guard path.hasPrefix("/"), !path.contains("\0") else { throw failure("invalid_playtest_disk_directory") } + // macOS exposes /var and /tmp through system aliases. Normalize only + // these known aliases; arbitrary links within an app-managed path fail. + let normalized = path == "/var" || path.hasPrefix("/var/") || path == "/tmp" || path.hasPrefix("/tmp/") ? "/private" + path : path + return URL(fileURLWithPath: normalized, isDirectory: true) + } + private static func directoryFD(_ directory: URL, create: Bool) throws -> (Int32, URL) { + let root = try canonicalDirectory(directory) + var current = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW) + guard current >= 0 else { throw POSIXError(.EIO) } + do { + for component in root.path.split(separator: "/") { + let name = String(component) + var next = openat(current, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW) + if next < 0, errno == ENOENT, create { + guard mkdirat(current, name, 0o700) == 0 || errno == EEXIST else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + next = openat(current, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW) + } + guard next >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + close(current); current = next + } + var info = stat() + guard fstat(current, &info) == 0, info.st_mode & S_IFMT == S_IFDIR, info.st_uid == geteuid(), + info.st_mode & 0o077 == 0 else { throw failure("invalid_playtest_disk_directory") } + return (current, root) + } catch { close(current); throw error } + } + private static func regularFD(_ parent: Int32, _ name: String, maximum: Int) throws -> (Int32, Int) { + let fd = openat(parent, name, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK) + guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + var info = stat() + guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == geteuid(), info.st_nlink == 1, + info.st_size > 0, info.st_size <= off_t(maximum) else { close(fd); throw failure("invalid_retained_disk_file") } + return (fd, Int(info.st_size)) + } + private static func read(_ parent: Int32, _ name: String, maximum: Int) throws -> Data { + let (fd, size) = try regularFD(parent, name, maximum: maximum) + defer { close(fd) } + var result = Data(), buffer = [UInt8](repeating: 0, count: 16384) + while true { + let count = buffer.withUnsafeMutableBytes { Darwin.read(fd, $0.baseAddress, $0.count) } + if count < 0, errno == EINTR { continue } + guard count >= 0 else { throw POSIXError(.EIO) } + if count == 0 { break } + result.append(contentsOf: buffer.prefix(count)) + guard result.count <= maximum else { throw failure("retained_disk_size_limit") } + } + guard result.count == size else { throw failure("retained_disk_changed") } + return result + } + private static func childFD(_ parent: Int32, _ id: String) throws -> Int32 { + let fd = openat(parent, id, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW) + guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + var info = stat() + guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFDIR, info.st_uid == geteuid(), info.st_mode & 0o077 == 0 else { + close(fd); throw failure("invalid_retained_disk_record") + } + return fd + } + private static func record(_ parent: Int32, id: String) throws -> Record { + let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .iso8601 + let record = try decoder.decode(Record.self, from: read(parent, "record.json", maximum: maximumSidecarBytes)) + guard [1, 2].contains(record.version), record.id == id, + (try? identifier(record.runID)) == record.runID, + (record.version == 2 || record.runID == id), digest(record.diskSHA256), + (1...maximumDiskBytes).contains(record.byteCount), let created = record.createdAt, + created.timeIntervalSince1970.isFinite, created.timeIntervalSince1970 > 0 else { throw failure("invalid_retained_disk_record") } + try validate(record.provenance) + let (disk, size) = try regularFD(parent, "disk.dsk", maximum: maximumDiskBytes) + close(disk) + guard size == record.byteCount else { throw failure("retained_disk_changed") } + return record + } + + /// Bounded metadata enumeration. A resume rechecks every disk byte against + /// its receipt; listing does not hash hundreds of unrelated disk images. + static func list(directory: URL, projectKey: String) async throws -> [Record] { + guard digest(projectKey) else { throw failure("invalid_playtest_project_key") } + return try await Task.detached { + let parent: Int32 + do { parent = try directoryFD(directory, create: false).0 } + catch let error as POSIXError where error.code == .ENOENT { return [] } + defer { close(parent) } + guard let stream = fdopendir(dup(parent)) else { throw POSIXError(.EIO) } + defer { closedir(stream) } + var names: [String] = [], scanned = 0 + while let entry = readdir(stream) { + scanned += 1 + guard scanned <= 4098 else { throw failure("playtest_disk_listing_limit") } + let name = withUnsafePointer(to: &entry.pointee.d_name) { + $0.withMemoryRebound(to: CChar.self, capacity: Int(NAME_MAX) + 1) { String(cString: $0) } + } + if let id = try? identifier(name), id == name { names.append(id) } + } + var records: [Record] = [] + for id in names.sorted() { + guard let fd = try? childFD(parent, id) else { continue } + defer { close(fd) } + guard let candidate = try? record(fd, id: id), candidate.provenance.projectKey == projectKey else { continue } + records.append(candidate) + } + return Array(records.sorted { ($0.createdAt ?? .distantPast, $0.id) > ($1.createdAt ?? .distantPast, $1.id) }.prefix(1000)) + }.value + } + + static func load(directory: URL, id suppliedID: String, expectedSHA256: String, projectKey: String, + artifactDiskSHA256: String, mediaKey: String = "primary", mediaBaseSHA256: String? = nil) async throws -> (data: Data, record: Record) { + let id = try identifier(suppliedID) + guard digest(expectedSHA256), digest(projectKey), digest(artifactDiskSHA256) else { throw failure("invalid_retained_disk_receipt") } + return try await Task.detached { + let (parent, _) = try directoryFD(directory, create: false) + defer { close(parent) } + var info = stat() + if fstatat(parent, id, &info, AT_SYMLINK_NOFOLLOW) == 0 { + let child = try childFD(parent, id); defer { close(child) } + let stored = try record(child, id: id) + guard stored.diskSHA256 == expectedSHA256, stored.provenance.projectKey == projectKey, + stored.provenance.artifactDiskSHA256 == artifactDiskSHA256, + (stored.provenance.mediaKey ?? "primary") == mediaKey, + (mediaBaseSHA256 == nil || (stored.provenance.mediaBaseSHA256 ?? stored.provenance.artifactDiskSHA256) == mediaBaseSHA256) else { throw failure("retained_disk_provenance_mismatch") } + let bytes = try read(child, "disk.dsk", maximum: maximumDiskBytes) + guard CMOCProject.sha256(bytes) == expectedSHA256 else { throw failure("retained_disk_changed") } + return (bytes, stored) + } + guard errno == ENOENT else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + // An absent sidecar cannot confer project or artifact provenance. + // Only an exact UUID+SHA receipt may recover the old owned bytes. + if fstatat(parent, id + ".json", &info, AT_SYMLINK_NOFOLLOW) == 0 { throw failure("unrecognized_retained_disk_metadata") } + guard errno == ENOENT else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + guard mediaKey == "primary" else { throw failure("retained_disk_provenance_mismatch") } + let bytes = try read(parent, id + ".dsk", maximum: maximumDiskBytes) + guard CMOCProject.sha256(bytes) == expectedSHA256 else { throw failure("retained_disk_changed") } + let legacy = Record(version: 0, id: id, runID: id, diskSHA256: expectedSHA256, + provenance: Provenance(projectKey: nil, artifactID: nil, artifactDiskSHA256: nil, origin: "legacy_receipt"), + createdAt: nil, byteCount: bytes.count) + return (bytes, legacy) + }.value + } + + static func save(directory: URL, runID suppliedID: String, data: Data, provenance: Provenance, + recordID: String? = nil) async throws -> Record { + let runID = try identifier(suppliedID) + let id = try identifier(recordID ?? suppliedID) + try validate(provenance) + guard !data.isEmpty, data.count <= maximumDiskBytes else { throw failure("invalid_retained_disk_size") } + let frozen = Data(data), hash = CMOCProject.sha256(data) + return try await Task.detached { + let (parent, _) = try directoryFD(directory, create: true) + defer { close(parent) } + var existing = stat() + if fstatat(parent, id, &existing, AT_SYMLINK_NOFOLLOW) == 0 { + let child = try childFD(parent, id); defer { close(child) } + let stored = try record(child, id: id) + guard stored.runID == runID, stored.diskSHA256 == hash, stored.provenance == provenance, + try read(child, "disk.dsk", maximum: maximumDiskBytes) == frozen else { throw failure("playtest_disk_exists") } + guard fsync(parent) == 0 else { throw failure("playtest_disk_commit_failed") } + return stored + } + guard errno == ENOENT else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + if fstatat(parent, id + ".dsk", &existing, AT_SYMLINK_NOFOLLOW) == 0 { throw failure("playtest_disk_exists") } + guard errno == ENOENT else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + let pending = "." + UUID().uuidString + ".pending" + guard mkdirat(parent, pending, 0o700) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + let stage = try childFD(parent, pending) + var published = false + defer { + if !published { unlinkat(stage, "disk.dsk", 0); unlinkat(stage, "record.json", 0) } + close(stage) + if !published { unlinkat(parent, pending, AT_REMOVEDIR) } + } + let stored = Record(version: recordID == nil ? 1 : 2, id: id, runID: runID, diskSHA256: hash, + provenance: provenance, createdAt: Date(), byteCount: frozen.count) + let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .iso8601; encoder.outputFormatting = [.sortedKeys] + let metadata = try encoder.encode(stored) + guard metadata.count <= maximumSidecarBytes else { throw failure("invalid_playtest_disk_provenance") } + func write(_ name: String, _ bytes: Data) throws { + let fd = openat(stage, name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + defer { close(fd) } + try bytes.withUnsafeBytes { raw in + var offset = 0 + while offset < raw.count { + let written = Darwin.write(fd, raw.baseAddress!.advanced(by: offset), raw.count - offset) + if written < 0, errno == EINTR { continue } + guard written > 0 else { throw POSIXError(.EIO) } + offset += written + } + } + guard fsync(fd) == 0 else { throw POSIXError(.EIO) } + } + try write("disk.dsk", frozen); try write("record.json", metadata) + guard fsync(stage) == 0, renameatx_np(parent, pending, parent, id, UInt32(RENAME_EXCL)) == 0 else { + throw failure("playtest_disk_commit_failed") + } + published = true + guard fsync(parent) == 0 else { throw failure("playtest_disk_commit_failed") } + return stored + }.value + } + + static func diskURL(directory: URL, id: String) throws -> URL { + try canonicalDirectory(directory).appendingPathComponent(identifier(id), isDirectory: true).appendingPathComponent("disk.dsk") + } +} + +/// One reviewed disk product. IDs bind the selection to this exact artifact; +/// keys bind retained copies to the same declared product across compatible builds. +struct MCPPlaytestMedium: Sendable { + let id: String + let name: String + let key: String + let baseSHA256: String + let data: Data + let provenance: MCPPlaytestDiskStore.Provenance + + static func identifier(artifactID: String, key: String) -> String { + CMOCProject.sha256(Data((artifactID + "\0" + key).utf8)) + } +} + +/// One approved artifact, one private worker process, bounded private media copies. +/// The worker's retained emulator globals never share the user's live machine. +@MainActor +final class MCPPlaytest { + static let mutationRequestLimit = 1024 + static let audioFieldLimit = 120 + static let audioCaptureLimit = 16 + static let audioByteLimit = 4 * 1024 * 1024 + private static let maximumAudioClipBytes = 44 + 131_072 * 4 + let runID: String + let projectID: String + let revision: Int + let artifactID: String + let processor: MCPPlaytestProcessor + private(set) var startReceipt: [String: Any] = [:] + private(set) var retainedDiskURL: URL? + private(set) var retainedDiskRecord: MCPPlaytestDiskStore.Record? + private(set) var retentionError: String? + private(set) var finalReceipt: [String: Any]? + private let worker: Worker + private let retentionDirectory: URL + private let diskProvenance: MCPPlaytestDiskStore.Provenance + private let resumedDiskID: String? + private var exportedDisk: Data? + private var exportedStatus: [String: Any]? + private var persistenceTask: Task<[String: Any], Error>? + private static var pendingRetentions: [String: MCPPlaytest] = [:] + private var cleanupTask: Task? + private var valid = true + private var busy = false + private var finished = false + private var accepted: [String: (Data, [String: Any])] = [:] + private var mutationRequestsAccepted = 0 + private var audioCapturesAccepted = 0 + private var audioBytesRetained = 0 + private var stopRequestID: String? + + private struct MediumState { + let source: MCPPlaytestMedium + var data: Data + var dirty = false + var retained: MCPPlaytestDiskStore.Record? + var pendingRecordID: String? + } + private var media: [String: MediumState]? + private var mediaOrder: [String] = [] + private var mountedMediaID: String? + private var mediaExchangeTask: Task<[String: Any], Error>? + private var mediaFailures: [String: (Data, String)] = [:] + private var mediaCommitPending = false + private var pendingMediaSelection: String? + private var lastSafeMediaExport: [String: Any]? + + private init(worker: Worker, projectID: String, revision: Int, artifactID: String, retentionDirectory: URL, + diskProvenance: MCPPlaytestDiskStore.Provenance, resumedDiskID: String?, runID: String, + processor: MCPPlaytestProcessor, media: [MCPPlaytestMedium]?) { + self.runID = runID + self.worker = worker; self.projectID = projectID; self.revision = revision; self.artifactID = artifactID + self.retentionDirectory = retentionDirectory; self.diskProvenance = diskProvenance; self.resumedDiskID = resumedDiskID + self.processor = processor + if let media { + self.media = Dictionary(uniqueKeysWithValues: media.map { ($0.id, MediumState(source: $0, data: $0.data)) }) + self.mediaOrder = media.map(\.id); self.mountedMediaID = media.first?.id + } + } + + static func start(systemROM: Data, diskROM: Data, disk: Data, bootCommands: String, + projectID: String, revision: Int, artifactID: String, + modules: [[String: Any]] = [], stopAt: UInt16? = nil, stopModule: String? = nil, flatGuards: [[String: Any]] = [], cpu: String = "6809", helperURL: URL? = nil, retentionDirectory: URL? = nil, + diskProvenance: MCPPlaytestDiskStore.Provenance? = nil, resumedDiskID: String? = nil, + graphicsBuffers: [[String: Any]] = [], runID: String = UUID().uuidString, + media: [MCPPlaytestMedium]? = nil) async throws -> MCPPlaytest { + guard let reservedID = UUID(uuidString: runID) else { throw failure("invalid_playtest_run_id") } + guard systemROM.count == 32768, diskROM.count == 8192, !disk.isEmpty, disk.count <= 512 * 1024, + ["6809", "6309"].contains(cpu), bootCommands.utf8.count <= 256 else { throw failure("invalid_playtest_artifact") } + for pending in Array(pendingRetentions.values) { try? await pending.retainForReplacement() } + guard pendingRetentions.isEmpty else { throw failure("playtest_retention_recovery_required") } + let provenance = diskProvenance ?? MCPPlaytestDiskStore.Provenance(projectKey: CMOCProject.sha256(Data(projectID.utf8)), + artifactID: artifactID, artifactDiskSHA256: CMOCProject.sha256(disk)) + try MCPPlaytestDiskStore.validate(provenance) + guard provenance.artifactID == artifactID else { throw failure("invalid_playtest_disk_provenance") } + if let resumedDiskID { + guard diskProvenance != nil, let parent = UUID(uuidString: resumedDiskID), + let recorded = provenance.parentDiskID.flatMap(UUID.init(uuidString:)), parent == recorded else { throw failure("invalid_retained_disk_receipt") } + } else { + guard provenance.parentDiskID == nil, provenance.origin == "verified_artifact", + provenance.artifactDiskSHA256 == CMOCProject.sha256(disk) else { throw failure("invalid_playtest_disk_provenance") } + } + if let media { + guard (1...9).contains(media.count), media.first?.key == "primary", media.first?.data == disk, media.first?.provenance == provenance, + Set(media.map(\.id)).count == media.count, Set(media.map(\.key)).count == media.count else { + throw failure("invalid_playtest_media") + } + for item in media { + try MCPPlaytestDiskStore.validate(item.provenance) + guard item.id == MCPPlaytestMedium.identifier(artifactID: artifactID, key: item.key), + item.provenance.artifactID == artifactID, + item.provenance.projectKey == provenance.projectKey, + item.provenance.artifactDiskSHA256 == provenance.artifactDiskSHA256, + item.provenance.mediaKey == item.key, + item.provenance.mediaBaseSHA256 == item.baseSHA256, + !item.data.isEmpty, item.data.count <= 512 * 1024, + item.provenance.parentDiskID != nil || CMOCProject.sha256(item.data) == item.baseSHA256 else { + throw failure("invalid_playtest_media") + } + } + } + let paste = try CocoPaste(bootCommands, mode: .text) + guard paste.chords.count <= 256 else { throw failure("invalid_playtest_boot") } + let helper = helperURL ?? Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/vcc-playtest") + let worker = try Worker(helper: helper) + let test = MCPPlaytest(worker: worker, projectID: projectID, revision: revision, artifactID: artifactID, + retentionDirectory: retentionDirectory ?? AppIdentity.supportDirectory.appendingPathComponent("Development Runs/Assistant Playtests"), + diskProvenance: provenance, resumedDiskID: resumedDiskID.map { UUID(uuidString: $0)!.uuidString }, runID: reservedID.uuidString, + processor: cpu == "6309" ? .hd6309 : .mc6809, media: media) + var setup: [String: Any] = ["op": "init", "system_rom": systemROM.base64EncodedString(), + "disk_rom": diskROM.base64EncodedString(), "disk": disk.base64EncodedString(), + "boot_keys": paste.chords.map { NSNumber(value: $0) }, "modules": modules, "cpu": cpu, + "graphics_buffers": graphicsBuffers, "flat_guards": flatGuards] + if let media { setup["media_id"] = media[0].id } + if let stopAt { + guard (modules.isEmpty && !flatGuards.isEmpty && stopModule == nil) || + (!modules.isEmpty && flatGuards.isEmpty && stopModule != nil) else { + await test.invalidate().value; throw failure("unverified_stop_module") + } + setup["stop_at"] = Int(stopAt) + if let stopModule { setup["stop_module"] = stopModule } + } + do { + let result = try await worker.request(setup) + guard result["cpu"] as? String == cpu, result["processor"] as? String == test.processor.rawValue else { + throw failure("playtest_processor_mismatch") + } + test.startReceipt = test.scoped(result) + return test + } catch { + await test.invalidate().value + throw error + } + } + + @discardableResult func invalidate() -> Task { + if let cleanupTask { return cleanupTask } + valid = false + let cleanup = Task { [self] in + do { _ = try await persistStoppedDisk() } + catch { + retentionError = error.localizedDescription + // Revoked access stays revoked. Keep the exported immutable + // bytes alive for a retry instead of discarding a saved disk. + if exportedDisk != nil { Self.pendingRetentions[runID] = self } + else { worker.close() } + } + if finished { worker.close() } + } + cleanupTask = cleanup + return cleanup + } + + /// Replacement is allowed only after durable retention. A failed write + /// leaves the exported disk in memory; retry never sends a second STOP. + func retainForReplacement() async throws { + guard !busy else { throw Self.failure("playtest_busy") } + busy = true; defer { busy = false } + _ = try await persistStoppedDisk() + } + + private func persistStoppedDisk() async throws -> [String: Any] { + if finished, let finalReceipt { return finalReceipt } + if let persistenceTask { return try await persistenceTask.value } + let task = Task { try await performDiskPersistence() } + persistenceTask = task + do { + let result = try await task.value + persistenceTask = nil + return result + } catch { + persistenceTask = nil + throw error + } + } + + private func performDiskPersistence() async throws -> [String: Any] { + if finished, let finalReceipt { return finalReceipt } + if media != nil { return try await performMediaPersistence() } + if exportedDisk == nil { + var result = try await worker.request(["op": "stop"]) + guard let encoded = result.removeValue(forKey: "disk_base64") as? String, + let data = Data(base64Encoded: encoded), !data.isEmpty, data.count <= 512 * 1024 else { + throw Self.failure("playtest_disk_export_failed") + } + exportedDisk = Data(data); exportedStatus = result + } + guard let data = exportedDisk else { throw Self.failure("playtest_disk_export_failed") } + do { + let record = try await MCPPlaytestDiskStore.save(directory: retentionDirectory, runID: runID, data: data, provenance: diskProvenance) + retainedDiskRecord = record + retainedDiskURL = try MCPPlaytestDiskStore.diskURL(directory: retentionDirectory, id: record.id) + var result = exportedStatus ?? [:] + result["disk_retained"] = true; result["retained_disk_id"] = record.id + result["retained_disk_sha256"] = record.diskSHA256; result["retained_disk"] = record.publicFields + result["status"] = "stopped" + finished = true; retentionError = nil; worker.close() + let receipt = scoped(result) + finalReceipt = receipt; exportedDisk = nil; exportedStatus = nil + Self.pendingRetentions.removeValue(forKey: runID) + return receipt + } catch { + retentionError = error.localizedDescription + Self.pendingRetentions[runID] = self + throw error + } + } + + private func mediaFields(status: [String: Any]) -> [String: Any] { + var fields = status + let actualID = status["media_id"] == nil ? mountedMediaID : status["media_id"] as? String + let present = status["disk_present"] as? Bool ?? (mountedMediaID != nil) + fields["drive"] = "FD0" + fields["media"] = mediaOrder.compactMap { id -> [String: Any]? in + guard let item = media?[id] else { return nil } + let mounted = present && actualID == id + let hash = mounted ? status["disk_sha256"] as? String ?? CMOCProject.sha256(item.data) : CMOCProject.sha256(item.data) + var row: [String: Any] = ["media_id": id, "name": item.source.name, "media_key": item.source.key, + "base_sha256": item.source.baseSHA256, "media_sha256": hash, "byte_count": item.data.count, + "inserted": mounted, "dirty": mounted ? status["disk_dirty"] as? Bool ?? item.dirty : item.dirty, + "modified_from_artifact": hash != item.source.baseSHA256, + "retained": item.retained?.diskSHA256 == hash] + if let record = item.retained { row["retained_disk"] = record.publicFields } + if let parent = item.source.provenance.parentDiskID { row["resumed_from_disk_id"] = parent } + return row + } + return fields + } + + /// Only called with a bounded, complete export from the app-owned helper. + /// Keep these bytes even if the lease was revoked while the pipe was read. + private func receiveMediaExport(_ status: [String: Any]) throws { + guard media != nil, let present = status["disk_present"] as? Bool else { throw Self.failure("invalid_playtest_media_reply") } + if !present { + guard (mountedMediaID == nil || (mediaCommitPending && pendingMediaSelection == nil)), + status["disk_base64"] == nil, (status["disk_sha256"] as? String) == "" else { + throw Self.failure("invalid_playtest_media_reply") + } + mountedMediaID = nil + return + } + guard let id = status["media_id"] as? String, + id == mountedMediaID || (mediaCommitPending && id == pendingMediaSelection), + var item = media?[id], + let encoded = status["disk_base64"] as? String, let bytes = Data(base64Encoded: encoded), + !bytes.isEmpty, bytes.count <= 512 * 1024, CMOCProject.sha256(bytes) == status["disk_sha256"] as? String else { + throw Self.failure("invalid_playtest_media_reply") + } + if item.data != bytes { item.pendingRecordID = nil } + item.data = bytes; item.dirty = status["disk_dirty"] as? Bool ?? false + media?[id] = item; mountedMediaID = id + } + + private func retainMedium(_ id: String) async throws -> MCPPlaytestDiskStore.Record { + guard var item = media?[id] else { throw Self.failure("invalid_playtest_media_selection") } + let hash = CMOCProject.sha256(item.data) + if let existing = item.retained, existing.diskSHA256 == hash { return existing } + let recordID = item.pendingRecordID ?? UUID().uuidString + item.pendingRecordID = recordID; media?[id] = item + let stored = try await MCPPlaytestDiskStore.save(directory: retentionDirectory, runID: runID, + data: item.data, provenance: item.source.provenance, recordID: recordID) + // The paused worker and serialized owner cannot change this medium + // during the off-main-thread durable write. + guard var current = media?[id], current.data == item.data else { throw Self.failure("playtest_media_changed") } + current.retained = stored; current.pendingRecordID = nil; media?[id] = current + return stored + } + + private func exchangeMedia(_ selected: String?, expectedSHA: String?, isCurrent: (() -> Bool)?) async throws -> [String: Any] { + guard valid, isCurrent?() != false else { throw Self.failure("stale_run") } + let before = try await worker.request(["op": "export_media"]) + let expectedOldID = mountedMediaID + try receiveMediaExport(before) + guard mountedMediaID == expectedOldID, valid, isCurrent?() != false, + let generation = before["media_generation"] as? NSNumber, + let oldHash = before["disk_sha256"] as? String else { throw Self.failure("stale_playtest_media") } + if let selected { + guard let item = media?[selected], expectedSHA == CMOCProject.sha256(item.data) else { + throw Self.failure("playtest_media_hash_mismatch") + } + } + var old: [String: Any] = ["media_id": expectedOldID as Any? ?? NSNull(), "media_sha256": oldHash, + "dirty": before["disk_dirty"] as? Bool ?? false, "retained": false] + if let expectedOldID { + let retained = try await retainMedium(expectedOldID) + old["retained"] = true; old["retained_disk"] = retained.publicFields + } + // Retention can yield to a project edit, rebuild or revocation. Never + // commit a disk exchange after that ownership/evidence boundary changes. + guard valid, isCurrent?() != false else { throw Self.failure("stale_run") } + var request: [String: Any] = ["op": "exchange_media", "expected_media_generation": generation, + "expected_disk_sha256": oldHash] + if let selected, let item = media?[selected] { + request["media_id"] = selected; request["disk_base64"] = item.data.base64EncodedString() + } + lastSafeMediaExport = before + mediaCommitPending = true; pendingMediaSelection = selected + let after: [String: Any] + do { after = try await worker.request(request) } + catch let error as WorkerRejection { mediaCommitPending = false; pendingMediaSelection = nil; throw error } + // Commit is already complete. Record the mounted identity before a + // possible late revocation so cleanup exports the actual served copy. + mountedMediaID = selected; mediaCommitPending = false; pendingMediaSelection = nil + let selectedSHA = selected.flatMap { media?[$0] }.map { CMOCProject.sha256($0.data) } ?? "" + guard after["disk_sha256"] as? String == selectedSHA, + after["previous_disk_sha256"] as? String == oldHash, + after["media_id"] as? String == selected, + (after["disk_present"] as? Bool) == (selected != nil), + (after["media_generation"] as? NSNumber)?.intValue == generation.intValue + 1 else { + throw WorkerTransportFailure(reason: "invalid_playtest_media_reply") + } + for key in ["field_clock", "cycles", "generation", "boot", "pc"] { + guard let prior = before[key] as? NSNumber, let current = after[key] as? NSNumber, prior == current else { + throw WorkerTransportFailure(reason: "playtest_media_advanced_guest") + } + } + var result = mediaFields(status: after) + result["previous_media"] = old + result["exchange"] = selected == nil ? "ejected" : "inserted" + result["guest_advanced"] = false; result["guest_reset"] = false + return result + } + + private func performMediaPersistence() async throws -> [String: Any] { + if let pending = mediaExchangeTask { _ = await pending.result } + if finished, let finalReceipt { return finalReceipt } + if exportedDisk == nil { + var result: [String: Any] + do { + result = try await worker.request(["op": "stop"]) + try receiveMediaExport(result) + } catch let error as WorkerTransportFailure { + // A failed swap pipe cannot have advanced a paused guest. + // Every candidate copy is already frozen in the host; retain + // those bytes while reporting the unknown final selection. + guard let frozen = lastSafeMediaExport else { throw error } + result = frozen; result["media_selection_uncertain"] = true + result["media_id"] = NSNull(); result["disk_present"] = false + result["disk_sha256"] = NSNull(); result["media_generation"] = NSNull() + mountedMediaID = nil + } + mediaCommitPending = false; pendingMediaSelection = nil + result.removeValue(forKey: "disk_base64") + exportedStatus = result + // A nonempty frozen primary also marks an ejected-drive stop as + // retryable retention, without issuing a second STOP on failure. + guard let primary = mediaOrder.first, let bytes = media?[primary]?.data else { throw Self.failure("invalid_playtest_media") } + exportedDisk = bytes + } + do { + var retained: [[String: Any]] = [] + for id in mediaOrder { + let record = try await retainMedium(id) + var fields = record.publicFields; fields["media_id"] = id + fields["name"] = media?[id]?.source.name + retained.append(fields) + } + guard let primary = mediaOrder.first, let record = media?[primary]?.retained else { throw Self.failure("playtest_disk_export_failed") } + retainedDiskRecord = record; retainedDiskURL = try MCPPlaytestDiskStore.diskURL(directory: retentionDirectory, id: record.id) + var result = mediaFields(status: exportedStatus ?? [:]) + result["disk_retained"] = true; result["retained_disk_id"] = record.id + result["retained_disk_sha256"] = record.diskSHA256; result["retained_disk"] = record.publicFields + result["retained_media"] = retained; result["status"] = "stopped" + finished = true; retentionError = nil; worker.close() + let receipt = scoped(result); finalReceipt = receipt + exportedDisk = nil; exportedStatus = nil; Self.pendingRetentions.removeValue(forKey: runID) + return receipt + } catch { + retentionError = error.localizedDescription; Self.pendingRetentions[runID] = self + throw error + } + } + + /// The host rechecks project/revision/artifact identity before dispatching. + /// Cached write receipts are still bound to this live lease, never replayed. + func reply(_ tool: String, arguments: [String: Any], isCurrent: (() -> Bool)? = nil) async throws -> [String: Any] { + guard valid, arguments["run_id"] as? String == runID else { throw Self.failure("stale_run") } + guard !busy else { throw Self.failure("playtest_busy") } + busy = true + defer { busy = false } + if tool == "list_playtest_media" { + guard arguments.count == 1, media != nil else { throw Self.failure("invalid_arguments") } + if finished, let finalReceipt { return finalReceipt } + if exportedDisk != nil { return scoped(mediaFields(status: exportedStatus ?? [:])) } + let status = try await worker.request(["op": "media_status"]) + guard valid else { throw Self.failure("stale_run") } + return scoped(mediaFields(status: status)) + } + if tool == "capture_playtest_graphics" { + guard !finished, exportedDisk == nil, + Set(arguments.keys).isSubset(of: ["run_id", "buffer_id"]), (1...2).contains(arguments.count) else { throw Self.failure("invalid_arguments") } + var request: [String: Any] = ["op": "graphics_capture"] + if let value = arguments["buffer_id"] { + guard let id = value as? String, (1...64).contains(id.utf8.count), + id.utf8.allSatisfy({ (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) || $0 == 95 || $0 == 45 }) else { throw Self.failure("invalid_buffer_id") } + request["buffer_id"] = id + } + let result = try await worker.request(request) + guard valid else { throw Self.failure("stale_run") } + return scoped(result) + } + if tool == "capture_playtest" { + guard arguments.count == 1 else { throw Self.failure("invalid_arguments") } + if finished, let finalReceipt { return finalReceipt } + if exportedDisk != nil { return scoped(["status": "retention_pending", "disk_retained": false]) } + let result = try await worker.request(["op": "capture"]) + guard valid else { throw Self.failure("stale_run") } + return scoped(result) + } + if tool == "get_playtest_input" { + guard arguments.count == 1, !finished, exportedDisk == nil else { throw Self.failure("invalid_arguments") } + let result = try await worker.request(["op": "input_status"]) + guard valid else { throw Self.failure("stale_run") } + return scoped(result) + } + guard let requestID = arguments["request_id"] as? String, (1...64).contains(requestID.utf8.count), + ["playtest_input", "restart_playtest", "stop_playtest", "playtest_debug", "capture_playtest_audio", "exchange_playtest_media"].contains(tool) else { throw Self.failure("invalid_arguments") } + let signature = try JSONSerialization.data(withJSONObject: ["tool": tool, "arguments": arguments], options: [.sortedKeys]) + if let (prior, reason) = mediaFailures[requestID] { + guard signature == prior else { throw Self.failure("request_conflict") } + throw Self.failure(reason) + } + if let (prior, receipt) = accepted[requestID] { + guard signature == prior else { throw Self.failure("request_conflict") } + if tool != "stop_playtest" || receipt["status"] as? String != "retention_pending" { return receipt } + } + if tool == "stop_playtest", let stopRequestID, requestID != stopRequestID { + throw Self.failure("request_conflict: retry the original stop request_id") + } + guard exportedDisk == nil || tool == "stop_playtest" else { throw Self.failure("playtest_retention_pending") } + guard !finished else { throw Self.failure("stale_run") } + // Cleanup has its own single cached receipt and must remain possible + // after any execution/audio budget is exhausted. + guard tool == "stop_playtest" || mutationRequestsAccepted < Self.mutationRequestLimit || accepted[requestID] != nil else { + throw Self.failure("playtest_request_limit") + } + if tool == "exchange_playtest_media" { + guard media != nil, let action = arguments["action"] as? String, + ["insert", "eject"].contains(action), + Set(arguments.keys) == (action == "insert" ? ["run_id", "request_id", "action", "media_id", "media_sha256"] : ["run_id", "request_id", "action"]) else { + throw Self.failure("invalid_arguments") + } + let selected: String? + if action == "insert" { + guard let id = arguments["media_id"] as? String, media?[id] != nil, + let hash = arguments["media_sha256"] as? String, + hash.utf8.count == 64, hash.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }) else { + throw Self.failure("invalid_playtest_media_selection") + } + selected = id + } else { selected = nil } + mutationRequestsAccepted += 1 + accepted[requestID] = (signature, scoped(["request_id": requestID, "status": "interrupted"])) + let exchange = Task { try await self.exchangeMedia(selected, expectedSHA: arguments["media_sha256"] as? String, isCurrent: isCurrent) } + mediaExchangeTask = exchange + defer { mediaExchangeTask = nil } + var result: [String: Any] + do { + result = try await exchange.value + } catch let error as WorkerRejection { + accepted.removeValue(forKey: requestID); mediaFailures[requestID] = (signature, error.reason) + throw Self.failure(error.reason) + } catch let error as WorkerTransportFailure { + invalidate(); throw error + } catch { + // Validation/retention failures occur before the guarded commit. + accepted.removeValue(forKey: requestID); mediaFailures[requestID] = (signature, error.localizedDescription) + throw error + } + // The worker has acknowledged a committed exchange. Keep that + // outcome even if authority expired before the reply can be sent; + // a late stale lease is not a precommit validation failure. + result["request_id"] = requestID + let receipt = scoped(result); accepted[requestID] = (signature, receipt) + guard valid, isCurrent?() != false else { throw Self.failure("stale_run_after_commit") } + return receipt + } + var request: [String: Any] + switch tool { + case "capture_playtest_audio": + guard arguments.count == 3, let n = arguments["fields"] as? NSNumber, + CFGetTypeID(n) != CFBooleanGetTypeID(), n.doubleValue.isFinite, + n.doubleValue == Double(n.intValue), (1...Self.audioFieldLimit).contains(n.intValue) else { + throw Self.failure("invalid_arguments") + } + guard audioCapturesAccepted < Self.audioCaptureLimit, + audioBytesRetained <= Self.audioByteLimit - Self.maximumAudioClipBytes else { + throw Self.failure("playtest_audio_capture_limit") + } + request = ["op": "audio_capture", "fields": n.intValue] + case "playtest_input": + guard arguments.count == 3, let steps = arguments["steps"] as? [[String: Any]], (1...64).contains(steps.count) else { throw Self.failure("invalid_arguments") } + var plan: [[String: Any]] = [], total = 0 + for step in steps { + guard Set(step.keys).isSubset(of: ["keys", "fields", "joysticks"]), + let keys = step["keys"] as? [String], keys.count <= 8, + Set(keys).count == keys.count, let n = step["fields"] as? NSNumber, + CFGetTypeID(n) != CFBooleanGetTypeID(), n.doubleValue.isFinite, + n.doubleValue == Double(n.intValue), (1...600).contains(n.intValue) else { throw Self.failure("invalid_arguments") } + let mask = try keys.reduce(UInt64(0)) { value, key in + guard let chord = Self.chord(key) else { throw Self.failure("invalid_playtest_key") } + return value | chord + } + total += n.intValue + guard total <= 3600 else { throw Self.failure("playtest_input_limit") } + var translated: [String: Any] = ["mask": NSNumber(value: mask), "fields": n.intValue] + if let joysticks = step["joysticks"] { translated["joysticks"] = try MCPPlaytestJoystick.snapshots(joysticks) } + plan.append(translated) + } + request = ["op": "input", "steps": plan] + case "playtest_debug": + guard let action = arguments["action"] as? String else { throw Self.failure("invalid_arguments") } + if action == "stop_at" { + guard (5...6).contains(arguments.count), + Set(arguments.keys).isSubset(of: ["run_id", "request_id", "action", "selection", "module_id", "address"]), + arguments["selection"] == nil || arguments["selection"] is String, + arguments["module_id"] == nil || ((arguments["module_id"] as? String)?.isEmpty == false), + let address = arguments["address"] as? NSNumber, + CFGetTypeID(address) != CFBooleanGetTypeID(), address.doubleValue == Double(address.intValue), + (0...65535).contains(address.intValue) else { throw Self.failure("invalid_arguments") } + request = ["op": "stop_at", "address": address.intValue] + if let module = arguments["module_id"] { request["module_id"] = module } + } else { + guard arguments.count == 3, ["pause", "continue", "step"].contains(action) else { throw Self.failure("invalid_arguments") } + request = ["op": action] + } + case "restart_playtest": + guard arguments.count == 2 else { throw Self.failure("invalid_arguments") } + request = ["op": "restart"] + default: + guard arguments.count == 2 else { throw Self.failure("invalid_arguments") } + request = ["op": "stop"] + } + // Reserve the identity before execution. An interrupted operation must + // never be retried as a new input sequence with the same request ID. + if tool == "stop_playtest" { stopRequestID = requestID } + if tool != "stop_playtest" { mutationRequestsAccepted += 1 } + if tool == "capture_playtest_audio" { audioCapturesAccepted += 1 } + accepted[requestID] = (signature, scoped(["request_id": requestID, "status": "interrupted"])) + if tool == "stop_playtest" { + do { + var result = try await persistStoppedDisk() + result["request_id"] = requestID + finalReceipt = result; accepted[requestID] = (signature, result) + return result + } catch { + if exportedDisk != nil { + accepted[requestID] = (signature, scoped(["status": "retention_pending", "disk_retained": false])) + } else { invalidate() } + throw error + } + } + do { + lastSafeMediaExport = nil + var result = try await worker.request(request) + guard valid else { throw Self.failure("stale_run") } + if tool == "capture_playtest_audio" { + guard let encoded = result["audio_wav_base64"] as? String, + let wav = Data(base64Encoded: encoded), (44...Self.maximumAudioClipBytes).contains(wav.count), + let metadata = result["audio"] as? [String: Any], + metadata["sha256"] as? String == CMOCProject.sha256(wav), + (metadata["byte_count"] as? NSNumber)?.intValue == wav.count else { + throw Self.failure("invalid_playtest_audio") + } + audioBytesRetained += wav.count + } + result["request_id"] = requestID + let receipt = scoped(result) + accepted[requestID] = (signature, receipt) + return receipt + } catch { + // The worker can have advanced before a broken pipe/timeout. Retire + // this run rather than allowing uncertain input to execute twice. + invalidate() + throw error + } + } + + func capture() async throws -> [String: Any] { + try await reply("capture_playtest", arguments: ["run_id": runID]) + } + + /// Private app-side immutable snapshot. Raw memory never crosses the grant: + /// MCPCMOC applies verified source ranges and named-watch rules first. + func debugCapture() async throws -> [String: Any] { try await command(["op": "debug"]) } + func continuePlaytest() async throws -> [String: Any] { try await command(["op": "continue"]) } + func pausePlaytest() async throws -> [String: Any] { try await command(["op": "pause"]) } + func stepPlaytest() async throws -> [String: Any] { try await command(["op": "step"]) } + func stopAt(_ address: UInt16, moduleID: String) async throws -> [String: Any] { try await command(["op": "stop_at", "address": Int(address), "module_id": moduleID]) } + + private func command(_ request: [String: Any]) async throws -> [String: Any] { + guard valid, !finished else { throw Self.failure("stale_run") } + guard exportedDisk == nil else { throw Self.failure("playtest_retention_pending") } + guard !busy else { throw Self.failure("playtest_busy") } + busy = true + defer { busy = false } + if let operation = request["op"] as? String, ["continue", "step", "stop_at"].contains(operation) { lastSafeMediaExport = nil } + let result = try await worker.request(request) + guard valid else { throw Self.failure("stale_run") } + return scoped(result) + } + + private func scoped(_ result: [String: Any]) -> [String: Any] { + var result = result + result["run_id"] = runID; result["project_id"] = projectID + result["revision"] = revision; result["artifact_id"] = artifactID + result["requested_processor"] = processor.rawValue + result["mutation_request_limit"] = Self.mutationRequestLimit + result["mutation_requests_used"] = mutationRequestsAccepted + result["remaining_mutation_requests"] = max(0, Self.mutationRequestLimit - mutationRequestsAccepted) + result["stop_retention_exempt"] = true + result["audio_capture_limit"] = Self.audioCaptureLimit + result["remaining_audio_captures"] = max(0, Self.audioCaptureLimit - audioCapturesAccepted) + result["audio_byte_limit"] = Self.audioByteLimit + result["remaining_audio_bytes"] = max(0, Self.audioByteLimit - audioBytesRetained) + result["artifact_disk_sha256"] = diskProvenance.artifactDiskSHA256 as Any? ?? NSNull() + result["disk_origin"] = diskProvenance.origin; result["disk_provenance"] = diskProvenance.publicFields + if media != nil { + result["media_exchange"] = true + result["boot_disk_provenance"] = diskProvenance.publicFields + if let id = mountedMediaID, let current = media?[id] { + result["disk_origin"] = current.source.provenance.origin + result["disk_provenance"] = current.source.provenance.publicFields + } else { + result["disk_origin"] = NSNull(); result["disk_provenance"] = NSNull() + } + } + if let resumedDiskID { result["resumed_from_disk_id"] = resumedDiskID } + return result + } + + /// Names identify physical CoCo keys, independently of host keyboard layout. + static func chord(_ key: String) -> UInt64? { + let special: [String: Int] = ["up": 27, "down": 28, "left": 29, "backspace": 29, "right": 30, + "space": 31, "enter": 48, "clear": 49, "break": 50, "alt": 51, + "control": 52, "f1": 53, "f2": 54, "shift": 55, "period": 46] + if let bit = special[key] { return UInt64(1) << bit } + if key.utf8.count == 1, let c = key.utf8.first, + (97...122).contains(c) || (48...57).contains(c) { return CocoKeyboard.chord(for: key) } + return nil + } + + nonisolated private static func failure(_ value: String) -> ProfileFailure { .message(value) } + + /// Blocking pipe I/O stays on this dedicated queue. Deadline termination + /// also releases the worker's held keys, media and core globals by exit. + private struct WorkerTransportFailure: LocalizedError { + let reason: String + var errorDescription: String? { reason } + } + + private struct WorkerRejection: LocalizedError { + let reason: String + var errorDescription: String? { reason } + } + + private final class Worker: @unchecked Sendable { + private let process = Process() + private let input = Pipe(), output = Pipe() + private let queue = DispatchQueue(label: "com.brianholman.vccplus.playtest") + private var buffered = Data() + init(helper: URL) throws { + process.executableURL = helper + process.arguments = [] + process.standardInput = input; process.standardOutput = output + _ = fcntl(input.fileHandleForWriting.fileDescriptor, F_SETNOSIGPIPE, 1) + process.standardError = FileHandle.nullDevice + try process.run() + } + func close() { + if process.isRunning { process.terminate() } + } + func request(_ request: [String: Any]) async throws -> [String: Any] { + let data = try JSONSerialization.data(withJSONObject: request, options: [.sortedKeys]) + guard data.count <= 1024 * 1024 else { throw MCPPlaytest.failure("playtest_message_limit") } + return try await withCheckedThrowingContinuation { continuation in + queue.async { + let watchdog = DispatchWorkItem { [self] in close() } + DispatchQueue.global().asyncAfter(deadline: .now() + 45, execute: watchdog) + defer { watchdog.cancel() } + do { + guard self.process.isRunning else { throw MCPPlaytest.failure("playtest_worker_unavailable") } + try self.input.fileHandleForWriting.write(contentsOf: data + Data([10])) + while !self.buffered.contains(10) { + // FileHandle.read(upToCount:) can wait to fill its + // requested length on a pipe. JSONL replies may be + // much shorter while the worker waits for a new + // command, so use one POSIX read of available bytes. + var chunk = [UInt8](repeating: 0, count: 4096) + let count = chunk.withUnsafeMutableBytes { + Darwin.read(self.output.fileHandleForReading.fileDescriptor, $0.baseAddress, $0.count) + } + if count < 0 && errno == EINTR { continue } + guard count > 0 else { throw MCPPlaytest.failure("playtest_worker_unavailable") } + self.buffered.append(contentsOf: chunk.prefix(count)) + guard self.buffered.count <= 1024 * 1024 else { throw MCPPlaytest.failure("playtest_message_limit") } + } + let end = self.buffered.firstIndex(of: 10)! + let line = self.buffered[.. Data + let unixPath: String + let port: UInt16 + private let directory: URL + private let queue = DispatchQueue(label: "vcc.mcp.accept") + private let slots = DispatchSemaphore(value: 8) + private var listeners: [DispatchSourceRead] = [] + + private static func checked(_ rc: Int32) throws -> Int32 { + guard rc >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + return rc + } + + init(handler: @escaping Handler) throws { + directory = URL(fileURLWithPath: "/private/tmp/vcc-mcp-" + UUID().uuidString) + unixPath = directory.appendingPathComponent("host.sock").path + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false, + attributes: [.posixPermissions: 0o700]) + var sockets: [Int32] = [] + do { + let uds = try Self.checked(socket(AF_UNIX, SOCK_STREAM, 0)) + sockets.append(uds) + var un = sockaddr_un() + un.sun_family = sa_family_t(AF_UNIX) + let path = Array(unixPath.utf8CString) + guard path.count <= MemoryLayout.size(ofValue: un.sun_path) else { throw POSIXError(.ENAMETOOLONG) } + withUnsafeMutableBytes(of: &un.sun_path) { dest in + path.withUnsafeBytes { dest.copyBytes(from: $0) } + } + un.sun_len = UInt8(MemoryLayout.size) + try Self.bindSocket(uds, &un) + let tcp = try Self.checked(socket(AF_INET, SOCK_STREAM, 0)) + sockets.append(tcp) + var addr = sockaddr_in() + addr.sin_family = sa_family_t(AF_INET) + addr.sin_len = UInt8(MemoryLayout.size) + addr.sin_addr.s_addr = inet_addr("127.0.0.1") + try Self.bindSocket(tcp, &addr) + var size = socklen_t(MemoryLayout.size) + _ = try Self.checked(withUnsafeMutablePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(tcp, $0, &size) } + }) + port = UInt16(bigEndian: addr.sin_port) + for fd in sockets { + _ = try Self.checked(fcntl(fd, F_SETFL, O_NONBLOCK)) + _ = try Self.checked(fcntl(fd, F_SETFD, FD_CLOEXEC)) + _ = try Self.checked(listen(fd, 8)) + } + for fd in sockets { + let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: queue) + source.setEventHandler { [slots] in + let peer = accept(fd, nil, nil) + guard peer >= 0 else { return } + guard slots.wait(timeout: .now()) == .success else { close(peer); return } + // Spawn a bounded worker; synchronous socket IO never runs on Swift's executor. + DispatchQueue.global(qos: .utility).async { + func finish() { close(peer); slots.signal() } + if fd == uds { + var uid: uid_t = 0, gid: gid_t = 0 + guard getpeereid(peer, &uid, &gid) == 0, uid == geteuid() else { finish(); return } + } + var yes: Int32 = 1 + var timeout = timeval(tv_sec: 3, tv_usec: 0) + guard fcntl(peer, F_SETFD, FD_CLOEXEC) == 0, fcntl(peer, F_SETFL, 0) == 0, + setsockopt(peer, SOL_SOCKET, SO_NOSIGPIPE, &yes, socklen_t(MemoryLayout.size(ofValue: yes))) == 0, + setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) == 0, + setsockopt(peer, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) == 0, + let request = Self.readLine(peer) else { finish(); return } + Task { + let response = await handler(request) + DispatchQueue.global(qos: .utility).async { + Self.writeResponse(response, to: peer) + finish() + } + } + } + } + source.setCancelHandler { close(fd) } + listeners.append(source) + source.resume() + } + } catch { + for fd in sockets { close(fd) } + try? FileManager.default.removeItem(at: directory) + throw error + } + } + + private static func bindSocket(_ fd: Int32, _ addr: inout T) throws { + _ = try checked(withUnsafePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, socklen_t(MemoryLayout.size)) } + }) + } + + private static func readLine(_ fd: Int32) -> Data? { + let deadline = DispatchTime.now() + .seconds(5) + let limit = 48 * 1024 + var data = Data(), buffer = [UInt8](repeating: 0, count: 1024) + while data.count < limit && DispatchTime.now() < deadline { + let size = recv(fd, &buffer, min(limit - data.count, buffer.count), 0) + guard size > 0 else { return nil } + let bytes = buffer.prefix(size) + if let lf = bytes.firstIndex(of: 10) { + data.append(contentsOf: bytes[.. 0 else { return } + offset += n + } + } + } + + func stop() { + for listener in listeners { listener.cancel() } + listeners.removeAll() + try? FileManager.default.removeItem(at: directory) + } + deinit { stop() } +} diff --git a/platforms/macos/App/MachineInterface.swift b/platforms/macos/App/MachineInterface.swift new file mode 100644 index 0000000..0c7a25f --- /dev/null +++ b/platforms/macos/App/MachineInterface.swift @@ -0,0 +1,432 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit +import Combine + +extension MachineModel { + var executionDescription: String { + state == .running ? (settings.fastForward ? "Fast-forward · Sound silenced" : "Running") : state == .paused ? "Paused" : state == .closed ? "Stopped" : "Ready" + } + var tapeTransportDescription: String { + if tapeMode == 2 { return tapeMotor ? "Recording — export to save" : "Recording ready — waiting for the computer" } + if tapeMode == 1 { return tapeMotor ? "Playing" : "Ready — waiting for the computer" } + return tapeMounted ? "Tape stopped" : "No tape inserted" + } + var needsMediaAttention: Bool { + mediaNeedsManualSave || !cartridgeRestoreErrors.isEmpty || !diskRestoreErrors.isEmpty || !diskSaveErrors.isEmpty || + !hardRestoreErrors.isEmpty || !hardSaveErrors.isEmpty || diskSettingsError != nil + } + func requestColdReset() { + let alert = NSAlert(); alert.messageText = "Cold restart the CoCo?" + alert.informativeText = "This clears RAM and your working program. Mounted media and their changes are retained." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Cold Restart") + if alert.runModal() == .alertSecondButtonReturn { reset() } + } + func requestOrchestraWithoutROM(_ slot: Int) { + guard !busy, !diskSaving, (0..<5).contains(slot) else { return } + let alert = NSAlert(); alert.messageText = "Remove the Orchestra-90 ROM and restart?" + alert.informativeText = "This clears the working program in RAM. Orchestra-90 stays connected for stereo playback by supporting software. The ROM file and mounted disks are kept." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Remove ROM and Restart") + if alert.runModal() == .alertSecondButtonReturn { assignCartridge(.orchestra90, slot: slot, useBundledROM: false) } + } + func requestCartridge(_ kind: CartridgeAssignments.Kind, slot: Int) { + let old = cartridgeAssignments.slots[slot] + guard old.kind != kind else { return } + let alert = NSAlert(); alert.messageText = "Change \(slot == 0 ? "the cartridge" : "slot \(slot)") and restart?" + alert.informativeText = "This clears the working program in RAM. \(old.kind == .empty ? "" : "The current slot assignment will be replaced. ")A controller already in another Multi-Pak slot moves here. Mounted disks and their changes are retained." + if old.kind == .ramDisk { + alert.informativeText += " RAM disk data is volatile and is lost when its last assignment is removed." + } + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Change and Restart") + if alert.runModal() == .alertSecondButtonReturn { assignCartridge(kind, slot: slot) } + } +} + +struct MachineView: View { + @Environment(\.openWindow) private var openWindow + @ObservedObject var machine: MachineModel + @ObservedObject var presentation: PresentationSettings + let showManualHome: () -> Void + @State private var help = false + @FocusState private var controlsFocused: Bool + private let refresh = Timer.publish(every: 1.0 / 30, on: .main, in: .common).autoconnect() + private var system: Bool { presentation.mode == .system && !machine.hardware.custom } + var body: some View { + VStack(spacing: 12) { + HStack { + Button { openWindow(id: "machine-settings") } label: { + HardwareBadge(name: "coco-" + HardwareState.ramKeys[machine.settings.ram], label: "Color Computer 3, \(MachineSettings.memoryLabels[machine.settings.ram])") + .frame(maxWidth: 440, maxHeight: 42) + }.buttonStyle(.plain).help("Open Machine Settings for processor and memory") + Spacer(minLength: 24) + Button { openWindow(id: "machine-settings") } label: { + HardwareBadge(name: machine.use6309 ? "hitachi" : "motorola", label: machine.use6309 ? "Hitachi 6309" : "Motorola 6809").frame(width: 44, height: 44) + }.buttonStyle(.plain).help("Open Machine Settings for processor and memory") + } + Divider() + toolbar + if presentation.mode == .system && machine.hardware.custom { + HStack { + Label("Custom configuration", systemImage: "info.circle").fontWeight(.medium) + Text("This hardware layout uses conventional controls; your setup is unchanged.").foregroundStyle(.secondary) + Spacer() + Button("Cartridges…") { openWindow(id: "cartridges") } + }.font(.callout) + } + MachineStage(machine: machine, presentation: presentation, system: system) { + showManualHome() + openWindow(id: "manual-library") + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(system ? Color(red: 0.945, green: 0.933, blue: 0.904) : Color(red: 0.10, green: 0.14, blue: 0.12)) + .clipShape(RoundedRectangle(cornerRadius: 8)) + .modifier(MediaDropTarget(machine: machine)) + status + if let error = machine.displayError ?? machine.fileError ?? machine.error ?? machine.profileError { + Text(error).foregroundStyle(.red).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) + .lineLimit(3).help(error) + } + if machine.needsMediaAttention { + HStack { + Label(machine.tapeDirty || machine.tapeMode == 2 ? "Tape recording needs export" : "Media needs attention", systemImage: "exclamationmark.circle") + .foregroundStyle(.orange) + Button("Cassette…") { openWindow(id: "cassette") } + Button("Floppies…") { openWindow(id: "disks") } + Button("Hard Disks…") { openWindow(id: "hard-disks") } + Button("Cartridges…") { openWindow(id: "cartridges") } + Spacer() + }.font(.callout) + } + }.padding(20).frame(minWidth: 940, minHeight: 590) + .task(id: machine.guideRequest) { + guard let request = machine.guideRequest, + presentation.shouldIntroduce(request.profile) else { return } + // Bring the existing emulator forward after a successful profile load. + // Allow its window and popover anchor to attach before presenting help. + openWindow(id: "machine") + do { try await Task.sleep(for: .milliseconds(300)) } catch { return } + guard !machine.busy, machine.guideRequest == request, + machine.usageProfile == request.profile else { return } + help = true + } + .onChange(of: presentation.controlsFocusRequest) { _, _ in controlsFocused = true } + .background(MacShellPermissionPresenter(machine: machine).frame(width: 0, height: 0).accessibilityHidden(true)) + .onReceive(refresh) { _ in machine.poll() } + .onReceive(NSWorkspace.shared.notificationCenter.publisher(for: NSWorkspace.willSleepNotification)) { _ in machine.pause() } + // Changing presentation never invokes pause, reset, reload or a media command. + } + private var toolbar: some View { + HStack(spacing: 10) { + Button { openWindow(id: "profiles") } label: { + Label(machine.profileName.map { $0 + (machine.profileModified ? " • Modified" : "") } ?? "Profiles", systemImage: "circle.grid.2x2") + .lineLimit(1).frame(maxWidth: 170, alignment: .leading) + }.focusable().focused($controlsFocused).accessibilityIdentifier("profiles-button") + .onKeyPress(.space) { openWindow(id: "profiles"); return .handled } + .help("Review and load saved setups. A profile saves settings, not the running program.") + Button { + if machine.state == .running { machine.pause() } else { machine.resume() } + } label: { Label(machine.state == .running ? "Pause" : "Run", systemImage: machine.state == .running ? "pause.fill" : "play.fill") } + .buttonStyle(.borderedProminent).disabled(machine.busy || machine.diskEditorLocked || machine.state == .empty || machine.state == .closed) + .accessibilityIdentifier("execution") + MachineRestartMenu(machine: machine).equatable() + MediaActionsMenu() + MachineSettingsMenu(machine: machine).equatable() + Spacer(minLength: 0) + Picker("Presentation", selection: $presentation.mode) { + Label("Display", systemImage: "display").tag(PresentationSettings.Mode.display) + Label("System", systemImage: "shippingbox").tag(PresentationSettings.Mode.system) + }.pickerStyle(.segmented).labelsHidden().frame(width: 194).accessibilityIdentifier("presentation") + .help("Change the presentation without changing the running machine") + }.controlSize(.large) + } + private var status: some View { + HStack(spacing: 12) { + if machine.pasteRemaining > 0 { + Button("Cancel Paste (\(machine.pasteRemaining) left)") { machine.cancelPaste() } + .monospacedDigit().frame(width: 210, alignment: .leading) + .help("Stop typing. Text already entered in the CoCo is retained.") + } + Label(machine.executionDescription, systemImage: machine.state == .running ? "play.circle.fill" : "pause.circle") + .foregroundStyle(.secondary).fixedSize() + Divider().frame(height: 18) + ScrollView(.horizontal) { + HStack(spacing: 16) { + ForEach(Array(machine.disks.enumerated()), id: \.offset) { i, disk in + if disk.mounted { Button("FD\(i) \(disk.name)") { openWindow(id: "disks") }.help(disk.name) } + } + ForEach(Array(machine.hardDisks.enumerated()), id: \.offset) { i, disk in + if disk.mounted { Button("HD\(i) \(disk.name)") { openWindow(id: "hard-disks") }.help(disk.name) } + } + if machine.tapeMounted { + Button("Tape \(machine.tapeName)\(machine.tapeDirty || machine.tapeMode == 2 ? " — Unsaved" : "")") { openWindow(id: "cassette") } + .help(machine.tapeTransportDescription) + } + }.buttonStyle(.link).lineLimit(1) + }.scrollIndicators(.hidden) + if system { + Button { presentation.expanded.toggle() } label: { + Label(presentation.expanded ? "Return to system" : "Expand monitor", systemImage: presentation.expanded ? "arrow.down.right.and.arrow.up.left" : "arrow.up.left.and.arrow.down.right") + }.accessibilityIdentifier("expand-monitor").fixedSize() + } + Button { help.toggle() } label: { Image(systemName: "info.circle") }.help("Show the guide for this CoCo setup").accessibilityLabel("Using the CoCo") + .popover(isPresented: $help) { + CoCoUsageHelp(profile: machine.usageProfile, + floppyMounted: machine.disks.contains { $0.mounted }, + hardMounted: machine.hardDiskConnected && machine.hardDisks.first?.mounted == true, + tapeMounted: machine.tapeMounted).equatable() + .onAppear { + if let profile = machine.usageProfile { presentation.didShowGuide(profile) } + } + .onChange(of: machine.usageProfile) { _, profile in + if let profile { presentation.didShowGuide(profile) } + } + } + }.font(.callout) + } +} + +struct MediaActionsMenu: View { + @Environment(\.openWindow) private var openWindow + var body: some View { + Menu { + Button { openWindow(id: "software-library") } label: { Label("Software Library…", systemImage: "books.vertical") } + Divider() + Button("Floppy Disks…") { openWindow(id: "disks") } + Button("Virtual Hard Disks…") { openWindow(id: "hard-disks") } + Button("Cassette…") { openWindow(id: "cassette") } + Button("Printer Output…") { openWindow(id: "printer") } + Button("Cartridges…") { openWindow(id: "cartridges") } + } label: { Label("Media", systemImage: "externaldrive") }.fixedSize() + } +} + +// Polling redraws the enclosing MachineView. These explicit equality boundaries +// keep tracking native menus intact; their own deduplicated observation still +// updates genuine command state (including changes made from the menu bar). +struct MachineSettingsMenu: View, Equatable { + let machine: MachineModel + @ObservedObject private var menu: MachineMenuState + @Environment(\.openWindow) private var openWindow + init(machine: MachineModel) { self.machine = machine; self.menu = machine.menuState } + static func == (lhs: Self, rhs: Self) -> Bool { lhs.machine === rhs.machine } + var body: some View { + Menu { + Button("Machine Settings…") { openWindow(id: "machine-settings") } + Button("Display Settings…") { openWindow(id: "display-settings") } + Button("Cartridges and Multi-Pak…") { openWindow(id: "cartridges") } + Button("Keyboard and Joysticks…") { openWindow(id: "input") } + Divider() + Picker("Video Signal", selection: Binding(get: { menu.values.videoOutput }, set: machine.setVideoOutput)) { + ForEach(DisplayOutput.allCases, id: \.rawValue) { Text($0.label).tag($0) } + } + Toggle("Sound", isOn: Binding(get: { menu.values.audioEnabled }, set: machine.setAudio)) + Button("Sound and Cassette…") { openWindow(id: "cassette") } + Divider() + Button("Open System ROM…", action: machine.openROM) + if machine.hasBundledROMs { + Button("Restore App Defaults…") { machine.confirmRestoreAppDefaults() } + Divider() + Button("Restore Bundled System ROM…") { machine.restoreBundledROM(system: true) } + Button("Restore Bundled Disk ROM…") { machine.restoreBundledROM(system: false) } + } + Button("Load Binary…", action: machine.openBinary).disabled(!menu.values.canQuickLoad) + Button("Run Diagnostic", action: machine.loadDiagnostic) + } label: { Label("Settings", systemImage: "slider.horizontal.3") } + .fixedSize().disabled(menu.values.busy) + } +} + +struct MachineRestartMenu: View, Equatable { + let machine: MachineModel + @ObservedObject private var menu: MachineMenuState + init(machine: MachineModel) { self.machine = machine; self.menu = machine.menuState } + static func == (lhs: Self, rhs: Self) -> Bool { lhs.machine === rhs.machine } + var body: some View { + Menu { + Button("Soft Reset — Retain RAM", action: machine.softReset) + Button("Cold Restart — Clear RAM…", action: machine.requestColdReset) + } label: { Label("Restart", systemImage: "arrow.counterclockwise") } + .disabled(menu.values.busy || menu.values.state == .empty || menu.values.state == .closed).fixedSize() + } +} + + +// Value-only content keeps the open help stable during frame/activity refreshes. +private struct CoCoUsageHelp: View, Equatable { + let profile: SystemProfile? + let floppyMounted: Bool + let hardMounted: Bool + let tapeMounted: Bool + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 12) { + Label("Using your CoCo", systemImage: "book.closed").font(.headline) + if let profile { Text(profile.name).font(.subheadline.bold()) } + Text("Click the live display to type. Escape is Break; Home is Clear.") + if profile == .cocoSDC { + SDCUsageGuide() + } else if profile == .nitros9 { + Nitros9UsageGuide() + } else if profile == .hardDriveBasic { + if hardMounted { + instruction("Hard disk", "DIR 0", "Lists virtual volume 0 on HD0. RGBDOS selects hard-disk volumes at startup.") + } else { + Text("No image is mounted in HD0. Open Media → Virtual Hard Disks to insert one, or use the floppies below.") + } + instruction("Floppy drives", "DRIVE OFF\nDIR 0", "Lists FD0. Use DIR 1, DIR 2 or DIR 3 for the other floppies. OFF changes the drive mapping; it does not eject your images.") + instruction("Return to the hard disk", "DRIVE ON\nDIR 0", "Returns drive numbers to the hard disk's virtual volumes.") + } else if profile == .diskBasic { + instruction("Floppy drives", "DIR 0", "Lists FD0. Use DIR 1, DIR 2 or DIR 3 for the other floppies.") + } else { + Text("This is a custom setup. Disk and boot commands depend on its ROM and software; follow their instructions.") + } + if profile != nil && profile != .nitros9 && (floppyMounted || (profile == .hardDriveBasic && hardMounted)) { + instruction("Hello World example", "LOAD \"HELLO:0\"\nRUN", "On fresh starter media, HELLO asks where you live. Press 1 for Earth or 2 for Mars.") + } + if tapeMounted { + instruction("Cassette in BASIC", "CLOAD \"HELLO\"\nRUN", "For the starter tape, open Media → Cassette and press Play first.") + } + Text("Save disk programs or record and export a tape to keep your work. Profiles save settings and file locations, not the running program.") + .font(.caption).foregroundStyle(.secondary) + }.frame(maxWidth: .infinity, alignment: .leading).padding(20) + }.frame(width: 420).frame(maxHeight: 580) + .background(Color(nsColor: .windowBackgroundColor)) + } + private func instruction(_ title: String, _ commands: String, _ explanation: String) -> some View { + VStack(alignment: .leading, spacing: 4) { + Text(title).font(.subheadline.bold()) + Text(commands).font(.system(.callout, design: .monospaced)).textSelection(.enabled) + Text(explanation).font(.callout).foregroundStyle(.secondary) + } + } +} + +// Shared by the system-profile details and live help; the archive remains a +// private input, and links provide the full catalogue without copying it. +struct Nitros9UsageGuide: View { + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Getting around OS-9").font(.headline) + Text("Loading this profile automatically types DOS 255 at the RGBDOS prompt. Wait for the OS-9 shell prompt before typing. These are OS-9 commands, not BASIC commands.").font(.callout) + section("System disk · HD0", "dir /dd\ndir /dd/games\ndir /dd/apps", "The boot disk is /dd, also accessible as /h0. Use chd to change your working directory; chx changes where commands are found.") + section("Shared data disk · HD1", "dir /h1\nchd /h1\necho Hello from OS-9 >hello\nlist hello", "This is the OS-9 area of your Hard Drive BASIC disk. Its BASIC volumes are separate; the existing HELLO program is preserved. Return with chd /dd.") + section("Explore files", "dir /dd/sources\ndir /dd/grfx\ndir /dd/sound\nlist /dd/docs.txt", "dir lists files; list reads text. The archive includes software, source, pictures and sound. Programs may have their own startup instructions.") + section("Command help", "help\nhelp dir", "Use the installed help and the archive notes for more detail.") + section("Return to BASIC", "DOS 255", "Choose Restart → Cold Restart — Clear RAM…, then select 6 (EXIT TO BASIC) and press Return at the archive menu. At BASIC, type DOS 255 to boot OS-9 again. In BASIC, DIR 1 lists archive volume 1; DRIVE OFF switches drive numbers 0–3 to the floppies, and DRIVE ON restores hard-disk mapping.") + DriveWireNetworkingHelp() + Text("The archive also describes DriveWire disks, MIDI and Glenside IDE hardware. VCC Plus uses its native virtual hard disks for this profile.") + .font(.caption).foregroundStyle(.secondary) + Link("Archive contents and original notes", destination: URL(string: "https://colorcomputerarchive.com/repo/Virtual%20Hard%20Drives/NitrOS-9%20L2%20V3.3.0/Virtual%20Hard%20Drive.txt")!) + } + } + private func section(_ title: String, _ command: String, _ detail: String) -> some View { + VStack(alignment: .leading, spacing: 4) { + Text(title).font(.subheadline.bold()) + Text(command).font(.system(.callout, design: .monospaced)).textSelection(.enabled) + Text(detail).font(.callout).foregroundStyle(.secondary) + } + } +} + +struct DriveWireNetworkingHelp: View { + var body: some View { + SecondaryHelp(title: "Connect from NitrOS-9") { + Text("A fresh NitrOS-9 system disk loads its networking drivers at boot. At the OS-9 shell, enter the host name and port of your TCP service or BBS.") + Text("telnet HOST PORT") + .font(.system(.callout, design: .monospaced)).textSelection(.enabled) + .accessibilityIdentifier("drivewire-guest-commands") + Text("Use 127.0.0.1 for a service running on this Mac. If you turned networking off, you can enable it again in Machine Settings.") + Text("For your Mac’s own command line, enter telnet macshell 2323 and respond to the permission request in VCC Plus. Type exit to return to OS-9.") + Text("Use clear to clear the CoCo screen. Hold Option while pressing an arrow key to move. In vi, press i to insert and Escape to finish inserting.") + Text("Using an older system disk? In Configuration Profiles, select NitrOS-9 and choose Create Fresh Starter Media… for a separate disk with the drivers installed. To keep using the older disk, load its bundled drivers using the instructions below.") + SecondaryHelp(title: "Load drivers on an older disk") { + Text("Use an unused filename for the combined drivers. Create the file once, then load it after each boot.") + Text(""" + chd /dd/boot_with_beckerdw + merge dwio scdwv n n1 >/dd/dwnet + attr /dd/dwnet e + chd /dd + load /dd/dwnet + """).font(.system(.caption, design: .monospaced)).textSelection(.enabled) + } + } + } +} + +// Shared by system-profile details and firmware-aware live help. +struct SDCUsageGuide: View { + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Your SD card is a local Mac folder. On first use, the CoCo SDC system profile supplies a writable copy of HELLO.DSK and a startup.cfg that mounts it in drive 0. Your changes are kept when you reload the profile.") + Text("List and run the supplied example").font(.subheadline.bold()) + Text("DIR 0\nLOAD \"HELLO:0\"\nRUN").font(.system(.callout, design: .monospaced)).textSelection(.enabled) + Text("DIR lists files on the mounted disk. On a fresh card, HELLO asks you to press 1 for Earth or 2 for Mars.") + Text("Mount the starter disk again").font(.subheadline.bold()) + Text("DRIVE 0,\"/HELLO.DSK\"").font(.system(.callout, design: .monospaced)).textSelection(.enabled) + Text("Use this if another image is mounted. The leading / starts at your SD card folder's root. To mount another image, use its path instead.") + Text("Find your files on the Mac").font(.subheadline.bold()) + Text("Click the SDC cartridge or open Cartridge → Cartridges, then Show SD Card Folder in Finder. You can add extracted disk images there. The app keeps the bundled original; saves go directly to your local copy. Finish disk operations before changing files in Finder.") + Text("startup.cfg controls startup mounts. Changes to that file are preserved. Fresh Media Copy creates a separate clean card. This guide applies to the supplied SDC-DOS ROM; your chosen card may contain different files.").font(.caption).foregroundStyle(.secondary) + } + } +} + +// A guest cannot bring the app or a window to the front. The prompt waits for +// an active emulator/settings window and yields to existing sheets and panels. +struct MacShellPermissionPresenter: NSViewRepresentable { + @ObservedObject var machine: MachineModel + func makeCoordinator() -> Presenter { Presenter() } + func makeNSView(context: Context) -> NSView { + let anchor = NSView() + anchor.setAccessibilityElement(false) + return anchor + } + func updateNSView(_ anchor: NSView, context: Context) { + let presenter = context.coordinator + DispatchQueue.main.async { [weak anchor] in presenter.update(in: anchor?.window, machine: machine) } + } + static func dismantleNSView(_ anchor: NSView, coordinator: Presenter) { coordinator.dismiss() } + + @MainActor final class Presenter { + private var alert: NSAlert? + private var presented: MachineModel.MacShellRequest? + + func dismiss() { + presented = nil + guard let alert else { return } + self.alert = nil + alert.window.sheetParent?.endSheet(alert.window, returnCode: .abort) + } + + func update(in owner: NSWindow?, machine: MachineModel) { + let request = machine.macShellRequest + if alert != nil { + if presented != request { dismiss() } + return + } + guard let request, let owner, NSApp.isActive, owner.isKeyWindow, owner.isVisible, + !owner.isMiniaturized, owner.attachedSheet == nil, NSApp.modalWindow == nil, + !(NSApp.keyWindow is NSPanel) else { return } + + let alert = NSAlert() + alert.alertStyle = .warning + alert.messageText = "Allow this CoCo program to use your Mac shell?" + alert.informativeText = "The guest requested macshell. It can run commands as your Mac user, starting in your home folder, and read or change files your account and VCC Plus can access." + alert.addButton(withTitle: "Deny").keyEquivalent = "\r" + alert.addButton(withTitle: "Allow") + if request.disk != nil { + alert.showsSuppressionButton = true + alert.suppressionButton?.title = "Remember for any program running with this NitrOS-9 setup" + alert.suppressionButton?.state = .off + } + self.alert = alert + presented = request + alert.beginSheetModal(for: owner) { [weak self, weak machine, weak alert] result in + guard let self, let machine, let alert, self.alert === alert else { return } + self.alert = nil; self.presented = nil + machine.decideMacShell(request, allow: result == .alertSecondButtonReturn, + remember: alert.suppressionButton?.state == .on) + } + } + } +} diff --git a/platforms/macos/App/MachineMenuState.swift b/platforms/macos/App/MachineMenuState.swift new file mode 100644 index 0000000..574870b --- /dev/null +++ b/platforms/macos/App/MachineMenuState.swift @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Combine +import SwiftUI + +// SwiftUI rebuilds native menu groups when an observed Commands object changes. +// Keep frame, audio and media-status polling out of that observation: rebuilding +// the system View menu while it is tracking can dismiss it before selection. +@MainActor +final class MachineMenuState: ObservableObject { + struct Values: Equatable { + var busy: Bool + var diskSaving: Bool + var state: VCCMachineState + var videoOutput: DisplayOutput + var fastForward: Bool + var audioEnabled: Bool + var diskConnected: Bool + var hardDiskConnected: Bool + var pasting: Bool = false + var canPaste: Bool { !busy && state == .running && !pasting } + var canQuickLoad: Bool { !busy && !diskSaving && (state == .running || state == .paused) } + } + @Published private(set) var values: Values + private var observation: AnyCancellable? + + init(machine: MachineModel) { + values = Values(busy: machine.busy || machine.diskEditorLocked, diskSaving: machine.diskSaving, state: machine.state, + videoOutput: machine.videoOutput, fastForward: machine.settings.fastForward, audioEnabled: machine.audioEnabled, + diskConnected: machine.diskConnected, hardDiskConnected: machine.hardDiskConnected, pasting: machine.pasteRemaining > 0) + let effectiveBusy = Publishers.CombineLatest(machine.$busy, machine.$diskEditorLocked).map { $0 || $1 }.removeDuplicates() + observation = Publishers.CombineLatest4(effectiveBusy, machine.$diskSaving, machine.$state, machine.$videoOutput) + .combineLatest(machine.$settings.map(\.fastForward), machine.$diskConnected, machine.$hardDiskConnected) + .combineLatest(machine.$audioEnabled, machine.$pasteRemaining.map { $0 > 0 }.removeDuplicates()) + .map { controlsAndDevices, audioEnabled, pasting in + let (controls, fastForward, diskConnected, hardDiskConnected) = controlsAndDevices + return Values(busy: controls.0, diskSaving: controls.1, state: controls.2, videoOutput: controls.3, + fastForward: fastForward, audioEnabled: audioEnabled, diskConnected: diskConnected, hardDiskConnected: hardDiskConnected, pasting: pasting) + } + .removeDuplicates() + .sink { [weak self] value in + // The model and its published setters belong to the main actor. + guard let self, self.values != value else { return } + self.values = value + } + } +} + +/// Keep the emulator command available in its menu throughout the app. Only +/// the active emulator window owns its keyboard equivalent. +struct FastForwardMenuItem: View { + let machine: MachineModel + let values: MachineMenuState.Values + let emulatorFocused: Bool + + var body: some View { + Toggle("Fast-forward", isOn: Binding(get: { values.fastForward }, set: machine.setFastForward)) + .keyboardShortcut(emulatorFocused ? KeyboardShortcut("f", modifiers: [.command, .shift]) : nil) + .disabled(values.busy || values.diskSaving || values.state == .closed) + } +} diff --git a/platforms/macos/App/MachineModel.swift b/platforms/macos/App/MachineModel.swift new file mode 100644 index 0000000..52da57a --- /dev/null +++ b/platforms/macos/App/MachineModel.swift @@ -0,0 +1,2837 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit +import Combine +import UniformTypeIdentifiers + +enum DisplayOutput: Int, CaseIterable { + case rgb = 0, composite = 1, compositeAlternate = 2 + var label: String { + switch self { + case .rgb: return "RGB Monitor" + case .composite: return "Composite TV" + case .compositeAlternate: return "Composite TV — Alternate Colors" + } + } + static let preferenceKey = "videoOutput" + static func remembered(in defaults: UserDefaults) -> Self { + guard let raw = defaults.object(forKey: preferenceKey) as? Int else { return .composite } + return Self(rawValue: raw) ?? .composite + } +} + +enum DiskInsertionExecution: Int, CaseIterable, Sendable { + case keepCurrentState, pause, run + var label: String { + switch self { + case .keepCurrentState: return "Keep current state" + case .pause: return "Pause" + case .run: return "Run" + } + } +} + +enum DiskInsertionReset: Int, CaseIterable, Sendable { + case none, softReset, coldRestart + var label: String { + switch self { + case .none: return "No Reset" + case .softReset: return "Soft Reset" + case .coldRestart: return "Cold Restart" + } + } + var explanation: String { + switch self { + case .none: return "Insert without resetting the current program." + case .softReset: return "Reset the CoCo before insertion. The current program stops; RAM is retained, but its contents may be changed by the ROM's reset routine." + case .coldRestart: return "Restart the CoCo before insertion. Programs and other contents of RAM are cleared. Mounted media are retained." + } + } + var controllerValue: VCCDiskInsertionReset { + switch self { + case .none: return .none + case .softReset: return .softReset + case .coldRestart: return .coldRestart + } + } +} + +@MainActor +final class DiskMediaOpenOptions: NSObject { + let action = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 340, height: 28)) + let drive = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 340, height: 28)) + let execution = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 340, height: 28)) + let reset = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 340, height: 28)) + let view: NSStackView + private let resetExplanation = NSTextField(wrappingLabelWithString: "") + private let driveLabel = NSTextField(labelWithString: "Floppy drive") + private var hardDriveShown = false + private var floppySelection = 0 + private var hardSelection = 0 + init(preferred: MediaDestination?, supportsHardDisk: Bool = false) { + view = NSStackView(); view.orientation = .vertical; view.alignment = .leading; view.spacing = 6 + super.init() + action.addItems(withTitles: ["Edit Disk Image", "Insert into Floppy Drive"]) + if supportsHardDisk { action.addItem(withTitle: "Insert into Hard Disk") } + action.setAccessibilityLabel("Disk action"); action.identifier = NSUserInterfaceItemIdentifier("diskOpenAction") + action.setAccessibilityIdentifier("diskOpenAction") + drive.addItems(withTitles: (0..<4).map { "FD\($0)" }); drive.setAccessibilityLabel("Floppy drive") + drive.identifier = NSUserInterfaceItemIdentifier("diskOpenDrive"); drive.setAccessibilityIdentifier("diskOpenDrive") + execution.addItems(withTitles: DiskInsertionExecution.allCases.map(\.label)); execution.setAccessibilityLabel("After inserting") + execution.identifier = NSUserInterfaceItemIdentifier("diskOpenExecution"); execution.setAccessibilityIdentifier("diskOpenExecution") + reset.addItems(withTitles: DiskInsertionReset.allCases.map(\.label)); reset.setAccessibilityLabel("Before inserting") + reset.identifier = NSUserInterfaceItemIdentifier("diskOpenReset"); reset.setAccessibilityIdentifier("diskOpenReset") + if let preferred, case .floppy(let number) = preferred { action.selectItem(at: 1); drive.selectItem(at: number) } + if let preferred, case .hardDisk(let number) = preferred, supportsHardDisk { action.selectItem(at: 2); hardSelection = number } + view.addArrangedSubview(NSTextField(labelWithString: "Action")); view.addArrangedSubview(action) + view.addArrangedSubview(driveLabel); view.addArrangedSubview(drive) + view.addArrangedSubview(NSTextField(labelWithString: "Before inserting")); view.addArrangedSubview(reset) + resetExplanation.preferredMaxLayoutWidth = 340 + resetExplanation.font = .systemFont(ofSize: NSFont.smallSystemFontSize) + resetExplanation.textColor = .secondaryLabelColor + // Reserve room for the destructive-action explanation before the + // sheet opens; changing the popup must not clip its longer warning. + resetExplanation.widthAnchor.constraint(equalToConstant: 340).isActive = true + resetExplanation.heightAnchor.constraint(equalToConstant: 54).isActive = true + view.addArrangedSubview(resetExplanation) + view.addArrangedSubview(NSTextField(labelWithString: "After inserting")); view.addArrangedSubview(execution) + action.target = self; action.action = #selector(update) + reset.target = self; reset.action = #selector(update) + update() + view.setFrameSize(NSSize(width: 340, height: view.fittingSize.height)) + } + @objc func update() { + let hard = action.indexOfSelectedItem == 2 + if hard != hardDriveShown { + if hardDriveShown { hardSelection = drive.indexOfSelectedItem } else { floppySelection = drive.indexOfSelectedItem } + drive.removeAllItems() + drive.addItems(withTitles: hard ? ["HD0", "HD1"] : (0..<4).map { "FD\($0)" }) + drive.selectItem(at: hard ? hardSelection : floppySelection) + hardDriveShown = hard + } + driveLabel.stringValue = hard ? "Hard disk drive" : "Floppy drive" + drive.setAccessibilityLabel(hard ? "Hard disk drive" : "Floppy drive") + drive.isEnabled = action.indexOfSelectedItem != 0 + execution.isEnabled = action.indexOfSelectedItem == 1 + reset.isEnabled = action.indexOfSelectedItem == 1 + resetExplanation.stringValue = action.indexOfSelectedItem == 1 + ? (DiskInsertionReset(rawValue: reset.indexOfSelectedItem) ?? .none).explanation + : "Reset options apply only when inserting into a floppy drive." + } +} + +@MainActor +final class MachineModel: ObservableObject { + @Published private(set) var hardware = HardwareState() + private var sdcActivityTracker = ActivityTracker() + private var activityTrackers = Array(repeating: ActivityTracker(), count: 7) + @Published private(set) var videoOutput = DisplayOutput.composite + private let displayDefaults: UserDefaults + struct BASICDebugState: Equatable, Sendable { + var attached = false + var line: Int? = nil + var sourceRange: NSRange? = nil + var stepping = false + var status = "" + var generation: UInt64 = 0 + var paused = false + var cycles: UInt64 = 0 + var atPrompt = false + var canStepOut = false + var errorLine: Int? = nil + var errorCode = "" + } + @Published private(set) var basicDebug = BASICDebugState() + @Published var basicWorkspaceOwner: UUID? + @Published private(set) var state: VCCMachineState = .empty + @Published private(set) var frames: UInt64 = 0 + #if VCC_UI_TESTING + private(set) var uiTestSession = "" + #endif + @Published private(set) var pixels: Data? + @Published private(set) var activeVideoRect = VideoGeometry.fullFrame + @Published private(set) var title = "No ROM selected" + @Published private(set) var binaryName: String? + @Published private(set) var systemROMURL: URL? + struct GuideRequest: Equatable { + let id = UUID() + let profile: SystemProfile + } + @Published private(set) var guideRequest: GuideRequest? + @Published private(set) var profileName: String? + @Published private(set) var profileError: String? + private var cassetteURL: URL? + private var bootNitros9 = false + private var builtInNitros9 = false + private var libraryReturnToNitros9: ConfigurationProfile? + private var loadedProfileConfiguration: ConfigurationProfile? + var profileModified: Bool { + guard let baseline = loadedProfileConfiguration, profileName != nil else { return false } + return profileConfiguration != baseline || (tapeMounted && cassetteURL == nil) || + disks.enumerated().contains { $0.element.mounted && diskAssignments.drives[$0.offset] == nil } || + hardDisks.enumerated().contains { $0.element.mounted && hardSettings.drives[$0.offset] == nil } + } + private var profileConfiguration: ConfigurationProfile { + var p = ConfigurationProfile(name: "Current") + p.id = UUID(uuidString: "00000000-0000-0000-0000-000000000000")! + p.machine = settings; p.videoOutput = videoOutput.rawValue; p.sound = audioEnabled; p.volume = volume + p.systemROM = systemROMURL; p.media = diskAssignments; p.media.cartridges = cartridgeAssignments + p.media.hardDisks = hardSettings; p.cassette = tapeMounted ? cassetteURL : nil; p.fastCassette = tapeFast + p.input = input.settings; p.bootNitros9 = bootNitros9 ? true : nil + return p + } + var canQuickLoad: Bool { !busy && !diskSaving && !diskEditorLocked && (state == .running || state == .paused) } + @Published private(set) var settings = MachineSettings() + var use6309: Bool { settings.use6309 } + @Published private(set) var inputEpoch: UInt64 = 0 + @Published private(set) var focusRequest: UInt64 = 0 + func focusDisplay() { focusRequest += 1 } + @Published var displayError: String? + @Published private(set) var fileError: String? + @Published private(set) var error: String? + @Published private(set) var busy = false + @Published private(set) var pasteRemaining = 0 + @Published private(set) var driveWireEnabled = false + struct MacShellRequest: Equatable { + let id: UInt64 + let generation: UInt64 + let disk: [String: String]? + } + + private static let shellGrantKey = "driveWireNetworking.macShellGrant" + @Published private(set) var macShellStatus = "idle" + private var macShellRequestID: UInt64 = 0 + private var shellDecisionInFlight: UInt64? + private var deniedShellGeneration: UInt64? + private(set) var assemblyAttached = false + private(set) var assemblyMappingFingerprint: UInt64 = 0 + private var programRevision: UInt64 = 0 + private var presetProgramRevision: UInt64? + private let starterShellDiskURL: URL? + private var savedShellGrant: [String: String]? { + get { displayDefaults.dictionary(forKey: Self.shellGrantKey) as? [String: String] } + set { displayDefaults.set(newValue, forKey: Self.shellGrantKey) } + } + var hasRememberedMacShellPermission: Bool { savedShellGrant != nil } + + // The built-in system disk is the grant's boundary. A Library title, a + // personal profile or new code injected by an editor/quickload must ask. + private var shellDisk: [String: String]? { + guard builtInNitros9, usageProfile == .nitros9, presetProgramRevision == programRevision, + cartridgeAssignments.slots.map(\.kind) == [.empty, .hardDisk, .empty, .empty, .floppy], + let backing = hardBackings[0], backing.url.standardizedFileURL == starterShellDiskURL else { return nil } + return ["path": backing.url.path, "sha256": backing.digest] + } + + var currentSetupHasMacShellPermission: Bool { + guard let disk = shellDisk else { return false } + return disk == savedShellGrant + } + + var macShellRequest: MacShellRequest? { + guard macShellStatus == "requested", macShellRequestID != 0, + driveWireEnabled, !busy, !diskSaving, shellDecisionInFlight == nil else { return nil } + return MacShellRequest(id: macShellRequestID, generation: imageGeneration, disk: shellDisk) + } + + func startMacShellSession() { + guard driveWireEnabled, !busy, state != .closed else { return } + command(controller.startMacShell, onSuccess: { [self] in deniedShellGeneration = nil }) + } + + func stopMacShellSession() { + guard !busy, state != .closed else { return } + command(controller.stopMacShell, onSuccess: { [self] in deniedShellGeneration = imageGeneration }) + } + + func forgetMacShellPermission() { + savedShellGrant = nil + if macShellStatus != "idle" { stopMacShellSession() } + objectWillChange.send() + } + + private func applySavedMacShellDecision() { + guard let request = macShellRequest else { return } + if deniedShellGeneration == request.generation { + decideMacShell(request, allow: false) + } else if currentSetupHasMacShellPermission { + decideMacShell(request, allow: true) + } + } + + func decideMacShell(_ request: MacShellRequest, allow: Bool, remember: Bool = false) { + guard macShellRequest == request else { return } + shellDecisionInFlight = request.id + controller.decideMacShellRequest(request.id, allow: allow) { [weak self] snapshot in + MainActor.assumeIsolated { + guard let self else { return } + self.shellDecisionInFlight = nil + self.accept(snapshot) + guard snapshot.errorMessage == nil, self.imageGeneration == request.generation else { return } + if !allow { self.deniedShellGeneration = request.generation } + if allow, remember, let disk = request.disk, disk == self.shellDisk { self.savedShellGrant = disk } + } + } + } + + private static let driveWireKey = "driveWireNetworking.enabled" + @Published private(set) var audioEnabled = true + @Published var volume: Double = 0.5 + @Published private(set) var tapeMounted = false + @Published private(set) var tapeDirty = false + @Published private(set) var tapeFast = false + @Published private(set) var tapeWAV = false + @Published private(set) var tapeMode = 0 + @Published private(set) var tapeMotor = false + @Published private(set) var tapePosition: UInt64 = 0 + @Published private(set) var tapeLength: UInt64 = 0 + @Published private(set) var tapeName = "No tape" + @Published private(set) var cartridgeAssignments = CartridgeAssignments() + @Published private(set) var cartridgeRestoreErrors: [Int: String] = [:] + @Published private(set) var cartridgeNames = Array(repeating: "", count: 5) + @Published private(set) var sdcDriveNames = ["", ""] + @Published private(set) var sdcDirectory = "" + @Published private(set) var sdcReadOnly = true + @Published private(set) var sdcReadCount: UInt64 = 0 + @Published private(set) var sdcWriteCount: UInt64 = 0 + @Published private(set) var sdcError: String? + @Published private(set) var romSlot = 0 + @Published private(set) var ioSlot = 0 + @Published private(set) var diskConnected = false + private var cartridgeBytes = Array(repeating: Data(), count: 5) + @Published private(set) var diskEnabled = false + @Published private(set) var diskBusy = false + @Published private(set) var diskMotor = false + @Published private(set) var diskROMName = "" + @Published private(set) var diskSelectedDrive = -1 + @Published private(set) var diskTrack: UInt = 0 + @Published private(set) var diskSector: UInt = 0 + @Published private(set) var disks: [VCCDiskSnapshot] = [] + var dirtyDisks: Bool { disks.contains { $0.dirty } } + var unsavedMedia: Bool { dirtyDisks || hardDisks.contains { $0.dirty } || tapeDirty || tapeMode == 2 } + // Pending automatic writes still count as unsaved for quit/replacement + // safeguards, but do not ask the user to intervene during normal disk I/O. + var mediaNeedsManualSave: Bool { + tapeDirty || tapeMode == 2 || + disks.enumerated().contains { drive, disk in + disk.dirty && (diskTemporary[drive] || diskBackings[drive] == nil || disk.writeProtected || disk.sourceReadOnly) + } || hardDisks.enumerated().contains { drive, disk in + disk.dirty && (hardTemporary[drive] || hardBackings[drive] == nil || disk.writeProtected || disk.sourceReadOnly) + } + } + @Published private(set) var hardDisks: [VCCDiskSnapshot] = [] + @Published private(set) var hardDiskConnected = false + @Published private(set) var hardSelectedDrive = 0 + @Published private(set) var hardSector: UInt = 0 + @Published private(set) var hardStatus: UInt = 255 + @Published private(set) var hardSettings = HardDiskAssignments() + @Published private(set) var hardTemporary = [false, false] + @Published private(set) var hardRestoreErrors: [Int: String] = [:] + @Published private(set) var hardSaveErrors: [Int: String] = [:] + private struct HardBacking { var url: URL; var digest: String } + private var hardBackings: [HardBacking?] = [nil, nil] + private var nextHardSave = Date.distantPast + private var hardFlushRequests: UInt64 = 0 + private var savedHardFlushRequests: UInt64 = 0 + private let automaticHardDiskWriter: @Sendable (Data, Int, URL, String) async throws -> String + @Published private(set) var diskAssignments = DiskAssignments() + @Published private(set) var diskRestoreErrors: [Int: String] = [:] // -1 is the ROM + @Published private(set) var diskSettingsError: String? + @Published private(set) var diskSettingsNeedsSave = false + @Published private(set) var diskSaving = false + @Published private(set) var diskTemporary = Array(repeating: false, count: 4) + @Published private(set) var diskSaveErrors: [Int: String] = [:] + @Published private(set) var diskEditorLocked = false + private var activeDiskEditor: DiskEditorSession? + private var diskEditorBacking: Backing? + private var hardDiskEditorBacking: HardBacking? + private struct Backing { var url: URL; var bytes: Data } + private var diskBackings: [Backing?] = Array(repeating: nil, count: 4) + private var diskSaveTask: Task? + private var diskMonitor: Task? + private let automaticDiskWriter: @Sendable (Data, URL, Data) async throws -> Void + private let diskStore: DiskAssignmentStore + private let inputStore: InputSettingsStore + lazy var printer = PrinterModel(controller: controller) + private var existingInputHub: InputHub? + lazy var input: InputHub = { + let hub = InputHub(controller: controller, store: inputStore) + existingInputHub = hub + return hub + }() + // A read-only MCP observation must not initialize HID/timers or submit input. + func inputDiagnostics(machine observed: VCCMachineSnapshot) -> [String: Any] { + existingInputHub?.diagnostics(machine: observed) ?? InputHub.unavailableDiagnostics(machine: observed) + } + lazy var menuState = MachineMenuState(machine: self) + private let startupStore: StartupStore? + // A library-only background launch must not mount or run the user's machine. + // The same model is restored once if the user later opens VCC Plus normally. + private(set) var companionMachineRestoreDeferred = false + private var startupRestoreStarted = false + private var starterDiskROMURLs: [SystemProfile: URL] = [:] + // Identify the selected starter firmware, not a profile's editable name. + // Personal copies and relaunches keep these content-addressed references. + var usageProfile: SystemProfile? { + guard systemROMURL != nil else { return nil } + let slot = cartridgeAssignments.multiPak ? cartridgeAssignments.physicalSlot : 0 + let cartridge = cartridgeAssignments.slots[slot] + if cartridge.kind == .sdc, !cartridgeNames[slot].isEmpty, + let rom = cartridge.url, starterDiskROMURLs[.cocoSDC] == rom.standardizedFileURL { return .cocoSDC } + guard diskConnected, diskEnabled, let rom = diskAssignments.rom else { return nil } + if bootNitros9 && hardDiskConnected && hardDisks[0].mounted && starterDiskROMURLs[.nitros9] == rom.standardizedFileURL { return .nitros9 } + return [SystemProfile.diskBasic, .hardDriveBasic].first { starterDiskROMURLs[$0] == rom.standardizedFileURL } + } + var hasBundledROMs: Bool { startupStore?.kit != nil } + private var mediaPromptOpen = false + let recentMedia: RecentMedia + let displayPreferences: DisplayPreferences + private var screenshotInProgress = false + private let controller: VCCMachineController + init(diskStore: DiskAssignmentStore = .standard, controller: VCCMachineController = VCCMachineController(), + displayDefaults: UserDefaults = .standard, inputStore: InputSettingsStore = .standard, startupStore: StartupStore? = nil, + restoreMediaOnLaunch: Bool = true, + automaticHardDiskWriter: @escaping @Sendable (Data, Int, URL, String) async throws -> String = { patches, length, url, expected in + try await Task.detached(priority: .utility) { try HardDiskFiles.saveAutomatically(patches, length: length, to: url, expected: expected) }.value + }, + automaticDiskWriter: @escaping @Sendable (Data, URL, Data) async throws -> Void = { data, url, expected in + try await Task.detached(priority: .utility) { try DiskFiles.saveAutomatically(data, to: url, expected: expected) }.value + }) { + self.recentMedia = RecentMedia(defaults: displayDefaults) + self.displayPreferences = DisplayPreferences(defaults: displayDefaults) + self.startupStore = startupStore + self.starterShellDiskURL = startupStore?.directory.resolvingSymlinksInPath() + .appendingPathComponent("Starter Media/NitrOS-9 L2 V3.3.0.vhd").standardizedFileURL + self.inputStore = inputStore + self.displayDefaults = displayDefaults + videoOutput = DisplayOutput.remembered(in: displayDefaults) + let rememberedSettings = MachineSettings.remembered(in: displayDefaults) + settings = rememberedSettings + self.automaticHardDiskWriter = automaticHardDiskWriter + self.diskStore = diskStore; self.controller = controller; self.automaticDiskWriter = automaticDiskWriter + companionMachineRestoreDeferred = !restoreMediaOnLaunch + if restoreMediaOnLaunch { beginRememberedMachineRestore() } + } + + /// The app invokes this only for an explicit foreground/open-media action, + /// never for a library request or a companion reconnect. + func restoreDeferredCompanionMachine() { + guard companionMachineRestoreDeferred else { return } + companionMachineRestoreDeferred = false + beginRememberedMachineRestore() + } + private func beginRememberedMachineRestore() { + guard !startupRestoreStarted else { return } + startupRestoreStarted = true + if let store = startupStore, let kit = store.kit { + for kind in SystemProfile.allCases { + starterDiskROMURLs[kind] = try? kit.cachedROMURL(kind.diskROMName, in: store.directory).standardizedFileURL + } + } + busy = true + if displayDefaults.bool(forKey: Self.driveWireKey) { + controller.setDriveWireEnabled(true) { [weak self] snapshot in + MainActor.assumeIsolated { self?.accept(snapshot) } + } + } + controller.setAudioEnabled(true, volume: 0.5) { [weak self] snapshot in + MainActor.assumeIsolated { self?.accept(snapshot) } + } + controller.setVideoOutput(videoOutput.rawValue) { [weak self] snapshot in + MainActor.assumeIsolated { self?.accept(snapshot) } + } + controller.configureMachine(use6309: settings.use6309, ram: settings.ram, + overclock: settings.overclock, frameInterval: settings.frameInterval, + fastForward: settings.fastForward) { [weak self] snapshot in + MainActor.assumeIsolated { self?.accept(snapshot) } + } + Task { @MainActor in + var startup: StartupStore.Selection? + do { startup = try startupStore?.prepare(diskStore: diskStore) } + catch { fileError = "Startup setup: " + error.localizedDescription } + do { + diskAssignments = try await Task.detached { try self.diskStore.load() }.value + if let saved = diskAssignments.cartridges { cartridgeAssignments = saved } + else if diskAssignments.rom != nil { cartridgeAssignments.slots[0].kind = .floppy } + await restoreCartridges() + await restoreDisks() + hardSettings = diskAssignments.hardDisks ?? HardDiskAssignments() + await restoreHardDisks() + } catch { diskSettingsError = "Could not read remembered disks: \(error.localizedDescription)" } + if let startup { await restoreStartup(startup) } + busy = false + startDiskMonitor() + } + } + private func rememberStartup() { + guard !companionMachineRestoreDeferred, let startupStore else { return } + do { try startupStore.save(.init(systemROM: systemROMURL, cassette: cassetteURL, bootNitros9: bootNitros9 ? true : nil, + builtInNitros9: builtInNitros9 ? true : nil)) } + catch { fileError = "Could not remember startup choices: " + error.localizedDescription } + } + private func restoreStartup(_ selection: StartupStore.Selection) async { + systemROMURL = selection.systemROM; cassetteURL = selection.cassette; bootNitros9 = selection.bootNitros9 == true + var ready = false + if let url = selection.systemROM { + do { + let data = try await Task.detached { try ROMImage.read(url) }.value + let result = await diskStep { controller.loadROM(data, use6309: use6309, completion: $0) } + if let error = result.errorMessage { throw ProfileFailure.message(error) } + title = url.lastPathComponent; ready = true + } catch { fileError = "System ROM unavailable: " + error.localizedDescription } + } + if let url = selection.cassette { + do { + let data = try await Task.detached { try TapeImage.read(url) }.value + let result = await diskStep { controller.mountTape(data, wav: url.pathExtension.lowercased() == "wav", completion: $0) } + if let error = result.errorMessage { throw ProfileFailure.message(error) } + tapeName = url.lastPathComponent + } catch { fileError = "Remembered cassette unavailable: " + error.localizedDescription } + } + guard await applyDriveWireDefault(selection.builtInNitros9 == true && bootNitros9) else { return } + // Ordinary defaults never type commands. NitrOS-9 profiles explicitly opt into DOS 255. + if ready && fileError == nil && diskSettingsError == nil && diskRestoreErrors.isEmpty && cartridgeRestoreErrors.isEmpty && hardRestoreErrors.isEmpty { + if bootNitros9 { _ = await diskStep(controller.requestNitros9Boot) } + let resumed = await diskStep(controller.resume) + focusRequest += 1 + if resumed.errorMessage == nil, let profile = usageProfile { + guideRequest = GuideRequest(profile: profile) + } + } + } + func restoreBundledROM(system: Bool) { + guard !busy, !diskSaving, let store = startupStore, let kit = store.kit else { return } + let alert = NSAlert(); alert.messageText = "Restore bundled \(system ? "system" : "disk") ROM and restart?" + alert.informativeText = "The working program in RAM will be cleared. Mounted media and cartridge assignments are retained." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Restore ROM") + guard alert.runModal() == .alertSecondButtonReturn else { return } + do { + let url = try kit.rom(system ? "coco3.rom" : "disk11.rom", in: store.directory) + if system { installROM(try ROMImage.read(url), url: url) } + else { selectDiskROM(url) } + } catch { fileError = error.localizedDescription } + } + func confirmRestoreAppDefaults(onSuccess: (() -> Void)? = nil) { + guard !busy, !diskSaving, state != .closed else { return } + let alert = NSAlert(); alert.messageText = "Restore app defaults and restart?" + alert.informativeText = "This clears the program in RAM and any RAM disk contents, and restores the 6809, 512 KB, normal speed, composite color, sound, default keyboard/joystick settings, and bundled ROMs. The floppy controller returns to Multi-Pak slot 4, with the Hello World disk and stopped cassette. Other media is detached. Saved profiles and media files are kept; existing Hello World files are not overwritten. Writable disks are saved first. Unsaved temporary disks or recordings block the restore. Neither example program loads or runs automatically." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Restore Defaults") + guard alert.runModal() == .alertSecondButtonReturn else { return } + Task { @MainActor in if await restoreAppDefaults() { onSuccess?() } } + } + // Shared by both presentations. The profile transaction already pauses the + // worker, drains automatic writes and rejects any unsaved media atomically. + @discardableResult func restoreAppDefaults() async -> Bool { + await loadSystemProfile(.diskBasic) + } + func systemProfileUnavailableReason(_ kind: SystemProfile) -> String? { + guard let startupStore else { return StartupStore.Failure.unavailable.localizedDescription } + return startupStore.unavailableReason(for: kind) + } + func makeSystemProfile(_ kind: SystemProfile, freshMedia: Bool = false) async throws -> ConfigurationProfile { + guard !busy, state != .closed else { throw ProfileFailure.message("Wait for the current operation to finish.") } + guard let startupStore else { throw StartupStore.Failure.unavailable } + busy = true; defer { busy = false } + return try await Task.detached(priority: .userInitiated) { + try startupStore.systemProfile(kind, freshMedia: freshMedia) + }.value + } + @discardableResult func loadSystemProfile(_ kind: SystemProfile) async -> Bool { + guard !busy, !diskSaving, state != .closed else { return false } + await loadProfile(preparing: { [startupStore] in + guard let startupStore else { throw StartupStore.Failure.unavailable } + return try await Task.detached(priority: .userInitiated) { try startupStore.systemProfile(kind) }.value + }, startRunning: true, builtInNitros9: kind == .nitros9) + let succeeded = profileError == nil && fileError == nil + if succeeded { guideRequest = GuideRequest(profile: kind) } + return succeeded + } + private func startDiskMonitor() { + diskMonitor = Task { [weak self] in + while !Task.isCancelled { + do { try await Task.sleep(nanoseconds: 250_000_000) } catch { return } + if self == nil { return } + self?.poll() + self?.startAutomaticDiskSave() + } + } + } + private var polling = false + private var imageGeneration: UInt64 = 0 + private var imageRevision: UInt64 = 0 + + private func accept(_ snapshot: VCCMachineSnapshot) { + diskEditorLocked = snapshot.diskEditorLocked + printer.observe(snapshot) + let basic = BASICDebugState(attached: snapshot.basicDebugAttached, + line: snapshot.basicStoppedLine >= 0 ? snapshot.basicStoppedLine : nil, + sourceRange: snapshot.basicSourceOffset >= 0 ? NSRange(location: snapshot.basicSourceOffset, length: Int(snapshot.basicSourceLength)) : nil, + stepping: snapshot.basicStepping, + status: snapshot.basicDebugStatus, generation: snapshot.generation, + paused: snapshot.state == .paused, + cycles: snapshot.state == .paused ? snapshot.cycles : 0, + atPrompt: snapshot.state == .paused && snapshot.programCounter == 0xac7c, + canStepOut: snapshot.basicCanStepOut, + errorLine: snapshot.basicErrorLine >= 0 ? snapshot.basicErrorLine : nil, + errorCode: snapshot.basicErrorCode) + if basic != basicDebug { basicDebug = basic } + pasteRemaining = Int(snapshot.pasteRemaining) + #if VCC_UI_TESTING + uiTestSession = "\(snapshot.generation),\(snapshot.frames),\(snapshot.audioStarts)" + #endif + if snapshot.generation != imageGeneration { binaryName = nil } + videoOutput = DisplayOutput(rawValue: snapshot.videoOutput) ?? .composite + settings = MachineSettings(use6309: snapshot.use6309, ram: Int(snapshot.ramConfiguration), + overclock: Int(snapshot.cpuOverclock), frameInterval: Int(snapshot.frameInterval), + fastForward: snapshot.fastForward) + driveWireEnabled = snapshot.driveWireEnabled + assemblyAttached = snapshot.debuggerAssemblyAttached + assemblyMappingFingerprint = snapshot.debuggerMappingFingerprint + programRevision = snapshot.debuggerProgramRevision + macShellRequestID = snapshot.macShellRequestID + if macShellStatus != snapshot.macShellStatus { macShellStatus = snapshot.macShellStatus } + audioEnabled = snapshot.audioEnabled + tapeMounted = snapshot.tapeMounted; tapeDirty = snapshot.tapeDirty + tapeMotor = snapshot.tapeMotor; tapeMode = snapshot.tapeMode + tapeFast = snapshot.tapeFast; tapeWAV = snapshot.tapeWAV + tapePosition = snapshot.tapePosition; tapeLength = snapshot.tapeLength + cartridgeNames = snapshot.cartridgeNames; romSlot = Int(snapshot.romSlot); ioSlot = Int(snapshot.ioSlot) + if sdcDriveNames != snapshot.sdcDriveNames { sdcDriveNames = snapshot.sdcDriveNames } + if sdcReadOnly != snapshot.sdcReadOnly { sdcReadOnly = snapshot.sdcReadOnly } + if sdcDirectory != snapshot.sdcDirectory { sdcDirectory = snapshot.sdcDirectory } + if sdcReadCount != snapshot.sdcReadCount { sdcReadCount = snapshot.sdcReadCount } + if sdcWriteCount != snapshot.sdcWriteCount { sdcWriteCount = snapshot.sdcWriteCount } + if sdcError != snapshot.sdcError { sdcError = snapshot.sdcError } + diskConnected = snapshot.diskConnected + hardDisks = snapshot.hardDisks; hardDiskConnected = snapshot.hardDiskConnected + hardSelectedDrive = Int(snapshot.hardSelectedDrive); hardSector = snapshot.hardSector; hardStatus = snapshot.hardStatus + hardFlushRequests = snapshot.hardFlushRequests + diskEnabled = snapshot.diskEnabled; diskBusy = snapshot.diskBusy; diskMotor = snapshot.diskMotor + diskROMName = snapshot.diskROMName; diskSelectedDrive = snapshot.diskSelectedDrive + diskTrack = snapshot.diskTrack; diskSector = snapshot.diskSector; disks = snapshot.disks + let now = ProcessInfo.processInfo.systemUptime + var activity: [ActivityTracker.State] = [] + for (i, disk) in (snapshot.disks + snapshot.hardDisks).enumerated() { + activity.append(activityTrackers[i].update(reads: disk.readEvents, writes: disk.writeEvents, mounted: disk.mounted, + running: snapshot.state == .running, now: now)) + } + activity.append(activityTrackers[6].update(reads: snapshot.tapeReadEvents, writes: snapshot.tapeWriteEvents, + mounted: snapshot.tapeMounted, running: snapshot.state == .running, now: now)) + let sdcActivity = sdcActivityTracker.update(reads: snapshot.sdcReadCount, writes: snapshot.sdcWriteCount, + mounted: snapshot.sdcDriveNames.contains { !$0.isEmpty }, running: snapshot.state == .running, now: now) + let nextHardware = HardwareState(snapshot: snapshot, activities: activity, sdcActivity: sdcActivity) + if hardware != nextHardware { hardware = nextHardware } + state = snapshot.state + frames = snapshot.frames + error = snapshot.errorMessage + guard snapshot.pixels != nil else { + pixels = nil; activeVideoRect = VideoGeometry.fullFrame; imageGeneration = snapshot.generation; imageRevision = 0 + return + } + if pixels == nil || imageGeneration != snapshot.generation || imageRevision != snapshot.pixelRevision { + pixels = snapshot.pixels + activeVideoRect = VideoGeometry.validated(snapshot.activeVideoRect) + imageGeneration = snapshot.generation; imageRevision = snapshot.pixelRevision + } + } + + private func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void, + onSuccess: (() -> Void)? = nil) { + guard !diskEditorLocked else { fileError = "Close the Disk Image Editor before changing the CoCo or its media."; return } + busy = true; inputEpoch += 1; fileError = nil + operation { [weak self] snapshot in + MainActor.assumeIsolated { + self?.accept(snapshot); self?.busy = false + if snapshot.errorMessage == nil { onSuccess?() } + if snapshot.state == .running { self?.focusRequest += 1 } + } + } + } + /// Includes folders because an SDC owns every file beneath its assigned folder. + var diskEditorReferences: [URL] { developmentAssignedMediaURLs } + private static func diskEditorSameFile(_ first: URL, _ second: URL) -> Bool { + let a = first.standardizedFileURL.resolvingSymlinksInPath() + let b = second.standardizedFileURL.resolvingSymlinksInPath() + if a.path == b.path { return true } + let aa = try? FileManager.default.attributesOfItem(atPath: a.path) + let bb = try? FileManager.default.attributesOfItem(atPath: b.path) + guard let inode = aa?[.systemFileNumber] as? NSNumber, + let volume = aa?[.systemNumber] as? NSNumber else { return false } + return inode == bb?[.systemFileNumber] as? NSNumber && volume == bb?[.systemNumber] as? NSNumber + } + func diskEditorSourceIsAssigned(_ url: URL) -> Bool { + let path = url.standardizedFileURL.resolvingSymlinksInPath().path + return diskEditorReferences.contains { reference in + let resolved = reference.standardizedFileURL.resolvingSymlinksInPath() + let type = (try? FileManager.default.attributesOfItem(atPath: resolved.path))?[.type] as? FileAttributeType + return Self.diskEditorSameFile(url, reference) || + (type == .typeDirectory && path.hasPrefix(resolved.path + "/")) + } + } + func mountedEditorDrive(for url: URL) -> Int? { + (0..<4).first { drive in + guard disks.indices.contains(drive), disks[drive].mounted, + let source = diskBackings[drive]?.url ?? diskAssignments.drives[drive]?.url else { return false } + return Self.diskEditorSameFile(url, source) + } + } + func mountedHardDiskEditorDrive(for url: URL) -> Int? { + (0..<2).first { drive in + guard hardDisks.indices.contains(drive), hardDisks[drive].mounted, + let source = hardBackings[drive]?.url ?? hardSettings.drives[drive]?.url else { return false } + return Self.diskEditorSameFile(url, source) + } + } + private func diskEditorAliasRestriction(_ drive: Int, source: URL?, hardDisk: Bool = false) -> String? { + guard let source else { return nil } + let otherFloppies = (0..<4).filter { hardDisk || $0 != drive }.compactMap { diskBackings[$0]?.url ?? diskAssignments.drives[$0]?.url } + let otherHardDisks = (0..<2).filter { !hardDisk || $0 != drive }.flatMap { [hardSettings.drives[$0]?.url, hardBackings[$0]?.url].compactMap { $0 } } + let otherReferences = otherFloppies + otherHardDisks + [cassetteURL, systemROMURL, diskAssignments.rom].compactMap { $0 } + + cartridgeAssignments.slots.flatMap { [$0.url, $0.speechROMURL, $0.sdcFolderURL].compactMap { $0 } } + let path = source.standardizedFileURL.resolvingSymlinksInPath().path + for reference in otherReferences { + let resolved = reference.standardizedFileURL.resolvingSymlinksInPath() + let type = (try? FileManager.default.attributesOfItem(atPath: resolved.path))?[.type] as? FileAttributeType + if Self.diskEditorSameFile(source, reference) || (type == .typeDirectory && path.hasPrefix(resolved.path + "/")) { + return "This file is also assigned elsewhere in the machine. Save an edited copy instead, or close the editor and remove the other assignment first." + } + } + return nil + } + /// Export owns the media-command guard through the coordinated write. + /// An editor lease is allowed here because exporting never changes it. + func saveDiskEditorExport(_ data: Data, to url: URL, protecting sourceURL: URL?, + replacing expected: Data? = nil, requireNew: Bool = false) async throws { + try await writeDiskEditorExport(data, to: url, protecting: sourceURL, + replacing: expected, requireNew: requireNew, receivedPromise: false) + } + func saveDiskEditorImageCopy(_ data: Data, to url: URL, protecting sourceURL: URL?, + replacing expected: Data? = nil, requireNew: Bool = false) async throws { + try await writeDiskEditorExport(data, to: url, protecting: sourceURL, + replacing: expected, requireNew: requireNew, receivedPromise: false, + maximum: DiskEditorIO.imageLimit) + } + /// Only the file-promise delegate uses the receiver's already-coordinated + /// destination. Keep the media guard held until the actual write completes. + func savePromisedDiskEditorExport(_ data: Data, to url: URL, protecting sourceURL: URL?) async throws { + try await writeDiskEditorExport(data, to: url, protecting: sourceURL, + replacing: nil, requireNew: true, receivedPromise: true) + } + private func writeDiskEditorExport(_ data: Data, to url: URL, protecting sourceURL: URL?, + replacing expected: Data?, requireNew: Bool, receivedPromise: Bool, maximum: Int = DiskEditorIO.limit) async throws { + DiskEditorPromiseDiagnostics.record("machine export entered busy=\(busy)") + guard !busy, !diskSaving, state != .closed else { + throw ProfileFailure.message("Wait for the current disk operation before exporting files.") + } + busy = true; defer { busy = false } + let references = diskEditorReferences + [sourceURL].compactMap { $0 } + try await Task.detached(priority: .userInitiated) { + if FileManager.default.fileExists(atPath: url.path), !FileManager.default.isWritableFile(atPath: url.path) { + throw ProfileFailure.message("This destination is read only. Choose a separate writable file.") + } + if receivedPromise { + DiskEditorPromiseDiagnostics.record("machine detached receiver-coordinated export") + try DiskFiles.writeReceivedFilePromise(data, to: url, protecting: references) + } else { + try DiskEditorIO.write(data, to: url, protecting: references, allowEmpty: true, + replacing: expected, requireNew: requireNew, maximum: maximum) + } + }.value + } + /// Offline replacement owns the model's media-command guard until the + /// coordinated compare-and-swap completes; the guest keeps running. + func saveOfflineDiskEditor(_ data: Data, to url: URL, replacing original: Data) async throws { + guard !busy, !diskSaving, !diskEditorLocked, state != .closed else { + throw ProfileFailure.message("Wait for the current machine or disk edit operation to finish.") + } + busy = true; defer { busy = false } + let references = diskEditorReferences + try await Task.detached(priority: .userInitiated) { + let source = try DiskEditorIO.readImage(url) + guard !source.readOnly else { throw ProfileFailure.message("This source file is read only. Save an edited copy instead.") } + try DiskEditorIO.write(data, to: url, protecting: references, replacing: original, maximum: DiskEditorIO.imageLimit) + }.value + } + func beginDiskEditor(inDrive drive: Int) async throws -> DiskEditorSession { + guard !busy, !diskEditorLocked, state != .closed, (0..<4).contains(drive) else { + throw ProfileFailure.message("Wait for the current operation or disk editor to finish.") + } + busy = true; inputEpoch += 1; defer { busy = false } + if let task = diskSaveTask { await task.value } + // Flush existing automatic saves before taking the immutable edit lease. + await saveAutomaticDisks() + // Let an already-running transfer finish; never reset or advance a paused transfer. + for _ in 0..<100 { + let snapshot = await diskStep(controller.snapshot) + if !snapshot.diskBusy || snapshot.state != .running { break } + try await Task.sleep(nanoseconds: 20_000_000) + } + let (capture, snapshot): (VCCDiskEditCapture?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.beginDiskEditor(inDrive: drive) { continuation.resume(returning: ($0, $1)) } + } + accept(snapshot) + guard let capture else { throw ProfileFailure.message(snapshot.errorMessage ?? "Could not open this disk for editing.") } + let backing = diskBackings[drive] + var restriction = capture.canApply ? nil : "This disk is write protected or its source is read only. Save an edited copy instead." + restriction = restriction ?? diskEditorAliasRestriction(drive, source: backing?.url) + if let backing, restriction == nil { + let valid = await Task.detached(priority: .userInitiated) { + (try? DiskFiles.readImage(backing.url)).map { $0.data == backing.bytes && !$0.readOnly } ?? false + }.value + if !valid { restriction = "The source file changed, disappeared or became read only. Save an edited copy instead." } + } + let session = DiskEditorSession(id: UUID(), token: capture.token, drive: drive, name: capture.name, + data: capture.data, canApply: restriction == nil, sourceURL: backing?.url, + temporary: diskTemporary[drive], applyRestriction: restriction) + activeDiskEditor = session; diskEditorBacking = backing; hardDiskEditorBacking = nil + return session + } + func beginHardDiskEditor(inDrive drive: Int) async throws -> DiskEditorSession { + guard !busy, !diskEditorLocked, state != .closed, (0..<2).contains(drive) else { + throw ProfileFailure.message("Wait for the current operation or disk editor to finish.") + } + busy = true; inputEpoch += 1; defer { busy = false } + if let task = diskSaveTask { await task.value } + await saveAutomaticDisks(); await saveAutomaticHardDisks(force: true) + for _ in 0..<100 { + let snapshot = await diskStep(controller.snapshot) + if !snapshot.diskBusy || snapshot.state != .running { break } + try await Task.sleep(nanoseconds: 20_000_000) + } + let (capture, snapshot): (VCCDiskEditCapture?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.beginHardDiskEditor(inDrive: drive) { continuation.resume(returning: ($0, $1)) } + } + accept(snapshot) + guard let capture else { throw ProfileFailure.message(snapshot.errorMessage ?? "Could not open this hard disk for editing.") } + let backing = hardBackings[drive] + var restriction = capture.canApply ? nil : "This disk is write protected or its source is read only. Save an edited copy instead." + restriction = restriction ?? diskEditorAliasRestriction(drive, source: backing?.url, hardDisk: true) + if let backing, restriction == nil { + let valid = await Task.detached(priority: .userInitiated) { + (try? HardDiskFiles.readImage(backing.url)).map { $0.digest == backing.digest && !$0.readOnly } ?? false + }.value + if !valid { restriction = "The source file changed, disappeared or became read only. Save an edited copy instead." } + } + let session = DiskEditorSession(id: UUID(), token: capture.token, drive: drive, name: capture.name, + data: capture.data, canApply: restriction == nil, sourceURL: backing?.url, + temporary: hardTemporary[drive], applyRestriction: restriction, hardDisk: true) + activeDiskEditor = session; diskEditorBacking = nil; hardDiskEditorBacking = backing + return session + } + private func requireDiskEditor(_ session: DiskEditorSession) throws { + guard activeDiskEditor?.id == session.id, activeDiskEditor?.token == session.token, + activeDiskEditor?.drive == session.drive, activeDiskEditor?.hardDisk == session.hardDisk, diskEditorLocked else { + throw ProfileFailure.message("This disk edit session has ended. Reopen the disk to edit it.") + } + } + func cancelDiskEditor(_ session: DiskEditorSession) async throws { + try requireDiskEditor(session) + guard !busy else { throw ProfileFailure.message("Wait for the current disk edit operation to finish.") } + busy = true; defer { busy = false } + let result = await diskStep { controller.cancelDiskEditor(token: session.token, completion: $0) } + if let error = result.errorMessage { throw ProfileFailure.message(error) } + activeDiskEditor = nil; diskEditorBacking = nil; hardDiskEditorBacking = nil + } + func applyDiskEditor(_ session: DiskEditorSession, data: Data, restartConfirmed: Bool) async throws { + try requireDiskEditor(session) + guard !busy, !diskSaving else { throw ProfileFailure.message("Wait for the current disk operation to finish.") } + guard session.canApply else { throw ProfileFailure.message(session.applyRestriction ?? "Save an edited copy of this disk instead.") } + guard restartConfirmed else { throw ProfileFailure.message("Confirm the cold restart before applying disk edits.") } + if let restriction = diskEditorAliasRestriction(session.drive, source: session.sourceURL, hardDisk: session.hardDisk) { throw ProfileFailure.message(restriction) } + guard !printer.unsaved, !printer.saving else { throw ProfileFailure.message("Save the captured printer output before applying edits and restarting the CoCo.") } + guard !tapeDirty, tapeMode != 2, + !disks.enumerated().contains(where: { (session.hardDisk || $0.offset != session.drive) && $0.element.dirty }), + !hardDisks.enumerated().contains(where: { (!session.hardDisk || $0.offset != session.drive) && $0.element.dirty }) else { + throw ProfileFailure.message("Save or export changes on the other media before applying edits and restarting the CoCo.") + } + busy = true; inputEpoch += 1; defer { busy = false } + let (prepared, validation): (Bool, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.prepareDiskEditor(token: session.token, data: data) { continuation.resume(returning: ($0, $1)) } + } + accept(validation) + guard prepared else { throw ProfileFailure.message(validation.errorMessage ?? "The edited disk could not be validated.") } + let backing = diskEditorBacking + let hardBacking = hardDiskEditorBacking + var sourceSaved = false + var hardDigest: String? + var hardSourceBeforeWrite: Data? + if session.hardDisk, let hardBacking, !session.temporary { + let plan = try await Task.detached(priority: .userInitiated) { + // Include guest writes not yet acknowledged by automatic save, + // not just the differences from the editor's initial snapshot. + let source = try HardDiskFiles.readImage(hardBacking.url) + guard source.digest == hardBacking.digest else { throw HardDiskFiles.Failure.changed } + guard !source.readOnly, source.data.count <= data.count, data.count % 256 == 0 else { throw HardDiskFiles.Failure.patch } + var patches = Data() + for position in stride(from: 0, to: data.count, by: 256) where + position >= source.data.count || source.data[position..<(position + 256)] != data[position..<(position + 256)] { + let sector = UInt32(position / 256) + patches.append(contentsOf: (0..<4).map { UInt8(truncatingIfNeeded: sector >> ($0 * 8)) }) + patches.append(data[position..<(position + 256)]) + } + return (patches, source.data) + }.value + hardSourceBeforeWrite = plan.1 + hardDigest = try await automaticHardDiskWriter(plan.0, data.count, hardBacking.url, hardBacking.digest) + sourceSaved = true + } else if let backing, !session.temporary { + try await automaticDiskWriter(data, backing.url, backing.bytes) + sourceSaved = true + } + let (applied, snapshot): (Bool, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.commitDiskEditor(token: session.token, restartConfirmed: restartConfirmed, sourceSaved: sourceSaved) { + continuation.resume(returning: ($0, $1)) + } + } + accept(snapshot) + guard applied else { + if sourceSaved, let hardBacking, hardDigest != nil { + do { + let baseline = hardSourceBeforeWrite + try await Task.detached(priority: .userInitiated) { + // Reconstruct the original source from the save's + // retained baseline; guest bytes remain in the lease. + guard let baseline else { throw HardDiskFiles.Failure.patch } + try DiskEditorIO.write(baseline, to: hardBacking.url, protecting: [], replacing: data, + maximum: DiskEditorIO.imageLimit) + }.value + } catch { throw ProfileFailure.message("The CoCo retained its original disk, but restoring the source file failed: \(error.localizedDescription). Keep an edited copy and check the source file before continuing.") } + } else if sourceSaved, let backing { + do { try await automaticDiskWriter(backing.bytes, backing.url, data) } + catch { throw ProfileFailure.message("The CoCo retained its original disk, but restoring the source file failed: \(error.localizedDescription). Keep an edited copy and check the source file before continuing.") } + } + throw ProfileFailure.message(snapshot.errorMessage ?? "Could not apply the edited disk.") + } + if sourceSaved { + if session.hardDisk { + if let hardDigest { hardBackings[session.drive]?.digest = hardDigest } + hardSaveErrors[session.drive] = nil + // A filesystem edit invalidates any previous shell trust digest. + if session.drive == 0 { savedShellGrant = nil } + } else { diskBackings[session.drive]?.bytes = data; diskSaveErrors[session.drive] = nil } + } + activeDiskEditor = nil; diskEditorBacking = nil; hardDiskEditorBacking = nil; binaryName = nil; deniedShellGeneration = nil + // Native C/BASIC documents and drafts are independent and remain intact. + } + func saveDiskAssignments() { + do { try diskStore.save(diskAssignments); diskSettingsError = nil; diskSettingsNeedsSave = false } + catch { + diskSettingsNeedsSave = true + diskSettingsError = "Could not remember disk choices: \(error.localizedDescription). Your mounted disks are unchanged. Retry Saving before quitting." + } + } + private func rememberDrive(_ drive: Int, url: URL?) { + diskAssignments.drives[drive] = url.map { + DiskAssignments.Drive(url: $0, writeProtected: disks[drive].writeProtected, temporary: diskTemporary[drive]) + } + diskRestoreErrors[drive] = nil + saveDiskAssignments() + } + private func setBacking(_ drive: Int, url: URL?, bytes: Data = Data()) { + diskBackings[drive] = url.map { Backing(url: $0.resolvingSymlinksInPath(), bytes: bytes) } + diskSaveErrors[drive] = nil + } + func setDiskTemporary(_ drive: Int, _ value: Bool) { + guard !busy, !diskSaving, (0..<4).contains(drive) else { return } + command(controller.pauseForDiskChange, onSuccess: { [self] in + diskTemporary[drive] = value + if let url = diskAssignments.drives[drive]?.url { rememberDrive(drive, url: url) } + }) + } + func retryDiskSave(_ drive: Int) { + guard !busy, !diskSaving else { return } + diskSaveErrors[drive] = nil; startAutomaticDiskSave() + } + private func startAutomaticDiskSave() { + guard !busy, !diskSaving, !diskEditorLocked, state != .closed else { return } + guard disks.indices.contains(where: { disks[$0].dirty && !disks[$0].writeProtected && !disks[$0].sourceReadOnly && diskBackings[$0] != nil && !diskTemporary[$0] && diskSaveErrors[$0] == nil }) || (hardNeedsSaving && (Date() >= nextHardSave || hardFlushRequests != savedHardFlushRequests)) else { return } + diskSaving = true + diskSaveTask = Task { @MainActor in + await saveAutomaticDisks() + diskSaving = false; diskSaveTask = nil + } + } + private func saveAutomaticDisks() async { + for drive in 0..<4 { + guard !diskTemporary[drive], diskSaveErrors[drive] == nil, let backing = diskBackings[drive] else { continue } + let (data, token, snapshot): (Data?, UInt64, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.captureDiskForSaving(inDrive: drive) { continuation.resume(returning: ($0, $1, $2)) } + } + accept(snapshot) + guard let data else { continue } + do { + try await automaticDiskWriter(data, backing.url, backing.bytes) + // The host now contains this snapshot, even if the guest wrote + // newer sectors during I/O and the acknowledgement stays dirty. + diskBackings[drive]?.bytes = data + _ = await diskStep { controller.acknowledgeDiskSave(inDrive: drive, token: token, completion: $0) } + } catch { + diskSaveErrors[drive] = "Drive \(drive) could not save: \(error.localizedDescription)" + _ = await diskStep(controller.pause) + } + } + await saveAutomaticHardDisks() + } + private func diskStep(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + let snapshot = await withCheckedContinuation { continuation in + operation { continuation.resume(returning: $0) } + } + accept(snapshot) + return snapshot + } + func retryRememberedDisks() { + guard !busy, !diskSaving else { return } + busy = true; inputEpoch += 1 + Task { @MainActor in await restoreDisks(); busy = false } + } + private func restoreDisks() async { + diskRestoreErrors = [:] + guard let rom = diskAssignments.rom else { return } + let paused = await diskStep(controller.pauseForDiskChange) + guard paused.errorMessage == nil else { + diskRestoreErrors[-1] = paused.errorMessage; return + } + if !diskEnabled { + do { + let bytes = try await Task.detached { try DiskFiles.readROM(rom) }.value + let result = await diskStep { controller.loadDiskROM(bytes, name: rom.lastPathComponent, completion: $0) } + if let error = result.errorMessage { throw NSError(domain: "VCC", code: 1, userInfo: [NSLocalizedDescriptionKey: error]) } + } catch { + diskRestoreErrors[-1] = "Disk ROM \(rom.lastPathComponent): \(error.localizedDescription)"; return + } + } + for drive in 0..<4 { + // Retry never replaces a mounted disk, including unexported guest writes. + guard !disks[drive].mounted, let saved = diskAssignments.drives[drive] else { continue } + do { + let image = try await Task.detached { try DiskFiles.readImage(saved.url) }.value + var result = await diskStep { + controller.mountDisk(image.data, drive: drive, name: saved.url.lastPathComponent, + readOnly: image.readOnly, completion: $0) + } + if result.errorMessage == nil && saved.writeProtected && !result.disks[drive].writeProtected { + result = await diskStep { controller.setDiskWriteProtected(true, drive: drive, completion: $0) } + } + if let error = result.errorMessage { throw NSError(domain: "VCC", code: 1, userInfo: [NSLocalizedDescriptionKey: error]) } + setBacking(drive, url: saved.url, bytes: image.data) + diskTemporary[drive] = saved.temporary + } catch { diskRestoreErrors[drive] = "Drive \(drive), \(saved.url.lastPathComponent): \(error.localizedDescription)" } + } + } + func forgetUnavailableDisks() { + guard !busy, !diskSaving, !diskEnabled else { return } + let alert = NSAlert(); alert.messageText = "Forget the remembered disk setup?" + alert.informativeText = "This removes the remembered disk ROM and drive assignments. The files will not be changed." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Forget") + guard alert.runModal() == .alertSecondButtonReturn else { return } + diskAssignments.rom = nil; diskAssignments.drives = Array(repeating: nil, count: 4) + diskRestoreErrors = [:]; saveDiskAssignments() + } + func loadDiagnostic() { + binaryName = nil; systemROMURL = nil; profileName = nil; bootNitros9 = false + title = "Diagnostic preview"; fileError = nil + busy = true; inputEpoch += 1 + Task { @MainActor in + defer { busy = false } + let result = await diskStep { controller.loadDiagnostic(use6309: use6309, completion: $0) } + if result.errorMessage == nil { _ = await applyDriveWireDefault(false) } + } + } + var canPaste: Bool { state == .running && !busy && pasteRemaining == 0 } + func pasteClipboard(_ mode: CocoPaste.Mode = .text) { + guard canPaste else { return } + guard let text = NSPasteboard.general.string(forType: .string) else { + fileError = "The clipboard does not contain text."; return + } + do { + let paste = try CocoPaste(text, mode: mode) + if mode != .text { + let alert = NSAlert() + alert.messageText = mode == .newBASIC ? "Replace the BASIC program?" : "Merge BASIC lines?" + alert.informativeText = (mode == .newBASIC + ? "This types NEW, clearing the program in CoCo memory, then enters the clipboard's numbered lines. Saved files are kept." + : "This enters the clipboard's numbered lines into the current program. Matching line numbers are replaced; a line number alone deletes that line.") + + " Make sure the computer is waiting at the BASIC prompt. Nothing is run automatically. Cancel Paste or Pause stops further typing, but cannot undo lines already entered." + alert.addButton(withTitle: "Cancel") + alert.addButton(withTitle: mode == .newBASIC ? "Replace and Paste" : "Merge and Paste") + guard alert.runModal() == .alertSecondButtonReturn else { return } + } + startPaste(paste) + } catch { fileError = error.localizedDescription } + } + func startPaste(_ paste: CocoPaste) { + guard canPaste else { return } + command { controller.pasteChords(paste.chords.map { NSNumber(value: $0) }, completion: $0) } + } + func cancelPaste() { command(controller.cancelPaste) } + func copyScreenText() { + guard !busy, state == .running || state == .paused else { return } + controller.copyScreenText { [weak self] text, snapshot in + MainActor.assumeIsolated { + self?.accept(snapshot) + guard let text else { return } + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(text, forType: .string) + } + } + } + func setKeyboard(_ mask: UInt64) { controller.setKeyboardMask(mask) } + // UI confirms CPU/RAM changes before calling this method. The controller + // checks active disk writes and recordings again on its serial queue. + func applyMachineSettings(_ value: MachineSettings) { + guard !busy, !diskSaving, state != .closed, value.valid else { return } + command({ controller.configureMachine(use6309: value.use6309, ram: value.ram, + overclock: value.overclock, frameInterval: value.frameInterval, + fastForward: value.fastForward, completion: $0) }, onSuccess: { [self] in + value.save(in: displayDefaults) + }) + } + func setFastForward(_ enabled: Bool) { + var next = settings; next.fastForward = enabled; applyMachineSettings(next) + } + func openROM() { + guard !busy else { return } + busy = true; inputEpoch += 1; controller.setKeyboardMask(0) + let panel = NSOpenPanel() + panel.title = "Open CoCo 3 System ROM" + panel.message = "Select an alternative 32 KiB CoCo 3 system ROM. This choice is remembered. Bundled ROMs can be restored from Settings when available." + panel.allowedContentTypes = [UTType(filenameExtension: "rom") ?? .data, .data] + panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + panel.begin { [weak self] result in + guard let self else { return } + guard result == .OK, let url = panel.url else { self.busy = false; return } + self.busy = true; self.fileError = nil + Task { @MainActor in + do { + let data = try await Task.detached(priority: .userInitiated) { try ROMImage.read(url) }.value + self.installROM(data, url: url) + } catch { self.fileError = error.localizedDescription; self.busy = false } + } + } + } + func installROM(_ data: Data, url: URL) { + busy = true; inputEpoch += 1 + controller.loadROM(data, use6309: use6309) { [weak self] snapshot in + MainActor.assumeIsolated { + guard let self else { return } + self.accept(snapshot) + guard snapshot.errorMessage == nil else { self.busy = false; return } + self.title = url.lastPathComponent; self.systemROMURL = url; self.profileName = nil + self.binaryName = nil; self.bootNitros9 = false + Task { @MainActor in + let configured = await self.applyDriveWireDefault(false) + self.rememberStartup() + self.recentMedia.record(url, as: .systemROM) + if configured { self.resume() } else { self.busy = false } + } + } + } + } + func openBinary() { + guard canQuickLoad else { return } + prepareBinaryLoad { [self] in + let panel = NSOpenPanel() + panel.title = "Load CoCo Binary" + panel.message = "Choose a CoCo block-format .bin program. Loading replaces its memory ranges and starts the program without resetting. Cancel leaves emulation paused." + panel.allowedContentTypes = [UTType(filenameExtension: "bin") ?? .data] + panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false; panel.allowsMultipleSelection = false + panel.begin { [self] result in + guard result == .OK, let url = panel.url else { busy = false; return } + readBinary(url) + } + } + } + func startReviewedC(_ binary: Data, disk: Data?, name: String, stop: UInt16, expected: VCCMachineSnapshot) async -> VCCMachineSnapshot { + await diskStep { controller.startReviewedC(binary, disk: disk, name: name, stop: stop, expected: expected, completion: $0) } + } + func continueReviewedC(_ expected: VCCMachineSnapshot, name: String, stop: UInt16, bytes: Data) async -> VCCMachineSnapshot { + await diskStep { controller.continueReviewedC(expected, name: name, stop: stop, bytes: bytes, completion: $0) } + } + func ejectReviewedCDisk(_ name: String) async { + _ = await diskStep { controller.ejectReviewedCDisk(name, completion: $0) } + } + func reviewedCOutput() async -> (String?, VCCMachineSnapshot) { + await withCheckedContinuation { c in controller.inspectScreenText { c.resume(returning: ($0, $1)) } } + } + + func mcpReadinessSnapshot() async -> VCCMachineSnapshot { + await withCheckedContinuation { c in controller.assistantReadiness { c.resume(returning: $0) } } + } + + func mcpMachineSnapshot() async -> VCCMachineSnapshot { + await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } } + } + + func checkReviewedBASIC(_ expected: VCCMachineSnapshot, source: String) async throws -> VCCMachineSnapshot { + let state = await diskStep { controller.checkReviewedBASIC(expected, source: source, completion: $0) } + if let message = state.errorMessage { throw ProfileFailure.message(message) } + return state + } + + func mcpScreen(expected: VCCMachineSnapshot, source: String) async throws -> [String: Any] { + let (screen, snapshot): ([String: Any]?, VCCMachineSnapshot) = await withCheckedContinuation { c in + controller.assistantScreen(expected: expected, source: source) { c.resume(returning: ($0, $1)) } + } + guard let screen, snapshot.errorMessage == nil else { + throw ProfileFailure.message(snapshot.errorMessage ?? "Guest text is unavailable.") + } + return screen.merging(["frame": snapshot.frames, "signal": snapshot.videoOutput, "paste_remaining": Int(snapshot.pasteRemaining)]) { _, new in new } + } + + func mcpCompiledGuest(lease: VCCCompiledRunLease, runID: String, expected: VCCMachineSnapshot, + assembly: Bool, key: NSNumber?, readScreen: Bool, finalScreen: Bool = false) async throws -> [String: Any] { + let (text, state): (String?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.compiledGuest(lease: lease, runID: runID, expected: expected, assembly: assembly, + key: key, readScreen: readScreen, finalScreen: finalScreen) { + continuation.resume(returning: ($0, $1)) + } + } + if let error = state.errorMessage { throw ProfileFailure.message(error) } + guard let text else { return [:] } + return ["run_id": runID, "text": text, "frame": state.frames, "signal": state.videoOutput, + "paste_remaining": Int(state.pasteRemaining), "status": state.state == .paused ? "paused" : "running"] + } + + func cancelMCPInput(runID: String) { controller.cancelAssistantPaste(runID) } + + func mcpPaste(_ text: String, runID: String, direct: Bool, expected: VCCMachineSnapshot, source: String) async throws { + let keys = try CocoPaste(text, mode: .text).chords.map { NSNumber(value: $0) } + let result = await diskStep { controller.assistantPaste(chords: keys, runID: runID, direct: direct, expected: expected, source: source, completion: $0) } + if let error = result.errorMessage { throw ProfileFailure.message(error) } + } + + func loadBASICSource(_ source: String, run: Bool, breakpoints: Set = [], + review: (expected: VCCMachineSnapshot, existing: String)? = nil) async -> VCCMachineSnapshot? { + guard !busy, !diskSaving, state != .closed else { + fileError = "The machine is busy. Try the BASIC transfer again when it is ready." + return nil + } + busy = true; inputEpoch += 1; fileError = nil + defer { busy = false } + let points = breakpoints.sorted().map { NSNumber(value: $0) } + let result = await diskStep { completion in + if let review { + controller.assistantLoad(source: source, breakpoints: points, expected: review.expected, existing: review.existing, completion: completion) + } else { + controller.basicLoadSource(source, run: run, breakpoints: points, completion: completion) + } + } + if let error = result.errorMessage { fileError = error; return nil } + binaryName = nil + if run { focusRequest += 1 } + return result + } + func configureBASICBreakpoints(_ lines: Set, source: String) async -> Bool { + guard !busy, !diskSaving, state != .closed else { return false } + busy = true; defer { busy = false } + let snapshot = await diskStep { controller.basicSetBreakpoints(lines.sorted().map { NSNumber(value: $0) }, source: source, completion: $0) } + return snapshot.errorMessage == nil + } + func continueBASIC(source: String) async -> Bool { + guard !busy, !diskSaving, state == .paused else { return false } + busy = true; inputEpoch += 1; defer { busy = false } + let snapshot = await diskStep { controller.basicContinue(source: source, completion: $0) } + return snapshot.errorMessage == nil + } + func stepBASIC(source: String, over: Bool) async -> Bool { + guard !busy, !diskSaving, state == .paused else { return false } + busy = true; inputEpoch += 1; defer { busy = false } + let snapshot = await diskStep { controller.basicStep(source: source, over: over, completion: $0) } + return snapshot.errorMessage == nil + } + func stepOutBASIC(source: String) async -> Bool { + guard !busy, !diskSaving, state == .paused else { return false } + busy = true; inputEpoch += 1; defer { busy = false } + let snapshot = await diskStep { controller.basicStepOut(source: source, completion: $0) } + return snapshot.errorMessage == nil + } + func detachBASICDebug() { + controller.basicClearDebug { [weak self] snapshot in + MainActor.assumeIsolated { self?.accept(snapshot) } + } + } + func exportBASICSource(_ source: String, name: String, cassette: Bool) async -> Data? { + guard !busy, !diskSaving, state != .closed else { + fileError = "The machine is busy. Try exporting BASIC again when it is ready." + return nil + } + busy = true; fileError = nil + defer { busy = false } + let (data, snapshot): (Data?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.basicExportSource(source, name: name, cassette: cassette) { data, snapshot in + continuation.resume(returning: (data, snapshot)) + } + } + accept(snapshot) + return snapshot.errorMessage == nil ? data : nil + } + /// Exporting source creates a separate file; it must never become an implicit + /// overwrite of an assigned disk, cassette, ROM, SD card file or editor source. + func writeBASICExport(_ data: Data, to destination: URL, sourceURL: URL?) async throws { + try await writeDevelopmentFile(data, to: destination, protecting: [sourceURL].compactMap { $0 }) + } + + func writeDevelopmentFile(_ data: Data, to destination: URL, protecting sources: [URL], + allowEmpty: Bool = false, replacing expected: Data? = nil) async throws { + guard !busy, !diskSaving, state != .closed else { + throw ProfileFailure.message("The machine is busy. Try saving again when the current operation finishes.") + } + busy = true + defer { busy = false } + let protected = developmentAssignedMediaURLs + sources + try await Task.detached(priority: .userInitiated) { + try DiskFiles.writeDevelopmentFile(data, to: destination, protecting: protected, allowEmpty: allowEmpty, replacing: expected) + }.value + } + func inspectBASIC(source: String, stop: BASICDebugState) async -> ([BASICVariable]?, String?) { + await withCheckedContinuation { continuation in + controller.basicInspect(source: source) { rows, snapshot in + guard snapshot.generation == stop.generation, snapshot.cycles == stop.cycles, + snapshot.state == .paused, snapshot.basicDebugAttached, + snapshot.basicStoppedLine == (stop.line ?? -1) else { + continuation.resume(returning: (nil, "The BASIC stop changed. Waiting for the current position.")); return + } + let values = rows?.compactMap(BASICVariable.init) + continuation.resume(returning: (snapshot.errorMessage == nil ? values : nil, snapshot.errorMessage)) + } + } + } + func readBASICSource() async -> String? { + guard !busy, !diskSaving, state != .closed else { + fileError = "The machine is busy. Try reading BASIC again when it is ready." + return nil + } + busy = true; fileError = nil + defer { busy = false } + let (source, snapshot): (String?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.basicReadSource { text, snapshot in continuation.resume(returning: (text, snapshot)) } + } + accept(snapshot) + return snapshot.errorMessage == nil ? source : nil + } + func loadBinary(_ url: URL) { + guard canQuickLoad else { return } + prepareBinaryLoad { [self] in readBinary(url) } + } + private func prepareBinaryLoad(_ ready: @escaping () -> Void) { + busy = true; inputEpoch += 1; fileError = nil + controller.pause { [weak self] snapshot in + MainActor.assumeIsolated { + guard let self else { return } + self.accept(snapshot) + guard snapshot.errorMessage == nil else { self.busy = false; return } + ready() + } + } + } + private func readBinary(_ url: URL) { + Task { @MainActor in + do { + let bytes = try await Task.detached(priority: .userInitiated) { try BinaryFile.read(url) }.value + command({ controller.quickLoadBinary(bytes, completion: $0) }, onSuccess: { [self] in + binaryName = url.lastPathComponent; recentMedia.record(url, as: .binary) + }) + } catch { fileError = error.localizedDescription; busy = false } + } + } + func setVideoOutput(_ output: DisplayOutput) { + command({ controller.setVideoOutput(output.rawValue, completion: $0) }) { + self.displayDefaults.set(output.rawValue, forKey: DisplayOutput.preferenceKey) + } + } + // The switch records a local override. A profile document can never grant + // outbound networking, even if it has the same name/ROMs as a system preset. + private func applyDriveWireDefault(_ builtInNitros9: Bool) async -> Bool { + self.builtInNitros9 = builtInNitros9 + presetProgramRevision = builtInNitros9 ? programRevision : nil + let enabled = (displayDefaults.object(forKey: Self.driveWireKey) as? Bool) ?? builtInNitros9 + guard enabled != driveWireEnabled else { return true } + let result = await diskStep { controller.setDriveWireEnabled(enabled, completion: $0) } + if let error = result.errorMessage { fileError = error; return false } + return true + } + + func setDriveWireNetworking(_ enabled: Bool) { + guard !busy, state != .closed else { return } + command({ controller.setDriveWireEnabled(enabled, completion: $0) }, onSuccess: { [self] in + displayDefaults.set(enabled, forKey: Self.driveWireKey) + }) + } + func setAudio(_ enabled: Bool) { + command { controller.setAudioEnabled(enabled, volume: Float(volume), completion: $0) } + } + func seekTape(_ position: Double) { command { controller.seekTape(UInt64(max(0, position)), completion: $0) } } + func setFastTape(_ enabled: Bool) { command { controller.setTapeFast(enabled, completion: $0) } } + func tapeAction(_ action: Int) { + if action >= 3 && tapeDirty { return } + if action == 3 { tapeName = "No tape" } + if action >= 4 { tapeName = action == 4 ? "New recording.cas" : "New recording.wav" } + command({ controller.tapeAction(action, completion: $0) }, onSuccess: { [self] in + if action >= 3 { cassetteURL = nil; rememberStartup() } + }) + } + func openTape() { + guard !busy, !tapeDirty else { return } + fileError = nil + busy = true; inputEpoch += 1; controller.setKeyboardMask(0) + let panel = NSOpenPanel() + panel.title = "Insert Cassette Image" + panel.allowedContentTypes = [UTType(filenameExtension: "cas") ?? .data, .wav] + panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + panel.begin { [weak self] result in + guard let self else { return } + guard result == .OK, let url = panel.url else { self.busy = false; return } + self.readTape(url) + + } + } + private func readTape(_ url: URL) { + Task { @MainActor in + do { + let data = try await Task.detached(priority: .userInitiated) { try TapeImage.read(url) }.value + command({ controller.mountTape(data, wav: url.pathExtension.lowercased() == "wav", completion: $0) }, onSuccess: { [self] in + tapeName = url.lastPathComponent; cassetteURL = url; rememberStartup() + recentMedia.record(url, as: .cassette) + }) + } catch { fileError = error.localizedDescription; busy = false } + } + } + func exportTape() { + guard !busy, tapeMounted else { return } + busy = true; inputEpoch += 1; controller.setKeyboardMask(0); fileError = nil + controller.exportTape { [weak self] data, snapshot in + MainActor.assumeIsolated { + guard let self else { return } + self.accept(snapshot) + guard let data else { self.busy = false; return } + let panel = NSSavePanel() + panel.title = "Export Cassette Image" + panel.allowedContentTypes = [self.tapeWAV ? .wav : UTType(filenameExtension: "cas") ?? .data] + panel.nameFieldStringValue = self.tapeName + panel.begin { result in + guard result == .OK, let url = panel.url else { self.busy = false; return } + Task { @MainActor in + do { + try await Task.detached(priority: .userInitiated) { try data.write(to: url, options: .atomic) }.value + self.tapeName = url.lastPathComponent + self.command(self.controller.markTapeSaved, onSuccess: { self.cassetteURL = url; self.rememberStartup() }) + } catch { self.fileError = error.localizedDescription; self.busy = false } + } + } + } + } + } + func discardTape() { + let alert = NSAlert() + alert.messageText = "Discard this recording?" + alert.informativeText = "The unsaved recording will be lost. Export it first to keep a copy." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard") + guard alert.runModal() == .alertSecondButtonReturn else { return } + tapeName = "No tape" + command(controller.discardTape, onSuccess: { self.cassetteURL = nil; self.rememberStartup() }) + } + // Start dialogs only after the worker has frozen a safe, idle disk controller. + private func diskDialog(_ show: @escaping () -> Void) { + guard !busy, !diskSaving else { return } + busy = true; inputEpoch += 1; fileError = nil + controller.pauseForDiskChange { [weak self] snapshot in + MainActor.assumeIsolated { + guard let self else { return } + self.accept(snapshot) + guard snapshot.errorMessage == nil else { self.busy = false; return } + show() + } + } + } + func openDiskROM() { + diskDialog { [self] in + let panel = NSOpenPanel() + panel.title = "Choose Floppy Disk ROM" + panel.message = "Select an 8 or 16 KiB disk ROM, such as disk11.rom. This cold-resets the machine and clears its BASIC program. Mounted disks are retained. Press Run afterward." + panel.allowedContentTypes = [UTType(filenameExtension: "rom") ?? .data, .data] + panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + panel.begin { [self] result in + guard result == .OK, let url = panel.url else { busy = false; return } + selectDiskROM(url) + } + } + } + func openDisk(_ drive: Int) { + diskDialog { [self] in + let panel = NSOpenPanel(); panel.title = "Insert Disk in Drive \(drive)" + panel.message = "Writable disks save automatically. Enable Temporary changes in the drive controls to keep changes in memory." + panel.allowedContentTypes = DiskFiles.extensions.map { UTType(filenameExtension: $0) ?? .data } + panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false; panel.allowsMultipleSelection = false + panel.begin { [self] result in + guard result == .OK, let url = panel.url else { busy = false; return } + insertDisk(url, drive: drive) + } + } + } + func selectDiskROM(_ url: URL) { + guard !diskSaving else { return } + busy = true; inputEpoch += 1; fileError = nil + Task { @MainActor in + do { + let bytes = try await Task.detached(priority: .userInitiated) { try DiskFiles.readROM(url) }.value + command({ controller.loadDiskROM(bytes, name: url.lastPathComponent, completion: $0) }, onSuccess: { [self] in + diskAssignments.rom = url; diskRestoreErrors[-1] = nil + recentMedia.record(url, as: .diskROM) + // Preserve existing ROM cartridges. Use the first free slot + // only when this mode has no floppy assignment yet. + let indices = cartridgeAssignments.multiPak ? Array(1...4).reversed().map { $0 } : [0] + if !indices.contains(where: { cartridgeAssignments.slots[$0].kind == .floppy }), + let free = indices.first(where: { cartridgeAssignments.slots[$0].kind == .empty }) { + cartridgeAssignments.slots[free].kind = .floppy + } + busy = true + Task { @MainActor in + _ = await applyCartridges(cartridgeAssignments, bytes: cartridgeBytes) + diskAssignments.cartridges = cartridgeAssignments; saveDiskAssignments() + await restoreDisks(); busy = false + } + }) + } catch { fileError = error.localizedDescription; busy = false } + } + } + func insertDisk(_ url: URL, drive: Int) { + guard !diskSaving else { return } + busy = true; inputEpoch += 1; fileError = nil + Task { @MainActor in + do { + let image = try await Task.detached(priority: .userInitiated) { try DiskFiles.readImage(url) }.value + command({ controller.mountDisk(image.data, drive: drive, name: url.lastPathComponent, readOnly: image.readOnly, completion: $0) }, + onSuccess: { [self] in setBacking(drive, url: url, bytes: image.data); rememberDrive(drive, url: url); recentMedia.record(url, as: .floppy(drive)) }) + } catch { fileError = error.localizedDescription; busy = false } + } + } + /// A Finder/drop insertion has an explicit execution policy; mounting alone + /// never boots a disk or replaces the running guest program. + func insertDiskFromMedia(_ url: URL, drive: Int, execution: DiskInsertionExecution, reset: DiskInsertionReset = .none) async throws { + guard !busy, !diskSaving, !diskEditorLocked, state != .closed, + RecentMedia.isLocalFile(url), (0..<4).contains(drive) else { + throw ProfileFailure.message("Wait for the current operation before inserting this disk.") + } + guard diskConnected else { throw ProfileFailure.message("Connect a floppy controller in Cartridges before inserting this disk.") } + busy = true; inputEpoch += 1; fileError = nil + defer { busy = false } + let epoch = inputEpoch + let initial = await diskStep(controller.snapshot) + _ = try await Task.detached(priority: .userInitiated) { try DiskFiles.readImage(url) }.value + let current = await diskStep(controller.snapshot) + guard inputEpoch == epoch, current.generation == initial.generation, !current.diskEditorLocked, current.state != .closed else { + throw ProfileFailure.message("The machine changed while this disk was being opened. Choose the disk again.") + } + let paused = await diskStep(controller.pauseForDiskChange) + if let error = paused.errorMessage { throw ProfileFailure.message(error) } + if let pending = diskSaveTask { await pending.value } + await saveAutomaticDisks(); await saveAutomaticHardDisks(force: true) + let ready = await diskStep(controller.snapshot) + guard inputEpoch == epoch, ready.generation == initial.generation, !ready.diskEditorLocked else { + throw ProfileFailure.message("The machine changed while preparing to insert the disk. Choose it again.") + } + guard !unsavedMedia else { + throw ProfileFailure.message("Save As or export unsaved media before opening another file. The machine is paused; your media and recordings are kept.") + } + // Automatic saving can update the very file being inserted. Read its + // final bytes after flushing, then recheck machine identity before mount. + let image = try await Task.detached(priority: .userInitiated) { try DiskFiles.readImage(url) }.value + let final = await diskStep(controller.snapshot) + guard inputEpoch == epoch, final.generation == initial.generation, !final.diskEditorLocked, final.state != .closed else { + throw ProfileFailure.message("The machine changed while this disk was being opened. Choose the disk again.") + } + // Parse and validate the full image on the controller queue before any + // optional reset. Reset precedes installation in that same transaction. + let mounted = await diskStep { controller.mountDisk(image.data, drive: drive, name: url.lastPathComponent, readOnly: image.readOnly, reset: reset.controllerValue, completion: $0) } + if let error = mounted.errorMessage { throw ProfileFailure.message(error) } + if reset != .none { binaryName = nil; deniedShellGeneration = nil } + setBacking(drive, url: url, bytes: image.data); rememberDrive(drive, url: url) + recentMedia.record(url, as: .floppy(drive)) + if execution == .run || (execution == .keepCurrentState && initial.state == .running) { + let resumed = await diskStep(controller.resume) + if let error = resumed.errorMessage { throw ProfileFailure.message("The disk was inserted, but the CoCo could not run: \(error)") } + } + } + func createDisk(_ drive: Int, format: VCCFloppyFormat = .standard) { + guard !busy, !diskSaving else { return } + command({ controller.createDisk(inDrive: drive, format: format, completion: $0) }, onSuccess: { [self] in setBacking(drive, url: nil); rememberDrive(drive, url: nil) }) + } + func ejectDisk(_ drive: Int) { + guard !busy, !diskSaving else { return } + command({ controller.ejectDisk(inDrive: drive, discard: false, completion: $0) }, onSuccess: { [self] in setBacking(drive, url: nil); rememberDrive(drive, url: nil) }) + } + func protectDisk(_ drive: Int, _ value: Bool) { + guard !busy, !diskSaving else { return } + command({ controller.setDiskWriteProtected(value, drive: drive, completion: $0) }, onSuccess: { [self] in + if let url = diskAssignments.drives[drive]?.url { rememberDrive(drive, url: url) } + }) + } + func discardDisk(_ drive: Int) { + diskDialog { [self] in + let alert = NSAlert(); alert.messageText = "Discard changes to drive \(drive)?" + alert.informativeText = "This ejects the in-memory disk and loses its unsaved changes. The original file will not be changed." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard and Eject") + guard alert.runModal() == .alertSecondButtonReturn else { busy = false; return } + command({ controller.ejectDisk(inDrive: drive, discard: true, completion: $0) }, onSuccess: { [self] in setBacking(drive, url: nil); rememberDrive(drive, url: nil) }) + } + } + func disableDisks() { + diskDialog { [self] in + let alert = NSAlert(); alert.messageText = "Disable the floppy controller?" + alert.informativeText = "All four disks will be ejected and the machine will cold-reset, clearing its BASIC program. Save or discard modified disks first." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Disable") + guard alert.runModal() == .alertSecondButtonReturn else { busy = false; return } + command(controller.disableDisks, onSuccess: { [self] in + diskAssignments.rom = nil; diskAssignments.drives = Array(repeating: nil, count: 4) + diskRestoreErrors = [:]; saveDiskAssignments() + diskBackings = Array(repeating: nil, count: 4); diskSaveErrors = [:] + diskTemporary = Array(repeating: false, count: 4) + }) + } + } + /// Companion handoff takes immutable guest-visible bytes, including unsaved + /// writes. It neither exports/acknowledges a save nor pauses the emulator. + func snapshotDiskCopy(inDrive drive: Int) async throws -> Data { + guard !busy, !diskSaving, !diskEditorLocked, state != .closed, (0..<4).contains(drive) else { + throw ProfileFailure.message("Wait for the current media operation before copying this disk.") + } + busy = true; defer { busy = false } + let (data, snapshot): (Data?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.snapshotDiskCopy(inDrive: drive) { continuation.resume(returning: ($0, $1)) } + } + accept(snapshot) + guard let data else { throw ProfileFailure.message(snapshot.errorMessage ?? "Could not copy this disk. Wait for disk activity to finish and try again.") } + return data + } + func exportDisk(_ drive: Int, to destination: URL? = nil) { + guard !busy, !diskSaving else { return } + busy = true; inputEpoch += 1; fileError = nil + controller.exportDisk(inDrive: drive) { [weak self] data, token, snapshot in + MainActor.assumeIsolated { + guard let self else { return } + self.accept(snapshot) + guard let data else { self.busy = false; return } + if let destination { + self.finishDiskExport(data, token: token, drive: drive, url: destination); return + } + let panel = NSSavePanel(); panel.title = "Save Disk from Drive \(drive) As" + let ext = self.disks[drive].floppyExtension ?? "dsk" + panel.allowedContentTypes = [UTType(filenameExtension: ext) ?? .data] + let stem = (self.disks[drive].name as NSString).deletingPathExtension + panel.nameFieldStringValue = (stem.isEmpty ? "Untitled" : stem) + "." + ext + panel.begin { result in + guard result == .OK, let url = panel.url else { self.busy = false; return } + self.finishDiskExport(data, token: token, drive: drive, url: url) + } + } + } + } + private func finishDiskExport(_ data: Data, token: UInt64, drive: Int, url: URL) { + Task { @MainActor in + do { + try await Task.detached(priority: .userInitiated) { try DiskFiles.export(data, to: url) }.value + command({ controller.markDiskSaved(inDrive: drive, token: token, name: url.lastPathComponent, completion: $0) }, + onSuccess: { [self] in setBacking(drive, url: url, bytes: data); rememberDrive(drive, url: url) }) + } catch { fileError = error.localizedDescription; busy = false } + } + } + func prepareToQuit(_ completion: @escaping () -> Void) { + busy = true; inputEpoch += 1 + Task { @MainActor in + _ = await diskStep(controller.pause) + if let pending = diskSaveTask { await pending.value } + await saveAutomaticDisks() + await saveAutomaticHardDisks(force: true) + _ = await diskStep(controller.snapshot) + busy = false; completion() + } + } + func resume() { command(controller.resume) } + func pause() { command(controller.pause) } + + // Debugger operations share the machine queue and normal busy/input state, + // but keep keyboard focus in the debugger after Continue or an edit. + func readDebugger(address: UInt16, followPC: Bool, memoryAddress: UInt16, + physicalAddress: UInt32 = 0, physicalMemory: Bool = false, + completion: @escaping (VCCDebuggerSnapshot?) -> Void) { + guard !busy, !diskSaving, state != .closed else { completion(nil); return } + controller.debuggerSnapshot(address: address, followPC: followPC, memoryAddress: memoryAddress, + physicalAddress: physicalAddress, physicalMemory: physicalMemory) { [weak self] snapshot in + MainActor.assumeIsolated { + self?.accept(snapshot.machine) + completion(snapshot) + } + } + } + private func debuggerCommand(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void, + completion: @escaping () -> Void) { + developmentCommand(operation) { _ in completion() } + } + + private func developmentCommand(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void, + completion: @escaping (VCCMachineSnapshot?) -> Void) { + guard canQuickLoad else { completion(nil); return } + busy = true; inputEpoch += 1; fileError = nil + operation { [weak self] snapshot in + MainActor.assumeIsolated { + self?.accept(snapshot); self?.busy = false; completion(snapshot) + } + } + } + var developmentDefaults: UserDefaults { displayDefaults } + /// Assigned files and live writable backings protect build snapshots from cleanup. + var developmentAssignedMediaURLs: [URL] { + var urls = [systemROMURL, cassetteURL, diskAssignments.rom].compactMap { $0 } + urls += diskAssignments.drives.compactMap { $0?.url } + urls += hardSettings.drives.compactMap { $0?.url } + urls += diskBackings.compactMap { $0?.url } + urls += hardBackings.compactMap { $0?.url } + for slot in cartridgeAssignments.slots { + urls += [slot.url, slot.speechROMURL, slot.sdcFolderURL].compactMap { $0 } + } + return urls + } + var developmentRunDirectory: URL { diskStore.url.deletingLastPathComponent().appendingPathComponent("Development Runs", isDirectory: true) } + var assemblyProgramRevision: UInt64 { programRevision } + func launchAssembly(_ data: Data, breakpoints: [UInt16], guards: [UInt16: Data], + pauseAtEntry: Bool, requires6309: Bool, expectedGeneration: UInt64, + expectedRevision: UInt64, expectedMapping: UInt64, shared: Bool = false, completion: @escaping (VCCMachineSnapshot?) -> Void) { + guard usageProfile != .nitros9, !builtInNitros9 else { + fileError = "Choose a BASIC profile to run a standalone assembly program. You can still assemble and export here." + completion(nil); return + } + guard !unsavedMedia else { + fileError = "Save pending media changes before running a development program." + completion(nil); return + } + let entries = guards.sorted { $0.key < $1.key } + developmentCommand({ controller.launchAssembly(data, points: breakpoints.map { NSNumber(value: $0) }, + addresses: entries.map { NSNumber(value: $0.key) }, bytes: entries.map { $0.value }, + pauseAtEntry: pauseAtEntry, requires6309: requires6309, generation: expectedGeneration, + revision: expectedRevision, mapping: expectedMapping, shared: shared, completion: $0) }, completion: completion) + } + func pauseAssembly(expected: VCCMachineSnapshot, completion: @escaping (VCCMachineSnapshot?) -> Void) { + developmentCommand({ controller.pauseAssembly(expected, completion: $0) }, completion: completion) + } + func controlAssembly(step: Bool, expected: VCCMachineSnapshot, completion: @escaping (VCCMachineSnapshot?) -> Void) { + developmentCommand({ controller.controlAssembly(step, expected: expected, completion: $0) }, completion: completion) + } + func updateAssembly(breakpoints: [UInt16], guards: [UInt16: Data], expected: VCCMachineSnapshot, + completion: @escaping (VCCMachineSnapshot?) -> Void) { + guard breakpoints.allSatisfy({ guards[$0] != nil }) else { completion(nil); return } + developmentCommand({ controller.updateAssembly(breakpoints.map { NSNumber(value: $0) }, expected: expected, + completion: $0) }, completion: completion) + } + func clearAssembly(expected: VCCMachineSnapshot) { + // The queue checks ownership again even if a new build has launched in the meantime. + controller.clearAssembly(expected) { [weak self] snapshot in + MainActor.assumeIsolated { self?.accept(snapshot) } + } + } + func debuggerLoadDevelopmentBinary(_ data: Data, breakpoints: [UInt16], completion: @escaping (VCCMachineSnapshot?) -> Void) { + guard canQuickLoad else { completion(nil); return } + busy = true; inputEpoch += 1; fileError = nil + controller.debuggerLoadBinary(data, breakpoints: breakpoints.map { NSNumber(value: $0) }) { [weak self] snapshot in + MainActor.assumeIsolated { self?.accept(snapshot); self?.busy = false; completion(snapshot) } + } + } + func armDevelopmentBreakpoints(_ addresses: [UInt16], guards: [UInt16:Data], completion: @escaping (VCCMachineSnapshot?) -> Void) { + guard !busy, !diskSaving, state == .paused else { completion(nil); return } + let sorted = guards.keys.sorted() + busy = true; inputEpoch += 1 + controller.debuggerArmDevelopmentBreakpoints(addresses.map { NSNumber(value: $0) }, + guardAddresses: sorted.map { NSNumber(value: $0) }, guardBytes: sorted.map { guards[$0]! }) { [weak self] snapshot in + MainActor.assumeIsolated { self?.accept(snapshot); self?.busy = false; completion(snapshot) } + } + } + func armDevelopmentBreakpoints(_ addresses: [UInt16], sourceMap: CMOCProjectSourceMap, + pointModules: [UInt16: Set]? = nil, completion: @escaping (VCCMachineSnapshot?) -> Void) { + guard let layout = sourceMap.bankedLayout else { + armDevelopmentBreakpoints(addresses, guards: Dictionary(uniqueKeysWithValues: + sourceMap.instructions.map { ($0.address, Data($0.bytes)) }), completion: completion) + return + } + guard !busy, !diskSaving, state == .paused else { completion(nil); return } + let modules: [[String: Any]] = layout.modules.compactMap { module in + let code = module.codeGuards + guard !code.isEmpty else { return nil } + var definition: [String: Any] = ["id": module.id, "pages": module.pages.map { + ["logicalPage": $0.logicalPage, "physicalPage": $0.physicalPage] + }, "addresses": code.map { NSNumber(value: $0.address) }, "bytes": code.map { Data($0.bytes) }] + if let pointModules { + definition["breakpoints"] = addresses.filter { pointModules[$0]?.contains(module.id) == true }.map { NSNumber(value: $0) } + } + return definition + } + busy = true; inputEpoch += 1 + controller.debuggerArmBankedDevelopmentBreakpoints(addresses.map { NSNumber(value: $0) }, modules: modules) { [weak self] snapshot in + MainActor.assumeIsolated { self?.accept(snapshot); self?.busy = false; completion(snapshot) } + } + } + func clearDevelopmentBreakpoints(completion: @escaping () -> Void) { + debuggerCommand(controller.debuggerClearDevelopmentBreakpoints, completion: completion) + } + func runDevelopmentBinary(_ data: Data, completion: @escaping (VCCMachineSnapshot?) -> Void) { + // The strict development loader validates every record before mutating RAM. + guard data.count >= 5 else { completion(nil); return } + let entry = UInt16(data[data.count - 2]) << 8 | UInt16(data[data.count - 1]) + debuggerLoadDevelopmentBinary(data, breakpoints: [entry]) { [weak self] snapshot in + guard let self, let snapshot, snapshot.errorMessage == nil else { completion(snapshot); return } + self.controller.debuggerClearDevelopmentBreakpoints { [weak self] cleared in + MainActor.assumeIsolated { + self?.accept(cleared) + self?.debuggerContinue { completion(cleared) } + } + } + } + } + func mountDevelopmentDisk(_ url: URL, completion: @escaping (VCCMachineSnapshot?) -> Void) { + guard !busy, !diskSaving, diskEnabled, !unsavedMedia else { completion(nil); return } + busy = true; inputEpoch += 1; fileError = nil + Task { @MainActor in + do { + let image = try await Task.detached { try DiskFiles.readImage(url) }.value + let snapshot = await controller.mountDisk(image.data, drive: 0, name: url.lastPathComponent, readOnly: false) + accept(snapshot); busy = false + if snapshot.errorMessage == nil { + // A working copy is writable and independently saved. The build artifact remains pristine. + diskTemporary[0] = false; setBacking(0, url: url, bytes: image.data); rememberDrive(0, url: url) + } + completion(snapshot) + } catch { fileError = error.localizedDescription; busy = false; completion(nil) } + } + } + func debuggerLoadBinary(_ data: Data, breakpoint: UInt16, completion: @escaping (VCCMachineSnapshot?) -> Void) { + guard canQuickLoad else { completion(nil); return } + busy = true; inputEpoch += 1; fileError = nil + controller.debuggerLoadBinary(data, breakpoint: breakpoint) { [weak self] snapshot in + MainActor.assumeIsolated { + self?.accept(snapshot); self?.busy = false + if snapshot.errorMessage == nil { self?.binaryName = "main.bin" } + completion(snapshot) + } + } + } + func debuggerPause(completion: @escaping () -> Void) { debuggerCommand(controller.pause, completion: completion) } + func debuggerContinue(completion: @escaping () -> Void) { debuggerCommand(controller.resume, completion: completion) } + // Match highlights only to captures on either side of this exact instruction. + private(set) var lastDebuggerStep: (generation: UInt64, before: UInt64, after: UInt64)? + func debuggerStep(completion: @escaping () -> Void) { + guard canQuickLoad, state == .paused else { completion(); return } + let before = basicDebug + debuggerCommand(controller.debuggerStep) { [self] in + if before.generation == basicDebug.generation, basicDebug.paused, before.cycles != basicDebug.cycles { + lastDebuggerStep = (before.generation, before.cycles, basicDebug.cycles) + } + completion() + } + } + + func readGraphicsPreview(currentPage: Bool, address: UInt32, physical: Bool, mode: Int, + alternatePalette: Bool) async -> VCCDebugGraphicsCapture? { + guard canQuickLoad else { return nil } + return await withCheckedContinuation { continuation in + controller.debuggerGraphics(currentPage: currentPage, address: address, physical: physical, + mode: mode, alternatePalette: alternatePalette) { capture in + continuation.resume(returning: capture) + } + } + } + func debuggerStepSource(mode: Int, addresses: [NSNumber], locations: [NSNumber], bytes: [Data], + expected: VCCMachineSnapshot, moduleIdentifiers: [String]? = nil, completion: @escaping () -> Void) { + if let moduleIdentifiers { + debuggerCommand({ controller.debuggerStepBankedSource(mode: mode, addresses: addresses, locations: locations, + bytes: bytes, moduleIdentifiers: moduleIdentifiers, generation: expected.generation, + programRevision: expected.debuggerProgramRevision, mappingFingerprint: expected.debuggerMappingFingerprint, + programCounter: expected.programCounter, completion: $0) }, completion: completion) + return + } + debuggerCommand({ controller.debuggerStepSource(mode: mode, addresses: addresses, locations: locations, + bytes: bytes, generation: expected.generation, programRevision: expected.debuggerProgramRevision, + mappingFingerprint: expected.debuggerMappingFingerprint, programCounter: expected.programCounter, + completion: $0) }, completion: completion) + } + func debuggerSetPC(_ address: UInt16, completion: @escaping () -> Void) { + debuggerCommand({ controller.debuggerSetPC(address, completion: $0) }, completion: completion) + } + func debuggerSetBreakpoints(_ addresses: [NSNumber], completion: @escaping () -> Void) { + debuggerCommand({ controller.debuggerSetBreakpoints(addresses, completion: $0) }, completion: completion) + } + func debuggerConfigureBreakpoints(_ enabled: [NSNumber], disabled: [NSNumber], completion: @escaping () -> Void) { + debuggerCommand({ controller.debuggerConfigureBreakpoints(enabled, disabled: disabled, completion: $0) }, completion: completion) + } + func readDebuggerMemory(address: UInt32, count: UInt32, physical: Bool, logicalAddress: UInt16, + os9: Bool, decode: Bool, completion: @escaping (VCCDebugMemoryCapture?) -> Void) { + guard !busy, !diskSaving, state != .closed else { completion(nil); return } + controller.debuggerMemory(address: address, count: count, physical: physical, logicalAddress: logicalAddress, + os9: os9, decode: decode) { [weak self] capture in + MainActor.assumeIsolated { self?.accept(capture.machine); completion(capture) } + } + } + func startDebuggerTrace(maximum: UInt, starts: [NSNumber], stops: [NSNumber], screen: Bool, scheduler: Bool, completion: @escaping () -> Void) { + debuggerCommand({ controller.debuggerStartTrace(maximum, starts: starts, stops: stops, screen: screen, scheduler: scheduler, completion: $0) }, completion: completion) + } + func stopDebuggerTrace(completion: @escaping () -> Void) { debuggerCommand(controller.debuggerStopTrace, completion: completion) } + func clearDebuggerTrace(completion: @escaping () -> Void) { debuggerCommand(controller.debuggerClearTrace, completion: completion) } + func readDebuggerTrace(offset: UInt, completion: @escaping (VCCTraceSnapshot?) -> Void) { + guard !busy, !diskSaving, state != .closed else { completion(nil); return } + controller.debuggerTrace(offset: offset) { [weak self] trace, machine in + MainActor.assumeIsolated { self?.accept(machine); completion(trace) } + } + } + func exportDebuggerTrace(first: UInt, count: UInt, completion: @escaping (String?) -> Void) { + guard !busy, !diskSaving, state != .closed else { completion(nil); return } + controller.debuggerExportTrace(first: first, count: count) { [weak self] text, machine in + MainActor.assumeIsolated { self?.accept(machine); completion(text) } + } + } + func debuggerWriteMemory(address: UInt16, data: Data, completion: @escaping () -> Void) { + debuggerCommand({ controller.debuggerWriteMemory(address: address, data: data, completion: $0) }, completion: completion) + } + func softReset() { command(controller.softReset, onSuccess: { [self] in binaryName = nil; deniedShellGeneration = nil }) } + func reset() { command(controller.reset, onSuccess: { [self] in binaryName = nil; deniedShellGeneration = nil }) } + func poll() { + guard !polling, !busy, state != .closed else { return } + polling = true + controller.snapshot { [weak self] snapshot in + MainActor.assumeIsolated { + self?.accept(snapshot); self?.polling = false + self?.applySavedMacShellDecision() + } + } + } + func shutdown(completion: @escaping () -> Void = {}) { + diskMonitor?.cancel(); diskMonitor = nil + busy = true + Task { @MainActor in + if let pending = diskSaveTask { await pending.value } + _ = await diskStep(controller.shutdown) + busy = false; completion() + } + } + private func applyCartridges(_ layout: CartridgeAssignments, bytes: [Data]) async -> Bool { + let result = await diskStep { + controller.configureCartridges(layout.slots.map { NSNumber(value: $0.kind.rawValue) }, + roms: bytes, names: layout.slots.map { $0.url?.lastPathComponent ?? "" }, + multiPak: layout.multiPak, physicalSlot: layout.physicalSlot, + sdcFolders: layout.slots.map { $0.sdcFolderURL?.path ?? "" }, + sdcReadOnly: layout.slots.map { NSNumber(value: $0.sdcReadOnly ?? true) }, completion: $0) + } + return result.errorMessage == nil + } + private func restoreCartridges() async { + // Retry only unavailable ROMs; never replace a working loaded image. + var bytes = cartridgeBytes; var errors = cartridgeRestoreErrors + for index in 0..<5 where (cartridgeAssignments.slots[index].kind == .rom || cartridgeAssignments.slots[index].kind == .orchestra90 || cartridgeAssignments.slots[index].kind == .speechSound || cartridgeAssignments.slots[index].kind == .sdc) && bytes[index].isEmpty { + let assignment = cartridgeAssignments.slots[index] + guard assignment.url != nil || assignment.kind == .speechSound || assignment.kind == .sdc else { continue } + do { + bytes[index] = try await Task.detached { try DiskFiles.readCartridgeAssignment(assignment) }.value + errors[index] = nil + } catch { errors[index] = "\(index == 0 ? "Single cartridge" : "Slot \(index)"): \(error.localizedDescription)" } + } + if await applyCartridges(cartridgeAssignments, bytes: bytes) { + cartridgeBytes = bytes; cartridgeRestoreErrors = errors + } + } + func retryRememberedCartridges() { + guard !busy, !diskSaving else { return } + busy = true; inputEpoch += 1 + Task { @MainActor in await restoreCartridges(); busy = false } + } + private func changeCartridges(_ layout: CartridgeAssignments, bytes: [Data], changedSlot: Int? = nil) { + busy = true; inputEpoch += 1; fileError = nil + Task { @MainActor in + if await applyCartridges(layout, bytes: bytes) { + cartridgeAssignments = layout; cartridgeBytes = bytes + if let changedSlot { + cartridgeRestoreErrors[changedSlot] = nil + if layout.slots[changedSlot].kind == .rom, let url = layout.slots[changedSlot].url { + recentMedia.record(url, as: .cartridge(changedSlot)) + } + } + cartridgeRestoreErrors = cartridgeRestoreErrors.filter { (layout.slots[$0.key].url != nil || layout.slots[$0.key].kind == .speechSound || layout.slots[$0.key].kind == .sdc) && bytes[$0.key].isEmpty } + // First MPI activation can copy an unavailable single ROM. Keep + // recovery visible even if the original assignment is removed. + for index in 0..<5 where (layout.slots[index].url != nil || layout.slots[index].kind == .speechSound || layout.slots[index].kind == .sdc) && bytes[index].isEmpty { + if cartridgeRestoreErrors[index] == nil { + cartridgeRestoreErrors[index] = layout.slots[index].kind == .sdc ? "SDC needs an available SDC-DOS ROM and SD card folder. Choose both in Details, or retry." : "ROM unavailable. Reconnect the file and retry, or choose a replacement." + } + } + diskAssignments.cartridges = layout; saveDiskAssignments() + } + busy = false + } + } + func setMultiPak(_ enabled: Bool) { + guard !busy, !diskSaving else { return } + var layout = cartridgeAssignments; var bytes = cartridgeBytes + // First activation carries the single cartridge into slot 4. Later + // toggles preserve both configurations, including intentionally empty MPI. + if enabled && !layout.mpiConfigured { + layout.slots[4] = layout.slots[0]; bytes[4] = bytes[0] + } + if enabled { layout.mpiConfigured = true } + layout.multiPak = enabled + changeCartridges(layout, bytes: bytes) + } + func selectPhysicalSlot(_ slot: Int) { + guard !busy, !diskSaving, (1...4).contains(slot) else { return } + var layout = cartridgeAssignments; layout.physicalSlot = slot + changeCartridges(layout, bytes: cartridgeBytes) + } + func assignCartridge(_ kind: CartridgeAssignments.Kind, slot: Int, useBundledROM: Bool = true) { + guard !busy, !diskSaving, (0..<5).contains(slot), kind != .rom else { return } + var layout = cartridgeAssignments; var bytes = cartridgeBytes + var replacement = CartridgeAssignments.Slot(kind: kind) + var replacementBytes = Data() + var moved = false + if (kind == .orchestra90 || kind == .speechSound || kind == .sdc), slot > 0, + let previous = (1...4).first(where: { $0 != slot && layout.slots[$0].kind == kind }) { + replacement = layout.slots[previous]; replacementBytes = bytes[previous] + moved = true + } + if (kind == .floppy || kind == .hardDisk || kind == .ramDisk || kind == .orchestra90 || kind == .speechSound || kind == .sdc) && slot > 0 { + for index in 1...4 where layout.slots[index].kind == kind { + layout.slots[index] = .init(); bytes[index] = Data() + } + } + layout.slots[slot] = replacement; bytes[slot] = replacementBytes + if kind == .sdc, useBundledROM, !moved, + let store = startupStore, let kit = store.kit, + FileManager.default.fileExists(atPath: kit.directory.appendingPathComponent("sdcdos.rom").path) { + busy = true; inputEpoch += 1; fileError = nil + Task { @MainActor in + do { + let url = try await Task.detached { try kit.rom("sdcdos.rom", in: store.directory) }.value + layout.slots[slot].url = url + // The ROM is retained, but hardware stays inactive until a folder is selected. + changeCartridges(layout, bytes: bytes, changedSlot: slot) + } catch { fileError = "Bundled SDC-DOS ROM: " + error.localizedDescription; busy = false } + } + return + } + if kind == .speechSound, useBundledROM, !moved, + let store = startupStore, let kit = store.kit, + FileManager.default.fileExists(atPath: kit.directory.appendingPathComponent("pic-7040-510.bin").path), + FileManager.default.fileExists(atPath: kit.directory.appendingPathComponent("sp0256-al2.bin").path) { + busy = true; inputEpoch += 1; fileError = nil + Task { @MainActor in + do { + let (assignment, data) = try await Task.detached { + let assignment = CartridgeAssignments.Slot(kind: .speechSound, + url: try kit.rom("pic-7040-510.bin", in: store.directory), + speechROMURL: try kit.rom("sp0256-al2.bin", in: store.directory)) + return (assignment, try DiskFiles.readCartridgeAssignment(assignment)) + }.value + layout.slots[slot] = assignment; bytes[slot] = data + changeCartridges(layout, bytes: bytes, changedSlot: slot) + } catch { fileError = "Bundled Speech/Sound ROMs: " + error.localizedDescription; busy = false } + } + return + } + if kind == .orchestra90, useBundledROM, !moved, + let store = startupStore, let kit = store.kit, + FileManager.default.fileExists(atPath: kit.directory.appendingPathComponent("orch90.rom").path) { + busy = true; inputEpoch += 1; fileError = nil + Task { @MainActor in + do { + let (url, data) = try await Task.detached { + let url = try kit.rom("orch90.rom", in: store.directory) + return (url, try DiskFiles.readOrchestraROM(url)) + }.value + layout.slots[slot].url = url; bytes[slot] = data + changeCartridges(layout, bytes: bytes, changedSlot: slot) + } catch { fileError = "Bundled Orchestra-90 ROM: " + error.localizedDescription; busy = false } + } + return + } + changeCartridges(layout, bytes: bytes, changedSlot: slot) + } + func openSDCFolder(_ slot: Int) { + guard (0..<5).contains(slot), cartridgeAssignments.slots[slot].kind == .sdc else { return } + diskDialog { [self] in + let panel = NSOpenPanel(); panel.title = "Choose SD Card Folder" + panel.message = "Choose a folder containing your extracted SDC files. Changing it restarts the CoCo and clears the working program. Read-only protection is on by default." + panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.allowsMultipleSelection = false + panel.directoryURL = cartridgeAssignments.slots[slot].sdcFolderURL + panel.begin { [self] result in + guard result == .OK, let url = panel.url else { busy = false; return } + selectSDCFolder(url, slot: slot) + } + } + } + func selectSDCFolder(_ url: URL, slot: Int) { + guard !diskSaving, (0..<5).contains(slot), cartridgeAssignments.slots[slot].kind == .sdc else { return } + busy = true; inputEpoch += 1; fileError = nil + var assignment = cartridgeAssignments.slots[slot]; assignment.sdcFolderURL = url + Task { @MainActor in + do { + let data = try await Task.detached { + try DiskFiles.validateSDCFolder(url) + // Keep a valid new folder even if the remembered ROM is missing. + // Each half can be repaired independently; incomplete hardware stays inactive. + return (try? DiskFiles.readCartridgeAssignment(assignment)) ?? Data() + }.value + var layout = cartridgeAssignments; var bytes = cartridgeBytes + layout.slots[slot] = assignment; bytes[slot] = data + changeCartridges(layout, bytes: bytes, changedSlot: slot) + } catch { fileError = error.localizedDescription; busy = false } + } + } + private func selectSDCROM(_ url: URL, slot: Int) { + busy = true; inputEpoch += 1; fileError = nil + var assignment = cartridgeAssignments.slots[slot].kind == .sdc ? cartridgeAssignments.slots[slot] : .init(kind: .sdc) + assignment.url = url + Task { @MainActor in + do { + let data = try await Task.detached { + _ = try DiskFiles.readSDCROM(url) + // A missing folder must not prevent replacing a missing ROM. + return (try? DiskFiles.readCartridgeAssignment(assignment)) ?? Data() + }.value + var layout = cartridgeAssignments; var bytes = cartridgeBytes + if slot > 0 { + for i in 1...4 where i != slot && layout.slots[i].kind == .sdc { + layout.slots[i] = .init(); bytes[i] = Data() + } + } + layout.slots[slot] = assignment; bytes[slot] = data + changeCartridges(layout, bytes: bytes, changedSlot: slot) + } catch { fileError = error.localizedDescription; busy = false } + } + } + func setSDCReadOnly(_ protected: Bool, slot: Int) { + guard !busy, !diskSaving, (0..<5).contains(slot), cartridgeAssignments.slots[slot].kind == .sdc, + (cartridgeAssignments.slots[slot].sdcReadOnly ?? true) != protected else { return } + let alert = NSAlert(); alert.messageText = protected ? "Protect the SD card folder and restart?" : "Allow changes to the SD card folder and restart?" + alert.informativeText = "This clears the working program in RAM. " + (protected + ? "The guest can read files but cannot change them. Existing files are kept." + : "SDC software can write disk images and create, rename or delete files inside the selected folder. Changes save directly to those files. Use a copy of a collection if you want to preserve its originals.") + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: protected ? "Protect and Restart" : "Allow Changes and Restart") + guard alert.runModal() == .alertSecondButtonReturn else { return } + var layout = cartridgeAssignments; layout.slots[slot].sdcReadOnly = protected + changeCartridges(layout, bytes: cartridgeBytes, changedSlot: slot) + } + func openSpeechROM(_ slot: Int, speech: Bool) { + guard (0..<5).contains(slot), cartridgeAssignments.slots[slot].kind == .speechSound else { return } + diskDialog { [self] in + let panel = NSOpenPanel() + panel.title = speech ? "Choose Speech ROM" : "Choose PIC Firmware" + panel.message = "Speech/Sound requires pic-7040-510.bin (4 KiB) and sp0256-al2.bin (2 KiB). Changing either clears the working BASIC program and restarts the machine; mounted media are retained." + panel.allowedContentTypes = ["bin", "rom"].map { UTType(filenameExtension: $0) ?? .data } + panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false; panel.allowsMultipleSelection = false + panel.begin { [self] result in + guard result == .OK, let url = panel.url else { busy = false; return } + selectSpeechROM(url, slot: slot, speech: speech) + } + } + } + func selectSpeechROM(_ url: URL, slot: Int, speech: Bool) { + guard !diskSaving, (0..<5).contains(slot), cartridgeAssignments.slots[slot].kind == .speechSound else { return } + busy = true; inputEpoch += 1; fileError = nil + var assignment = cartridgeAssignments.slots[slot] + if speech { assignment.speechROMURL = url } else { assignment.url = url } + Task { @MainActor in + do { + let data = try await Task.detached { + _ = try DiskFiles.readSpeechChipROM(url, speech: speech) + return try assignment.url != nil && assignment.speechROMURL != nil ? DiskFiles.readCartridgeAssignment(assignment) : Data() + }.value + var layout = cartridgeAssignments; var bytes = cartridgeBytes + layout.slots[slot] = assignment; bytes[slot] = data + changeCartridges(layout, bytes: bytes, changedSlot: slot) + } catch { fileError = error.localizedDescription; busy = false } + } + } + func openCartridgeROM(_ slot: Int, kind: CartridgeAssignments.Kind = .rom) { + guard (0..<5).contains(slot) else { return } + diskDialog { [self] in + let panel = NSOpenPanel(); panel.title = kind == .sdc ? "Choose SDC-DOS ROM" : kind == .orchestra90 ? "Choose Orchestra-90 ROM" : "Choose Cartridge ROM" + panel.message = (kind == .sdc ? "Choose an 8 or 16 KiB SDC-DOS ROM. " : kind == .orchestra90 ? "Choose an 8 KiB Orchestra-90 ROM. " : "") + "Choose a raw ROM, not a DLL. Changing cartridges cold-resets the machine and clears its BASIC program. Replacing the last RAM disk assignment also discards its contents." + panel.allowedContentTypes = ["rom", "ccc", "bin", "pak"].map { UTType(filenameExtension: $0) ?? .data } + panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false; panel.allowsMultipleSelection = false + panel.begin { [self] result in + guard result == .OK, let url = panel.url else { busy = false; return } + selectCartridgeROM(url, slot: slot, kind: kind) + } + } + } + func selectCartridgeROM(_ url: URL, slot: Int, kind: CartridgeAssignments.Kind = .rom) { + guard !diskSaving, (0..<5).contains(slot), kind == .rom || kind == .orchestra90 || kind == .sdc else { return } + if kind == .sdc { selectSDCROM(url, slot: slot); return } + busy = true; inputEpoch += 1; fileError = nil + Task { @MainActor in + do { + let data = try await Task.detached { try kind == .orchestra90 ? DiskFiles.readOrchestraROM(url) : DiskFiles.readCartridgeROM(url) }.value + var layout = cartridgeAssignments; var bytes = cartridgeBytes + if kind == .orchestra90 && slot > 0 { + for i in 1...4 where i != slot && layout.slots[i].kind == kind { + layout.slots[i] = .init(); bytes[i] = Data() + } + } + layout.slots[slot] = .init(kind: kind, url: url); bytes[slot] = data + changeCartridges(layout, bytes: bytes, changedSlot: slot) + } catch { fileError = error.localizedDescription; busy = false } + } + } + + private var hardNeedsSaving: Bool { + hardDisks.indices.contains { hardDisks[$0].dirty && !hardDisks[$0].writeProtected && !hardDisks[$0].sourceReadOnly && !hardTemporary[$0] && hardBackings[$0] != nil && hardSaveErrors[$0] == nil } + } + private func rememberHardDisk(_ drive: Int, url: URL?) { + hardSettings.drives[drive] = url.map { .init(url: $0, writeProtected: hardDisks[drive].writeProtected, temporary: hardTemporary[drive]) } + hardRestoreErrors[drive] = nil; diskAssignments.hardDisks = hardSettings; saveDiskAssignments() + } + private func saveAutomaticHardDisks(force: Bool = false) async { + guard force || Date() >= nextHardSave || hardFlushRequests != savedHardFlushRequests else { return } + savedHardFlushRequests = hardFlushRequests + for drive in 0..<2 { + guard !hardTemporary[drive], hardSaveErrors[drive] == nil, let backing = hardBackings[drive] else { continue } + let (save, snapshot): (VCCHardDiskSave?, VCCMachineSnapshot) = await withCheckedContinuation { c in + controller.captureHardDisk(inDrive: drive, full: false) { c.resume(returning: ($0, $1)) } + } + accept(snapshot); guard let save else { continue } + do { + let digest = try await automaticHardDiskWriter(save.data, Int(save.byteCount), backing.url, backing.digest) + // Our own coordinated write advances the trusted working disk; + // an externally replaced disk with the same name must ask again. + if drive == 0, let disk = shellDisk, disk == savedShellGrant, + disk["sha256"] == backing.digest { + savedShellGrant = ["path": backing.url.path, "sha256": digest] + } + hardBackings[drive]?.digest = digest + _ = await diskStep { controller.acknowledgeHardDisk(inDrive: drive, token: save.token, name: nil, completion: $0) } + } catch { + hardSaveErrors[drive] = "Hard disk \(drive) could not save: \(error.localizedDescription)" + _ = await diskStep(controller.pause) + } + } + nextHardSave = Date().addingTimeInterval(1) + } + private func restoreHardDisks() async { + hardRestoreErrors = [:] + let paused = await diskStep { controller.configureHardClock(hardSettings.clockEnabled, readOnly: hardSettings.clockReadOnly, completion: $0) } + guard paused.errorMessage == nil else { fileError = paused.errorMessage; return } + for drive in 0..<2 { + guard !hardDisks[drive].mounted, let saved = hardSettings.drives[drive] else { continue } + do { + let image = try await Task.detached { try HardDiskFiles.readImage(saved.url) }.value + var result = await diskStep { controller.mountHardDisk(image.data, drive: drive, name: saved.url.lastPathComponent, readOnly: image.readOnly, completion: $0) } + if result.errorMessage == nil && saved.writeProtected && !result.hardDisks[drive].writeProtected { + result = await diskStep { controller.hardDiskAction(2, drive: drive, completion: $0) } + } + if let error = result.errorMessage { throw NSError(domain: "VCC", code: 1, userInfo: [NSLocalizedDescriptionKey: error]) } + hardBackings[drive] = .init(url: saved.url.resolvingSymlinksInPath(), digest: image.digest) + hardTemporary[drive] = saved.temporary; hardSaveErrors[drive] = nil + } catch { hardRestoreErrors[drive] = "Hard disk \(drive), \(saved.url.lastPathComponent): \(error.localizedDescription)" } + } + } + func retryHardDisks() { + guard !busy, !diskSaving else { return } + busy = true; inputEpoch += 1 + Task { @MainActor in await restoreHardDisks(); busy = false } + } + func retryHardSave(_ drive: Int) { + guard !busy, !diskSaving else { return } + hardSaveErrors[drive] = nil; nextHardSave = .distantPast; startAutomaticDiskSave() + } + func setHardTemporary(_ drive: Int, _ temporary: Bool) { + guard !busy, !diskSaving else { return } + command(controller.pauseForDiskChange, onSuccess: { [self] in + hardTemporary[drive] = temporary + if let url = hardSettings.drives[drive]?.url { rememberHardDisk(drive, url: url) } + }) + } + func setHardProtection(_ drive: Int, _ protected: Bool) { + guard !busy, !diskSaving else { return } + command({ controller.hardDiskAction(protected ? 2 : 3, drive: drive, completion: $0) }, onSuccess: { [self] in + if let url = hardSettings.drives[drive]?.url { rememberHardDisk(drive, url: url) } + }) + } + func setHardClock(enabled: Bool, readOnly: Bool) { + guard !busy, !diskSaving else { return } + command({ controller.configureHardClock(enabled, readOnly: readOnly, completion: $0) }, onSuccess: { [self] in + hardSettings.clockEnabled = enabled; hardSettings.clockReadOnly = readOnly + diskAssignments.hardDisks = hardSettings; saveDiskAssignments() + }) + } + func openHardDisk(_ drive: Int) { + diskDialog { [self] in + let panel = NSOpenPanel(); panel.title = "Insert Hard Disk \(drive)" + panel.message = "Choose a raw VHD, OS9 or IMG sector image. Writable images save automatically unless Temporary changes is enabled." + panel.allowedContentTypes = ["vhd", "os9", "img"].map { UTType(filenameExtension: $0) ?? .data } + panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false; panel.allowsMultipleSelection = false + panel.begin { [self] result in + guard result == .OK, let url = panel.url else { busy = false; return } + insertHardDisk(url, drive: drive) + } + } + } + func insertHardDisk(_ url: URL, drive: Int) { + guard !diskSaving, (0..<2).contains(drive) else { return } + busy = true; inputEpoch += 1; fileError = nil + Task { @MainActor in + do { + let image = try await Task.detached(priority: .userInitiated) { try HardDiskFiles.readImage(url) }.value + command({ controller.mountHardDisk(image.data, drive: drive, name: url.lastPathComponent, readOnly: image.readOnly, completion: $0) }, onSuccess: { [self] in + hardBackings[drive] = .init(url: url.resolvingSymlinksInPath(), digest: image.digest) + hardSaveErrors[drive] = nil; rememberHardDisk(drive, url: url); recentMedia.record(url, as: .hardDisk(drive)) + }) + } catch { fileError = error.localizedDescription; busy = false } + } + } + func createHardDisk(_ drive: Int, sizeKiB: Int) { + guard !busy, !diskSaving, (1...524288).contains(sizeKiB) else { return } + command({ controller.createHardDisk(inDrive: drive, size: UInt(sizeKiB * 1024), completion: $0) }, onSuccess: { [self] in + hardBackings[drive] = nil; hardSaveErrors[drive] = nil; rememberHardDisk(drive, url: nil) + }) + } + func ejectHardDisk(_ drive: Int, discard: Bool = false) { + guard !busy, !diskSaving else { return } + diskDialog { [self] in + if discard { + let alert = NSAlert(); alert.messageText = "Discard changes to hard disk \(drive)?" + alert.informativeText = "This ejects unsaved in-memory changes. Earlier automatic saves cannot be undone." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard and Eject") + guard alert.runModal() == .alertSecondButtonReturn else { busy = false; return } + } + command({ controller.hardDiskAction(discard ? 1 : 0, drive: drive, completion: $0) }, onSuccess: { [self] in + hardBackings[drive] = nil; hardSaveErrors[drive] = nil; rememberHardDisk(drive, url: nil) + }) + } + } + func exportHardDisk(_ drive: Int, to destination: URL? = nil) { + guard !busy, !diskSaving else { return } + busy = true; inputEpoch += 1; fileError = nil + controller.captureHardDisk(inDrive: drive, full: true) { [weak self] save, snapshot in + MainActor.assumeIsolated { [self] in + guard let self else { return }; self.accept(snapshot) + guard snapshot.errorMessage == nil, let save else { self.busy = false; return } + if let destination { self.finishHardExport(save, drive: drive, url: destination); return } + let panel = NSSavePanel(); panel.title = "Save Hard Disk \(drive) As" + panel.allowedContentTypes = [UTType(filenameExtension: "vhd") ?? .data] + panel.nameFieldStringValue = (self.hardDisks[drive].name as NSString).deletingPathExtension + ".vhd" + panel.begin { [self] result in + guard result == .OK, let url = panel.url else { self.busy = false; return } + self.finishHardExport(save, drive: drive, url: url) + } + } + } + } + private func finishHardExport(_ save: VCCHardDiskSave, drive: Int, url: URL) { + let data = save.data + Task { @MainActor in + do { + let digest = try await Task.detached(priority: .userInitiated) { try HardDiskFiles.export(data, to: url) }.value + command({ controller.acknowledgeHardDisk(inDrive: drive, token: save.token, name: url.lastPathComponent, completion: $0) }, onSuccess: { [self] in + hardBackings[drive] = .init(url: url.resolvingSymlinksInPath(), digest: digest) + hardSaveErrors[drive] = nil; rememberHardDisk(drive, url: url); recentMedia.record(url, as: .hardDisk(drive)) + }) + } catch { fileError = error.localizedDescription; busy = false } + } + } + +} + + +extension MachineModel { + func captureProfile(name: String, replacing id: UUID? = nil) async throws -> ConfigurationProfile { + guard !busy, state != .closed else { throw ProfileFailure.message("Wait for the current operation to finish.") } + busy = true + defer { busy = false } + if let pending = diskSaveTask { await pending.value } + _ = await diskStep(controller.snapshot) + var value = ConfigurationProfile(name: name.trimmingCharacters(in: .whitespacesAndNewlines)) + if let id { value.id = id } + value.machine = settings; value.videoOutput = videoOutput.rawValue + value.sound = audioEnabled; value.volume = volume; value.systemROM = systemROMURL + value.media = diskAssignments; value.media.cartridges = cartridgeAssignments; value.media.hardDisks = hardSettings + for i in disks.indices where disks[i].mounted { + guard value.media.drives[i] != nil else { throw ProfileFailure.message("Save floppy drive \(i) with Save As before including it in a profile.") } + value.media.drives[i]?.writeProtected = disks[i].writeProtected + value.media.drives[i]?.temporary = diskTemporary[i] + } + for i in hardDisks.indices where hardDisks[i].mounted { + guard value.media.hardDisks?.drives[i] != nil else { throw ProfileFailure.message("Save hard disk \(i) with Save As before including it in a profile.") } + value.media.hardDisks?.drives[i]?.writeProtected = hardDisks[i].writeProtected + value.media.hardDisks?.drives[i]?.temporary = hardTemporary[i] + } + if tapeMounted && cassetteURL == nil { throw ProfileFailure.message("Export the cassette to a file before including it in a profile.") } + value.cassette = tapeMounted ? cassetteURL : nil; value.fastCassette = tapeFast + value.input = input.settings; value.bootNitros9 = bootNitros9 ? true : nil + try value.validate(); return value + } + + // Called after the profile window's explicit cold-restart confirmation. + // Failures retain the old machine/media, paused for recovery. No automatic + // discard is offered for temporary images or unfinished tape recordings. + func loadProfile(_ profile: ConfigurationProfile) async { + await loadProfile(preparing: { profile }, startRunning: false) + } + @discardableResult private func loadProfile(preparing: () async throws -> ConfigurationProfile, startRunning: Bool, + builtInNitros9: Bool = false, afterStart: (() async throws -> Void)? = nil) async -> Bool { + guard !busy, state != .closed else { return false } + var committed = false + guideRequest = nil + busy = true; inputEpoch += 1; profileError = nil; fileError = nil + defer { busy = false } + do { + let paused = await diskStep(controller.pauseForDiskChange) + if let error = paused.errorMessage { throw ProfileFailure.message(error) } + if let pending = diskSaveTask { await pending.value } + await saveAutomaticDisks(); await saveAutomaticHardDisks(force: true) + _ = await diskStep(controller.snapshot) + guard !unsavedMedia else { + throw ProfileFailure.message("The current setup has unsaved media. Save As or export your recordings, or explicitly discard them in the media controls, before loading a profile. The machine is paused.") + } + try Task.checkCancellation() + let profile = try await preparing() + try profile.validate() + let prepared = try await Task.detached(priority: .userInitiated) { [startupStore] in + let checked = try PreparedProfile.read(profile) + if try startupStore?.initializeSharedOS9(for: profile) == true { return try PreparedProfile.read(profile) } + return checked + }.value + try Task.checkCancellation() + let request = prepared.request() + let (applied, snapshot): (Bool, VCCMachineSnapshot) = await withCheckedContinuation { c in + controller.applyProfile(request) { c.resume(returning: ($0, $1)) } + } + accept(snapshot) + committed = applied + guard applied else { throw ProfileFailure.message(snapshot.errorMessage ?? "Could not load the profile.") } + // Publish the new host file/backing bookkeeping only once the worker + // has installed that exact payload. Failed preflight never persists it. + systemROMURL = profile.systemROM; title = profile.systemROM?.lastPathComponent ?? "No ROM selected" + binaryName = nil; profileName = profile.name; bootNitros9 = profile.bootNitros9 == true + cassetteURL = profile.cassette; tapeName = profile.cassette?.lastPathComponent ?? "No tape" + cartridgeAssignments = profile.media.cartridges ?? CartridgeAssignments(); cartridgeBytes = prepared.cartridges + diskAssignments = profile.media; diskAssignments.cartridges = cartridgeAssignments + hardSettings = profile.media.hardDisks ?? HardDiskAssignments(); diskAssignments.hardDisks = hardSettings + cartridgeRestoreErrors = [:]; diskRestoreErrors = [:]; hardRestoreErrors = [:] + diskSaveErrors = [:]; hardSaveErrors = [:] + diskBackings = Array(repeating: nil, count: 4); hardBackings = [nil, nil] + diskTemporary = Array(repeating: false, count: 4); hardTemporary = [false, false] + for i in 0..<4 { + if let saved = profile.media.drives[i], let image = prepared.floppies[i] { + setBacking(i, url: saved.url, bytes: image.data); diskTemporary[i] = saved.temporary + } + } + for i in 0..<2 { + if let saved = hardSettings.drives[i], let image = prepared.hardDisks[i] { + hardBackings[i] = .init(url: saved.url.resolvingSymlinksInPath(), digest: image.digest) + hardTemporary[i] = saved.temporary + } + } + nextHardSave = .distantPast; savedHardFlushRequests = hardFlushRequests + volume = profile.volume; input.settings = profile.input + _ = await applyDriveWireDefault(builtInNitros9) + rememberStartup() + loadedProfileConfiguration = profileConfiguration + settings.save(in: displayDefaults); displayDefaults.set(profile.videoOutput, forKey: DisplayOutput.preferenceKey) + saveDiskAssignments() + if let error = snapshot.errorMessage { throw ProfileFailure.message("The profile was installed, but the machine could not start: \(error)") } + if let error = diskSettingsError ?? input.error ?? fileError { throw ProfileFailure.message("The profile was loaded, but preferences could not be saved: \(error)") } + if bootNitros9 { _ = await diskStep(controller.requestNitros9Boot) } + if startRunning { + let resumed = await diskStep(controller.resume) + if let error = resumed.errorMessage { throw ProfileFailure.message(error) } + focusRequest += 1 + } + try await afterStart?() + } catch { profileError = error.localizedDescription } + return committed + } +} + +@MainActor +extension MachineModel { + func reportMediaError(_ message: String) { fileError = message } + func openMedia() { + guard !busy, !diskSaving, !mediaPromptOpen else { return } + mediaPromptOpen = true + let panel = NSOpenPanel(); panel.title = "Open Media" + panel.message = "Choose a disk, cassette, cartridge, system ROM or binary program. You will choose its destination before it is loaded." + panel.canChooseDirectories = false; panel.allowsMultipleSelection = false + panel.begin { [weak self] result in + self?.mediaPromptOpen = false + guard result == .OK, let url = panel.url else { return } + self?.offerMedia(url) + } + } + func offerMedia(_ url: URL, preferred: MediaDestination? = nil, fromHistory: Bool = false) { + guard !busy, !diskSaving, !diskEditorLocked, !mediaPromptOpen, state != .closed else { fileError = "Wait for the current operation before opening media."; return } + mediaPromptOpen = true + var sheetPending = false + defer { if !sheetPending { mediaPromptOpen = false } } + guard RecentMedia.isLocalFile(url), (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else { + fileError = "Media file unavailable: \(url.lastPathComponent). Reconnect its volume or choose the file's new location with Open Media. Recent history has been kept."; return + } + var choices = MediaDestination.choices(for: url) + // Explicit existing file selections can have nonstandard extensions. + if let preferred, preferred.valid, !choices.contains(preferred) { + guard fromHistory else { fileError = "This file does not match \(preferred.label). Drop it onto the main display to choose a compatible destination."; return } + choices.insert(preferred, at: 0) + } + guard !choices.isEmpty else { fileError = "Unsupported media type. Use a DSK/JVC/OS9, VHD/IMG, CAS/WAV, ROM/CCC/PAK or CoCo BIN file. Windows DLLs are not Mac cartridges."; return } + // OS-9 images retain both floppy and hard-disk destinations alongside + // filesystem editing; hard-disk insertion keeps its existing pause policy. + if DiskFiles.extensions.contains(url.pathExtension.lowercased()) { + let supportsHardDisk = choices.contains { if case .hardDisk = $0 { return true }; return false } + let options = DiskMediaOpenOptions(preferred: preferred, supportsHardDisk: supportsHardDisk) + let alert = NSAlert(); alert.messageText = "Open \(url.lastPathComponent)?" + alert.informativeText = "Edit the disk's files, or insert it into a drive. Floppy insertion can optionally reset the CoCo first, then keep the current running or paused state, pause, or run. Inserting does not boot the disk or run its contents. Hard-disk insertion pauses the CoCo. Unsaved media must be saved or exported first. Cancel leaves the session unchanged." + alert.accessoryView = options.view + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Open") + guard let sourceAttributes = try? FileManager.default.attributesOfItem(atPath: url.path) else { + fileError = "The disk file is unavailable. Choose it again."; return + } + let sourceVolume = sourceAttributes[.systemNumber] as? NSNumber + let sourceInode = sourceAttributes[.systemFileNumber] as? NSNumber + let sourceDate = sourceAttributes[.modificationDate] as? Date + let sourceSize = sourceAttributes[.size] as? NSNumber + let expectedEpoch = inputEpoch + let finish: @MainActor (NSApplication.ModalResponse) -> Void = { [weak self] response in + guard let self else { return } + self.mediaPromptOpen = false + guard response == .alertSecondButtonReturn else { return } + guard !self.busy, !self.diskSaving, !self.diskEditorLocked, self.state != .closed, + self.inputEpoch == expectedEpoch else { + self.fileError = "The machine changed while choosing a disk action. Open the disk again."; return + } + let current = try? FileManager.default.attributesOfItem(atPath: url.path) + guard current?[.type] as? FileAttributeType == .typeRegular, + sourceVolume != nil, sourceInode != nil, + current?[.systemNumber] as? NSNumber == sourceVolume, + current?[.systemFileNumber] as? NSNumber == sourceInode, + current?[.modificationDate] as? Date == sourceDate, + current?[.size] as? NSNumber == sourceSize else { + self.fileError = "The disk file changed while choosing an action. Open it again to use its current contents."; return + } + if options.action.indexOfSelectedItem == 0 { + DiskImageEditorCoordinator.shared.open(url, machine: self) + } else if options.action.indexOfSelectedItem == 2 { + self.loadMedia(url, destination: .hardDisk(options.drive.indexOfSelectedItem)) + } else { + let drive = options.drive.indexOfSelectedItem + let execution = DiskInsertionExecution(rawValue: options.execution.indexOfSelectedItem) ?? .keepCurrentState + let reset = DiskInsertionReset(rawValue: options.reset.indexOfSelectedItem) ?? .none + Task { @MainActor in + do { try await self.insertDiskFromMedia(url, drive: drive, execution: execution, reset: reset) } + catch { self.fileError = error.localizedDescription } + } + } + } + if let window = NSApp.keyWindow ?? NSApp.mainWindow { + sheetPending = true + alert.beginSheetModal(for: window) { response in + Task { @MainActor in finish(response) } + } + } else { + finish(alert.runModal()) + } + return + } + let alert = NSAlert(); alert.messageText = "Open \(url.lastPathComponent)?" + alert.informativeText = "Choose where to use this file. ROM and cartridge changes restart the computer; binary programs start immediately. Disk and cassette images are mounted without running their contents. Unsaved media must be saved or exported first. Cancel leaves the current session unchanged." + let picker = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 340, height: 28)) + picker.addItems(withTitles: choices.map(\.label)); picker.setAccessibilityLabel("Media destination") + if let preferred, let index = choices.firstIndex(of: preferred) { picker.selectItem(at: index) } + else if ["ccc", "pak"].contains(url.pathExtension.lowercased()), let index = choices.firstIndex(of: .cartridge(cartridgeAssignments.multiPak ? cartridgeAssignments.physicalSlot : 0)) { picker.selectItem(at: index) } + alert.accessoryView = picker + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Open") + guard alert.runModal() == .alertSecondButtonReturn else { return } + loadMedia(url, destination: choices[picker.indexOfSelectedItem]) + } + // One path for recents, Finder opening and all drop targets. Preflight is + // performed before pausing; actual replacement reuses device safeguards. + // Return the existing scheduled operation for callers that need to await it. + // The floppy task covers its complete insertion; other device helpers retain + // their callback-based completion and busy state. Floppy insertion reserves + // busy inside its transaction; setting it here would reject our own request. + @discardableResult + func loadMedia(_ url: URL, destination: MediaDestination) -> Task? { + guard !busy, !diskSaving, !diskEditorLocked, state != .closed, RecentMedia.isLocalFile(url), destination.valid else { return nil } + if case .floppy(let drive) = destination { + return Task { @MainActor in + do { try await insertDiskFromMedia(url, drive: drive, execution: .keepCurrentState) } + catch { fileError = error.localizedDescription } + } + } + if case .hardDisk = destination, !hardDiskConnected { fileError = "Connect the hard-disk controller in Cartridges before inserting this image."; return nil } + if case .cartridge(let slot) = destination, (cartridgeAssignments.multiPak ? slot == 0 : slot != 0) { + fileError = "This cartridge destination is not active. Choose the direct cartridge or an enabled Multi-Pak slot."; return nil + } + busy = true; fileError = nil + return Task { @MainActor in + do { + // Validate fully before disturbing current execution or files. + let bytes: Data? = try await Task.detached(priority: .userInitiated) { + switch destination { + case .systemROM: return try ROMImage.read(url) + case .diskROM: return try DiskFiles.readROM(url) + case .binary: return try BinaryFile.read(url) + case .cassette: return try TapeImage.read(url) + case .floppy: _ = try DiskFiles.readImage(url); return nil + case .hardDisk: _ = try HardDiskFiles.readImage(url); return nil + case .cartridge: return try DiskFiles.readCartridgeROM(url) + } + }.value + let paused = await diskStep(controller.pauseForDiskChange) + if let error = paused.errorMessage { throw ProfileFailure.message(error) } + if let pending = diskSaveTask { await pending.value } + await saveAutomaticDisks(); await saveAutomaticHardDisks(force: true) + _ = await diskStep(controller.snapshot) + guard !unsavedMedia else { throw ProfileFailure.message("Save As or export unsaved media before opening another file. The machine is paused; your media and recordings are kept.") } + switch destination { + case .systemROM: installROM(bytes!, url: url) + case .diskROM: selectDiskROM(url) + case .binary: + command({ controller.quickLoadBinary(bytes!, completion: $0) }, onSuccess: { [self] in binaryName = url.lastPathComponent; recentMedia.record(url, as: .binary) }) + case .cassette: readTape(url) + case .floppy(let n): insertDisk(url, drive: n) + case .hardDisk(let n): insertHardDisk(url, drive: n) + case .cartridge(let n): selectCartridgeROM(url, slot: n) + } + } catch { fileError = error.localizedDescription; busy = false } + } + } +} + +@MainActor +extension MachineModel { + func saveScreenshot() { + guard !screenshotInProgress else { return } + let capture: ScreenCapture + do { capture = try ScreenCapture(pixels: pixels, area: activeVideoRect) } + catch { fileError = error.localizedDescription; return } + screenshotInProgress = true; fileError = nil + let panel = NSSavePanel() + panel.title = "Save CoCo Screen" + panel.message = "Save the picture captured when you chose this command. PNG uses the active picture’s native resolution, without the window, scaling or scanline effects. The CoCo keeps running." + panel.allowedContentTypes = [.png]; panel.canCreateDirectories = true + let format = DateFormatter(); format.dateFormat = "yyyy-MM-dd HH-mm-ss" + panel.nameFieldStringValue = "VCC Screen \(format.string(from: Date())).png" + panel.begin { [weak self] result in + guard let self else { return } + guard result == .OK, let url = panel.url else { self.screenshotInProgress = false; return } + Task { @MainActor in + defer { self.screenshotInProgress = false } + do { try await Task.detached(priority: .userInitiated) { try capture.save(to: url) }.value } + catch { self.fileError = error.localizedDescription } + } + } + } +} + +// Library launches reuse the profile transaction; neither this preview nor the +// catalog owns a second emulator. The captured setup is configuration, not RAM. +struct PreparedLibraryLaunch { + let plan: SoftwareLibraryLaunchPlan + let profile: ConfigurationProfile + let previousSetup: ConfigurationProfile? + fileprivate let expectedConfiguration: ConfigurationProfile + fileprivate let expectedEpoch: UInt64 +} +struct LibraryMachineLaunchResult { + let message: String? +} + +extension MachineModel { + var canLaunchLibrarySoftware: Bool { !busy && !diskSaving && state != .closed } + + func prepareLibraryLaunch(_ plan: SoftwareLibraryLaunchPlan) async throws -> PreparedLibraryLaunch { + guard canLaunchLibrarySoftware else { throw ProfileFailure.message("Wait for the current machine operation to finish.") } + busy = true; defer { busy = false } + let previous = profileConfiguration, epoch = inputEpoch + try await Task.detached(priority: .userInitiated) { try plan.validateMedia() }.value + var profile = ConfigurationProfile(name: String(plan.title.prefix(100))) + profile.machine = MachineSettings(use6309: plan.use6309, ram: plan.ramIndex, + overclock: 1, frameInterval: 1, fastForward: false) + profile.videoOutput = plan.videoOutput ?? videoOutput.rawValue + profile.sound = audioEnabled; profile.volume = volume + profile.input = input.settings + // Native keyboard controls (for example Double Dragon) must reach the + // guest rather than being consumed by keyboard-emulated joysticks. + if plan.controls["keyboard"].string != nil { + for port in 0..<2 where profile.input[port].source == .keyboard { profile.input[port].source = .none } + } + // Hardware choices the user already made remain in effect; Archive hints + // only supply an otherwise unassigned port, never replace a real controller. + for (name, port) in [("right", 0), ("left", 1)] where profile.input[port].source == .none && plan.controls["keyboard"].string == nil { + switch plan.controls[name]["suggested_input"].string { + case "keyboard-joystick": profile.input[port].source = .keyboard + case "mouse-joystick": profile.input[port].source = .mouse + default: break + } + } + let kit = startupStore?.kit, support = startupStore?.directory + func firmware(_ name: String, fallback: URL?) throws -> URL { + if let kit, let support, let url = try? kit.rom(name, in: support) { return url } + guard let fallback else { throw ProfileFailure.message("The recommended setup needs \(name). Choose that firmware in the existing machine or cartridge settings, then try again.") } + return fallback + } + profile.systemROM = try firmware("coco3.rom", fallback: systemROMURL) + var layout = CartridgeAssignments() + layout.multiPak = true; layout.mpiConfigured = true; layout.physicalSlot = plan.controllerSlot + switch plan.profile { + case .romCartridge: + guard let cartridge = plan.cartridgeURL else { throw ProfileFailure.message("Choose a cartridge file before starting this title.") } + layout.slots[plan.controllerSlot] = .init(kind: plan.cartridgeDevice == .orchestra90 ? .orchestra90 : .rom, url: cartridge) + case .diskBasic: + profile.media.rom = try firmware("disk11.rom", fallback: diskAssignments.rom) + layout.slots[plan.controllerSlot].kind = .floppy + case .cocoSDC: + let priorROM = cartridgeAssignments.slots.first { $0.kind == .sdc }?.url + layout.slots[plan.controllerSlot] = .init(kind: .sdc, url: try firmware("sdcdos.rom", fallback: priorROM), + sdcFolderURL: plan.sdcFolderURL, sdcReadOnly: false) + } + profile.media.cartridges = layout + profile.media.hardDisks = HardDiskAssignments() + for (drive, url) in plan.floppyURLs { profile.media.drives[drive] = .init(url: url, writeProtected: false) } + profile.cassette = plan.cassetteURL; profile.fastCassette = plan.cassetteURL != nil + profile.bootNitros9 = nil + try profile.validate() + let checked = profile + _ = try await Task.detached(priority: .userInitiated) { try PreparedProfile.read(checked) }.value + try Task.checkCancellation() + guard inputEpoch == epoch, profileConfiguration == previous else { throw ProfileFailure.message("The machine setup changed while preparing this title. Choose Play again to review the new setup.") } + var returnSetup = previous; returnSetup.name = "Previous Setup" + let hasUnbackedMedia = (tapeMounted && cassetteURL == nil) || + disks.enumerated().contains { $0.element.mounted && previous.media.drives[$0.offset] == nil } || + hardDisks.enumerated().contains { $0.element.mounted && previous.media.hardDisks?.drives[$0.offset] == nil } + return PreparedLibraryLaunch(plan: plan, profile: profile, + previousSetup: state == .empty || previous.systemROM == nil || hasUnbackedMedia ? nil : returnSetup, + expectedConfiguration: previous, expectedEpoch: epoch) + } + + func launchLibrary(_ prepared: PreparedLibraryLaunch) async throws -> LibraryMachineLaunchResult { + guard canLaunchLibrarySoftware, inputEpoch == prepared.expectedEpoch, + profileConfiguration == prepared.expectedConfiguration else { + throw ProfileFailure.message("The machine setup changed after this preview. Choose Play again before restarting it.") + } + try Task.checkCancellation() + var startupMessage: String? + let returnToNitros9 = builtInNitros9 ? prepared.previousSetup : nil + let applied = await loadProfile(preparing: { + try await Task.detached(priority: .userInitiated) { try prepared.plan.validateMedia() }.value + return prepared.profile + }, startRunning: true, afterStart: { [self] in + do { + try Task.checkCancellation() + if prepared.plan.cassetteURL != nil && !prepared.plan.commands.isEmpty { + let playing = await diskStep { controller.tapeAction(1, completion: $0) } + if let error = playing.errorMessage { throw ProfileFailure.message(error) } + } + if !prepared.plan.commands.isEmpty { + let generation = imageGeneration + try await waitForLibraryPrompt(generation: generation, timeout: 15) + for (index, command) in prepared.plan.commands.enumerated() { + try Task.checkCancellation() + let paste = try CocoPaste(command + "\n", mode: .text) + let queued = await diskStep { controller.pasteChords(paste.chords.map { NSNumber(value: $0) }, completion: $0) } + if let error = queued.errorMessage { throw ProfileFailure.message(error) } + try await waitForLibraryPaste(generation: generation, timeout: 60) + if index + 1 < prepared.plan.commands.count || !prepared.plan.automaticallyStarts { + try await waitForLibraryPrompt(generation: generation, timeout: prepared.plan.cassetteURL == nil ? 30 : 120) + } + } + try Task.checkCancellation() + // A running game need not return to BASIC or remain in text + // mode. Still catch an immediate final RUN/EXEC/DOS failure. + let (text, snapshot): (String?, VCCMachineSnapshot) = await withCheckedContinuation { c in + controller.inspectScreenText { c.resume(returning: ($0, $1)) } + } + guard snapshot.generation == generation, snapshot.state == .running else { + throw ProfileFailure.message("The CoCo stopped or changed while starting the software.") + } + if let error = snapshot.errorMessage { throw ProfileFailure.message(error) } + if let text, Self.libraryScreenHasBASICError(text) { + throw ProfileFailure.message("BASIC reported a loading error. Check the mounted files and instructions.") + } + } + } catch { + _ = await diskStep(controller.cancelPaste) + _ = await diskStep(controller.pause) + startupMessage = error is CancellationError ? "Automatic loading stopped. The installed setup is paused; its files are still mounted." : "The setup is installed and paused. " + error.localizedDescription + " Follow the loading instructions or return to the previous setup." + } + }) + guard applied else { throw ProfileFailure.message(profileError ?? "The setup could not be installed; the previous media has been preserved.") } + libraryReturnToNitros9 = returnToNitros9 + return LibraryMachineLaunchResult(message: startupMessage ?? profileError) + } + + func returnLibrarySetup(_ profile: ConfigurationProfile) async throws { + guard canLaunchLibrarySoftware else { throw ProfileFailure.message("Wait for the current machine operation to finish.") } + _ = try await Task.detached(priority: .userInitiated) { try PreparedProfile.read(profile) }.value + try Task.checkCancellation() + let applied = await loadProfile(preparing: { profile }, startRunning: true, builtInNitros9: profile == libraryReturnToNitros9) + guard applied, profileError == nil else { throw ProfileFailure.message(profileError ?? "The previous setup could not be restored.") } + libraryReturnToNitros9 = nil + } + + private func waitForLibraryPaste(generation: UInt64, timeout: TimeInterval) async throws { + let deadline = Date().addingTimeInterval(timeout) + while Date() < deadline { + try Task.checkCancellation() + let snapshot = await diskStep(controller.snapshot) + guard snapshot.generation == generation, snapshot.state == .running else { throw ProfileFailure.message("The CoCo stopped or changed while entering the loading command.") } + if let error = snapshot.errorMessage { throw ProfileFailure.message(error) } + if snapshot.pasteRemaining == 0 { return } + try await Task.sleep(nanoseconds: 100_000_000) + } + throw ProfileFailure.message("Entering the loading command timed out.") + } + private static func libraryScreenHasBASICError(_ text: String) -> Bool { + text.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty }.suffix(3).contains { $0.hasPrefix("?") && $0.contains("ERROR") } + } + #if DEBUG + func waitForMCPFixturePrompt() async throws { + let snapshot = await mcpMachineSnapshot() + let deadline = ContinuousClock.now.advanced(by: .seconds(15)) + var reason = "" + while ContinuousClock.now < deadline { + do { + let observed = try await mcpScreen(expected: snapshot, source: "") + if observed["direct_prompt"] as? Bool == true { return } + reason = observed["text"] as? String ?? "" + } catch { reason = error.localizedDescription } + try await Task.sleep(for: .milliseconds(100)) + } + let (text, last): (String?, VCCMachineSnapshot) = await withCheckedContinuation { c in + controller.inspectScreenText { c.resume(returning: ($0, $1)) } + } + throw ProfileFailure.message("BASIC fixture did not reach direct input. " + reason + " Screen: " + (text ?? "(unavailable)") + + String(format: " PC %04X, frame %llu.", last.programCounter, last.frames)) + } + #endif + private func waitForLibraryPrompt(generation: UInt64, timeout: TimeInterval) async throws { + let deadline = Date().addingTimeInterval(timeout) + var readyObservations = 0 + while Date() < deadline { + try Task.checkCancellation() + let (text, snapshot): (String?, VCCMachineSnapshot) = await withCheckedContinuation { c in + controller.inspectScreenText { c.resume(returning: ($0, $1)) } + } + guard snapshot.generation == generation, snapshot.state == .running else { throw ProfileFailure.message("The CoCo stopped or changed while waiting for BASIC.") } + if let error = snapshot.errorMessage { throw ProfileFailure.message(error) } + // Text-mode discovery may fail transiently during boot. Only a real, + // visible BASIC prompt permits typing; a timer never implies readiness. + if let text, snapshot.pasteRemaining == 0 { + let lines = text.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } + if Self.libraryScreenHasBASICError(text) { + throw ProfileFailure.message("BASIC reported a loading error. Check the mounted files and instructions.") + } + readyObservations = lines.last == "OK" ? readyObservations + 1 : 0 + if readyObservations >= 2 { accept(snapshot); return } + } else { readyObservations = 0 } + try await Task.sleep(nanoseconds: 100_000_000) + } + throw ProfileFailure.message("A BASIC prompt was not detected before the loading timeout; no further commands were sent.") + } +} diff --git a/platforms/macos/App/MachineSettings.swift b/platforms/macos/App/MachineSettings.swift new file mode 100644 index 0000000..fc758f3 --- /dev/null +++ b/platforms/macos/App/MachineSettings.swift @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +struct MachineSettings: Codable, Equatable { + var use6309 = false + var ram = 1 + var overclock = 1 + var frameInterval = 1 + var fastForward = false + static let preferenceKey = "machineSettings.v1" + static let memoryLabels = ["128 KB", "512 KB", "2 MB", "8 MB"] + var valid: Bool { (0...3).contains(ram) && (1...16).contains(overclock) && (1...6).contains(frameInterval) } + func needsRestart(comparedTo previous: Self) -> Bool { use6309 != previous.use6309 || ram != previous.ram } + static func remembered(in defaults: UserDefaults) -> Self { + guard let data = defaults.data(forKey: preferenceKey), + let value = try? JSONDecoder().decode(Self.self, from: data), value.valid else { return Self() } + return value + } + func save(in defaults: UserDefaults) { + guard valid, let data = try? JSONEncoder().encode(self) else { return } + defaults.set(data, forKey: Self.preferenceKey) + } +} diff --git a/platforms/macos/App/MachineSettingsView.swift b/platforms/macos/App/MachineSettingsView.swift new file mode 100644 index 0000000..7973225 --- /dev/null +++ b/platforms/macos/App/MachineSettingsView.swift @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI + +struct MachineSettingsView: View { + @ObservedObject var machine: MachineModel + @State private var draft = MachineSettings() + @State private var confirmRestart = false + private var restartRequired: Bool { + (machine.state == .running || machine.state == .paused) && draft.needsRestart(comparedTo: machine.settings) + } + var body: some View { + VStack(alignment: .leading, spacing: 0) { + SecondaryHeader(title: "Machine Settings", symbol: "cpu", subtitle: "Review changes, then apply them to the CoCo.") + .padding(20) + Divider() + ScrollView { + VStack(alignment: .leading, spacing: 16) { + SecondaryCard { + Label("Hardware", systemImage: "cpu").font(.headline) + Picker("Processor", selection: $draft.use6309) { + Text("Motorola 6809").tag(false) + Text("Hitachi 6309").tag(true) + }.accessibilityIdentifier("machine-processor") + Picker("Memory", selection: $draft.ram) { + ForEach(0..<4) { Text(MachineSettings.memoryLabels[$0]).tag($0) } + }.accessibilityIdentifier("machine-memory") + Label("Hardware changes restart the CoCo and clear RAM. Mounted media stays attached.", systemImage: "arrow.counterclockwise") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + SecondaryCard { + Label("Performance", systemImage: "speedometer").font(.headline) + Stepper("CPU overclock: \(draft.overclock)×", value: $draft.overclock, in: 1...16) + .monospacedDigit() + Toggle("Fast-forward", isOn: $draft.fastForward) + Text("Fast-forward temporarily silences playback. Disk and cassette operations continue.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + Divider() + Picker("Present frames", selection: $draft.frameInterval) { + Text("Every frame").tag(1) + ForEach(2...6, id: \.self) { Text("Every \($0) frames").tag($0) } + }.accessibilityIdentifier("machine-frame-interval") + SecondaryHelp(title: "About speed and display timing") { + Text("1× is normal. Overclock increases CPU speed when software selects double-speed mode. Video and device timing stay unchanged.") + Text("Fast-forward runs faster than real time as this Mac allows. Presenting fewer frames reduces display updates only; CPU, video timing, sound and devices still run every frame.") + } + } + SecondaryCard { + Label("Networking", systemImage: "network").font(.headline) + Toggle("Enable DriveWire networking", isOn: Binding( + get: { machine.driveWireEnabled }, set: machine.setDriveWireNetworking)) + .accessibilityIdentifier("machine-drivewire-networking") + Text("Lets compatible NitrOS-9 programs open outbound TCP connections through the FD-502 Becker port. Networking defaults on for the built-in NitrOS-9 profile. Your choice here applies across profiles. Turning it off closes connections immediately.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + DriveWireNetworkingHelp() + Divider() + Label("Mac shell", systemImage: "terminal").font(.subheadline.bold()) + Text("At the OS-9 prompt, enter telnet macshell 2323 to request access to your Mac command line. Programs in the guest can then run commands with your Mac account’s permissions. Type exit to return to OS-9.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + if machine.macShellStatus == "idle" { + Button("Start Mac Shell Session", action: machine.startMacShellSession) + .disabled(!machine.driveWireEnabled || machine.busy) + } else { + Text(machine.macShellStatus == "ready" ? "Ready for one guest connection." : + machine.macShellStatus == "requested" ? "Waiting for your permission." : "Mac shell session connected.") + .font(.callout) + Button("Stop Mac Shell Session", action: machine.stopMacShellSession) + } + if machine.hasRememberedMacShellPermission { + Button("Forget Mac Shell Permission", action: machine.forgetMacShellPermission) + } + } + SecondaryCard { + Label("Recovery", systemImage: "arrow.counterclockwise").font(.headline) + Text(machine.hasBundledROMs ? "Restore the complete standard setup, including ROMs and media assignments. This is separate from editing the hardware above." : "Bundled defaults are unavailable in this source build. Choose your own ROMs, or add the private development ROMs.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + Button { machine.confirmRestoreAppDefaults { draft = machine.settings } } label: { + Label("Restore App Defaults…", systemImage: "arrow.counterclockwise") + }.disabled(!machine.hasBundledROMs) + } + }.padding(20) + } + Divider() + VStack(alignment: .leading, spacing: 8) { + if let error = machine.profileError ?? machine.fileError ?? machine.error { + Text(error).foregroundStyle(.red).font(.callout).textSelection(.enabled) + .fixedSize(horizontal: false, vertical: true) + } + HStack { + Button { draft = MachineSettings() } label: { + Label("Hardware Defaults", systemImage: "arrow.counterclockwise") + }.help("Reset this form's draft only. Choose Apply to change the machine.") + Spacer() + Button { draft = machine.settings } label: { Label("Revert", systemImage: "arrow.uturn.backward") } + .disabled(draft == machine.settings) + Button { + if restartRequired { confirmRestart = true } + else { machine.applyMachineSettings(draft) } + } label: { + Label(restartRequired ? "Apply and Restart…" : "Apply", + systemImage: restartRequired ? "arrow.clockwise" : "checkmark") + }.keyboardShortcut(.defaultAction).disabled(draft == machine.settings || !draft.valid) + } + Text("Hardware Defaults edits this draft. Applied settings are remembered for the next launch.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + }.padding(16) + } + .background(MacShellPermissionPresenter(machine: machine)) + .frame(minWidth: 540, minHeight: 520) + .disabled(machine.busy || machine.diskSaving || machine.state == .closed) + .onAppear { draft = machine.settings } + .onChange(of: machine.settings) { old, new in if draft == old { draft = new } } + .alert("Cold-restart the machine?", isPresented: $confirmRestart) { + Button("Cancel", role: .cancel) { } + Button("Apply and Restart", role: .destructive) { machine.applyMachineSettings(draft) } + } message: { + Text("Programs and other contents of RAM will be cleared. Mounted disks, cartridges, and cassette contents are retained. The machine will keep its current running or paused state.") + } + } +} diff --git a/platforms/macos/App/ManualLibraryView.swift b/platforms/macos/App/ManualLibraryView.swift new file mode 100644 index 0000000..224ea50 --- /dev/null +++ b/platforms/macos/App/ManualLibraryView.swift @@ -0,0 +1,294 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import Combine +import SwiftUI +import WebKit + +struct ManualLibraryContent { + let root: URL + + init(root: URL) { + // WebKit checks its read grant against the exact path used by a citation. + self.root = root.standardizedFileURL.resolvingSymlinksInPath() + } + + static var bundled: Self? { + Bundle.main.url(forResource: "ManualLibrary", withExtension: nil).map { Self(root: $0) } + } + + var home: URL { root.appendingPathComponent("index.html") } + + func allowsExternalReference(_ url: URL) -> Bool { + guard ["http", "https"].contains(url.scheme?.lowercased() ?? "") else { return false } + let existing = ["https://colorcomputerarchive.com/", "https://learn.chatgpt.com/docs/extend/mcp?surface=app", + "https://learn.chatgpt.com/docs/extend/mcp?surface=cli", + "https://vccplus-git.brianholman.com/VCCPlusApps/CoCoCapitalQuiz", + "https://vccplus-git.brianholman.com/VCCPlusApps/CoCoCapitalQuiz/src/branch/main/CHATGPT_PROMPT.md", + "https://www.fla-shop.com/svg/usa/", "https://creativecommons.org/licenses/by/4.0/"] + if existing.contains(url.absoluteString) { return true } + let provenance = root.appendingPathComponent("toolchain-reference/provenance.json") + guard relativePath(for: provenance) != nil, + let data = try? Data(contentsOf: provenance), + let record = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let references = record["externalReferences"] as? [String] else { return false } + return references.contains(url.absoluteString) + } + + func relativePath(for url: URL) -> String? { + guard url.isFileURL, url.host?.isEmpty != false else { return nil } + let base = root.standardizedFileURL.resolvingSymlinksInPath().pathComponents + let file = url.standardizedFileURL.resolvingSymlinksInPath() + let parts = file.pathComponents + guard parts.count > base.count, parts.starts(with: base), + (try? file.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true + else { return nil } + return parts.dropFirst(base.count).joined(separator: "/") + } + + func basicTopicURL(for entry: BASICReferenceEntry) -> URL? { + let page: String + let anchor: String + if entry.id.hasPrefix("ERROR.") { + page = "errors.html" + anchor = "err-" + entry.keyword.lowercased().replacingOccurrences(of: "/0", with: "div-zero") + } else { + page = "reference.html" + anchor = "term-" + entry.id.lowercased() + .replacingOccurrences(of: ".", with: "-") + .replacingOccurrences(of: "$", with: "-string") + .replacingOccurrences(of: "@", with: "-at") + } + let url = root.appendingPathComponent("programming-in-coco-basic").appendingPathComponent(page) + var destination = URLComponents(url: url, resolvingAgainstBaseURL: false) + destination?.fragment = anchor + return destination?.url + } + + // Only files in a book's designated practice areas offer a writable copy. + func copyTitle(for relativePath: String) -> String? { + let parts = relativePath.split(separator: "/") + guard parts.count == 3 else { return nil } + let url = root.appendingPathComponent(relativePath) + guard self.relativePath(for: url) == relativePath else { return nil } + if parts[0] == "toolchain-reference", parts[1] == "sources", + ["markdown", "sgml"].contains(url.pathExtension.lowercased()) || url.lastPathComponent == "lwtools-manual.html.txt" { + return "Save Original Manual Source" + } + if parts[0] == "toolchain-reference", parts[1] == "sources", + ["cmoc-help.txt", "lwasm-help.txt", "lwlink-help.txt"].contains(url.lastPathComponent) { + return "Save Command-Line Help" + } + switch (parts[1], url.pathExtension.lowercased()) { + case ("media", "dsk"): return "Save Practice Disk" + case ("media", "cas"): return "Save Practice Cassette" + case ("examples", "asm"), ("examples", "a"): return "Save Assembly Example" + case ("examples", "b09"): return "Save BASIC09 Example" + case ("examples", "c"): return "Save C Example" + case ("examples", "zip"): return "Save Example Project" + case ("examples", "txt"): return "Save Example Text" + default: return nil + } + } + + func exampleURL(for relativePath: String) -> URL? { + let parts = relativePath.components(separatedBy: "/") + guard parts.count == 3, parts[1] == "examples" else { return nil } + let url = root.appendingPathComponent(relativePath) + guard url.pathExtension.lowercased() == "bas", + self.relativePath(for: url) == relativePath else { return nil } + return url + } +} + +@MainActor +final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate { + let webView: WKWebView + let content: ManualLibraryContent? + lazy var pageFind = ManualPageFind(webView: webView) + private var searchNavigation: WKNavigation? + var openExample: ((String) -> Void)? + @Published private(set) var canGoBack = false + @Published private(set) var canGoForward = false + @Published private(set) var error: String? + + init(content: ManualLibraryContent? = .bundled) { + self.content = content + let configuration = WKWebViewConfiguration() + configuration.websiteDataStore = .nonPersistent() + webView = WKWebView(frame: .zero, configuration: configuration) + super.init() + webView.navigationDelegate = self + webView.allowsBackForwardNavigationGestures = true + webView.publisher(for: \.canGoBack).receive(on: RunLoop.main).assign(to: &$canGoBack) + webView.publisher(for: \.canGoForward).receive(on: RunLoop.main).assign(to: &$canGoForward) + } + + func showHome() { + loadPage(content?.home) + } + + func showLibrarySearch() { + pageFind.close() + if let url = webView.url, content?.relativePath(for: url) == "index.html", !webView.isLoading { + focusLibrarySearch() + } else { + searchNavigation = loadPage(content?.home) + } + } + + private func focusLibrarySearch() { + webView.window?.makeFirstResponder(webView) + webView.evaluateJavaScript(""" + document.getElementById('search').scrollIntoView(); + var input = document.getElementById('manual-query'); + input.focus({preventScroll: true}); + input.select(); + """, in: nil, in: .defaultClient, completionHandler: nil) + } + + func showBASICTopic(_ entry: BASICReferenceEntry) { + loadPage(content?.basicTopicURL(for: entry)) + } + + @discardableResult + private func loadPage(_ url: URL?) -> WKNavigation? { + guard let content, let url, content.relativePath(for: url) != nil else { + error = "This page is missing from the bundled Manual Library." + return nil + } + error = nil + return webView.loadFileURL(url, allowingReadAccessTo: content.root) + } + + func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, + decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { + guard let url = action.request.url, action.targetFrame?.isMainFrame != false else { + decisionHandler(.cancel) + return + } + if let path = content?.relativePath(for: url) { + let fileExtension = url.pathExtension.lowercased() + if let saveTitle = content?.copyTitle(for: path) { + decisionHandler(.cancel) + if action.navigationType == .linkActivated { + let panel = NSSavePanel() + panel.nameFieldStringValue = url.lastPathComponent + panel.title = saveTitle + panel.begin { [weak self] response in + guard response == .OK, let destination = panel.url else { return } + do { + try Data(contentsOf: url).write(to: destination, options: .atomic) + } catch { + self?.error = "The practice file could not be saved. " + error.localizedDescription + } + } + } + return + } + if fileExtension == "bas" { + decisionHandler(.cancel) + if action.navigationType == .linkActivated, content?.exampleURL(for: path) != nil { + openExample?(path) + } + return + } + decisionHandler(.allow) + return + } + decisionHandler(.cancel) + if action.navigationType == .linkActivated { + if content?.allowsExternalReference(url) == true { + if !NSWorkspace.shared.open(url) { error = "The reference could not open in your browser." } + } else { + error = "This link does not lead to an available page in the bundled Manual Library." + } + } + } + + func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { + pageFind.pageChanged() + } + + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + error = nil + if let searchNavigation, navigation === searchNavigation { + self.searchNavigation = nil + focusLibrarySearch() + } + } + + func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { + showLoadFailure(error) + } + + func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { + showLoadFailure(error) + } + + private func showLoadFailure(_ failure: Error) { + let reason = failure as NSError + guard !(reason.domain == NSURLErrorDomain && reason.code == NSURLErrorCancelled) else { return } + error = "The manual page could not open. " + failure.localizedDescription + } + + func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { + error = "The manual reader stopped responding. Choose Library Home to reopen it." + } +} + +private struct ManualWebPage: NSViewRepresentable { + let reader: ManualReader + let openExample: (String) -> Void + + func makeNSView(context: Context) -> WKWebView { reader.webView } + + func updateNSView(_ webView: WKWebView, context: Context) { reader.openExample = openExample } +} + +struct ManualLibraryView: View { + @Environment(\.openWindow) private var openWindow + @ObservedObject var reader: ManualReader + + var body: some View { + VStack(spacing: 0) { + if let error = reader.error { + Label(error, systemImage: "exclamationmark.triangle") + .frame(maxWidth: .infinity, alignment: .leading).padding(10) + Divider() + } + ManualPageFindBar(finder: reader.pageFind) + ManualWebPage(reader: reader) { path in + openWindow(id: "basic-example", value: "manual/" + path) + } + } + .focusedSceneValue(\.manualPageFind, reader.pageFind) + .toolbar { + ToolbarItemGroup(placement: .primaryAction) { + Button("Find on This Page", systemImage: "magnifyingglass") { reader.pageFind.show() } + .help("Find on this page (⌘F)").accessibilityIdentifier("manual.find") + + Button { + reader.showLibrarySearch() + } label: { + Label("Ask the Manuals", systemImage: "books.vertical").labelStyle(.titleAndIcon) + } + .help("Search all manuals by keyword") + .accessibilityIdentifier("manual.ask") + } + ToolbarItemGroup(placement: .navigation) { + Button("Back", systemImage: "chevron.backward") { reader.webView.goBack() } + .help("Back").disabled(!reader.canGoBack) + .accessibilityIdentifier("manual.back") + Button("Forward", systemImage: "chevron.forward") { reader.webView.goForward() } + .help("Forward").disabled(!reader.canGoForward) + .accessibilityIdentifier("manual.forward") + Button("Library Home", systemImage: "books.vertical") { reader.showHome() } + .help("Library Home").accessibilityIdentifier("manual.home") + } + } + .frame(minWidth: 420, minHeight: 340) + .onAppear { + if reader.error == nil && reader.webView.url == nil && !reader.webView.isLoading { reader.showHome() } + } + } +} diff --git a/platforms/macos/App/ManualPageFind.swift b/platforms/macos/App/ManualPageFind.swift new file mode 100644 index 0000000..ca13787 --- /dev/null +++ b/platforms/macos/App/ManualPageFind.swift @@ -0,0 +1,189 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import WebKit + +/// Find within the displayed HTML, including words split by inline formatting. +/// DOM Ranges preserve links, source listings and the page's original markup. +@MainActor +final class ManualPageFind: ObservableObject { + private weak var webView: WKWebView? + @Published private(set) var visible = false + @Published private(set) var focusRequest = 0 + @Published var query = "" { didSet { if query != oldValue { refresh() } } } + @Published private(set) var count = 0 + @Published private(set) var position = 0 + @Published private(set) var searching = false + private var revision = 0 + private var requested = 0 + + init(webView: WKWebView) { self.webView = webView } + + func show() { + if !visible { + visible = true + refresh() + } + focusRequest += 1 + } + + func close() { + guard visible else { return } + visible = false + clear() + if let webView { webView.window?.makeFirstResponder(webView) } + } + + func pageChanged() { + // An in-flight reply belongs to the document which produced it. + visible = false + clear() + } + + private func clear() { + revision += 1 + requested = 0 + count = 0 + position = 0 + searching = false + webView?.callAsyncJavaScript(Self.script, arguments: ["query": "", "index": 0], + in: nil, in: .defaultClient, completionHandler: nil) + } + + func move(backward: Bool = false) { + guard visible else { show(); return } + guard count > 0 else { return } + requested = (requested + (backward ? count - 1 : 1)) % count + run() + } + + private func refresh() { + requested = 0 + count = 0 + position = 0 + if visible { run() } + } + + private func run() { + guard let webView else { return } + revision += 1 + let expected = revision + searching = true + webView.callAsyncJavaScript(Self.script, arguments: ["query": query, "index": requested], + in: nil, in: .defaultClient) { [weak self] result in + guard let self, revision == expected else { return } + let values = (try? result.get()) as? [Int] + count = values?.first ?? 0 + position = values?.last ?? 0 + searching = false + } + } + + // Each WebKit document owns its match ranges in an isolated content world. + // Group adjacent inline nodes so a phrase can span a link or a bold word, + // while keeping headings, paragraphs, table cells and code blocks distinct. + private static let script = #""" + const term = query.trim(); + let state = globalThis.vccPageFind; + if (!term) { + CSS.highlights?.delete('vcc-page-find'); + if (state?.selected) getSelection()?.removeAllRanges(); + delete globalThis.vccPageFind; + return [0, 0]; + } + if (state?.term !== term) { + CSS.highlights?.delete('vcc-page-find'); + if (state?.selected) getSelection()?.removeAllRanges(); + state = {term, ranges: []}; + globalThis.vccPageFind = state; + const root = document.querySelector('article.lesson') || document.querySelector('main') || document.body; + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + const pattern = term.split(/\s+/).map(word => word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('\\s+'); + const re = new RegExp(pattern, 'giu'); + let group, text = '', nodes = []; + function collect() { + let start = 0; + for (const match of text.matchAll(re)) { + const last = match.index + match[0].length; + while (start + 1 < nodes.length && nodes[start + 1].offset <= match.index) start++; + let end = start; + while (end + 1 < nodes.length && nodes[end + 1].offset < last) end++; + const range = document.createRange(); + range.setStart(nodes[start].node, match.index - nodes[start].offset); + range.setEnd(nodes[end].node, last - nodes[end].offset); + state.ranges.push(range); + } + nodes = []; + text = ''; + } + while (walker.nextNode()) { + const node = walker.currentNode, parent = node.parentElement; + if (!parent || parent.closest('script, style, noscript, [hidden], [aria-hidden="true"]')) continue; + const block = parent.closest('p, h1, h2, h3, h4, li, dt, dd, td, th, pre, figcaption, summary, nav, label, button, section, article, div') || root; + if (block !== group) { collect(); group = block; } + nodes.push({node, offset:text.length}); + text += node.data; + } + collect(); + } + if (!state.ranges.length) return [0, 0]; + const active = index % state.ranges.length; + const range = state.ranges[active]; + const element = range.startContainer.parentElement; + for (let p = element; p; p = p.parentElement) { + if (p.tagName === 'DETAILS') p.open = true; + } + if (CSS.highlights && typeof Highlight === 'function') { + CSS.highlights.set('vcc-page-find', new Highlight(range)); + } else { + const selection = getSelection(); + selection.removeAllRanges(); + selection.addRange(range); + state.selected = true; + } + element.scrollIntoView({block:'nearest', inline:'nearest'}); + const rect = range.getBoundingClientRect(); + if (rect.top < 72 || rect.bottom > innerHeight) scrollBy(0, rect.top - innerHeight / 2); + return [state.ranges.length, active + 1]; + """# +} + +private struct ManualPageFindKey: FocusedValueKey { typealias Value = ManualPageFind } +extension FocusedValues { + var manualPageFind: ManualPageFind? { + get { self[ManualPageFindKey.self] } + set { self[ManualPageFindKey.self] = newValue } + } +} + +struct ManualPageFindBar: View { + @ObservedObject var finder: ManualPageFind + @FocusState private var focused: Bool + + var body: some View { + if finder.visible { + HStack(spacing: 8) { + TextField("Find on This Page", text: $finder.query) + .textFieldStyle(.roundedBorder) + .focused($focused) + .onSubmit { finder.move() } + .accessibilityIdentifier("manual.find.field") + if !finder.query.isEmpty && !finder.searching { + Text(finder.count == 0 ? "No matches" : "\(finder.position) of \(finder.count)") + .font(.caption).foregroundStyle(.secondary).monospacedDigit() + .accessibilityIdentifier("manual.find.status") + } + Button { finder.move(backward: true) } label: { Image(systemName: "chevron.up") } + .disabled(finder.count == 0).accessibilityLabel("Find Previous") + .help("Find previous occurrence (⇧⌘G)") + Button { finder.move() } label: { Image(systemName: "chevron.down") } + .disabled(finder.count == 0).accessibilityLabel("Find Next") + .help("Find next occurrence (⌘G)") + Button("Done") { finder.close() }.keyboardShortcut(.escape, modifiers: []) + } + .padding(.horizontal, 10).padding(.vertical, 5).background(.bar) + .onAppear { focused = true } + .onChange(of: finder.focusRequest) { focused = true } + .onExitCommand { finder.close() } + } + } +} diff --git a/platforms/macos/App/MediaOpenControls.swift b/platforms/macos/App/MediaOpenControls.swift new file mode 100644 index 0000000..f9fe627 --- /dev/null +++ b/platforms/macos/App/MediaOpenControls.swift @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import UniformTypeIdentifiers + +struct MediaDropTarget: ViewModifier { + let machine: MachineModel + var destination: MediaDestination? + @State private var targeted = false + func body(content: Content) -> some View { + content.overlay { if targeted { RoundedRectangle(cornerRadius: 10).strokeBorder(Color.accentColor, lineWidth: 3).allowsHitTesting(false) } } + .onDrop(of: [UTType.fileURL], isTargeted: $targeted) { providers in + guard providers.count == 1, let provider = providers.first else { + machine.reportMediaError("Drop one media file at a time so its destination is explicit."); return false + } + guard !machine.busy, !machine.diskSaving else { return false } + provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier, options: nil) { item, _ in + let url: URL? + if let value = item as? URL { url = value } + else if let data = item as? Data { url = URL(dataRepresentation: data, relativeTo: nil) } + else { url = nil } + Task { @MainActor in + guard let url, url.isFileURL else { machine.reportMediaError("Drop a local media file from Finder."); return } + machine.offerMedia(url, preferred: destination) + } + } + return true + } + } +} + +struct RecentMediaCommands: View { + let machine: MachineModel + @ObservedObject var recent: RecentMedia + @ObservedObject var menu: MachineMenuState + var body: some View { + Menu("Open Recent Media") { + if recent.entries.isEmpty { Text("No Recent Media") } + ForEach(recent.entries) { entry in + Button(entry.label) { machine.offerMedia(entry.url, preferred: entry.destination, fromHistory: true) } + .help(entry.url.path).disabled(menu.values.busy || menu.values.diskSaving) + } + Divider() + Button("Clear Recent Media") { recent.clear() }.disabled(recent.entries.isEmpty) + } + } +} diff --git a/platforms/macos/App/MemoryToolsModel.swift b/platforms/macos/App/MemoryToolsModel.swift new file mode 100644 index 0000000..5d4331c --- /dev/null +++ b/platforms/macos/App/MemoryToolsModel.swift @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import Combine + +@MainActor +final class MemoryToolsModel: ObservableObject { + enum Space: String, CaseIterable { case mapped = "Mapped CPU", physical = "Physical RAM" } + struct Row: Identifiable { + let id: Int + let location: UInt32 + let logicalAddress: UInt16 + let bytes: String + let mnemonic: String + let operand: String + } + let machine: MachineModel + @Published var space = Space.physical + @Published var startText = "000000" + @Published var endText = "0000FF" + @Published var logicalText = "0000" + @Published var os9 = false + @Published private(set) var pending = false + @Published private(set) var rows: [Row] = [] + @Published private(set) var caption = "Capture memory to inspect it. The machine keeps its current running or paused state." + @Published var error: String? + @Published var saveMessage: String? + private(set) var capturedPhysical = true + private var subscriptions: Set = [] + init(machine: MachineModel) { + self.machine = machine + // Observe only command availability and RAM capacity, not the 60 Hz + // display publisher. A profile change must update range validation even + // while this tab retains an older, explicitly labeled capture. + let changes: [AnyPublisher] = [ + machine.$state.removeDuplicates().map { _ in () }.eraseToAnyPublisher(), + machine.$busy.removeDuplicates().map { _ in () }.eraseToAnyPublisher(), + machine.$diskSaving.removeDuplicates().map { _ in () }.eraseToAnyPublisher(), + machine.$settings.map(\.ram).removeDuplicates().map { _ in () }.eraseToAnyPublisher() + ] + Publishers.MergeMany(changes).sink { [weak self] in self?.objectWillChange.send() }.store(in: &subscriptions) + } + var available: Bool { !pending && !machine.busy && !machine.diskSaving && (machine.state == .paused || machine.state == .running) } + var capacity: UInt32 { space == .mapped ? 65536 : [0x20000, 0x80000, 0x200000, 0x800000][min(3, max(0, machine.settings.ram))] } + + static func range(start: String, end: String, capacity: UInt32) -> (UInt32, UInt32)? { + guard capacity > 0, + let first = DebuggerModel.hexadecimalAddress(start, maximum: capacity - 1), + let last = DebuggerModel.hexadecimalAddress(end, maximum: capacity - 1), last >= first else { return nil } + return (first, last - first + 1) + } + + private func capture(decode: Bool) async -> VCCDebugMemoryCapture? { + guard available else { return nil } + guard let (start, length) = Self.range(start: startText, end: endText, capacity: capacity) else { + error = "Enter an inclusive hexadecimal range within 000000–\(DebuggerModel.hex(capacity - 1, width: 6)). The end must not precede the start."; return nil + } + let physical = space == .physical + guard let logical = decode && physical ? DebuggerModel.hexadecimal(logicalText) : 0 else { + error = "Enter a logical origin from 0000 to FFFF."; return nil + } + let interpretOS9 = os9 + pending = true; error = nil; saveMessage = nil + defer { pending = false } + let capture: VCCDebugMemoryCapture? = await withCheckedContinuation { continuation in + machine.readDebuggerMemory(address: start, count: decode ? min(length, 4096) : length, + physical: physical, logicalAddress: logical, os9: interpretOS9, decode: decode) { continuation.resume(returning: $0) } + } + guard let capture else { error = "The machine is busy. Try again when its current operation finishes."; return nil } + guard capture.machine.errorMessage == nil else { error = capture.machine.errorMessage; return nil } + if decode { + capturedPhysical = physical + rows = capture.instructions.enumerated().map { index, instruction in + Row(id: index, location: capture.address + capture.instructionOffsets[index].uint32Value, + logicalAddress: instruction.address, + bytes: instruction.bytes.map { String(format: "%02X", $0) }.joined(separator: " "), + mnemonic: instruction.mnemonic, operand: instruction.operand) + } + caption = "\(physical ? "Physical RAM" : "Mapped CPU") capture at \(capture.machine.cycles.formatted()) cycles · \(rows.count) rows · \(capture.machine.use6309 ? "HD6309" : "MC6809")\(physical ? " · \(capture.capacity / 1024) KB captured RAM space" : "")\(interpretOS9 ? " · OS-9 interpretation" : "")" + } + return capture + } + + func decode() async { _ = await capture(decode: true) } + + func exportBytes() async -> Data? { + guard let result = await capture(decode: false) else { return nil } + guard !result.bytes.isEmpty, result.available.count == result.bytes.count, + result.available.allSatisfy({ $0 != 0 }) else { + error = "This range contains I/O that cannot be read without side effects. Choose a range excluding it, or export physical RAM. No file was written." + return nil + } + return result.bytes + } + + func save(_ data: Data, to url: URL) async { + pending = true; error = nil + defer { pending = false } + do { + try await Task.detached { + let access = url.startAccessingSecurityScopedResource() + defer { if access { url.stopAccessingSecurityScopedResource() } } + try data.write(to: url, options: .atomic) + }.value + saveMessage = "Saved \(data.count.formatted()) raw bytes to \(url.lastPathComponent)." + } catch { self.error = error.localizedDescription } + } +} diff --git a/platforms/macos/App/MemoryToolsView.swift b/platforms/macos/App/MemoryToolsView.swift new file mode 100644 index 0000000..522c462 --- /dev/null +++ b/platforms/macos/App/MemoryToolsView.swift @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit +import UniformTypeIdentifiers + +struct MemoryToolsView: View { + @ObservedObject var model: MemoryToolsModel + var body: some View { + VStack(alignment: .leading, spacing: 12) { + HStack { + Picker("Address space", selection: $model.space) { + ForEach(MemoryToolsModel.Space.allCases, id: \.self) { Text($0.rawValue).tag($0) } + }.frame(width: 240).accessibilityIdentifier("memory-tools-space") + Spacer() + Text("All addresses are hexadecimal").font(.caption).foregroundStyle(.secondary) + DebuggerHelpButton(title: "Memory capture and export", text: "Physical addresses identify RAM locations, not CPU execution addresses. The assumed CPU origin controls relative branch targets. Captures are read-only; Disassemble shows up to 128 rows. Export writes the entire selected range as raw bytes, without a LOADM header.") + } + HStack(spacing: 12) { + entry("Start", text: $model.startText, id: "memory-tools-start") + entry("End (inclusive)", text: $model.endText, id: "memory-tools-end") + if model.space == .physical { entry("Assumed CPU origin", text: $model.logicalText, id: "memory-tools-origin") } + } + HStack { + Toggle("Interpret OS-9 calls and module headers", isOn: $model.os9) + .toggleStyle(.checkbox).accessibilityIdentifier("memory-tools-os9") + Spacer() + Button { Task { await model.decode() } } label: { Label("Disassemble", systemImage: "list.bullet.rectangle") }.disabled(!model.available) + .accessibilityIdentifier("memory-tools-decode") + Button(action: export) { Label("Export Binary…", systemImage: "square.and.arrow.up") }.disabled(!model.available) + .accessibilityIdentifier("memory-tools-export") + } + Divider() + Text(model.caption).font(.caption).foregroundStyle(.secondary) + .accessibilityIdentifier("memory-tools-caption") + ScrollView([.horizontal, .vertical]) { + LazyVStack(alignment: .leading, spacing: 4) { + HStack(spacing: 12) { + Text("Location").frame(width: 75, alignment: .leading) + Text("CPU").frame(width: 45, alignment: .leading) + Text("Bytes").frame(width: 160, alignment: .leading) + Text("Instruction / annotation") + }.foregroundStyle(.secondary) + ForEach(model.rows) { row in + HStack(alignment: .top, spacing: 12) { + Text(DebuggerModel.hex(row.location, width: model.capturedPhysical ? 6 : 4)).frame(width: 75, alignment: .leading) + Text(DebuggerModel.hex(row.logicalAddress)).frame(width: 45, alignment: .leading) + Text(row.bytes.isEmpty ? "—" : row.bytes).frame(width: 160, alignment: .leading) + Text(row.mnemonic).frame(width: 60, alignment: .leading) + Text(row.operand) + }.accessibilityElement(children: .combine) + .accessibilityIdentifier("memory-tools-row-\(row.id)") + .contextMenu { + Button("Copy Row") { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString("\(DebuggerModel.hex(row.location, width: 6)) \(row.bytes) \(row.mnemonic) \(row.operand)", forType: .string) + } + } + } + }.font(.system(size: 12, design: .monospaced)).padding(8) + }.frame(minHeight: 180).background(Color(nsColor: .textBackgroundColor), in: RoundedRectangle(cornerRadius: 6)) + if let error = model.error { + Text(error).foregroundStyle(.red).font(.caption).fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier("memory-tools-error") + } + if let message = model.saveMessage { + Text(message).font(.caption).accessibilityIdentifier("memory-tools-saved") + } + if model.pending { ProgressView().controlSize(.small) } + }.padding(16).frame(minWidth: 760, idealWidth: 900, minHeight: 420, idealHeight: 600) + } + + private func entry(_ label: String, text: Binding, id: String) -> some View { + HStack { + Text(label) + TextField(label, text: text).labelsHidden().textFieldStyle(.roundedBorder) + .font(.system(.body, design: .monospaced)).frame(width: 90) + .accessibilityLabel(label + " in hexadecimal").accessibilityIdentifier(id) + } + } + private func export() { + Task { + guard let bytes = await model.exportBytes() else { return } + let panel = NSSavePanel() + panel.title = "Export Raw Memory" + panel.nameFieldStringValue = "memory.raw" + panel.allowedContentTypes = [.data] + panel.begin { result in + guard result == .OK, let url = panel.url else { return } + Task { await model.save(bytes, to: url) } + } + } + } +} diff --git a/platforms/macos/App/MetalRenderer.swift b/platforms/macos/App/MetalRenderer.swift new file mode 100644 index 0000000..9c44cfb --- /dev/null +++ b/platforms/macos/App/MetalRenderer.swift @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import MetalKit +import Combine +import ImageIO +import UniformTypeIdentifiers + +enum DisplayScaling: String, CaseIterable { + case sharp, smooth, integer + var label: String { + switch self { + case .sharp: return "Sharp — Fit Window" + case .smooth: return "Smooth — Fit Window" + case .integer: return "Integer Pixels" + } + } +} + +struct DisplayStyle: Equatable { + var scaling: DisplayScaling = .smooth + var scanlines = false +} + +// Host presentation preferences deliberately stay outside machine profiles. +// Separate observation prevents emulator polls from rebuilding open controls. +@MainActor +final class DisplayPreferences: ObservableObject { + @Published var style: DisplayStyle { didSet { + defaults.set(style.scaling.rawValue, forKey: "displayScaling") + defaults.set(style.scanlines, forKey: "displayScanlines") + } } + private let defaults: UserDefaults + init(defaults: UserDefaults) { + self.defaults = defaults + style = DisplayStyle(scaling: DisplayScaling(rawValue: defaults.string(forKey: "displayScaling") ?? "") ?? .smooth, + scanlines: defaults.bool(forKey: "displayScanlines")) + } +} + +// Immutable pixels and their matching active bounds, captured together before +// the save panel opens. Encoding and file writing need no emulator commands. +struct ScreenCapture: Sendable { + let pixels: Data + let area: CGRect + enum Failure: LocalizedError { + case noFrame, encoding + var errorDescription: String? { self == .noFrame ? "No CoCo picture is available to save yet." : "The CoCo picture could not be encoded as a PNG." } + } + init(pixels: Data?, area: CGRect) throws { + guard let pixels, pixels.count == 640 * 480 * 4 else { throw Failure.noFrame } + self.pixels = pixels; self.area = VideoGeometry.validated(area).integral + } + func png() throws -> Data { + let width = Int(area.width), height = Int(area.height) + var rgba = Data(count: width * height * 4) + rgba.withUnsafeMutableBytes { output in + pixels.withUnsafeBytes { input in + let src = input.bindMemory(to: UInt8.self), dst = output.bindMemory(to: UInt8.self) + for y in 0.. CGRect { + guard [rect.origin.x,rect.origin.y,rect.width,rect.height].allSatisfy({ $0.isFinite }), + rect.width > 0, rect.height > 0 else { return fullFrame } + let clipped = rect.intersection(fullFrame) + return clipped.isNull || clipped.isEmpty ? fullFrame : clipped + } + static func picture(in size: CGSize, source: CGRect, inset: CGFloat = border, scaling: DisplayScaling = .sharp) -> CGRect { + let source = validated(source) + let available = CGSize(width:max(0,size.width-2*inset),height:max(0,size.height-2*inset)) + let fit = min(available.width/source.width,available.height/source.height) + let scale = scaling == .integer && fit >= 1 ? floor(fit) : fit + let width = source.width*scale, height = source.height*scale + let x = (size.width-width)/2, y = (size.height-height)/2 + return CGRect(x:scaling == .integer && fit >= 1 ? floor(x) : x, + y:scaling == .integer && fit >= 1 ? floor(y) : y,width:width,height:height) + } + static func mouse(_ point: CGPoint, in size: CGSize, source: CGRect, + scaling: DisplayScaling = .sharp, backing: CGFloat = 1, + drawableSize: CGSize? = nil) -> CGPoint? { + guard size.width > 0, size.height > 0 else { return nil } + let physical = drawableSize ?? CGSize(width:size.width*max(1,backing),height:size.height*max(1,backing)) + guard physical.width > 0, physical.height > 0 else { return nil } + // Use the actual drawable dimensions: fractional SwiftUI layouts can + // round backing pixels differently from bounds * screen scale. + let r = picture(in:physical,source:source,inset:border*physical.width/size.width,scaling:scaling) + // Metal's viewport starts at the top; AppKit mouse coordinates at bottom. + let pixel = CGPoint(x:point.x*physical.width/size.width,y:(size.height-point.y)*physical.height/size.height) + guard r.width > 0, r.height > 0, r.contains(pixel) else { return nil } + return CGPoint(x:(pixel.x-r.minX)/r.width,y:(pixel.y-r.minY)/r.height) + } +} + +// All CPU-side access is on the main thread. Each submission owns its upload +// texture until the GPU finishes; no texture is overwritten while in flight. +final class MetalRenderer { + let device: MTLDevice + private let queue: MTLCommandQueue + private let pipeline: MTLRenderPipelineState + private let inFlight = DispatchSemaphore(value: 3) + enum Failure: LocalizedError { + case unavailable, shaders, resources + var errorDescription: String? { + switch self { + case .unavailable: return "Metal is unavailable on this Mac." + case .shaders: return "The app’s display shaders could not be loaded. Rebuild the app in Xcode." + case .resources: return "The Mac could not allocate the display resources." + } + } + } + static func library(device: MTLDevice, bundle: Bundle) throws -> MTLLibrary { + guard let url = bundle.url(forResource: "DisplayShader", withExtension: "txt") else { throw Failure.shaders } + return try device.makeLibrary(source: String(contentsOf: url, encoding: .utf8), options: nil) + } + init(device: MTLDevice, library: MTLLibrary) throws { + self.device = device + guard let queue = device.makeCommandQueue() else { throw Failure.resources } + self.queue = queue + let descriptor = MTLRenderPipelineDescriptor() + descriptor.vertexFunction = library.makeFunction(name: "vccVertex") + descriptor.fragmentFunction = library.makeFunction(name: "vccFragment") + guard descriptor.vertexFunction != nil, descriptor.fragmentFunction != nil else { throw Failure.shaders } + descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm + pipeline = try device.makeRenderPipelineState(descriptor: descriptor) + } + func encode(pixels: Data?, target: MTLTexture, drawable: CAMetalDrawable? = nil, activeArea: CGRect = VideoGeometry.fullFrame, inset: CGFloat = VideoGeometry.border, style: DisplayStyle = DisplayStyle()) throws -> MTLCommandBuffer? { + guard inFlight.wait(timeout: .now()) == .success else { return nil } + var submitted = false + defer { if !submitted { inFlight.signal() } } + guard let command = queue.makeCommandBuffer() else { throw Failure.resources } + let pass = MTLRenderPassDescriptor() + pass.colorAttachments[0].texture = target + pass.colorAttachments[0].loadAction = .clear + pass.colorAttachments[0].storeAction = .store + pass.colorAttachments[0].clearColor = VideoGeometry.surround + var source: MTLTexture? + if let pixels, pixels.count == 640 * 480 * 4 { + let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm, + width: 640, height: 480, mipmapped: false) + descriptor.storageMode = device.hasUnifiedMemory ? .shared : .managed; descriptor.usage = .shaderRead + guard let texture = device.makeTexture(descriptor: descriptor) else { throw Failure.resources } + pixels.withUnsafeBytes { data in + texture.replace(region: MTLRegionMake2D(0, 0, 640, 480), mipmapLevel: 0, + withBytes: data.baseAddress!, bytesPerRow: 640 * 4) + } + source = texture + } + guard let encoder = command.makeRenderCommandEncoder(descriptor: pass) else { throw Failure.resources } + if let source, CGFloat(target.width) > 2*inset, CGFloat(target.height) > 2*inset { + let crop = VideoGeometry.validated(activeArea) + let r = VideoGeometry.picture(in:CGSize(width:target.width,height:target.height),source:crop,inset:inset,scaling:style.scaling) + encoder.setViewport(MTLViewport(originX:Double(r.minX),originY:Double(r.minY),width:Double(r.width),height:Double(r.height),znear:0,zfar:1)) + var region = SIMD4(Float(crop.minX/640),Float(crop.minY/480),Float(crop.width/640),Float(crop.height/480)) + encoder.setFragmentBytes(®ion,length:MemoryLayout>.stride,index:0) + // Fade out at small sizes, where scanlines would alias or hide rows. + let strength: Float = style.scanlines ? 0.25 * Float(min(1,max(0,r.height/crop.height-1))) : 0 + var effects = SIMD2(style.scaling == .smooth ? 1 : 0, strength) + encoder.setFragmentBytes(&effects,length:MemoryLayout>.stride,index:1) + encoder.setRenderPipelineState(pipeline) + encoder.setFragmentTexture(source, index: 0) + encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3) + } + encoder.endEncoding() + if let drawable { command.present(drawable) } + let semaphore = inFlight + command.addCompletedHandler { _ in semaphore.signal() } + command.commit(); submitted = true + return command + } +} diff --git a/platforms/macos/App/PrinterOutput.swift b/platforms/macos/App/PrinterOutput.swift new file mode 100644 index 0000000..7d0aa87 --- /dev/null +++ b/platforms/macos/App/PrinterOutput.swift @@ -0,0 +1,276 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit +import Combine +import UniformTypeIdentifiers + +// Text is an interpretation of the captured bytes, never their replacement. +// Classic BASIC can send seven data bits; its stop bit appears as bit 7 in +// the original VCC write-sampled decoder. Raw export always keeps that bit. +enum PrinterText { + static let previewLimit = 65_536 + static func decode(_ data: Data, sevenBit: Bool) -> String { + var result = "" + result.reserveCapacity(data.count) + var carriageReturn = false + for raw in data { + let byte = sevenBit ? raw & 0x7f : raw + if byte == 10 && carriageReturn { carriageReturn = false; continue } + carriageReturn = byte == 13 + switch byte { + case 13, 10: result.append("\n") + case 9: result.append("\t") + case 32...126: result.append(Character(UnicodeScalar(byte))) + case 12: result.append("\n⟨FF⟩\n") + case 27: result.append("⟨ESC⟩") + default: result.append(String(format: "⟨%02X⟩", Int(byte))) + } + } + return result + } + static func export(_ bytes: Data, raw: Bool, sevenBit: Bool) -> Data { + raw ? bytes : Data(decode(bytes, sevenBit: sevenBit).utf8) + } +} + +@MainActor +final class PrinterModel: ObservableObject { + @Published private(set) var enabled = false + @Published private(set) var byteCount = 0 + @Published private(set) var dropped: UInt64 = 0 + @Published private(set) var preview = "" + @Published private(set) var busy = false + @Published private(set) var saving = false + @Published private(set) var unsaved = false + @Published var sevenBit = true { didSet { updatePreview() } } + @Published var followOutput = true + @Published var error: String? + private let controller: VCCMachineController + private var revision: UInt64 = 0 + private var savedRevision: UInt64 = 0 + private var loadedRevision: UInt64 = .max + private var fetching = false + private var bytes = Data() + var previewIsTruncated: Bool { byteCount > PrinterText.previewLimit } + init(controller: VCCMachineController) { self.controller = controller } + + // Called by the existing machine poll. No per-frame byte copies or view + // invalidation: output is fetched only after its revision actually changes. + func observe(_ snapshot: VCCMachineSnapshot) { + if enabled != snapshot.printerEnabled { enabled = snapshot.printerEnabled } + if byteCount != Int(snapshot.printerByteCount) { byteCount = Int(snapshot.printerByteCount) } + if dropped != snapshot.printerDroppedBytes { dropped = snapshot.printerDroppedBytes } + revision = snapshot.printerRevision + let dirty = byteCount > 0 && revision != savedRevision + if unsaved != dirty { unsaved = dirty } + refreshIfNeeded() + } + private func refreshIfNeeded() { + guard !fetching, loadedRevision != revision else { return } + fetching = true + controller.printerOutput { [weak self] output, snapshot in + MainActor.assumeIsolated { + guard let self else { return } + self.fetching = false + self.bytes = output.bytes; self.loadedRevision = output.revision + self.updatePreview(); self.observe(snapshot) + } + } + } + private func updatePreview() { + let text = PrinterText.decode(Data(bytes.suffix(PrinterText.previewLimit)), sevenBit: sevenBit) + if preview != text { preview = text } + } + func setCapture(_ value: Bool) { + guard !busy else { return } + busy = true; error = nil + controller.setPrinterEnabled(value) { [weak self] snapshot in + MainActor.assumeIsolated { + self?.observe(snapshot); self?.busy = false; self?.error = snapshot.errorMessage + } + } + } + func clear() { + guard !busy, !saving else { return } + let alert = NSAlert() + alert.messageText = "Clear printer output?" + alert.informativeText = "This removes the captured output from this session. Save Text or Export Raw Bytes first to keep it. Capture will stop; the CoCo keeps running." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Clear Output") + guard alert.runModal() == .alertSecondButtonReturn else { return } + busy = true; error = nil + // Both commands are queued in order, so a guest write cannot refill the + // cleared capture between the clear acknowledgement and the next poll. + controller.setPrinterEnabled(false) { _ in } + controller.clearPrinterOutput { [weak self] snapshot in + MainActor.assumeIsolated { + guard let self else { return } + self.savedRevision = snapshot.printerRevision + self.observe(snapshot); self.busy = false; self.error = snapshot.errorMessage + } + } + } + private func capture(_ completion: @escaping (VCCPrinterOutput) -> Void) { + controller.printerOutput { [weak self] output, snapshot in + MainActor.assumeIsolated { self?.observe(snapshot); completion(output) } + } + } + func copy() { + let sevenBit = sevenBit + capture { output in + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(PrinterText.decode(output.bytes, sevenBit: sevenBit), forType: .string) + } + } + func save(raw: Bool) { + guard !saving else { return } + saving = true; error = nil + let sevenBit = sevenBit + capture { [weak self] output in + guard let self else { return } + let data = PrinterText.export(output.bytes, raw: raw, sevenBit: sevenBit) + let panel = NSSavePanel() + panel.title = raw ? "Export Raw Printer Bytes" : "Save Printer Text" + panel.message = "Saves the output captured when you chose this command. New output continues collecting separately." + panel.nameFieldStringValue = raw ? "CoCo Printer Output.bin" : "CoCo Printer Output.txt" + panel.allowedContentTypes = raw ? [.data] : [.plainText] + panel.canCreateDirectories = true + panel.begin { [weak self] response in + guard let self else { return } + guard response == .OK, let url = panel.url else { self.saving = false; return } + Task { @MainActor in + defer { self.saving = false } + do { + try await Task.detached(priority: .userInitiated) { try data.write(to: url, options: .atomic) }.value + self.savedRevision = output.revision + self.unsaved = self.byteCount > 0 && self.revision != self.savedRevision + } catch { self.error = "Could not save printer output: \(error.localizedDescription)" } + } + } + } + } + func printOutput() { + let window = NSApp.keyWindow + let sevenBit = sevenBit + capture { output in + let info = NSPrintInfo.shared.copy() as! NSPrintInfo + info.topMargin = 36; info.bottomMargin = 36; info.leftMargin = 36; info.rightMargin = 36 + info.horizontalPagination = .fit; info.verticalPagination = .automatic + info.isVerticallyCentered = false + let width = max(100, info.paperSize.width - info.leftMargin - info.rightMargin) + let text = NSTextView(frame: NSRect(x: 0, y: 0, width: width, height: 1)) + text.isVerticallyResizable = true + text.textContainer?.containerSize = NSSize(width: width, height: .greatestFiniteMagnitude) + text.textContainer?.widthTracksTextView = true + text.font = .monospacedSystemFont(ofSize: 10, weight: .regular) + text.textColor = .black; text.backgroundColor = .white + text.string = PrinterText.decode(output.bytes, sevenBit: sevenBit) + if let container = text.textContainer, let layout = text.layoutManager { + layout.ensureLayout(for: container) + text.setFrameSize(NSSize(width: width, height: max(1, layout.usedRect(for: container).height + 12))) + } + let operation = NSPrintOperation(view: text, printInfo: info) + operation.jobTitle = "CoCo Printer Output" + if let window { operation.runModal(for: window, delegate: nil, didRun: nil, contextInfo: nil) } + else { operation.run() } + } + } +} + +struct PrinterOutputView: View { + @ObservedObject var printer: PrinterModel + var body: some View { + VStack(spacing: 0) { + SecondaryHeader(title: "Tandy Thermal Printer TP-10", badge: "printer", + subtitle: "Printer output from the CoCo’s serial port").padding(20) + Divider() + HStack(spacing: 12) { + Button { printer.setCapture(!printer.enabled) } label: { + Label(printer.enabled ? "Stop Capture" : "Start Capture", systemImage: printer.enabled ? "stop.fill" : "record.circle") + }.disabled(printer.busy).accessibilityIdentifier("printer-capture") + Spacer() + SecondaryAction(title: "Copy", systemImage: "doc.on.doc", action: printer.copy) + SecondaryAction(title: "Save Text…", systemImage: "square.and.arrow.up") { printer.save(raw: false) } + .disabled(printer.saving).accessibilityIdentifier("printer-save-text") + SecondaryAction(title: "Print…", systemImage: "printer", action: printer.printOutput) + .accessibilityIdentifier("printer-print") + }.padding(16) + PrinterTextView(text: printer.preview, follow: printer.followOutput) + .overlay(alignment: .topLeading) { + if printer.byteCount == 0 { + VStack(alignment: .leading, spacing: 8) { + Text(printer.enabled ? "Waiting for printer output…" : "Ready to capture printer output").font(.headline) + Text("Start Capture, then use PRINT #-2, \"HELLO WORLD\" or LLIST in CoCo BASIC.") + .font(.callout).foregroundStyle(.secondary) + }.padding(20).allowsHitTesting(false) + } + } + .padding(.horizontal, 16) + HStack { + Label(printer.enabled ? "Capturing" : "Capture stopped", systemImage: printer.enabled ? "record.circle" : "stop.circle") + Text("\(printer.byteCount.formatted()) bytes\(printer.unsaved ? " · Not saved" : "")") + .accessibilityIdentifier("printer-output-status") + Spacer() + Toggle("Follow Output", isOn: $printer.followOutput) + }.font(.caption).padding(.horizontal, 16).padding(.vertical, 10) + if printer.previewIsTruncated { + Text("Showing the latest 64 KiB. Copy, Save and Print include all captured output.") + .font(.caption).foregroundStyle(.secondary).padding(.horizontal, 16) + } + if printer.dropped > 0 { + Label("Capture is full (1 MiB). \(printer.dropped.formatted()) additional bytes were not retained. Stop, save and clear to start a new capture.", systemImage: "exclamationmark.triangle") + .font(.callout).foregroundStyle(.orange).padding(.horizontal, 16) + } + if let error = printer.error { Text(error).foregroundStyle(.red).textSelection(.enabled).padding(.horizontal, 16) } + Divider() + HStack { + Toggle("7-bit BASIC Text", isOn: $printer.sevenBit) + .help("Ignore the high bit for text only. Raw export always preserves every captured byte.") + Spacer() + SecondaryAction(title: "Export Raw Bytes…", systemImage: "doc.badge.gearshape") { printer.save(raw: true) } + .disabled(printer.saving).accessibilityIdentifier("printer-save-raw") + SecondaryAction(title: "Clear…", systemImage: "trash", action: printer.clear) + .disabled(printer.busy || printer.saving || printer.byteCount == 0).accessibilityIdentifier("printer-clear") + }.padding(16) + SecondaryHelp(title: "Using printer output") { + Text("Start capture before printing. Closing this window keeps capture and output; quitting requires saving or discarding unsaved output. Clear stops capture without restarting the CoCo.") + Text("Text converts carriage returns to new lines. Control codes appear as ⟨ESC⟩, ⟨FF⟩ or hexadecimal markers. This is a text capture, not TP-10 graphics emulation. Raw export is unchanged.") + Text("The serial output shares a PIA register with other CoCo hardware. Capture only while printing; other software can generate unrelated data. For DriveWire TCP connections, use the FD-502 Becker port in Machine Settings.") + }.padding(.horizontal, 20).padding(.bottom, 16) + }.frame(minWidth: 720, minHeight: 540) + } +} + +// An existing selection and scroll position survive every live refresh. The +// native read-only text view provides keyboard selection, Copy and VoiceOver. +private struct PrinterTextView: NSViewRepresentable { + let text: String + let follow: Bool + func makeNSView(context: Context) -> NSScrollView { + let scroll = NSScrollView() + scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = true + scroll.borderType = .bezelBorder + let view = NSTextView(frame: scroll.contentView.bounds) + view.isEditable = false; view.isSelectable = true + view.font = .monospacedSystemFont(ofSize: 13, weight: .regular) + view.textContainerInset = NSSize(width: 12, height: 12) + view.isVerticallyResizable = true; view.isHorizontallyResizable = true + view.autoresizingMask = [.width] + view.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) + view.textContainer?.containerSize = view.maxSize + view.textContainer?.widthTracksTextView = false + view.setAccessibilityLabel("Captured printer output") + view.setAccessibilityIdentifier("printer-text") + scroll.documentView = view + return scroll + } + func updateNSView(_ scroll: NSScrollView, context: Context) { + guard let view = scroll.documentView as? NSTextView, view.string != text else { return } + let range = view.selectedRange(), origin = scroll.contentView.bounds.origin + view.string = text + let length = (text as NSString).length + let start = min(range.location, length) + view.setSelectedRange(NSRange(location: start, length: min(range.length, length - start))) + if follow { view.scrollRangeToVisible(NSRange(location: length, length: 0)) } + else { scroll.contentView.scroll(to: origin); scroll.reflectScrolledClipView(scroll.contentView) } + } +} diff --git a/platforms/macos/App/ProfileControlsView.swift b/platforms/macos/App/ProfileControlsView.swift new file mode 100644 index 0000000..26e1dc8 --- /dev/null +++ b/platforms/macos/App/ProfileControlsView.swift @@ -0,0 +1,350 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit +import UniformTypeIdentifiers + +struct ProfileControlsView: View { + private static let profileType = UTType(exportedAs: "com.brianholman.vccplus.mac.configuration-profile", conformingTo: .json) + private static let legacyProfileType = UTType(importedAs: "org.vcc.mac.configuration-profile", conformingTo: .json) + @ObservedObject var machine: MachineModel + @StateObject private var library: ProfileLibrary + init(machine: MachineModel, store: ProfileStore = .standard) { + self.machine = machine + _library = StateObject(wrappedValue: ProfileLibrary(store: store)) + } + @State private var selection: String? = SystemProfile.diskBasic.id + @State private var working = false + private var selected: ConfigurationProfile? { library.profiles.first { $0.id.uuidString == selection } } + private var selectedSystem: SystemProfile? { SystemProfile.allCases.first { $0.id == selection } } + private var unavailable: Bool { working || machine.busy || machine.state == .closed } + var body: some View { + VStack(alignment: .leading, spacing: 0) { + VStack(alignment: .leading, spacing: 14) { + SecondaryHeader(title: "Configuration Profiles", symbol: "square.grid.2x2", subtitle: "Named setups and file locations — not saved machine snapshots.") + HStack { + Button(action: saveCurrent) { Label("Save Current As…", systemImage: "doc.badge.plus") } + Button(action: importProfile) { Label("Import…", systemImage: "folder") } + Spacer() + Button(action: library.reload) { Label("Refresh", systemImage: "arrow.clockwise") } + }.disabled(unavailable) + }.padding(20) + Divider() + HSplitView { + List(selection: $selection) { + Section("System Profiles") { + ForEach(SystemProfile.allCases) { profile in + Label(profile.name, systemImage: "lock.fill").tag(profile.id) + .accessibilityIdentifier(profile.id) + } + } + Section("My Profiles") { + ForEach(library.profiles) { profile in + Label(profile.name, systemImage: "doc.text").tag(profile.id.uuidString) + } + } + }.listStyle(.sidebar).frame(minWidth: 175, idealWidth: 220, maxWidth: 280) + ScrollView { + VStack(alignment: .leading, spacing: 16) { + if let kind = selectedSystem { systemDetails(kind) } + else if let profile = selected { personalDetails(profile) } + else { + Label("Select a profile", systemImage: "square.grid.2x2").font(.title2) + Text(library.profiles.isEmpty ? "Save your current setup to create the first personal profile." : "Select a profile to review its setup and files.") + .foregroundStyle(.secondary) + } + }.frame(maxWidth: .infinity, alignment: .leading).padding(20) + }.frame(minWidth: 380) + }.frame(minHeight: 260).disabled(unavailable) + Divider() + VStack(alignment: .leading, spacing: 10) { + if let error = library.error ?? machine.profileError { + ScrollView { + Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.red).textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + }.frame(maxHeight: 100) + } + HStack(spacing: 12) { + if working || machine.busy { ProgressView().controlSize(.small) } + if let name = machine.profileName { + Text("Last loaded: \(name)").font(.caption).foregroundStyle(.secondary) + .lineLimit(1).truncationMode(.middle) + .help("Later changes do not update the saved profile automatically.") + } else { + Text(selectedSystem != nil ? "System profiles are read-only." : "Load replaces the current setup and clears RAM.") + .font(.caption).foregroundStyle(.secondary) + } + Spacer() + if selected != nil { personalActions.disabled(unavailable) } + Button(action: loadSelected) { Label("Load…", systemImage: "arrow.clockwise") } + .keyboardShortcut(.defaultAction) + .disabled(unavailable || (selected == nil && selectedSystem == nil) || + selectedSystem.map { machine.systemProfileUnavailableReason($0) != nil } == true) + } + }.padding(16) + }.frame(minWidth: 740, minHeight: 540) + } + @ViewBuilder private var personalActions: some View { + if let profile = selected { + ProfileActionsMenu(profileID: profile.id, update: updateSelected, rename: renameSelected, + export: exportSelected, delete: deleteSelected).equatable() + } + } + private func systemDetails(_ kind: SystemProfile) -> some View { + VStack(alignment: .leading, spacing: 16) { + VStack(alignment: .leading, spacing: 6) { + Label(kind.name, systemImage: "lock.fill").font(.title2.bold()) + Text(kind.summary).foregroundStyle(.secondary) + } + SecondaryCard { + VStack(alignment: .leading, spacing: 10) { + Label("Setup", systemImage: "cpu").font(.headline) + Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 6) { + summaryRow("Hardware", "Motorola 6809 · 512 KB") + summaryRow("Video", "Composite TV") + summaryRow("Startup", kind == .cocoSDC ? "Slot 4 · SDC-DOS" : kind == .diskBasic ? "Slot 4 · Disk BASIC" : "Slot 4 · RGBDOS") + Divider().gridCellColumns(2).gridCellUnsizedAxes(.horizontal).padding(.vertical, 4) + if kind == .cocoSDC { + summaryRow("SD card", "Local writable folder · CoCo SDC") + summaryRow("SDC0", "HELLO.DSK · mounted at startup") + } else { summaryRow("FD0", "Hello World floppy") } + if kind == .hardDriveBasic || kind == .nitros9 { + summaryRow("HD0", kind == .nitros9 ? "NitrOS-9 system disk" : "Hello World hard disk") + } + if kind == .nitros9 { summaryRow("HD1", "Shared Hard Drive BASIC disk") } + if kind == .diskBasic { summaryRow("Cassette", "Hello World · stopped") } + } + SecondaryHelp(title: "Setup details") { Text(kind.explanation) } + } + } + VStack(alignment: .leading, spacing: 6) { + Label(kind == .nitros9 ? "Load restarts and automatically boots NitrOS-9." : "Load restarts BASIC with an empty program. Examples do not run automatically.", systemImage: "arrow.clockwise") + .font(.callout).fixedSize(horizontal: false, vertical: true) + Text(kind == .nitros9 ? "Existing data is kept. An empty shared OS-9 area is initialized with a backup." : kind == .diskBasic ? "Your writable media is preserved. This is the same setup as Restore App Defaults." : "Your writable media is preserved.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + if let reason = machine.systemProfileUnavailableReason(kind) { + Label(reason, systemImage: "exclamationmark.triangle").foregroundStyle(.orange) + .fixedSize(horizontal: false, vertical: true) + } + SecondaryCard { + VStack(alignment: .leading, spacing: 10) { + Label("Make it yours", systemImage: "doc.on.doc").font(.headline) + ViewThatFits(in: .horizontal) { + HStack(alignment: .top, spacing: 16) { + copyChoice(kind, freshMedia: false).frame(width: 180, alignment: .leading) + copyChoice(kind, freshMedia: true).frame(width: 230, alignment: .leading) + } + VStack(alignment: .leading, spacing: 12) { + copyChoice(kind, freshMedia: false) + copyChoice(kind, freshMedia: true) + } + } + Text("Both create an editable personal profile. Existing files and the current session stay unchanged; load the new profile when ready.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + } + SecondaryHelp(title: kind == .nitros9 ? "Using NitrOS-9" : "Try the examples") { + if kind == .nitros9 { Nitros9UsageGuide() } + else if kind == .cocoSDC { SDCUsageGuide() } + else { Text(kind.instructions).textSelection(.enabled) } + } + } + } + private func summaryRow(_ title: String, _ value: String) -> some View { + GridRow(alignment: .firstTextBaseline) { + Text(title).foregroundStyle(.secondary) + Text(value).fixedSize(horizontal: false, vertical: true) + } + } + private func copyChoice(_ kind: SystemProfile, freshMedia: Bool) -> some View { + VStack(alignment: .leading, spacing: 4) { + Button { copySystem(kind, freshMedia: freshMedia) } label: { + Label(freshMedia ? "Create Fresh Starter Media…" : "Save as My Profile…", + systemImage: freshMedia ? "doc.badge.plus" : "doc.on.doc") + }.fixedSize().accessibilityIdentifier(freshMedia ? "fresh-system-media" : "copy-system-profile") + .disabled(machine.systemProfileUnavailableReason(kind) != nil) + Text(freshMedia ? "New, clean media copies." : "The same working media files.") + .font(.caption).foregroundStyle(.secondary) + } + } + private func personalDetails(_ profile: ConfigurationProfile) -> some View { + VStack(alignment: .leading, spacing: 16) { + VStack(alignment: .leading, spacing: 6) { + Label(profile.name, systemImage: "doc.text").font(.title2.bold()) + Text(ProfileGuidance(profile).title).foregroundStyle(.secondary) + } + SecondaryCard { + Label("Setup", systemImage: "cpu").font(.headline) + Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 6) { + summaryRow("Processor", profile.machine.use6309 ? "Hitachi 6309" : "Motorola 6809") + summaryRow("Memory", MachineSettings.memoryLabels[profile.machine.ram]) + summaryRow("CPU overclock", "\(profile.machine.overclock)×") + summaryRow("Pacing", profile.machine.fastForward ? "Fast-forward · playback silenced" : "Normal") + summaryRow("Cartridges", profile.media.cartridges?.multiPak == true ? "Multi-Pak" : "Single cartridge") + } + Text(ProfileGuidance(profile).coverage).font(.caption).foregroundStyle(.secondary) + } + if profile.systemROM == nil { + Label("No system ROM assigned. Choose one after loading this setup.", systemImage: "exclamationmark.triangle") + .foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true) + } + if profile.bootNitros9 == true { + Label("After Run, this profile automatically boots NitrOS-9 with DOS 255. Cold Restart opens the archive menu; select 6 (EXIT TO BASIC) and press Return.", systemImage: "info.circle") + .font(.callout).fixedSize(horizontal: false, vertical: true) + } + SecondaryCard { + Label("Files", systemImage: "folder").font(.headline) + if profile.references.isEmpty { Text("No files assigned.").foregroundStyle(.secondary) } + ForEach(profile.references, id: \.key) { reference in + HStack(alignment: .top, spacing: 12) { + VStack(alignment: .leading, spacing: 3) { + Text(reference.key.label).font(.caption).foregroundStyle(.secondary) + Text(reference.url.lastPathComponent).lineLimit(1).truncationMode(.middle) + Text(reference.url.path).font(.caption).foregroundStyle(.secondary) + .lineLimit(1).truncationMode(.middle).textSelection(.enabled).help(reference.url.path) + }.frame(maxWidth: .infinity, alignment: .leading) + Button { replace(reference.key, in: profile) } label: { Label("Replace…", systemImage: "folder") } + .accessibilityLabel("Replace \(reference.key.label)") + } + } + Text("Replace updates this saved profile's file location. Load the profile to apply it; files are not copied.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + SecondaryHelp(title: "About this configuration") { + Text(ProfileGuidance(profile).explanation).fixedSize(horizontal: false, vertical: true) + Text("Later changes do not update the saved profile automatically. Use Actions → Update from Current to replace its saved setup.") + } + } + } + private func namePrompt(_ title: String, initial: String) -> String? { + let alert = NSAlert(); alert.messageText = title + let field = NSTextField(string: initial); field.frame = NSRect(x: 0, y: 0, width: 320, height: 24) + field.setAccessibilityIdentifier("profile-name") + alert.accessoryView = field; alert.addButton(withTitle: "Save"); alert.addButton(withTitle: "Cancel") + alert.window.initialFirstResponder = field + guard alert.runModal() == .alertFirstButtonReturn else { return nil } + return field.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) + } + private func confirm(_ title: String, detail: String, action: String) -> Bool { + let alert = NSAlert(); alert.messageText = title; alert.informativeText = detail + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: action) + return alert.runModal() == .alertSecondButtonReturn + } + private func saveCurrent() { + guard let name = namePrompt("Save Current Setup as Profile", initial: "") else { return } + capture(name: name, id: nil) + } + private func capture(name: String, id: UUID?) { + working = true + Task { @MainActor in + defer { working = false } + do { + let profile = try await machine.captureProfile(name: name, replacing: id) + if library.save(profile) { selection = profile.id.uuidString } + } catch { library.error = error.localizedDescription } + } + } + private func copySystem(_ kind: SystemProfile, freshMedia: Bool) { + guard let name = namePrompt(freshMedia ? "Name Setup with Fresh Starter Media" : "Save System Setup as My Profile", + initial: "My " + kind.name), !name.isEmpty else { return } + do { try ConfigurationProfile(name: name).validate() } + catch { library.error = error.localizedDescription; return } + // Check names before allocating a fresh hard disk. Never overwrite a profile. + guard !library.profiles.contains(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame }) else { + library.error = "A profile with that name already exists. Choose another name."; return + } + working = true; library.error = nil + Task { @MainActor in + defer { working = false } + do { + var profile = try await machine.makeSystemProfile(kind, freshMedia: freshMedia) + profile.name = name + if library.save(profile) { selection = profile.id.uuidString } + } catch { library.error = error.localizedDescription } + } + } + private func loadSelected() { + if let kind = selectedSystem { + guard confirm("Load “\(kind.name)â€�?", detail: (kind == .nitros9 ? "This restarts and boots NitrOS-9. Empty OS-9 space on the shared data disk is initialized with a backup. " : "This restarts BASIC with the system setup. ") + " Current RAM and RAM disk contents are cleared. Writable disks are saved first; unsaved temporary disks or recordings block the switch. Existing starter media is reused, never erased. Neither example loads or runs automatically.", action: "Load Profile") else { return } + library.error = nil; working = true + Task { @MainActor in _ = await machine.loadSystemProfile(kind); working = false } + return + } + guard let profile = selected, + confirm("Load “\(profile.name)â€�?", detail: "This clears the current machine's RAM and RAM disk contents and replaces its setup and media. Writable disk changes will be saved first; unsaved temporary images or recordings block the switch. The new machine starts paused. Profiles are not saved-game snapshots." + (profile.bootNitros9 == true ? " Pressing Run will automatically boot NitrOS-9." : ""), action: "Load Profile") else { return } + library.error = nil; working = true + Task { @MainActor in await machine.loadProfile(profile); working = false } + } + private func updateSelected() { + guard let profile = selected, + confirm("Update “\(profile.name)â€� from the current setup?", detail: "This replaces the saved configuration and file assignments. It does not copy media contents or alter their files.", action: "Update Profile") else { return } + capture(name: profile.name, id: profile.id) + } + private func renameSelected() { + guard var profile = selected, let name = namePrompt("Rename Profile", initial: profile.name) else { return } + profile.name = name; library.save(profile) + } + private func deleteSelected() { + guard let profile = selected, + confirm("Delete “\(profile.name)â€� from Profiles?", detail: "Its ROMs and media files are kept. The current machine is unchanged.", action: "Delete Profile") else { return } + library.delete(profile.id); if library.error == nil { selection = nil } + } + private func replace(_ reference: ConfigurationProfile.Reference, in original: ConfigurationProfile) { + let panel = NSOpenPanel(); panel.title = "Replace \(reference.label)" + if case .sdcFolder = reference { panel.canChooseDirectories = true; panel.canChooseFiles = false } + else { panel.canChooseDirectories = false; panel.canChooseFiles = true } + panel.allowsMultipleSelection = false + panel.begin { result in + guard result == .OK, let url = panel.url else { return } + var profile = original; profile.replace(reference, with: url); library.save(profile) + } + } + private func importProfile() { + let panel = NSOpenPanel(); panel.title = "Import Configuration Profile" + panel.allowedContentTypes = [Self.profileType, Self.legacyProfileType, .json] + panel.canChooseDirectories = false; panel.allowsMultipleSelection = false + panel.begin { result in + guard result == .OK, let url = panel.url else { return } + do { + var profile = try ProfileStore.read(url); profile.id = UUID() + guard let name = namePrompt("Name Imported Profile", initial: profile.name) else { return } + profile.name = name + if library.save(profile) { selection = profile.id.uuidString } + } catch { library.error = error.localizedDescription } + } + } + private func exportSelected() { + guard let profile = selected else { return } + let panel = NSSavePanel(); panel.title = "Export Configuration Profile" + panel.allowedContentTypes = [Self.profileType] + panel.nameFieldStringValue = profile.name.replacingOccurrences(of: "/", with: "-") + ".vccprofile" + panel.message = "The file includes local file paths and controller identifiers, but no ROM or media contents." + panel.begin { result in + guard result == .OK, let url = panel.url else { return } + do { try ProfileStore.write(profile, to: url); library.error = nil } + catch { library.error = error.localizedDescription } + } + } +} + + +// Frame/status updates must not replace an open menu. The selected profile is +// its identity; commands still read the authoritative library and machine state. +private struct ProfileActionsMenu: View, Equatable { + let profileID: UUID + let update: () -> Void + let rename: () -> Void + let export: () -> Void + let delete: () -> Void + static func == (lhs: Self, rhs: Self) -> Bool { lhs.profileID == rhs.profileID } + var body: some View { + Menu { + Button(action: update) { Label("Update from Current…", systemImage: "arrow.triangle.2.circlepath") } + Button(action: rename) { Label("Rename…", systemImage: "pencil") } + Button(action: export) { Label("Export…", systemImage: "square.and.arrow.up") } + Divider() + Button(role: .destructive, action: delete) { Label("Delete…", systemImage: "trash") } + } label: { Label("Actions", systemImage: "ellipsis.circle") } + .fixedSize().accessibilityIdentifier("profile-actions") + } +} diff --git a/platforms/macos/App/ROMImage.swift b/platforms/macos/App/ROMImage.swift new file mode 100644 index 0000000..9fc23b0 --- /dev/null +++ b/platforms/macos/App/ROMImage.swift @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +enum ROMImage { + enum Failure: LocalizedError { + case notFile, size, resetVector + var errorDescription: String? { + switch self { + case .notFile: return "Choose a regular CoCo 3 ROM file." + case .size: return "Choose a 32 KiB CoCo 3 system ROM. This file has a different size." + case .resetVector: return "This file does not have a valid CoCo 3 ROM reset address." + } + } + } + static func validate(_ bytes: Data) throws { + guard bytes.count == 32768 else { throw Failure.size } + let start = Int(bytes[bytes.startIndex + 32766]) * 256 + Int(bytes[bytes.startIndex + 32767]) + guard (0x8000...0xfeff).contains(start) else { throw Failure.resetVector } + } + static func read(_ url: URL) throws -> Data { + guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw Failure.notFile } + let file = try FileHandle(forReadingFrom: url) + defer { try? file.close() } + // Read at most the allowed size plus one byte, even for huge input files. + let bytes = try file.read(upToCount: 32769) ?? Data() + try validate(bytes) + return bytes + } +} diff --git a/platforms/macos/App/RecentMedia.swift b/platforms/macos/App/RecentMedia.swift new file mode 100644 index 0000000..fc21eee --- /dev/null +++ b/platforms/macos/App/RecentMedia.swift @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import Combine + +enum MediaDestination: Codable, Hashable, Sendable { + case systemROM, diskROM, binary, cassette, floppy(Int), hardDisk(Int), cartridge(Int) + var label: String { + switch self { + case .systemROM: return "CoCo 3 system ROM" + case .diskROM: return "Floppy controller ROM" + case .binary: return "Run binary program" + case .cassette: return "Cassette" + case .floppy(let n): return "Floppy FD\(n)" + case .hardDisk(let n): return "Hard disk HD\(n)" + case .cartridge(let n): return n == 0 ? "Direct cartridge" : "Multi-Pak slot \(n)" + } + } + var valid: Bool { + switch self { + case .floppy(let n): return (0..<4).contains(n) + case .hardDisk(let n): return (0..<2).contains(n) + case .cartridge(let n): return (0..<5).contains(n) + default: return true + } + } + static func choices(for url: URL) -> [Self] { + switch url.pathExtension.lowercased() { + case "vhd", "img": return (0..<2).map(Self.hardDisk) + case "os9": return (0..<4).map(Self.floppy) + (0..<2).map(Self.hardDisk) + case let ext where DiskFiles.extensions.contains(ext): return (0..<4).map(Self.floppy) + case "cas", "wav": return [.cassette] + case "ccc", "pak": return (0..<5).map(Self.cartridge) + case "rom": return [.systemROM, .diskROM] + (0..<5).map(Self.cartridge) + case "bin": return [.binary] + (0..<5).map(Self.cartridge) + default: return [] + } + } +} + +@MainActor +final class RecentMedia: ObservableObject { + struct Entry: Codable, Equatable, Identifiable { + var url: URL + var destination: MediaDestination + var id: String { url.absoluteString + "|" + destination.label } + var label: String { url.lastPathComponent + " — " + destination.label } + } + static func isLocalFile(_ url: URL) -> Bool { + url.isFileURL && (url.host == nil || url.host == "" || url.host == "localhost") && url.path.hasPrefix("/") + } + static let key = "RecentMedia.v1" + @Published private(set) var entries: [Entry] = [] + private let defaults: UserDefaults + init(defaults: UserDefaults) { + self.defaults = defaults + if let data = defaults.data(forKey: Self.key), data.count < 262144, + let saved = try? JSONDecoder().decode([Entry].self, from: data) { + var seen = Set() + entries = saved.filter { Self.isLocalFile($0.url) && $0.destination.valid && seen.insert($0.id).inserted }.prefix(12).map { $0 } + } + } + func record(_ url: URL, as destination: MediaDestination) { + guard Self.isLocalFile(url), destination.valid else { return } + let entry = Entry(url: url.standardizedFileURL, destination: destination) + entries.removeAll { $0.id == entry.id }; entries.insert(entry, at: 0) + entries = Array(entries.prefix(12)); save() + } + func clear() { entries = []; defaults.removeObject(forKey: Self.key) } + private func save() { if let data = try? JSONEncoder().encode(entries) { defaults.set(data, forKey: Self.key) } } +} diff --git a/platforms/macos/App/ReleaseHistoryView.swift b/platforms/macos/App/ReleaseHistoryView.swift new file mode 100644 index 0000000..d6f359c --- /dev/null +++ b/platforms/macos/App/ReleaseHistoryView.swift @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI + +struct ReleaseHistoryView: View { + private let paragraphs: [String] = { + guard let url = Bundle.main.url(forResource: "RELEASES", withExtension: "md"), + let source = try? String(contentsOf: url, encoding: .utf8) else { return [] } + return source.components(separatedBy: "\n\n") + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + }() + + var body: some View { + Group { + if paragraphs.isEmpty { + ContentUnavailableView("Release history unavailable", systemImage: "doc.text", + description: Text("The release history is missing from this app. Rebuild or reinstall the complete application.")) + } else { + ScrollView { + VStack(alignment: .leading, spacing: 16) { + ForEach(Array(paragraphs.enumerated()), id: \.offset) { _, paragraph in + if paragraph.hasPrefix("# ") { + Text(String(paragraph.dropFirst(2))) + .font(.largeTitle.bold()) + .accessibilityAddTraits(.isHeader) + } else if paragraph.hasPrefix("## ") { + Text(String(paragraph.dropFirst(3))) + .font(.title2.weight(.semibold)) + .padding(.top, 12) + .accessibilityAddTraits(.isHeader) + } else { + Text((try? AttributedString(markdown: paragraph.replacingOccurrences(of: "\n", with: " "))) ?? AttributedString(paragraph)) + .lineSpacing(4) + } + } + } + .textSelection(.enabled) + .frame(maxWidth: 700, alignment: .leading) + .padding(24) + .frame(maxWidth: .infinity, alignment: .top) + } + .accessibilityLabel("VCC Plus release history") + .accessibilityIdentifier("release-history") + } + } + .background(Color(nsColor: .windowBackgroundColor)) + .frame(minWidth: 460, minHeight: 360) + } +} diff --git a/platforms/macos/App/SecondaryInterface.swift b/platforms/macos/App/SecondaryInterface.swift new file mode 100644 index 0000000..07fec1a --- /dev/null +++ b/platforms/macos/App/SecondaryInterface.swift @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI + +// Shared presentation only. Commands and live state remain in the existing +// machine/window models; a disclosure never changes emulation configuration. +struct SecondaryHeader: View { + let title: String + var badge: String? = nil + var symbol: String? = nil + var subtitle: String? = nil + var body: some View { + VStack(alignment: .leading, spacing: 8) { + if let badge { + HardwareBadge(name: badge, label: title) + .frame(maxWidth: 370, alignment: .leading).frame(height: 36) + } else if let symbol { + Label(title, systemImage: symbol).font(.title2.weight(.semibold)) + } else { + Text(title).font(.title2.weight(.semibold)) + } + if let subtitle { + Text(subtitle).font(.callout).foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + }.frame(maxWidth: .infinity, alignment: .leading) + } +} + +/// The ruler paints the existing markers. A transparent native button on each +/// visible target supplies its action, hover help and VoiceOver semantics. +class BreakpointRuler: NSRulerView { + typealias Row = (number: Int, rect: NSRect) + private var buttons: [NSButton] = [] + var points: Set = [] { didSet { if oldValue != points { invalidateMarkers() } } } + var active = true { didSet { if oldValue != active { invalidateMarkers() } } } + var onClick: (Int) -> Void = { _ in } + + override init(scrollView: NSScrollView?, orientation: NSRulerView.Orientation) { + super.init(scrollView: scrollView, orientation: orientation) + if let clip = scrollView?.contentView { + clip.postsBoundsChangedNotifications = true + NotificationCenter.default.addObserver(self, selector: #selector(invalidateMarkers), + name: NSView.boundsDidChangeNotification, object: clip) + } + setAccessibilityElement(true) + setAccessibilityRole(.group) + setAccessibilityLabel("Source breakpoints") + } + required init(coder: NSCoder) { fatalError("init(coder:) is not supported") } + @objc func invalidateMarkers() { needsLayout = true; needsDisplay = true } + func visibleRows() -> [Row] { [] } + override func accessibilityChildren() -> [Any]? { buttons } + + static func actionName(_ number: Int, set: Bool) -> String { + "\(set ? "Remove" : "Set") breakpoint on line \(number)" + } + override func layout() { + super.layout() + let rows = visibleRows() + while buttons.count > rows.count { buttons.removeLast().removeFromSuperview() } + for (index, row) in rows.enumerated() { + if index == buttons.count { + let button = NSButton(title: "", target: self, action: #selector(toggleLine(_:))) + button.isTransparent = true + button.refusesFirstResponder = true + addSubview(button) + buttons.append(button) + } + let button = buttons[index] + let name = Self.actionName(row.number, set: points.contains(row.number)) + if button.frame != row.rect { button.frame = row.rect } + if button.toolTip != name { + button.toolTip = name + button.setAccessibilityLabel(name) + button.setAccessibilityIdentifier("breakpoint.gutter.line.\(row.number)") + } + button.tag = row.number + button.isEnabled = active + } + } + @objc private func toggleLine(_ sender: NSButton) { + guard active else { return } + onClick(sender.tag) + } +} + +/// Line numbers align with the editor's actual laid-out lines, including scroll. +final class CLineRuler: BreakpointRuler { + override var isFlipped: Bool { true } + override init(scrollView: NSScrollView?, orientation: NSRulerView.Orientation) { + super.init(scrollView: scrollView, orientation: orientation) + // Keep the native ruler and its breakpoint buttons from painting over the source. + clipsToBounds = true + ruleThickness = 48 + clientView = scrollView?.documentView + } + required init(coder: NSCoder) { fatalError("init(coder:) is not supported") } + + override func visibleRows() -> [Row] { + guard let editor = clientView as? NSTextView, let layout = editor.layoutManager, + let container = editor.textContainer else { return [] } + let text = editor.string as NSString + let origin = editor.textContainerOrigin + // Horizontal scrolling must not change which rows appear in the gutter. + let viewport = NSRect(x: 0, y: editor.visibleRect.minY - origin.y, + width: max(1, editor.bounds.width), height: editor.visibleRect.height) + let visible = layout.glyphRange(forBoundingRect: viewport, in: container) + guard visible.length > 0 else { return [] } + var rows: [Row] = [] + var start = 0 + var number = 1 + layout.enumerateLineFragments(forGlyphRange: visible) { fragment, _, _, range, _ in + let character = layout.characterIndexForGlyph(at: range.location) + number += text.substring(with: NSRange(location: start, length: character - start)).filter { $0 == "\n" || $0 == "\r\n" || $0 == "\r" }.count + start = character + let r = self.convert(fragment.offsetBy(dx: origin.x, dy: origin.y), from: editor) + let hit = NSRect(x: 0, y: r.minY, width: self.bounds.width, height: r.height) + if hit.intersects(self.bounds) { rows.append((number, hit)) } + } + return rows + } + override func drawHashMarksAndLabels(in rect: NSRect) { + NSColor.controlBackgroundColor.setFill(); bounds.fill() + let attributes: [NSAttributedString.Key: Any] = [.font: NSFont.monospacedDigitSystemFont(ofSize: 11, weight: .regular), .foregroundColor: NSColor.secondaryLabelColor] + for (number, row) in visibleRows() { + let label = "\(number)" as NSString + if points.contains(number) { + NSColor.controlAccentColor.setFill() + NSBezierPath(ovalIn: NSRect(x: 3, y: row.minY + 3, width: 8, height: 8)).fill() + } + label.draw(at: NSPoint(x: 42 - label.size(withAttributes: attributes).width, y: row.minY + 1), withAttributes: attributes) + } + } +} diff --git a/platforms/macos/App/SoftwareLibraryArtwork.swift b/platforms/macos/App/SoftwareLibraryArtwork.swift new file mode 100644 index 0000000..4f5d969 --- /dev/null +++ b/platforms/macos/App/SoftwareLibraryArtwork.swift @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import ImageIO +import UniformTypeIdentifiers +import CryptoKit + +/// Shared by the sidebar and both cover presentations. +enum SoftwareLibraryCategoryStyle { + static func symbol(for type: String) -> String { + switch type { + case "Games": return "gamecontroller" + case "Applications": return "macwindow" + case "Blank Media": return "document" + case "Hardware": return "airport.extreme" + case "Operating Systems": return "desktopcomputer.and.arrow.down" + case "Music": return "music.note" + case "Educational": return "graduationcap" + case "Programming": return "curlybraces" + case "Utilities": return "wrench.and.screwdriver" + case "Pictures": return "photo.on.rectangle" + case "Books", "Magazines": return "book" + case "Demos": return "play.rectangle" + default: return "books.vertical" + } + } + + static func tint(for type: String) -> Color { + switch type { + case "Games": return .indigo + case "Applications", "Operating Systems": return .blue + case "Educational": return .teal + case "Music": return .purple + case "Programming", "Utilities": return .orange + default: return .secondary + } + } +} + +/// Only appearance starts a request. Hosted, fingerprinted PNG thumbnails are +/// cached locally; originals and PDF manuals never pass through this loader. +struct SoftwareLibraryArtworkView: View { + @Environment(\.companionLibraryAccess) private var companion + let asset: SoftwareLibraryAsset? + let cacheDirectory: URL + let softwareType: String + @State private var image: CGImage? + @State private var loading = false + + var body: some View { + ZStack { + RoundedRectangle(cornerRadius: 9).fill(.quaternary.opacity(0.35)) + if let image { + Image(decorative: image, scale: 1).resizable().scaledToFit().padding(5) + } else { + VStack(spacing: 12) { + Image(systemName: SoftwareLibraryCategoryStyle.symbol(for: softwareType)) + .font(.system(size: 48, weight: .light)) + .foregroundStyle(SoftwareLibraryCategoryStyle.tint(for: softwareType).opacity(0.7)) + Text(softwareType == "Other" ? "Software" : softwareType) + .font(.caption.weight(.medium)).foregroundStyle(.secondary) + .lineLimit(1).minimumScaleFactor(0.8) + }.padding(16) + if loading { ProgressView().controlSize(.small).frame(maxHeight: .infinity, alignment: .bottom).padding(8) } + } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(image != nil ? "Artwork: " + (asset?.name ?? "") : softwareType + " category cover") + .accessibilityValue(image != nil ? "Loaded" : (loading ? "Loading artwork" : "Category illustration")) + .task(id: asset.map { SoftwareLibraryArtworkCache.cacheKey(for: $0) }) { + image = nil + loading = false + guard let asset else { return } + loading = true + defer { loading = false } + do { + let data: Data + if let companion { + let response = try await companion.libraryRequest(.init(operation: .thumbnail, assetID: asset.id)) + if let message = response.errorMessage { throw CompanionLibraryFailure(message: message) } + guard let received = response.assetData else { throw SoftwareLibraryArtworkCache.Failure.response } + data = received + } else { + data = try await SoftwareLibraryArtworkCache.shared.thumbnail(for: asset, directory: cacheDirectory) + } + try Task.checkCancellation() + image = SoftwareLibraryArtworkCache.image(from: data) + } catch { /* Quiet placeholder: art availability never blocks browsing. */ } + } + } +} + +actor SoftwareLibraryArtworkCache { + static let shared = SoftwareLibraryArtworkCache() + static let maximumSourceBytes = 8 * 1024 * 1024 + static let maximumThumbnailBytes = 2 * 1024 * 1024 + static let maximumPixelSize = 640 + private var active = 0 + private let session: URLSession + + init(session: URLSession? = nil) { + if let session { self.session = session } + else { + let configuration = URLSessionConfiguration.ephemeral + configuration.timeoutIntervalForRequest = 20 + configuration.timeoutIntervalForResource = 45 + configuration.httpMaximumConnectionsPerHost = 4 + configuration.urlCache = nil + self.session = URLSession(configuration: configuration, delegate: LibraryArtworkRedirects(), delegateQueue: nil) + } + } + + enum Failure: Error { case unsupported, oversized, response, fingerprint, invalidImage, invalidCache } + + static func accepts(_ url: URL) -> Bool { + guard url.scheme?.lowercased() == "https", url.host?.lowercased() == "vccplus.brianholman.com", + url.user == nil, url.password == nil, url.port == nil || url.port == 443, + url.path.hasPrefix("/dl/software/CoCoLibrary/Artwork/Thumbnails/"), + url.pathExtension.lowercased() == "png", url.query == nil, url.fragment == nil, + !url.path.contains("\\"), !url.pathComponents.contains(".."), + !url.pathComponents.contains(".") else { return false } + return true + } + + static func canDisplay(_ asset: SoftwareLibraryAsset) -> Bool { + guard let url = asset.thumbnailURL, accepts(url), + let checksum = asset.thumbnailSHA256, checksum.count == 64, + checksum.allSatisfy({ $0.isHexDigit }), + let size = asset.thumbnailByteSize, size > 0, size <= maximumThumbnailBytes else { return false } + return true + } + + static func cacheKey(for asset: SoftwareLibraryAsset) -> String { + let identity = "hosted-thumbnail-v2\n" + (asset.thumbnailURL ?? asset.sourceURL).absoluteString + "\n" + (asset.thumbnailSHA256 ?? "unverified") + return SHA256.hash(data: Data(identity.utf8)).map { String(format: "%02x", $0) }.joined() + } + + static func image(from data: Data) -> CGImage? { + guard data.count <= maximumThumbnailBytes, + let source = CGImageSourceCreateWithData(data as CFData, nil), + let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], + let width = properties[kCGImagePropertyPixelWidth] as? Int, + let height = properties[kCGImagePropertyPixelHeight] as? Int, + width > 0, height > 0, width <= maximumPixelSize, height <= maximumPixelSize else { return nil } + return CGImageSourceCreateImageAtIndex(source, 0, [kCGImageSourceShouldCache: false] as CFDictionary) + } + + static func downsample(_ data: Data, expectedSHA256: String?) throws -> Data { + guard data.count <= maximumSourceBytes else { throw Failure.oversized } + if let expectedSHA256 { + let actual = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + guard actual == expectedSHA256.lowercased() else { throw Failure.fingerprint } + } + guard let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary), + let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: maximumPixelSize, + kCGImageSourceShouldCacheImmediately: false + ] as CFDictionary) else { throw Failure.invalidImage } + let output = NSMutableData() + guard let destination = CGImageDestinationCreateWithData(output, UTType.png.identifier as CFString, 1, nil) else { throw Failure.invalidImage } + CGImageDestinationAddImage(destination, thumbnail, nil) + guard CGImageDestinationFinalize(destination), output.length <= maximumThumbnailBytes else { throw Failure.invalidImage } + return output as Data + } + + func thumbnail(for asset: SoftwareLibraryAsset, directory: URL) async throws -> Data { + try Task.checkCancellation() + guard Self.canDisplay(asset), let url = asset.thumbnailURL, + let fingerprint = asset.thumbnailSHA256 else { throw Failure.unsupported } + guard directory.isFileURL else { throw Failure.invalidCache } + let path = directory.appendingPathComponent(Self.cacheKey(for: asset) + ".png") + if let cached = cachedThumbnail(path, expectedSHA256: fingerprint) { return cached } + while active >= 4 { + try await Task.sleep(nanoseconds: 50_000_000) + } + try Task.checkCancellation() + // Another visible cell may have populated this shared cache while waiting. + if let cached = cachedThumbnail(path, expectedSHA256: fingerprint) { return cached } + active += 1 + defer { active -= 1 } + var request = URLRequest(url: url) + request.setValue("VCCPlus/SoftwareLibrary-Artwork", forHTTPHeaderField: "User-Agent") + let (bytes, response) = try await session.bytes(for: request) + guard let http = response as? HTTPURLResponse, http.statusCode == 200, + let finalURL = http.url, Self.accepts(finalURL) else { throw Failure.response } + guard http.expectedContentLength <= Self.maximumThumbnailBytes else { throw Failure.oversized } + var data = Data() + data.reserveCapacity(min(max(Int(http.expectedContentLength), 0), Self.maximumThumbnailBytes)) + for try await byte in bytes { + guard data.count < Self.maximumThumbnailBytes else { throw Failure.oversized } + data.append(byte) + if data.count.isMultiple(of: 4096) { try Task.checkCancellation() } + } + try Task.checkCancellation() + guard Int64(data.count) == asset.thumbnailByteSize, + SHA256.hash(data: data).map({ String(format: "%02x", $0) }).joined() == fingerprint.lowercased() + else { throw Failure.fingerprint } + guard Self.image(from: data) != nil else { throw Failure.invalidImage } + let thumbnail = data + try Task.checkCancellation() + // A missing/unwritable cache must not suppress successfully decoded art. + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + guard !((try? path.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) ?? false) else { throw Failure.invalidCache } + try thumbnail.write(to: path, options: .atomic) + trim(directory) + } catch { } + return thumbnail + } + + private func cachedThumbnail(_ path: URL, expectedSHA256: String) -> Data? { + guard let values = try? path.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]), + values.isRegularFile == true, values.isSymbolicLink != true, + let size = values.fileSize, size <= Self.maximumThumbnailBytes, + let data = try? Data(contentsOf: path), Self.image(from: data) != nil, + SHA256.hash(data: data).map({ String(format: "%02x", $0) }).joined() == expectedSHA256.lowercased() else { return nil } + return data + } + + private func trim(_ directory: URL) { + let keys: Set = [.fileSizeKey, .contentModificationDateKey, .isRegularFileKey, .isSymbolicLinkKey] + guard let urls = try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: Array(keys)) else { return } + let entries = urls.compactMap { url -> (URL, Int, Date)? in + let stem = url.deletingPathExtension().lastPathComponent + guard url.pathExtension == "png", stem.count == 64, stem.allSatisfy({ $0.isHexDigit }), + let values = try? url.resourceValues(forKeys: keys), values.isRegularFile == true, + values.isSymbolicLink != true else { return nil } + return (url, values.fileSize ?? 0, values.contentModificationDate ?? .distantPast) + }.sorted { $0.2 < $1.2 } + var total = entries.reduce(0) { $0 + $1.1 } + for entry in entries where total > 128 * 1024 * 1024 { + do { try FileManager.default.removeItem(at: entry.0); total -= entry.1 } catch { } + } + } +} + +private final class LibraryArtworkRedirects: NSObject, URLSessionTaskDelegate { + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { + completionHandler(request.url.map(SoftwareLibraryArtworkCache.accepts) == true ? request : nil) + } +} diff --git a/platforms/macos/App/SoftwareLibraryCatalog.swift b/platforms/macos/App/SoftwareLibraryCatalog.swift new file mode 100644 index 0000000..b9be242 --- /dev/null +++ b/platforms/macos/App/SoftwareLibraryCatalog.swift @@ -0,0 +1,626 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import SQLite3 + +// Immutable snapshots cross from the loading task to the native browser. The +// bundled database is opened read-only; no user state is ever written into it. +struct SoftwareLibraryCatalog: Codable, Sendable { + let titles: [SoftwareLibraryTitle] + let metadata: [String: String] + var releaseCount: Int { titles.reduce(0) { $0 + $1.releases.count } } + var releases: [SoftwareLibraryRelease] { titles.flatMap(\.releases) } + var categories: [String] { Array(Set(releases.filter { $0.ownedGame == nil }.map(\.category))).sorted() } + + static func bundledURL(in bundle: Bundle = .main) -> URL? { + bundle.url(forResource: "catalog", withExtension: "sqlite", subdirectory: "SoftwareLibrary") + ?? bundle.url(forResource: "app-catalog", withExtension: "sqlite") + } + static func load(from url: URL) async throws -> Self { + try await Task.detached(priority: .userInitiated) { try read(from: url) }.value + } + static func loadBundled(in bundle: Bundle = .main) async throws -> Self { + guard let url = bundledURL(in: bundle) else { throw Failure.missing } + return try await load(from: url) + } + enum Failure: LocalizedError { + case missing, invalid(String), unsupported + var errorDescription: String? { + switch self { + case .missing: return "This build does not contain a Software Library catalog. Rebuild with the prepared catalog or install a build that includes it." + case .invalid(let reason): return "The Software Library catalog could not be read: \(reason). Replace the catalog with a newly prepared copy and rebuild the app. Your favorites and installed media are separate and have not been changed." + case .unsupported: return "This catalog uses an unsupported version. Install a matching VCC Plus build or rebuild with a compatible catalog." + } + } + } + private static func read(from url: URL) throws -> Self { + guard url.isFileURL, FileManager.default.fileExists(atPath: url.path) else { throw Failure.missing } + let db = try LibrarySQLite(url: url) + guard try db.rows("PRAGMA user_version").first?["user_version"] == "1" else { throw Failure.unsupported } + try db.execute("PRAGMA query_only=ON") + try db.execute("PRAGMA trusted_schema=OFF") + // Older macOS SQLite builds do not mark json_valid() innocuous, so + // executing the catalog's CHECK(json_valid(...)) during quick_check + // fails with trusted_schema=OFF. Skip schema CHECK expressions here; + // keep schema trust disabled and validate consumed JSON/byte sizes in + // Swift below. Physical, NOT NULL and foreign-key checks still run. + try db.execute("PRAGMA ignore_check_constraints=ON") + guard try db.rows("PRAGMA quick_check").first?.values.first == "ok" else { throw Failure.invalid("database integrity check failed") } + try db.execute("PRAGMA ignore_check_constraints=OFF") + guard try db.rows("PRAGMA foreign_key_check").isEmpty else { throw Failure.invalid("broken catalog relationships") } + var metadata: [String: String] = [:] + for row in try db.rows("SELECT key,value FROM metadata") { metadata[try row.required("key")] = try row.required("value") } + guard metadata["schema_version"] == "1", metadata["recipe_contract"] == "2" else { throw Failure.unsupported } + var assets: [String: [SoftwareLibraryAsset]] = [:] + let hasDelivery = !(try db.rows("SELECT name FROM sqlite_master WHERE type='table' AND name='asset_delivery'")).isEmpty + let assetSQL = hasDelivery + ? "SELECT ra.release_id,ra.status,ra.reason,a.*,d.manual_url,d.thumbnail_url,d.thumbnail_sha256,d.thumbnail_byte_size FROM release_asset ra JOIN asset a ON a.id=ra.asset_id LEFT JOIN asset_delivery d ON d.asset_id=a.id ORDER BY COALESCE(d.priority,99),a.name,a.id" + : "SELECT ra.release_id,ra.status,ra.reason,a.* FROM release_asset ra JOIN asset a ON a.id=ra.asset_id ORDER BY a.kind,a.name,a.id" + for row in try db.rows(assetSQL) { + var asset = SoftwareLibraryAsset(id: try row.required("id"), name: try row.required("name"), + kind: try row.required("kind"), sourceURL: try row.webURL("source_url"), sha256: row["sha256"], + byteSize: row["byte_size"].flatMap(Int64.init), credit: try row.required("credit"), + matchStatus: try row.required("status"), matchReason: try row.required("reason")) + if row["manual_url"] != nil { asset.manualURL = try row.webURL("manual_url") } + if row["thumbnail_url"] != nil { asset.thumbnailURL = try row.webURL("thumbnail_url") } + asset.thumbnailSHA256 = row["thumbnail_sha256"] + asset.thumbnailByteSize = row["thumbnail_byte_size"].flatMap(Int64.init) + assets[try row.required("release_id"), default: []].append(asset) + } + var downloads: [String: [URL]] = [:] + for row in try db.rows("SELECT * FROM download_location ORDER BY priority,url") { + downloads[try row.required("package_sha256"), default: []].append(try row.webURL("url")) + } + var grouped: [String: [SoftwareLibraryRelease]] = [:] + var names: [String: (String, String)] = [:] + let query = """ + SELECT r.*,t.name AS title_name,t.identity_status,p.byte_size,s.status,s.command,s.instructions, + s.configuration_json,s.selected_members_json,s.reasons_json,s.validation_json + FROM release r JOIN title t ON t.id=r.title_id JOIN package p ON p.sha256=r.package_sha256 + JOIN setup s ON s.release_id=r.id ORDER BY r.name COLLATE NOCASE,r.id + """ + for row in try db.rows(query) { + let id = try row.required("id"), titleID = try row.required("title_id"), sha = try row.required("package_sha256") + guard sha.count == 64, sha.allSatisfy({ $0.isHexDigit }), + let bytes = row["byte_size"].flatMap(Int64.init), bytes >= 0 else { throw Failure.invalid("invalid package fingerprint") } + let config: LibraryJSON = try row.json("configuration_json") + let setup = SoftwareLibrarySetup(status: try row.required("status"), command: row["command"], + instructions: try row.required("instructions"), configuration: config, + selectedMembers: try row.json("selected_members_json"), reasons: try row.json("reasons_json"), + validation: try row.json("validation_json")) + let release = SoftwareLibraryRelease(id: id, titleID: titleID, name: try row.required("name"), + category: try row.required("category").trimmingCharacters(in: CharacterSet(charactersIn: "/")), + mediaType: try row.required("media_type"), contentRole: try row.required("content_role"), + sourceURL: try row.webURL("source_url"), modifiedAt: row["modified_at"], + modifiedPrecision: row["modified_precision"], modifiedTimezone: row["modified_timezone"], + packageSHA256: sha, byteSize: bytes, languageStatus: try row.required("language_status"), + metadata: try row.json("metadata_json"), setup: setup, assets: assets[id] ?? [], downloadURLs: downloads[sha] ?? []) + try release.validatePresentationMetadata() + grouped[titleID, default: []].append(release) + names[titleID] = (try row.required("title_name"), try row.required("identity_status")) + } + let storedCount = try db.rows("SELECT count(*) AS count FROM release").first?["count"].flatMap(Int.init) + guard storedCount == grouped.values.reduce(0, { $0 + $1.count }) else { throw Failure.invalid("a release is missing its setup or title") } + let titles = grouped.map { id, releases in + SoftwareLibraryTitle(id: id, name: names[id]!.0, identityStatus: names[id]!.1, releases: releases) + }.sorted { a, b in + let order = a.name.localizedStandardCompare(b.name) + return order == .orderedSame ? a.id < b.id : order == .orderedAscending + } + return Self(titles: titles, metadata: metadata) + } +} + +struct SoftwareLibraryTitle: Identifiable, Codable, Sendable { + let id: String + let name: String + let identityStatus: String + let releases: [SoftwareLibraryRelease] + init(id: String, name: String, identityStatus: String, releases: [SoftwareLibraryRelease]) { + self.id = id; self.name = name; self.identityStatus = identityStatus + self.releases = Self.orderedOwnedEditions(releases) + } + var searchText: String { ([name] + releases.map(\.searchText)).joined(separator: " ") } + + /// Archive edition ordering is curated independently. Only a wholly owned + /// title defaults to its newest dated edition; a user's saved choice still + /// takes precedence in SoftwareLibraryModel.selectedRelease. + private static func orderedOwnedEditions(_ releases: [SoftwareLibraryRelease]) -> [SoftwareLibraryRelease] { + guard releases.count > 1, releases.allSatisfy({ $0.ownedGame != nil }) else { return releases } + let dated = releases.enumerated().map { index, release in + let publication = release.metadata["owned_publication"] + let verified = publication["state"].string == "verified" + let version = verified ? release.ownedGameVersion.flatMap(calendarDate) : nil + let published = verified ? publication["verified_at"].string.flatMap(absoluteDate) : nil + return (index: index, release: release, edition: version ?? published, published: published) + } + return dated.sorted { first, second in + if first.edition != second.edition { + if let a = first.edition, let b = second.edition { return a > b } + return first.edition != nil + } + if first.published != second.published { + if let a = first.published, let b = second.published { return a > b } + return first.published != nil + } + return first.index < second.index + }.map(\.release) + } + private static func calendarDate(_ text: String) -> Date? { + guard text.range(of: #"^[0-9]{4}-[0-9]{2}-[0-9]{2}$"#, options: .regularExpression) != nil else { return nil } + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.calendar = Calendar(identifier: .gregorian) + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd"; formatter.isLenient = false + guard let date = formatter.date(from: text), formatter.string(from: date) == text else { return nil } + return date + } + private static func absoluteDate(_ text: String) -> Date? { + // Require an explicit offset. Comparing raw ISO spellings would put + // 10:00+09:00 after 02:00Z even though it happened an hour earlier. + guard text.range(of: #"(?:Z|[+-][0-9]{2}:?[0-9]{2})$"#, options: .regularExpression) != nil else { return nil } + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + if let date = formatter.date(from: text) { return date } + formatter.formatOptions = [.withInternetDateTime] + return formatter.date(from: text) + } +} + +extension SoftwareLibraryTitle { + init(from decoder: Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + self.init(id: try values.decode(String.self, forKey: .id), name: try values.decode(String.self, forKey: .name), + identityStatus: try values.decode(String.self, forKey: .identityStatus), + releases: try values.decode([SoftwareLibraryRelease].self, forKey: .releases)) + } +} + +struct SoftwareLibraryRelease: Identifiable, Codable, Sendable { + let id: String + let titleID: String + let name: String + let category: String + let mediaType: String + let contentRole: String + let sourceURL: URL + let modifiedAt: String? + let modifiedPrecision: String? + let modifiedTimezone: String? + let packageSHA256: String + let byteSize: Int64 + let languageStatus: String + let metadata: LibraryJSON + let setup: SoftwareLibrarySetup + let assets: [SoftwareLibraryAsset] + let downloadURLs: [URL] + // The full reviewed project-title intake record lives in metadata.owned_game. + // Catalog and companion decoding validate it before exposing a release. + var ownedGame: SoftwareLibraryOwnedGame? { try? SoftwareLibraryOwnedGame.parse(metadata["owned_game"]) } + var browseCategories: [String] { + ownedGame?.browseCategories ?? metadata["browse_categories"].strings + } + var primaryBrowseCategory: String? { + ownedGame?.primaryBrowseCategory ?? metadata["primary_browse_category"].string + } + var categoryFeatured: Bool { + if let ownedGame { return ownedGame.categoryFeatured } + if case .bool(let value) = metadata["category_featured"] { return value } + return false + } + var gettingStarted: Bool { + if let ownedGame { return ownedGame.gettingStarted } + if case .bool(let value) = metadata["getting_started"] { return value } + return false + } + var primaryManualAsset: SoftwareLibraryAsset? { + guard let ownedGame else { return assets.first(where: { $0.isManual && $0.manualURL != nil }) } + var asset = SoftwareLibraryAsset(id: "owned-manual:" + id, name: "Manual", kind: "manual", + sourceURL: ownedGame.projectURL, sha256: ownedGame.manualPDF.sha256, byteSize: ownedGame.manualPDF.byteSize, + credit: ownedGame.author, matchStatus: "project-owned", matchReason: "Published project manual") + asset.manualURL = ownedGame.manualPDF.url + return asset + } + func validatePresentationMetadata() throws { + if let owned = try SoftwareLibraryOwnedGame.parse(metadata["owned_game"]) { + guard mediaType == "disk", owned.gameID == titleID, owned.releaseID == id, + owned.package.sha256 == packageSHA256, owned.package.byteSize == byteSize, + setup.profile == "disk-basic", setup.ramKiB == owned.ramKiB, setup.processor == owned.processor, + setup.command == "DOS\r", setup.selectedMembers.array.count == 1, + owned.configuration.object.allSatisfy({ setup.configuration[$0.key] == $0.value }), + setup.selectedMembers.array.first?["path"].string == owned.diskPath, + setup.selectedMembers.array.first?["target"].string == "disk0" else { + throw SoftwareLibraryCatalog.Failure.invalid("project-owned metadata does not match this release's package/setup") + } + } + try SoftwareLibraryOwnedGame.validateBrowseMetadata(metadata, optional: true) + } + var publisher: String? { metadata["publisher"].string } + var year: Int? { metadata["year"].integer } + var system: String { metadata["system"].string ?? "unknown" } + var videoModes: [String] { metadata["video_modes"].strings } + // These are catalog observations, not the launcher's generous defaults. + var environment: String { setup.configuration["browse_environment"].string ?? "unknown" } + var processorRequirement: String { setup.configuration["processor_requirement"].string ?? "unknown" } + var hardwareSupport: [String: String] { + setup.configuration["hardware_support"].object.compactMapValues(\.string) + } + var semigraphicsModes: [String] { videoModes.filter { $0 == "SG" || $0.hasPrefix("SG-") } } + var videoBadges: [String] { + videoModes.map { $0 + (metadata["video_scope"].string == "intro-only" ? " intro" : "") } + } + var mediaLabel: String { + switch mediaType { + case "cartridge": return "Cartridge" + case "cassette": return "Cassette" + case "disk": return "Disk" + case "hard-disk": return "Hard disk" + case "sdc": return "SDC SD card" + default: return mediaType + } + } + fileprivate var ownedGameVersion: String? { + guard ownedGame != nil, let value = metadata["owned_game"]["game_version"].string, + !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, value.utf8.count <= 160, + !value.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) else { return nil } + return value + } + var editionLabel: String { mediaLabel + " — " + (ownedGameVersion ?? name) } + var searchText: String { + [name, category, mediaLabel, publisher ?? "", year.map(String.init) ?? "", system, + metadata["catalog_number"].string ?? "", videoModes.joined(separator: " "), + metadata["media_tags"].strings.joined(separator: " "), browseCategories.joined(separator: " "), + ownedGame?.author ?? "", setup.compatibilityNotes.joined(separator: " ")].joined(separator: " ") + } +} + +/// Project-owned distribution metadata, never a source of executable host commands. +/// The native catalog stores the complete intake shape under metadata.owned_game; +/// only the fields below are consumed here. Publication remains a maintainer step. +struct SoftwareLibraryOwnedGame: Sendable, Equatable { + struct HostedFile: Codable, Sendable, Equatable { + let url: URL + let sha256: String + let byteSize: Int64 + } + struct Source: Sendable, Equatable { + let package: HostedFile + let projectDirectory: String + let configurationFile: String + let entrySource: String + let licenseFiles: [String] + var companionPackages: [HostedFile] = [] + var buildConfiguration: String? = nil + } + let gameID: String + let releaseID: String + let author: String + let license: String + let projectURL: URL + let onlineManualURL: URL + let manualPDF: HostedFile + let sourceRepositoryURL: URL + let source: Source + let gettingStarted: Bool + let categoryFeatured: Bool + let browseCategories: [String] + let primaryBrowseCategory: String + let firstPlayColdDOS: Bool + let diskPath: String + let diskSHA256: String + let diskByteSize: Int64 + let package: HostedFile + let ramKiB: Int + let processor: String + let configuration: LibraryJSON + + static let categoryNames: Set = ["Applications", "Games", "Music", "Educational", "Demos", "Utilities", + "Programming", "Magazines", "Books", "Pictures", "Hardware", "Operating Systems", "Blank Media", "Other"] + static func categoryLabel(_ id: String) -> String { id == "Educational" ? "Education" : id } + private static func invalid(_ detail: String) -> SoftwareLibraryCatalog.Failure { .invalid("project-owned title: " + detail) } + private static func text(_ value: LibraryJSON, _ name: String) throws -> String { + guard let result = value.string, !result.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + result.utf8.count <= 4096, + !result.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) else { throw invalid("invalid " + name) } + return result + } + private static func flag(_ value: LibraryJSON, _ name: String) throws -> Bool { + guard case .bool(let result) = value else { throw invalid("invalid " + name) } + return result + } + static func validRelativePath(_ value: String) -> Bool { + let parts = value.split(separator: "/", omittingEmptySubsequences: false) + return !value.isEmpty && value.utf8.count <= 1024 && parts.count <= 32 && + !value.contains("\\") && !value.contains(":") && + !parts.contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }) && + value == value.precomposedStringWithCanonicalMapping && + !value.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + } + private static func relative(_ value: LibraryJSON, _ name: String) throws -> String { + let result = try text(value, name) + guard validRelativePath(result) else { throw invalid("unsafe " + name) } + return result + } + private static func web(_ value: LibraryJSON, _ name: String) throws -> URL { + let raw = try text(value, name) + guard !raw.contains("\\"), !raw.unicodeScalars.contains(where: CharacterSet.whitespacesAndNewlines.contains), + let url = URL(string: raw), url.scheme == "https", url.host?.isEmpty == false, + url.user == nil, url.password == nil, url.port == nil || url.port == 443, + !url.pathComponents.contains("."), !url.pathComponents.contains(".."), + !url.path.contains("\\"), !url.path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) else { + throw invalid("invalid " + name) + } + return url + } + private static func fingerprint(_ value: LibraryJSON, _ maximum: Int64, _ name: String) throws -> (String, Int64) { + guard let sha = value["sha256"].string, sha.count == 64, + sha.allSatisfy({ "0123456789abcdef".contains($0) }), + let bytes = value["byte_size"].integer, bytes > 0, Int64(bytes) <= maximum else { + throw invalid("invalid " + name + " identity") + } + return (sha, Int64(bytes)) + } + private static func hosted(_ value: LibraryJSON, prefix: String, ext: String, + maximum: Int64, name: String) throws -> HostedFile { + let url = try web(value["url"], name) + let (sha, bytes) = try fingerprint(value, maximum, name) + guard url.host == "vccplus.brianholman.com", url.query == nil, url.fragment == nil, + url.path.hasPrefix("/dl/software/CoCoLibrary/" + prefix), url.pathExtension.lowercased() == ext else { + throw invalid("unapproved " + name + " delivery area") + } + return HostedFile(url: url, sha256: sha, byteSize: bytes) + } + static func validateBrowseMetadata(_ value: LibraryJSON, optional: Bool) throws { + let categories = value["browse_categories"] + if optional && categories == .null { + guard value["primary_browse_category"] == .null else { throw invalid("primary category has no memberships") } + } else { + guard case .array(let values) = categories, !values.isEmpty, values.count <= 8, + values.allSatisfy({ $0.string.map(categoryNames.contains) == true }), + Set(values.compactMap(\.string)).count == values.count, + let primary = value["primary_browse_category"].string, + values.contains(.string(primary)) else { throw invalid("invalid browse categories") } + } + for key in ["category_featured", "getting_started"] where !optional || value[key] != .null { + _ = try flag(value[key], key) + } + } + static func parse(_ value: LibraryJSON) throws -> Self? { + guard value != .null else { return nil } + guard case .object = value, value["schema_version"].integer == 1, + value["provenance"]["kind"].string == "project-owned", + value["provenance"]["collection"].string == "vccplus-exclusive" else { throw invalid("unsupported metadata") } + try validateBrowseMetadata(value, optional: false) + let provenance = value["provenance"], links = value["links"], sourceValue = value["source"] + let gameID = try text(value["id"], "game ID"), releaseID = try text(value["release_id"], "release ID") + guard gameID.range(of: "^vccplus\\.[a-z0-9]+(?:-[a-z0-9]+)*$", options: .regularExpression) != nil, + releaseID.utf8.count <= 160 else { throw invalid("invalid stable identity") } + let projectDirectory = try relative(sourceValue["project_directory"], "project directory") + let configurationFile = try relative(sourceValue["configuration_file"], "project configuration") + let entrySource = try relative(sourceValue["entry_source"], "entry source") + guard configurationFile == projectDirectory + "/vccplus-project.json", entrySource.lowercased().hasSuffix(".c"), + case .array(let licenses) = sourceValue["license_files"], !licenses.isEmpty, licenses.count <= 32 else { + throw invalid("explicit project entry/configuration/licenses required") + } + let licenseFiles = try licenses.map { try relative($0, "license path") } + guard Set(licenseFiles).count == licenseFiles.count else { throw invalid("duplicate license path") } + var companionPackages: [HostedFile] + if sourceValue["companion_packages"] == .null { companionPackages = [] } + else { + guard case .array(let packages) = sourceValue["companion_packages"], packages.count <= 8 else { + throw invalid("invalid related source packages") + } + companionPackages = try packages.map { + try hosted($0, prefix: "Sources/Exclusives/", ext: "zip", maximum: 64 * 1024 * 1024, name: "related source") + } + guard Set(companionPackages.map(\.url)).count == companionPackages.count else { throw invalid("duplicate related source package") } + } + // Retained publication receipts use a separate source-offer descriptor. + if value["library_sources"] != .null { + let library = try hosted(value["library_sources"], prefix: "Sources/Exclusives/", ext: "zip", + maximum: 64 * 1024 * 1024, name: "corresponding library source") + if let existing = companionPackages.first(where: { $0.url == library.url }) { + guard existing == library else { throw invalid("conflicting related source identity") } + } else { companionPackages.append(library) } + } + let buildConfiguration = sourceValue["build_configuration"] == .null ? nil + : try text(sourceValue["build_configuration"], "source build configuration") + let online = try web(links["manual_online"], "online manual") + guard online.host == "vccplus.brianholman.com", online.path.hasPrefix("/games/") else { throw invalid("unapproved online manual") } + let disk = value["disk"], setup = value["setup"], config = setup["configuration"] + let path = try relative(disk["path"], "disk member") + let (diskSHA, diskBytes) = try fingerprint(disk, 16 * 1024 * 1024, "disk") + guard path.lowercased().hasSuffix(".dsk"), config["profile"].string == "disk-basic", + let ram = config["ram_kib"].integer, [128, 512, 2048, 8192].contains(ram), + let processor = config["processor"].string, ["6809", "6309"].contains(processor), + setup["selected_members"] == .array([.object(["path": .string(path), "target": .string("disk0")])]), + setup["command"].string == "DOS\r", value["first_play"]["mode"].string == "cold-restart-dos", + setup["validation"]["disk_sha256"].string == diskSHA, + let status = value["publication_status"].string, ["fixture-only", "pending-review", "approved"].contains(status), + let scope = setup["validation"]["scope"].string, ["fixture-only", "runtime-verified"].contains(scope), + status != "approved" || scope == "runtime-verified" else { throw invalid("invalid vetted first-Play recipe") } + return Self(gameID: gameID, releaseID: releaseID, + author: try text(provenance["author"], "author"), license: try text(provenance["license"], "license"), + projectURL: try web(provenance["project_url"], "project link"), onlineManualURL: online, + manualPDF: try hosted(links["manual_pdf"], prefix: "Documents/Manuals/Exclusives/", ext: "pdf", maximum: 512 * 1024 * 1024, name: "manual"), + sourceRepositoryURL: try web(links["source_repository"], "source repository"), + source: Source(package: try hosted(sourceValue["package"], prefix: "Sources/Exclusives/", ext: "zip", maximum: 64 * 1024 * 1024, name: "source"), + projectDirectory: projectDirectory, configurationFile: configurationFile, entrySource: entrySource, + licenseFiles: licenseFiles, companionPackages: companionPackages, buildConfiguration: buildConfiguration), + gettingStarted: try flag(value["getting_started"], "Getting Started"), + categoryFeatured: try flag(value["category_featured"], "curated category"), + browseCategories: value["browse_categories"].strings, primaryBrowseCategory: value["primary_browse_category"].string!, + firstPlayColdDOS: status == "approved" && scope == "runtime-verified", + diskPath: path, diskSHA256: diskSHA, diskByteSize: diskBytes, + package: try hosted(value["disk_package"], prefix: "Exclusives/", ext: "zip", maximum: 1_073_741_824, name: "disk package"), + ramKiB: ram, processor: processor, configuration: config) + } +} + +extension SoftwareLibraryRelease { + // Companion snapshots must not silently turn malformed owned metadata back + // into an Archive record just because they bypass the SQLite loader. + init(from decoder: Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + self.init(id: try values.decode(String.self, forKey: .id), titleID: try values.decode(String.self, forKey: .titleID), + name: try values.decode(String.self, forKey: .name), category: try values.decode(String.self, forKey: .category), + mediaType: try values.decode(String.self, forKey: .mediaType), contentRole: try values.decode(String.self, forKey: .contentRole), + sourceURL: try values.decode(URL.self, forKey: .sourceURL), modifiedAt: try values.decodeIfPresent(String.self, forKey: .modifiedAt), + modifiedPrecision: try values.decodeIfPresent(String.self, forKey: .modifiedPrecision), modifiedTimezone: try values.decodeIfPresent(String.self, forKey: .modifiedTimezone), + packageSHA256: try values.decode(String.self, forKey: .packageSHA256), byteSize: try values.decode(Int64.self, forKey: .byteSize), + languageStatus: try values.decode(String.self, forKey: .languageStatus), metadata: try values.decode(LibraryJSON.self, forKey: .metadata), + setup: try values.decode(SoftwareLibrarySetup.self, forKey: .setup), assets: try values.decode([SoftwareLibraryAsset].self, forKey: .assets), + downloadURLs: try values.decode([URL].self, forKey: .downloadURLs)) + try validatePresentationMetadata() + } +} + +struct SoftwareLibrarySetup: Codable, Sendable { + let status: String + let command: String? + let instructions: String + let configuration: LibraryJSON + let selectedMembers: LibraryJSON + let reasons: [String] + let validation: LibraryJSON + var compatibilityNotes: [String] { configuration["compatibility_notes"].strings } + var configurationRequirements: [String] { configuration["configuration_requirements"].strings } + var profile: String? { configuration["profile"].string } + var processor: String? { configuration["processor"].string } + var ramKiB: Int? { configuration["ram_kib"].integer } + var controls: LibraryJSON { configuration["controls"] } + func controlDescription(_ key: String, source: String = "the Archive") -> String { + let value = controls[key] + if let text = value.string { return text } + let prefix = key.capitalized + " joystick: " + switch value["suggested_input"].string { + case "keyboard-joystick": return prefix + "keyboard control suggested by \(source)." + case "mouse-joystick": return prefix + "mouse control suggested by \(source)." + case "gamepad", "joystick": return prefix + "controller input suggested by \(source)." + default: return key.capitalized + " input is noted by \(source); check the available instructions." + } + } + var curationNote: String? { configuration["curation_note"].string } + var validationScope: String? { validation["scope"].string } + var statusLabel: String { + switch status { + case "source-ready": return "Archive-assisted loading" + case "inferred-ready": return "Inferred loading instructions" + case "spot-checked": return "VCC Plus spot-checked" + case "manual-setup": return "Manual setup" + default: return status + } + } +} + +struct SoftwareLibraryAsset: Identifiable, Codable, Sendable { + let id: String + let name: String + let kind: String + let sourceURL: URL + let sha256: String? + let byteSize: Int64? + let credit: String + let matchStatus: String + let matchReason: String + var manualURL: URL? = nil + var thumbnailURL: URL? = nil + var thumbnailSHA256: String? = nil + var thumbnailByteSize: Int64? = nil + var isManual: Bool { kind == "manual" } +} + +// Preserve optional and future metadata without translating unknown values into +// compatibility claims. Known display fields are exposed above as typed helpers. +indirect enum LibraryJSON: Codable, Sendable, Equatable { + case object([String: LibraryJSON]), array([LibraryJSON]), string(String), number(Double), bool(Bool), null + init(from decoder: Decoder) throws { + let value = try decoder.singleValueContainer() + if value.decodeNil() { self = .null } + else if let v = try? value.decode(Bool.self) { self = .bool(v) } + else if let v = try? value.decode(String.self) { self = .string(v) } + else if let v = try? value.decode(Double.self) { self = .number(v) } + else if let v = try? value.decode([String: LibraryJSON].self) { self = .object(v) } + else { self = .array(try value.decode([LibraryJSON].self)) } + } + func encode(to encoder: Encoder) throws { + var value = encoder.singleValueContainer() + switch self { + case .object(let v): try value.encode(v) + case .array(let v): try value.encode(v) + case .string(let v): try value.encode(v) + case .number(let v): try value.encode(v) + case .bool(let v): try value.encode(v) + case .null: try value.encodeNil() + } + } + subscript(_ key: String) -> Self { if case .object(let v) = self { return v[key] ?? .null }; return .null } + var string: String? { if case .string(let v) = self { return v }; return nil } + var integer: Int? { if case .number(let v) = self, v.isFinite, v >= Double(Int.min), v < Double(Int.max), v.rounded() == v { return Int(v) }; return nil } + var strings: [String] { if case .array(let v) = self { return v.compactMap(\.string) }; return [] } + var object: [String: Self] { if case .object(let v) = self { return v }; return [:] } + var array: [Self] { if case .array(let v) = self { return v }; return [] } +} + +final class LibrarySQLite { + private var handle: OpaquePointer? + private let describeError: (String) -> Error + init(url: URL, cancellable: Bool = false, + describeError: @escaping (String) -> Error = { SoftwareLibraryCatalog.Failure.invalid($0) }) throws { + self.describeError = describeError + let result = sqlite3_open_v2(url.path, &handle, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, nil) + guard result == SQLITE_OK else { + let reason = handle.map { String(cString: sqlite3_errmsg($0)) } ?? "cannot open database" + sqlite3_close(handle); handle = nil + throw describeError(reason) + } + if cancellable { + sqlite3_progress_handler(handle, 1024, { _ in Task.isCancelled ? 1 : 0 }, nil) + } + } + deinit { sqlite3_close(handle) } + func execute(_ sql: String) throws { _ = try rows(sql) } + func rows(_ sql: String, _ parameters: [String] = []) throws -> [[String: String]] { + var statement: OpaquePointer? + guard sqlite3_prepare_v2(handle, sql, -1, &statement, nil) == SQLITE_OK else { throw failure() } + defer { sqlite3_finalize(statement) } + for (index, value) in parameters.enumerated() { + let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self) + guard sqlite3_bind_text(statement, Int32(index + 1), value, -1, transient) == SQLITE_OK else { throw failure() } + } + var result: [[String: String]] = [] + while true { + let status = sqlite3_step(statement) + if status == SQLITE_DONE { break } + if status == SQLITE_INTERRUPT { throw CancellationError() } + guard status == SQLITE_ROW else { throw failure() } + var row: [String: String] = [:] + for column in 0.. Error { describeError(String(cString: sqlite3_errmsg(handle))) } +} + +private extension Dictionary where Key == String, Value == String { + func required(_ key: String) throws -> String { + guard let value = self[key] else { throw SoftwareLibraryCatalog.Failure.invalid("missing \(key)") } + return value + } + func json(_ key: String) throws -> T { + do { return try JSONDecoder().decode(T.self, from: Data(try required(key).utf8)) } + catch { throw SoftwareLibraryCatalog.Failure.invalid("malformed \(key)") } + } + func webURL(_ key: String) throws -> URL { + guard let text = self[key], let value = URL(string: text), + ["http", "https"].contains(value.scheme?.lowercased() ?? ""), + value.host != nil, value.user == nil, value.password == nil else { + throw SoftwareLibraryCatalog.Failure.invalid("invalid \(key)") + } + return value + } +} diff --git a/platforms/macos/App/SoftwareLibraryInstallFixture.swift b/platforms/macos/App/SoftwareLibraryInstallFixture.swift new file mode 100644 index 0000000..4a67974 --- /dev/null +++ b/platforms/macos/App/SoftwareLibraryInstallFixture.swift @@ -0,0 +1,286 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#if VCC_UI_TESTING +import Foundation +import CryptoKit + +// Authored transport + catalog for native install checks. Compiled only into the +// isolated UI-test app. Every request is intercepted, including unknown URLs, +// so the fixture cannot accidentally reach the production download service. +enum SoftwareLibraryInstallFixture { + static var enabled: Bool { CommandLine.arguments.contains("--library-install-fixture") || playEnabled || exclusiveEnabled } + static var playEnabled: Bool { CommandLine.arguments.contains("--library-play-fixture") } + static var exclusiveEnabled: Bool { CommandLine.arguments.contains("--library-exclusive-fixture") } + static var sourceConfiguration: URLSessionConfiguration { sessionConfiguration() } + static let titleID = "authored-library-title" + static let releaseID = "authored-library-cartridge" + static let downloadURL = URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Cartridges/Authored%20Library%20Cartridge.ccc")! + static let bytes: Data = { + var value = Data(repeating: 0x12, count: 8192) + value[0] = 0x20; value[1] = 0xfe + return value + }() + static let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() + static var catalog: SoftwareLibraryCatalog { + if exclusiveEnabled { return exclusiveCatalog } + if playEnabled { return playCatalog } + let setup = SoftwareLibrarySetup(status: "inferred-ready", command: nil, + instructions: "Authored UI-test cartridge. Installation does not attach or run it.", + configuration: .object(["profile": .string("disk-basic"), "processor": .string("6809"), "ram_kib": .number(512)]), + selectedMembers: .array([]), reasons: [], validation: .object([:])) + let release = SoftwareLibraryRelease(id: releaseID, titleID: titleID, + name: "Authored Library Cartridge.ccc", category: "Cartridges", mediaType: "cartridge", contentRole: "software", + sourceURL: URL(string: "https://example.invalid/Authored%20Library%20Cartridge.ccc")!, + modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, + packageSHA256: digest, byteSize: Int64(bytes.count), languageStatus: "english", + metadata: .object(["system": .string("coco3"), "publisher": .string("VCC Plus test fixture")]), + setup: setup, assets: [], downloadURLs: [downloadURL]) + return SoftwareLibraryCatalog(titles: [SoftwareLibraryTitle(id: titleID, + name: "Authored Library Cartridge", identityStatus: "confirmed", releases: [release])], + metadata: ["schema_version": "1", "recipe_contract": "2", "stage": "authored-ui-fixture", + "archive_attribution": "Authored test content; no Archive software is used."]) + } + static let manualReleaseID = "authored-library-manual-disk" + static let missingReleaseID = "authored-library-missing-member" + static let diskBytes = Data(repeating: 0, count: 161280) + private static func playRelease(id: String, name: String, media: String, data: Data, missing: Bool = false) -> SoftwareLibraryRelease { + let filename = name + (media == "cartridge" ? ".ccc" : ".dsk") + let source = URL(string: "https://example.invalid/")!.appendingPathComponent(filename) + let download = URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Fixtures/")!.appendingPathComponent(filename) + let hash = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + let cartridge = media == "cartridge" + var configuration: [String: LibraryJSON] = [ + "profile": .string(cartridge ? "rom-cartridge" : "disk-basic"), + "processor": .string("6809"), "ram_kib": .number(2048), "video": .string("composite"), + "controller_slot": .number(4), "cartridge_slot": .number(4), + "floppy_controller_enabled": .bool(!cartridge), "controls": .object([:]) + ] + if cartridge { configuration["launch_method"] = .string("cartridge-autostart") } + let setup = SoftwareLibrarySetup(status: cartridge ? "inferred-ready" : "manual-setup", command: nil, + instructions: cartridge ? "Authored cartridge: verifies setup and resume without a private ROM." : "Authored blank disk: mount it and use the BASIC prompt manually. No loading command is supplied.", + configuration: .object(configuration), + selectedMembers: .array([.object(["path": .string(missing ? "Missing.ccc" : filename), + "target": .string(cartridge ? "cartridge" : "disk0"), + "sha256": .string(hash), "byte_size": .number(Double(data.count))])]), + reasons: [], validation: .object([:])) + return SoftwareLibraryRelease(id: id, titleID: id, name: filename, + category: cartridge ? "Cartridges" : "Disks/Blank disks", mediaType: media, contentRole: "software", + sourceURL: source, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, + packageSHA256: hash, byteSize: Int64(data.count), languageStatus: "english", + metadata: .object(["system": .string("CoCo 3"), "publisher": .string("VCC Plus test fixture")]), + setup: setup, assets: [], downloadURLs: [download]) + } + static var playCatalog: SoftwareLibraryCatalog { + let releases = [ + playRelease(id: releaseID, name: "Authored Library Cartridge", media: "cartridge", data: bytes), + playRelease(id: manualReleaseID, name: "Authored Manual Disk", media: "disk", data: diskBytes), + playRelease(id: missingReleaseID, name: "Missing Media Reference", media: "cartridge", data: bytes, missing: true) + ] + return SoftwareLibraryCatalog(titles: releases.map { + SoftwareLibraryTitle(id: $0.titleID, name: $0.sourceURL.deletingPathExtension().lastPathComponent, + identityStatus: "confirmed", releases: [$0]) + }, metadata: ["schema_version": "1", "recipe_contract": "2", "stage": "authored-ui-fixture"]) + } + static func playData(for url: URL?) -> Data? { + guard let release = playCatalog.releases.first(where: { $0.downloadURLs.first == url }) else { return nil } + return release.mediaType == "disk" ? diskBytes : bytes + } + static func installer(root: URL) -> SoftwareLibraryInstaller { + SoftwareLibraryInstaller(root: root, session: URLSession(configuration: sessionConfiguration())) + } + static func sessionConfiguration() -> URLSessionConfiguration { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [LibraryFixtureURLProtocol.self] + configuration.urlCache = nil + configuration.requestCachePolicy = .reloadIgnoringLocalCacheData + return configuration + } + + static let exclusiveTitleID = "vccplus.fixture-orbit" + static let exclusiveReleaseID = "vccplus.fixture-orbit.1" + static let exclusiveBase = "https://vccplus.brianholman.com/dl/software/CoCoLibrary/" + static let exclusiveSourceURL = URL(string: exclusiveBase + "Sources/Exclusives/FixtureOrbit/1/FixtureOrbit-Source.zip")! + static let exclusiveDiskURL = URL(string: exclusiveBase + "Exclusives/FixtureOrbit/1/FixtureOrbit.zip")! + static let exclusiveManualURL = URL(string: exclusiveBase + "Documents/Manuals/Exclusives/FixtureOrbit/1/Manual.pdf")! + static let exclusiveArtworkURL = URL(string: exclusiveBase + "Artwork/Thumbnails/Exclusives/FixtureOrbit/1/Cover.png")! + static let exclusiveArtwork = Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=")! + static func checksum(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() } + static let exclusiveSourceBytes = storedZIP([ + ("FixtureOrbit/main.c", Data("/* Authored exclusive-title UI fixture. */\nint fixture_orbit;\nint main(void) { return 0; }\n".utf8)), + ("FixtureOrbit/Makefile", Data("UI_SENTINEL := $(shell touch MAKE_WAS_RUN)\nbuild:\n\ttouch MAKE_WAS_RUN\n".utf8)), + ("FixtureOrbit/vccplus-project.json", Data("{\"entrySource\":\"main.c\",\"makefile\":\"Makefile\",\"binary\":\"main.bin\"}".utf8)), + ("FixtureOrbit/LICENSE", Data("CC0-1.0: authored VCC Plus test fixture only.\n".utf8)) + ]) + static let exclusiveDiskPackage = storedZIP([("ORBIT.DSK", diskBytes)]) + static let exclusiveManual: Data = { + let stream = "BT /F1 18 Tf 30 170 Td (Fixture Orbit Manual) Tj 0 -30 Td /F1 11 Tf (Authored offline UI-test documentation.) Tj ET\n" + let objects = ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 320 220] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>", + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", "<< /Length \(stream.utf8.count) >>\nstream\n\(stream)endstream"] + var output = "%PDF-1.4\n", offsets = [0] + for (index, object) in objects.enumerated() { + offsets.append(output.utf8.count); output += "\(index + 1) 0 obj\n\(object)\nendobj\n" + } + let xref = output.utf8.count + output += "xref\n0 \(objects.count + 1)\n0000000000 65535 f \n" + for offset in offsets.dropFirst() { output += String(format: "%010d 00000 n \n", offset) } + output += "trailer\n<< /Size \(objects.count + 1) /Root 1 0 R >>\nstartxref\n\(xref)\n%%EOF\n" + return Data(output.utf8) + }() + private static func exclusiveFile(_ url: URL, _ data: Data) -> LibraryJSON { + .object(["url": .string(url.absoluteString), "sha256": .string(checksum(data)), "byte_size": .number(Double(data.count))]) + } + static var exclusiveCatalog: SoftwareLibraryCatalog { + let diskSHA = checksum(diskBytes) + let configuration: LibraryJSON = .object(["profile": .string("disk-basic"), "processor": .string("6809"), + "ram_kib": .number(128), "video": .string("rgb"), "controller_slot": .number(4)]) + let selected: LibraryJSON = .array([.object(["path": .string("ORBIT.DSK"), "target": .string("disk0")])]) + let validation: LibraryJSON = .object(["scope": .string("runtime-verified"), "disk_sha256": .string(diskSHA)]) + let owned: LibraryJSON = .object([ + "schema_version": .number(1), "id": .string(exclusiveTitleID), "release_id": .string(exclusiveReleaseID), + "publication_status": .string("approved"), "getting_started": .bool(true), "category_featured": .bool(true), + "browse_categories": .array([.string("Educational"), .string("Games")]), "primary_browse_category": .string("Educational"), + "provenance": .object(["kind": .string("project-owned"), "collection": .string("vccplus-exclusive"), + "author": .string("Fixture Author"), "license": .string("CC0-1.0 authored fixture"), "project_url": .string("https://example.invalid/fixture-orbit/")]), + "disk_package": exclusiveFile(exclusiveDiskURL, exclusiveDiskPackage), + "disk": .object(["path": .string("ORBIT.DSK"), "sha256": .string(diskSHA), "byte_size": .number(Double(diskBytes.count))]), + "setup": .object(["configuration": configuration, "selected_members": selected, "command": .string("DOS\r"), "validation": validation]), + "first_play": .object(["mode": .string("cold-restart-dos")]), + "links": .object(["manual_online": .string("https://vccplus.brianholman.com/games/fixture-orbit/"), + "manual_pdf": exclusiveFile(exclusiveManualURL, exclusiveManual), "source_repository": .string("https://example.invalid/FixtureOrbit")]), + "source": .object(["package": exclusiveFile(exclusiveSourceURL, exclusiveSourceBytes), + "project_directory": .string("FixtureOrbit"), "configuration_file": .string("FixtureOrbit/vccplus-project.json"), + "entry_source": .string("main.c"), "license_files": .array([.string("FixtureOrbit/LICENSE")]), + "build_configuration": .string("Release")]) + ]) + var art = SoftwareLibraryAsset(id: "fixture-orbit-cover", name: "Authored fixture cover", kind: "screenshot", + sourceURL: URL(string: "https://example.invalid/fixture-orbit/")!, sha256: checksum(exclusiveArtwork), + byteSize: Int64(exclusiveArtwork.count), credit: "Authored test fixture", matchStatus: "confirmed", matchReason: "Authored fixture") + art.thumbnailURL = exclusiveArtworkURL; art.thumbnailSHA256 = checksum(exclusiveArtwork); art.thumbnailByteSize = Int64(exclusiveArtwork.count) + let release = SoftwareLibraryRelease(id: exclusiveReleaseID, titleID: exclusiveTitleID, name: "FixtureOrbit.zip", + category: "Disks/Educational", mediaType: "disk", contentRole: "software", sourceURL: URL(string: "https://example.invalid/fixture-orbit/")!, + modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, packageSHA256: checksum(exclusiveDiskPackage), + byteSize: Int64(exclusiveDiskPackage.count), languageStatus: "english", + metadata: .object(["system": .string("CoCo 3"), "owned_game": owned]), + setup: .init(status: "spot-checked", command: "DOS\r", instructions: "Authored metadata fixture; do not use Play for this non-bootable disk.", + configuration: configuration, selectedMembers: selected, reasons: [], validation: validation), + assets: [art], downloadURLs: [exclusiveDiskURL]) + return SoftwareLibraryCatalog(titles: [.init(id: exclusiveTitleID, name: "Fixture Orbit", identityStatus: "authored-ui-fixture", releases: [release])], + metadata: ["schema_version": "1", "recipe_contract": "2", "stage": "authored-exclusive-ui-fixture"]) + } + /// Prepopulate only the isolated UI profile's verified passive assets. The + /// shared reader/artwork actors therefore perform no network request. + static func seedExclusiveAssets(manualDirectory: URL, artworkDirectory: URL) throws { + guard exclusiveEnabled else { return } + try FileManager.default.createDirectory(at: manualDirectory, withIntermediateDirectories: true) + try exclusiveManual.write(to: manualDirectory.appendingPathComponent(checksum(exclusiveManual) + ".pdf"), options: .atomic) + try FileManager.default.createDirectory(at: artworkDirectory, withIntermediateDirectories: true) + let art = exclusiveCatalog.releases[0].assets[0] + try exclusiveArtwork.write(to: artworkDirectory.appendingPathComponent(SoftwareLibraryArtworkCache.cacheKey(for: art) + ".png"), options: .atomic) + } + static func exclusiveData(for url: URL?) -> Data? { + guard let url else { return nil } + if url == exclusiveSourceURL { return exclusiveSourceBytes } + if url == exclusiveDiskURL { return exclusiveDiskPackage } + if url == exclusiveManualURL { return exclusiveManual } + if url == exclusiveArtworkURL { return exclusiveArtwork } + return nil + } + /// Minimal deterministic stored ZIP writer for these authored files. It + /// supplies normal regular-file attributes; production uses the safe reader. + private static func storedZIP(_ files: [(String, Data)]) -> Data { + func word(_ value: UInt32, bytes: Int) -> Data { + Data((0..> (8 * $0)) }) + } + func crc(_ bytes: Data) -> UInt32 { + var value = UInt32.max + for byte in bytes { + value ^= UInt32(byte) + for _ in 0..<8 { value = value & 1 == 1 ? (value >> 1) ^ 0xedb88320 : value >> 1 } + } + return value ^ UInt32.max + } + var output = Data(), central = Data() + for (name, data) in files { + let path = Data(name.utf8), size = UInt32(data.count), hash = crc(data), offset = UInt32(output.count) + for (value, bytes) in [(UInt32(0x04034b50), 4), (20, 2), (0, 2), (0, 2), (0, 2), (0, 2), + (hash, 4), (size, 4), (size, 4), (UInt32(path.count), 2), (0, 2)] { output.append(word(value, bytes: bytes)) } + output.append(path); output.append(data) + for (value, bytes) in [(UInt32(0x02014b50), 4), (0x0314, 2), (20, 2), (0, 2), (0, 2), (0, 2), (0, 2), + (hash, 4), (size, 4), (size, 4), (UInt32(path.count), 2), (0, 2), (0, 2), (0, 2), (0, 2), + (UInt32(0o100644) << 16, 4), (offset, 4)] { central.append(word(value, bytes: bytes)) } + central.append(path) + } + let offset = UInt32(output.count); output.append(central) + for (value, bytes) in [(UInt32(0x06054b50), 4), (0, 2), (0, 2), (UInt32(files.count), 2), + (UInt32(files.count), 2), (UInt32(central.count), 4), (offset, 4), (0, 2)] { output.append(word(value, bytes: bytes)) } + return output + } +} + +private final class LibraryFixtureAttempts: @unchecked Sendable { + private let lock = NSLock() + private var value = 0 + func next() -> Int { lock.lock(); defer { lock.unlock() }; value += 1; return value } +} + +private final class LibraryFixtureURLProtocol: URLProtocol, @unchecked Sendable { + private static let attempts = LibraryFixtureAttempts() + private let lock = NSLock() + private var cancelled = false + private var pending: DispatchWorkItem? + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + if SoftwareLibraryInstallFixture.exclusiveEnabled { + guard let data = SoftwareLibraryInstallFixture.exclusiveData(for: request.url), let url = request.url else { + client?.urlProtocol(self, didFailWithError: URLError(.unsupportedURL)); return + } + let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/octet-stream", "Content-Length": String(data.count)])! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: data); client?.urlProtocolDidFinishLoading(self) + return + } + if SoftwareLibraryInstallFixture.playEnabled { + guard let data = SoftwareLibraryInstallFixture.playData(for: request.url), let url = request.url else { + client?.urlProtocol(self, didFailWithError: URLError(.unsupportedURL)); return + } + let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/octet-stream", "Content-Length": String(data.count)])! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: data) + client?.urlProtocolDidFinishLoading(self) + return + } + guard request.url == SoftwareLibraryInstallFixture.downloadURL else { + client?.urlProtocol(self, didFailWithError: URLError(.unsupportedURL)); return + } + let attempt = Self.attempts.next() + if attempt == 1 { + let response = HTTPURLResponse(url: request.url!, statusCode: 503, httpVersion: "HTTP/1.1", headerFields: ["Content-Length": "0"])! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocolDidFinishLoading(self) + return + } + let data = SoftwareLibraryInstallFixture.bytes + let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/octet-stream", "Content-Length": String(data.count)])! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: data.prefix(data.count / 2)) + let work = DispatchWorkItem { [weak self] in + guard let self else { return } + self.lock.lock(); let cancelled = self.cancelled; self.lock.unlock() + guard !cancelled else { return } + self.client?.urlProtocol(self, didLoad: data.suffix(data.count / 2)) + self.client?.urlProtocolDidFinishLoading(self) + } + lock.lock(); pending = work; let stopped = cancelled; lock.unlock() + if stopped { work.cancel(); return } + // Long enough for an actual Cancel click, then a quick retry completes. + DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + (attempt == 2 ? 10 : 0.2), execute: work) + } + override func stopLoading() { + lock.lock(); cancelled = true; pending?.cancel(); pending = nil; lock.unlock() + } +} +#endif diff --git a/platforms/macos/App/SoftwareLibraryInstaller.swift b/platforms/macos/App/SoftwareLibraryInstaller.swift new file mode 100644 index 0000000..f089bbe --- /dev/null +++ b/platforms/macos/App/SoftwareLibraryInstaller.swift @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import CryptoKit +import Darwin + +/// All filesystem/verification work runs on this actor, away from the native UI. +/// A receipt is committed only after a complete staged tree has been renamed. +actor SoftwareLibraryInstaller { + static let maximumPackageBytes: Int64 = 1_073_741_824 + static let maximumExpandedBytes: UInt64 = 8 * 1024 * 1024 * 1024 + static let maximumEntries: UInt = 20_000 + let root: URL + private let session: URLSession + private var active: Set = [] + private(set) var recoveryWarnings: [String] = [] + private let manager = FileManager.default + + init(root: URL, session: URLSession? = nil) { + self.root = root.standardizedFileURL + if let session { self.session = session } + else { + let configuration = URLSessionConfiguration.ephemeral + configuration.urlCache = nil + configuration.timeoutIntervalForRequest = 60 + configuration.timeoutIntervalForResource = 1800 + self.session = URLSession(configuration: configuration) + } + } + + enum Failure: LocalizedError { + case invalidMetadata, unsafeLocation, invalidReceipt, busy, existingDifferentPackage + case response, size, fingerprint, unsupported, insufficientSpace + var errorDescription: String? { + switch self { + case .invalidMetadata: return "This catalog entry has invalid download details. Its files have not been installed." + case .unsafeLocation: return "The Software Library location contains an unexpected file or symbolic link. Existing files have been preserved." + case .invalidReceipt: return "An installation record is damaged or unsupported. Its media has been preserved." + case .busy: return "This title is already being installed." + case .existingDifferentPackage: return "Another version is already installed. Remove its Library entry first; its working files will be preserved." + case .response: return "The software server did not return the expected download. Please try again." + case .size: return "The download size does not match the catalog. The incomplete download was discarded." + case .fingerprint: return "The download fingerprint does not match the catalog. The changed download was discarded." + case .unsupported: return "This package format is not supported for installation yet." + case .insufficientSpace: return "There is not enough free space to prepare this software. Free space and try again." + } + } + } + + static func acceptsDownloadURL(_ url: URL) -> Bool { + guard url.scheme?.lowercased() == "https", url.host?.lowercased() == "vccplus.brianholman.com", + url.user == nil, url.password == nil, url.port == nil || url.port == 443, + url.query == nil, url.fragment == nil, url.path.hasPrefix("/dl/software/CoCoLibrary/") else { return false } + return !url.pathComponents.contains(where: { $0 == ".." || $0 == "." }) + && !url.path.contains("\\") && !url.path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + } + static func releaseKey(_ id: String) -> String { + SHA256.hash(data: Data(id.utf8)).map { String(format: "%02x", $0) }.joined() + } + private static func validSHA(_ value: String) -> Bool { value.count == 64 && value.allSatisfy { "0123456789abcdef".contains($0) } } + private static func validID(_ value: String) -> Bool { + !value.isEmpty && value.utf8.count <= 256 && !value.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + } + private static func validRelative(_ value: String) -> Bool { + !value.isEmpty && !value.hasPrefix("/") && !value.contains("\\") && !value.contains(":") + && !value.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + && value.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." } + } + private func directory(_ path: URL, create: Bool) throws { + guard path.isFileURL else { throw Failure.unsafeLocation } + if manager.fileExists(atPath: path.path) || (try? path.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) == true { + let values = try path.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) + guard values.isDirectory == true, values.isSymbolicLink != true else { throw Failure.unsafeLocation } + } else if create { try manager.createDirectory(at: path, withIntermediateDirectories: true) } + else { throw Failure.invalidReceipt } + } + private func prepareRoot() throws { + try directory(root, create: true) + for name in ["Installations", "Packages", ".Staging", ".Locks"] { try directory(root.appendingPathComponent(name), create: true) } + } + private func regularFile(_ url: URL) throws -> Int64 { + let attributes = try manager.attributesOfItem(atPath: url.path) + guard attributes[.type] as? FileAttributeType == .typeRegular, + let size = attributes[.size] as? NSNumber else { throw Failure.unsafeLocation } + return size.int64Value + } + private func acquireLock(_ key: String) throws -> Int32 { + let path = root.appendingPathComponent(".Locks").appendingPathComponent(key).path + let fd = open(path, O_CREAT | O_RDWR | O_NOFOLLOW, S_IRUSR | S_IWUSR) + guard fd >= 0 else { throw Failure.unsafeLocation } + guard flock(fd, LOCK_EX | LOCK_NB) == 0 else { close(fd); throw Failure.busy } + return fd + } + + func install(_ release: SoftwareLibraryRelease, + progress: @escaping @Sendable (SoftwareLibraryInstallProgress) -> Void = { _ in }) async throws -> SoftwareLibraryInstallationReceipt { + try release.validatePresentationMetadata() + guard Self.validID(release.id), Self.validSHA(release.packageSHA256), + release.byteSize > 0, release.byteSize <= Self.maximumPackageBytes else { throw Failure.invalidMetadata } + // Project provenance may be a repository/page; delivery has its own identity. + let format = (release.ownedGame?.package.url ?? release.sourceURL).pathExtension.lowercased() + guard ["zip", "ccc", "dsk", "os9"].contains(format) else { throw Failure.unsupported } + let downloadURL: URL + if let owned = release.ownedGame { + guard release.downloadURLs.contains(owned.package.url), Self.acceptsDownloadURL(owned.package.url) else { throw Failure.invalidMetadata } + downloadURL = owned.package.url + } else { + guard let accepted = release.downloadURLs.first(where: Self.acceptsDownloadURL) else { throw Failure.invalidMetadata } + downloadURL = accepted + } + try prepareRoot() + guard active.insert(release.id).inserted else { throw Failure.busy } + defer { active.remove(release.id) } + let key = Self.releaseKey(release.id), lock = try acquireLock(Self.releaseKey(release.id)) + defer { flock(lock, LOCK_UN); close(lock) } + if let previous = try records(releaseID: release.id).first { + guard previous.1.packageSHA256 == release.packageSHA256 else { throw Failure.existingDifferentPackage } + return previous.1.publicReceipt(in: previous.0) // Never replace a user's modified working copy. + } + try Task.checkCancellation() + if let free = freeBytes(), free < release.byteSize * 3 + 64 * 1024 * 1024 { throw Failure.insufficientSpace } + let stageID = UUID().uuidString + let stageLock = try acquireLock("stage-" + stageID) + defer { flock(stageLock, LOCK_UN); close(stageLock) } + let stage = root.appendingPathComponent(".Staging").appendingPathComponent(stageID) + try manager.createDirectory(at: stage, withIntermediateDirectories: false) + defer { try? manager.removeItem(at: stage) } + let cached = root.appendingPathComponent("Packages").appendingPathComponent(release.packageSHA256 + ".package") + var validCache = false + if manager.fileExists(atPath: cached.path) { + do { try verify(cached, size: release.byteSize, sha: release.packageSHA256); validCache = true } + catch is CancellationError { throw CancellationError() } + catch { + _ = try regularFile(cached) // Refuse to unlink unexpected links or directories. + try manager.removeItem(at: cached) + } + } + if !validCache { + progress(.init(stage: .downloading, receivedBytes: 0, totalBytes: release.byteSize)) + var request = URLRequest(url: downloadURL) + request.setValue("VCCPlus/SoftwareLibrary", forHTTPHeaderField: "User-Agent") + request.setValue("identity", forHTTPHeaderField: "Accept-Encoding") + let observer = LibraryDownloadObserver(expected: release.byteSize, progress: progress) + let temporary: URL, response: URLResponse + do { (temporary, response) = try await session.download(for: request, delegate: observer) } + catch { + if Task.isCancelled { throw CancellationError() } + if let failure = observer.failure { throw failure } + throw error + } + defer { try? manager.removeItem(at: temporary) } + guard let http = response as? HTTPURLResponse, http.statusCode == 200, + let finalURL = response.url, Self.acceptsDownloadURL(finalURL) else { throw Failure.response } + if let failure = observer.failure { throw failure } + if response.expectedContentLength >= 0 && response.expectedContentLength != release.byteSize { throw Failure.size } + progress(.init(stage: .verifying, receivedBytes: release.byteSize, totalBytes: release.byteSize)) + try verify(temporary, size: release.byteSize, sha: release.packageSHA256) + let stagedPackage = stage.appendingPathComponent("verified.package") + try copyFile(temporary, stagedPackage) + try manager.setAttributes([.posixPermissions: 0o444], ofItemAtPath: stagedPackage.path) + // A second title with the same package may have filled the cache. + if manager.fileExists(atPath: cached.path) { + try verify(cached, size: release.byteSize, sha: release.packageSHA256) + try manager.removeItem(at: stagedPackage) + } + else { try manager.moveItem(at: stagedPackage, to: cached) } + } + try Task.checkCancellation() + let original = stage.appendingPathComponent("Original") + try manager.createDirectory(at: original, withIntermediateDirectories: false) + let originalPackage = original.appendingPathComponent("package." + format) + try copyFile(cached, originalPackage) + try manager.setAttributes([.posixPermissions: 0o444], ofItemAtPath: originalPackage.path) + let originalFiles = original.appendingPathComponent("Files") + let relativeFiles: [String] + progress(.init(stage: .extracting, receivedBytes: 0, totalBytes: 0)) + let expandedAllowance: UInt64 + if let free = freeBytes() { + guard free > 64 * 1024 * 1024 else { throw Failure.insufficientSpace } + // Reserve space for both originals and writable copies. The native + // extractor enforces this budget before accepting each entry. + expandedAllowance = min(Self.maximumExpandedBytes, UInt64((free - 64 * 1024 * 1024) / 2)) + } else { expandedAllowance = Self.maximumExpandedBytes } + if format == "zip" { + do { + relativeFiles = try VCCLibraryArchive.extractZIP(at: originalPackage, toNewDirectory: originalFiles, + maximumExpandedBytes: expandedAllowance, maximumEntries: Self.maximumEntries, + shouldCancel: { Task.isCancelled }) + } catch { + if Task.isCancelled { throw CancellationError() } + throw error + } + } else { + guard UInt64(release.byteSize) <= expandedAllowance else { throw Failure.insufficientSpace } + try manager.createDirectory(at: originalFiles, withIntermediateDirectories: false) + let candidate = release.sourceURL.lastPathComponent + let name = Self.validRelative(candidate) && !candidate.contains("/") ? candidate : "Media." + format + try copyFile(cached, originalFiles.appendingPathComponent(name)) + relativeFiles = [name] + } + guard !relativeFiles.isEmpty, relativeFiles.count <= Self.maximumEntries, + relativeFiles.allSatisfy(Self.validRelative) else { throw Failure.invalidReceipt } + if let owned = release.ownedGame { + guard relativeFiles.contains(owned.diskPath) else { throw Failure.invalidMetadata } + try verify(originalFiles.appendingPathComponent(owned.diskPath), size: owned.diskByteSize, sha: owned.diskSHA256) + } + let sizes = try relativeFiles.map { try regularFile(originalFiles.appendingPathComponent($0)) } + let total = sizes.reduce(Int64(0), +) + guard UInt64(total) <= Self.maximumExpandedBytes else { throw Failure.size } + if let available = (try? manager.attributesOfFileSystem(forPath: root.path)[.systemFreeSize]) as? NSNumber, + available.int64Value < total + 16 * 1024 * 1024 { throw Failure.insufficientSpace } + let working = stage.appendingPathComponent("Working") + try manager.createDirectory(at: working, withIntermediateDirectories: false) + progress(.init(stage: .preparing, receivedBytes: 0, totalBytes: total)) + var copied: Int64 = 0 + var lastPreparationProgress = DispatchTime.now().uptimeNanoseconds + for (index, name) in relativeFiles.enumerated() { + try Task.checkCancellation() + let source = originalFiles.appendingPathComponent(name), target = working.appendingPathComponent(name) + try manager.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + try copyFile(source, target) + try manager.setAttributes([.posixPermissions: 0o444], ofItemAtPath: source.path) + copied += sizes[index] + let now = DispatchTime.now().uptimeNanoseconds + if index == relativeFiles.count - 1 || now &- lastPreparationProgress >= 100_000_000 { + progress(.init(stage: .preparing, receivedBytes: copied, totalBytes: total)) + lastPreparationProgress = now + } + } + let record = StoredReceipt(version: 1, releaseID: release.id, packageSHA256: release.packageSHA256, + installedAt: Date(), relativeFiles: relativeFiles, format: format) + let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys] + try encoder.encode(record).write(to: stage.appendingPathComponent("receipt.json"), options: .atomic) + try Task.checkCancellation() + let group = root.appendingPathComponent("Installations").appendingPathComponent(key) + try directory(group, create: true) + let final = group.appendingPathComponent(UUID().uuidString) + try manager.moveItem(at: stage, to: final) + progress(.init(stage: .complete, receivedBytes: total, totalBytes: total)) + return record.publicReceipt(in: final) + } + + private func freeBytes() -> Int64? { + ((try? manager.attributesOfFileSystem(forPath: root.path)[.systemFreeSize]) as? NSNumber)?.int64Value + } + private func cleanupAbandonedStages() throws { + let staging = root.appendingPathComponent(".Staging") + for stage in try manager.contentsOfDirectory(at: staging, includingPropertiesForKeys: nil) { + guard UUID(uuidString: stage.lastPathComponent) != nil else { continue } + try directory(stage, create: false) + let lockPath = root.appendingPathComponent(".Locks/stage-" + stage.lastPathComponent) + guard manager.fileExists(atPath: lockPath.path) else { continue } + let fd = open(lockPath.path, O_RDWR | O_NOFOLLOW) + guard fd >= 0 else { continue } + defer { close(fd) } + if flock(fd, LOCK_EX | LOCK_NB) == 0 { + defer { flock(fd, LOCK_UN) } + try manager.removeItem(at: stage) + } + } + } + private func verify(_ path: URL, size: Int64, sha: String) throws { + guard try regularFile(path) == size else { throw Failure.size } + let file = try FileHandle(forReadingFrom: path) + defer { try? file.close() } + var hasher = SHA256() + while let bytes = try file.read(upToCount: 1024 * 1024), !bytes.isEmpty { + try Task.checkCancellation(); hasher.update(data: bytes) + } + guard hasher.finalize().map({ String(format: "%02x", $0) }).joined() == sha else { throw Failure.fingerprint } + } + private func copyFile(_ source: URL, _ destination: URL) throws { + _ = try regularFile(source) + guard !manager.fileExists(atPath: destination.path), manager.createFile(atPath: destination.path, contents: nil, + attributes: [.posixPermissions: 0o644]) else { throw Failure.unsafeLocation } + let input = try FileHandle(forReadingFrom: source), output = try FileHandle(forWritingTo: destination) + defer { try? input.close(); try? output.close() } + while let bytes = try input.read(upToCount: 1024 * 1024), !bytes.isEmpty { + try Task.checkCancellation(); try output.write(contentsOf: bytes) + } + } + private struct StoredReceipt: Codable { + let version: Int + let releaseID: String + let packageSHA256: String + let installedAt: Date + let relativeFiles: [String] + let format: String + func publicReceipt(in directory: URL) -> SoftwareLibraryInstallationReceipt { + .init(releaseID: releaseID, packageSHA256: packageSHA256, installedAt: installedAt, + workingDirectory: directory.appendingPathComponent("Working"), relativeFiles: relativeFiles) + } + } + private func records(releaseID: String? = nil) throws -> [(URL, StoredReceipt)] { + if releaseID == nil { recoveryWarnings = [] } + try prepareRoot() + try cleanupAbandonedStages() + var result: [(URL, StoredReceipt)] = [] + let groups = try manager.contentsOfDirectory(at: root.appendingPathComponent("Installations"), includingPropertiesForKeys: nil) + for group in groups { + guard Self.validSHA(group.lastPathComponent), releaseID == nil || group.lastPathComponent == Self.releaseKey(releaseID!) else { continue } + do { result.append(contentsOf: try groupRecords(group)) } + catch { + // A damaged unrelated title cannot hide valid installations or + // block a new title. Its bytes remain available for recovery. + if releaseID != nil { throw error } + recoveryWarnings.append("An installation record could not be read. Its files were preserved at \(group.path). \(error.localizedDescription)") + } + } + return result + } + private func groupRecords(_ group: URL) throws -> [(URL, StoredReceipt)] { + try directory(group, create: false) + var result: [(URL, StoredReceipt)] = [] + for installation in try manager.contentsOfDirectory(at: group, includingPropertiesForKeys: nil) { + guard UUID(uuidString: installation.lastPathComponent) != nil else { continue } + try directory(installation, create: false) + let path = installation.appendingPathComponent("receipt.json") + guard manager.fileExists(atPath: path.path) else { continue } + guard try regularFile(path) <= 16 * 1024 * 1024 else { throw Failure.invalidReceipt } + let record: StoredReceipt + do { record = try JSONDecoder().decode(StoredReceipt.self, from: Data(contentsOf: path)) } + catch { throw Failure.invalidReceipt } + guard record.version == 1, Self.validID(record.releaseID), Self.releaseKey(record.releaseID) == group.lastPathComponent, + Self.validSHA(record.packageSHA256), !record.relativeFiles.isEmpty, + record.relativeFiles.count <= Self.maximumEntries, record.relativeFiles.allSatisfy(Self.validRelative), + Set(record.relativeFiles).count == record.relativeFiles.count, + ["zip", "ccc", "dsk", "os9"].contains(record.format) else { throw Failure.invalidReceipt } + try directory(installation.appendingPathComponent("Working"), create: false) + try directory(installation.appendingPathComponent("Original"), create: false) + _ = try regularFile(installation.appendingPathComponent("Original/package." + record.format)) + guard result.isEmpty else { throw Failure.invalidReceipt } + result.append((installation, record)) + } + return result + } + func recoverInstallations() throws -> [SoftwareLibraryInstallationReceipt] { + try records().map { $0.1.publicReceipt(in: $0.0) }.sorted { $0.installedAt < $1.installedAt } + } + /// Unregisters only. Original packages and all working files remain in place, + /// including media currently mounted in the emulator or modified by the user. + func forgetInstallation(releaseID: String) throws -> URL? { + guard Self.validID(releaseID), !active.contains(releaseID) else { throw Failure.busy } + try prepareRoot() + let lock = try acquireLock(Self.releaseKey(releaseID)) + defer { flock(lock, LOCK_UN); close(lock) } + guard let (directory, record) = try records(releaseID: releaseID).first else { return nil } + try manager.removeItem(at: directory.appendingPathComponent("receipt.json")) + return record.publicReceipt(in: directory).workingDirectory + } +} + +private final class LibraryDownloadObserver: NSObject, URLSessionDownloadDelegate, @unchecked Sendable { + private let expected: Int64 + private let progress: @Sendable (SoftwareLibraryInstallProgress) -> Void + private let lock = NSLock() + private var storedFailure: SoftwareLibraryInstaller.Failure? + private var lastProgressTime: UInt64? + private var reportedDownloadCompletion = false + var failure: SoftwareLibraryInstaller.Failure? { lock.lock(); defer { lock.unlock() }; return storedFailure } + init(expected: Int64, progress: @escaping @Sendable (SoftwareLibraryInstallProgress) -> Void) { + self.expected = expected; self.progress = progress + } + private func fail(_ failure: SoftwareLibraryInstaller.Failure, task: URLSessionTask) { + lock.lock(); storedFailure = failure; lock.unlock(); task.cancel() + } + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + guard totalBytesWritten <= expected, totalBytesExpectedToWrite <= expected else { fail(.size, task: downloadTask); return } + let now = DispatchTime.now().uptimeNanoseconds + lock.lock() + let isFinal = totalBytesWritten == expected && !reportedDownloadCompletion + let shouldReport = storedFailure == nil && (lastProgressTime == nil || isFinal + || now &- (lastProgressTime ?? now) >= 100_000_000) + if shouldReport { + lastProgressTime = now + if isFinal { reportedDownloadCompletion = true } + } + lock.unlock() + if shouldReport { progress(.init(stage: .downloading, receivedBytes: totalBytesWritten, totalBytes: expected)) } + } + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { + guard request.url.map(SoftwareLibraryInstaller.acceptsDownloadURL) == true else { + fail(.response, task: task); completionHandler(nil); return + } + completionHandler(request) + } + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { } +} diff --git a/platforms/macos/App/SoftwareLibraryLaunchPlan.swift b/platforms/macos/App/SoftwareLibraryLaunchPlan.swift new file mode 100644 index 0000000..fcb469c --- /dev/null +++ b/platforms/macos/App/SoftwareLibraryLaunchPlan.swift @@ -0,0 +1,337 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import CryptoKit + +/// A bounded interpretation of catalog data, not executable host instructions. +/// Preparation reads only the installed Working tree and never changes the machine. +struct SoftwareLibraryLaunchPlan: Sendable { + enum Profile: String, Sendable { case diskBasic = "disk-basic", romCartridge = "rom-cartridge", cocoSDC = "coco-sdc" } + enum CartridgeDevice: String, Sendable { case rom, orchestra90 } + struct Candidate: Identifiable, Equatable, Sendable { + let path: String + let mediaType: String + var id: String { path } + var label: String { path } + } + enum Failure: LocalizedError { + case invalidRecipe(String), unsafeMedia(String), missingMedia(String), unsupported(String), needsSelection([Candidate]) + var errorDescription: String? { + switch self { + case .invalidRecipe(let detail): return "This edition’s setup needs attention. " + detail + case .unsafeMedia(let detail): return "The installed media contains an unsafe file reference. " + detail + case .missingMedia(let detail): return "An installed file is missing. " + detail + case .unsupported(let detail): return detail + case .needsSelection: return "Choose the installed file to mount first. The catalog does not identify a startup file." + } + } + } + let workingDirectory: URL + private let canonicalWorkingDirectory: URL + let releaseID: String + let title: String + let profile: Profile + let use6309: Bool + let ramKiB: Int + let ramIndex: Int + let videoOutput: Int? + let controllerSlot: Int + let cartridgeDevice: CartridgeDevice + let floppyURLs: [Int: URL] + let cassetteURL: URL? + let cartridgeURL: URL? + let sdcFolderURL: URL? + let sdcInitialImages: [Int: String] + /// Plain BASIC lines without CR; the machine controller waits for readiness between lines. + let commands: [String] + let manualInstructions: String + let compatibilityNotes: [String] + let automaticallyStarts: Bool + let controls: LibraryJSON + private let curatedStartup: SoftwareLibraryOwnedGame? + var usesCuratedStartup: Bool { curatedStartup != nil } + + private static func supportsDisk(_ ext: String, profile: Profile) -> Bool { + switch profile { + case .diskBasic: return DiskFiles.extensions.contains(ext) + case .cocoSDC: return ["dsk", "jvc", "os9"].contains(ext) + case .romCartridge: return false + } + } + + /// Presentation only: downloaded files still undergo full preparation before + /// a restart is offered. Missing or ambiguous startup media remains Set Up. + static func hasAutomaticStartup(for release: SoftwareLibraryRelease) -> Bool { + guard let name = release.setup.configuration["profile"].string, + let profile = Profile(rawValue: name), + case .array(let members) = release.setup.selectedMembers, + !members.isEmpty, members.count <= 4 else { return false } + guard (try? recommendedCartridgeDevice(release.setup.configuration, profile: profile)) != nil else { return false } + var targets = Set() + for member in members { + guard let path = member["path"].string, validRelative(path), + let target = member["target"].string, targets.insert(target).inserted else { return false } + let ext = (path as NSString).pathExtension.lowercased() + switch profile { + case .romCartridge: + guard members.count == 1, target == "cartridge", ["ccc", "rom"].contains(ext) else { return false } + case .diskBasic: + guard (target == "media" && ["cas", "wav"].contains(ext)) || + (["disk0", "disk1", "disk2", "disk3"].contains(target) && Self.supportsDisk(ext, profile: profile)) else { return false } + case .cocoSDC: + guard ["disk0", "disk1"].contains(target), Self.supportsDisk(ext, profile: profile) else { return false } + } + } + return profile == .romCartridge || decodeCommands(release.setup.command)?.contains(where: startsSoftware) == true + } + + static func prepare(release: SoftwareLibraryRelease, receipt: SoftwareLibraryInstallationReceipt, + selectedMember: String? = nil) throws -> Self { + try release.validatePresentationMetadata() + guard receipt.releaseID == release.id, receipt.packageSHA256 == release.packageSHA256, + receipt.workingDirectory.isFileURL, receipt.workingDirectory.host.map({ $0.isEmpty || $0 == "localhost" }) != false, + receipt.workingDirectory.query == nil, receipt.workingDirectory.fragment == nil, + receipt.workingDirectory.lastPathComponent == "Working" else { + throw Failure.invalidRecipe("The installation does not match this catalog edition.") + } + let config = release.setup.configuration + guard let profileName = config["profile"].string, let profile = Profile(rawValue: profileName) else { + throw Failure.unsupported("This edition needs a custom machine setup. Its installed files and loading notes remain available.") + } + let cartridgeDevice = try recommendedCartridgeDevice(config, profile: profile) + for key in ["processor", "video"] where config[key] != .null { + guard config[key].string != nil else { throw Failure.invalidRecipe("Invalid " + key + " recommendation.") } + } + for key in ["ram_kib", "controller_slot", "cartridge_slot"] where config[key] != .null { + guard config[key].integer != nil else { throw Failure.invalidRecipe("Invalid " + key + " recommendation.") } + } + let cpu = config["processor"].string ?? "6809" + guard cpu == "6809" || cpu == "6309" else { throw Failure.invalidRecipe("Unsupported processor recommendation.") } + let ram = config["ram_kib"].integer ?? 2048 + guard let ramIndex = [128, 512, 2048, 8192].firstIndex(of: ram) else { throw Failure.invalidRecipe("Unsupported memory recommendation.") } + let slot = (profile == .romCartridge ? config["cartridge_slot"].integer : nil) ?? config["controller_slot"].integer ?? 4 + guard (1...4).contains(slot) else { throw Failure.invalidRecipe("The startup slot must be 1 through 4.") } + let video: Int? + switch config["video"].string { + case "rgb": video = 0 + case "composite": video = 1 + case nil: video = nil + default: throw Failure.invalidRecipe("Unsupported video recommendation.") + } + let root = receipt.workingDirectory.standardizedFileURL + try checkDirectory(root) + let known = Set(receipt.relativeFiles) + guard known.count == receipt.relativeFiles.count, receipt.relativeFiles.count <= 20_000, + receipt.relativeFiles.allSatisfy(validRelative) else { throw Failure.unsafeMedia("The installation inventory is invalid.") } + var selected: [(target: String, path: String)] = [] + guard case .array(let members) = release.setup.selectedMembers else { throw Failure.invalidRecipe("The startup media list is invalid.") } + for member in members { + guard let path = member["path"].string, let target = member["target"].string, + validRelative(path), known.contains(path) else { throw Failure.invalidRecipe("The startup file is not in this installation.") } + selected.append((target, path)) + } + // A user chooses only when the recipe has no selected startup media. + // Unlabelled .bin files are never guessed to be ROM cartridges. + if selected.isEmpty { + let candidates = receipt.relativeFiles.compactMap { path -> Candidate? in + let ext = (path as NSString).pathExtension.lowercased() + let type: String? + switch release.mediaType { + case "cartridge": type = ext == "ccc" ? "cartridge" : nil + case "cassette": type = ["cas", "wav"].contains(ext) ? "cassette" : nil + case "disk", "sdc": type = Self.supportsDisk(ext, profile: profile) ? "disk" : nil + default: type = nil + } + return type.map { Candidate(path: path, mediaType: $0) } + }.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending } + let choice: Candidate + if let selectedMember { + guard let match = candidates.first(where: { $0.path == selectedMember }) else { throw Failure.invalidRecipe("Choose a compatible file from this installation.") } + choice = match + } else if candidates.count == 1 { choice = candidates[0] } + else if !candidates.isEmpty { throw Failure.needsSelection(candidates) } + else { throw Failure.unsupported("No supported startup media has been identified for this edition. Open its installed files and use the loading notes to configure it manually.") } + selected = [(choice.mediaType == "cartridge" ? "cartridge" : choice.mediaType == "cassette" ? "media" : "disk0", choice.path)] + } else if selectedMember != nil { throw Failure.invalidRecipe("This edition already identifies its startup media.") } + guard selected.count <= 4, Set(selected.map(\.target)).count == selected.count else { throw Failure.invalidRecipe("Conflicting startup media assignments.") } + var floppies: [Int: URL] = [:] + var cassette: URL?, cartridge: URL? + var selectedSDC: [Int: URL] = [:] + for member in selected { + let url = try file(member.path, root: root) + let ext = url.pathExtension.lowercased() + switch member.target { + case "cartridge": + guard profile == .romCartridge, ["ccc", "rom"].contains(ext) else { throw Failure.invalidRecipe("The selected file is not a supported ROM cartridge.") } + cartridge = url + case "media": + guard profile == .diskBasic, ["cas", "wav"].contains(ext) else { throw Failure.invalidRecipe("The selected file is not a supported cassette.") } + cassette = url + case "disk0", "disk1", "disk2", "disk3": + guard Self.supportsDisk(ext, profile: profile), + let drive = Int(member.target.suffix(1)) else { throw Failure.invalidRecipe("Unsupported disk assignment.") } + if profile == .cocoSDC { + guard drive < 2 else { throw Failure.invalidRecipe("CoCo SDC has two drives.") } + selectedSDC[drive] = url + } else { floppies[drive] = url } + default: throw Failure.invalidRecipe("Unknown media target: " + member.target) + } + } + if profile == .romCartridge && cartridge == nil { throw Failure.invalidRecipe("A startup cartridge is required.") } + var sdcFolder: URL?, sdcNames: [Int: String] = [:] + if profile == .cocoSDC { + guard let first = selectedSDC.keys.sorted().first.flatMap({ selectedSDC[$0] }) else { throw Failure.invalidRecipe("Select an SDC startup image.") } + let folder: URL + if let relative = config["sd_working_directory"].string { + folder = try directory(relative, root: root) + } else { folder = first.deletingLastPathComponent() } + try inspectSDCTree(folder) + for (drive, url) in selectedSDC { + guard url.path.hasPrefix(folder.path + "/") else { throw Failure.invalidRecipe("The selected SDC image is outside its SD card folder.") } + let name = String(url.path.dropFirst(folder.path.count + 1)) + guard name.utf8.count <= 220, name.unicodeScalars.allSatisfy({ (32...126).contains($0.value) }), !name.contains("\"") else { + throw Failure.unsupported("This SD card image needs manual selection because its name cannot be entered safely in SDC-DOS.") + } + sdcNames[drive] = name + } + sdcFolder = folder + } + let decoded = members.isEmpty ? nil : decodeCommands(release.setup.command) + let canStart = cartridge != nil || (decoded?.contains(where: startsSoftware) == true) + var commands = canStart ? (decoded ?? []) : [] + // Mounting an image is separate from executing its program. Manual SDC + // editions still get their chosen image mounted before guidance appears. + if sdcFolder != nil { + commands = sdcNames.keys.sorted().map { "DRIVE \($0),\"\(sdcNames[$0]!)\"" } + commands + } + var instructions = release.setup.instructions.trimmingCharacters(in: .whitespacesAndNewlines) + if instructions.isEmpty { instructions = "The selected media is mounted. Follow its manual or directory listing to choose a program; no startup command has been established." } + if !canStart, let command = release.setup.command, !command.isEmpty { + instructions += "\n\nThe catalog’s loading sequence needs manual entry. Review it before typing: " + command.replacingOccurrences(of: "\\r", with: " → ") + } + return Self(workingDirectory: root, canonicalWorkingDirectory: root.resolvingSymlinksInPath(), releaseID: release.id, title: release.metadata["title"].string ?? release.name, + profile: profile, use6309: cpu == "6309", ramKiB: ram, ramIndex: ramIndex, + videoOutput: video, controllerSlot: slot, cartridgeDevice: cartridgeDevice, floppyURLs: floppies, cassetteURL: cassette, + cartridgeURL: cartridge, sdcFolderURL: sdcFolder, sdcInitialImages: sdcNames, + commands: commands, manualInstructions: instructions, + compatibilityNotes: release.setup.compatibilityNotes + release.setup.configurationRequirements, + automaticallyStarts: canStart, controls: release.setup.controls, + curatedStartup: release.ownedGame.flatMap { $0.firstPlayColdDOS ? $0 : nil }) + } + + private static func recommendedCartridgeDevice(_ config: LibraryJSON, profile: Profile) throws -> CartridgeDevice { + let value = config["cartridge_device"] + guard value != .null else { return .rom } + guard let name = value.string, let device = CartridgeDevice(rawValue: name), + profile == .romCartridge else { + throw Failure.unsupported("This edition specifies a cartridge device that automatic setup does not support. Its installed files and loading notes remain available for manual configuration.") + } + return device + } + + /// Recheck after a preview/dialog; a user or another process may have changed files. + func validateMedia() throws { + try Self.checkDirectory(workingDirectory) + guard workingDirectory.resolvingSymlinksInPath() == canonicalWorkingDirectory else { throw Failure.unsafeMedia("The working folder changed after setup was prepared.") } + if let curatedStartup { + // Verify the published original; working disks may contain saves/scores. + let original = try Self.file("Original/Files/" + curatedStartup.diskPath, root: workingDirectory.deletingLastPathComponent()) + let bytes = try Data(contentsOf: original, options: .mappedIfSafe) + guard bytes.count == curatedStartup.diskByteSize, + SHA256.hash(data: bytes).map({ String(format: "%02x", $0) }).joined() == curatedStartup.diskSHA256 else { + throw Failure.invalidRecipe("The original game disk no longer matches its verified startup recipe. Your working files are kept.") + } + } + for url in Array(floppyURLs.values) + [cassetteURL, cartridgeURL].compactMap({ $0 }) { + guard url.path.hasPrefix(workingDirectory.path + "/") else { throw Failure.unsafeMedia(url.lastPathComponent) } + _ = try Self.file(String(url.path.dropFirst(workingDirectory.path.count + 1)), root: workingDirectory) + } + if let sdcFolderURL { + guard sdcFolderURL == workingDirectory || sdcFolderURL.path.hasPrefix(workingDirectory.path + "/") else { throw Failure.unsafeMedia("The SD card folder left its installation.") } + if sdcFolderURL != workingDirectory { + _ = try Self.directory(String(sdcFolderURL.path.dropFirst(workingDirectory.path.count + 1)), root: workingDirectory) + } + try Self.inspectSDCTree(sdcFolderURL) + for name in sdcInitialImages.values { _ = try Self.file(name, root: sdcFolderURL) } + } + } + + private static func validRelative(_ path: String) -> Bool { + !path.isEmpty && path.utf8.count <= 4096 && !path.hasPrefix("/") && !path.contains("\\") && !path.contains(":") + && !path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + && path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." } + } + private static func checkDirectory(_ url: URL) throws { + guard let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]), values.isDirectory == true, + values.isSymbolicLink != true else { throw Failure.unsafeMedia(url.lastPathComponent) } + } + private static func checked(_ relative: String, root: URL, isDirectory: Bool) throws -> URL { + guard validRelative(relative) else { throw Failure.unsafeMedia(relative) } + var url = root + let components = relative.split(separator: "/") + for (index, component) in components.enumerated() { + url.appendPathComponent(String(component)) + guard let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey, .isRegularFileKey]), + values.isSymbolicLink != true else { throw Failure.missingMedia(relative) } + if index < components.count - 1 || isDirectory { + guard values.isDirectory == true else { throw Failure.unsafeMedia(relative) } + } else { guard values.isRegularFile == true else { throw Failure.unsafeMedia(relative) } } + } + guard url.resolvingSymlinksInPath().path.hasPrefix(root.resolvingSymlinksInPath().path + "/") else { throw Failure.unsafeMedia(relative) } + return url + } + private static func file(_ relative: String, root: URL) throws -> URL { try checked(relative, root: root, isDirectory: false) } + private static func directory(_ relative: String, root: URL) throws -> URL { try checked(relative, root: root, isDirectory: true) } + private static func inspectSDCTree(_ root: URL) throws { + try checkDirectory(root) + let keys: [URLResourceKey] = [.isSymbolicLinkKey, .isDirectoryKey, .isRegularFileKey] + var scanFailed = false + guard let entries = FileManager.default.enumerator(at: root, includingPropertiesForKeys: keys, + errorHandler: { _, _ in scanFailed = true; return false }) else { throw Failure.unsafeMedia("The SD card folder cannot be read.") } + var count = 0 + for case let url as URL in entries { + count += 1 + guard count <= 20_000 else { throw Failure.unsafeMedia("The SD card folder has too many entries.") } + let value = try url.resourceValues(forKeys: Set(keys)) + guard value.isSymbolicLink != true, value.isDirectory == true || value.isRegularFile == true else { throw Failure.unsafeMedia("The SD card folder contains a link or special file.") } + } + guard !scanFailed else { throw Failure.unsafeMedia("Part of the SD card folder cannot be read.") } + } + /// Recognize the bounded BASIC loading vocabulary used by reviewed recipes. + /// Unknown guest programs remain manual; nothing is passed to a host shell. + static func decodeCommands(_ input: String?) -> [String]? { + guard let input, input.utf8.count <= 4096 else { return nil } + let normalized = input.replacingOccurrences(of: "\\r", with: "\r").replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") + guard normalized.unicodeScalars.allSatisfy({ $0.value == 10 || (32...126).contains($0.value) }) else { return nil } + let lines = normalized.split(separator: "\n", omittingEmptySubsequences: true).map { String($0).trimmingCharacters(in: .whitespaces) } + guard !lines.isEmpty, lines.count <= 16, lines.allSatisfy({ !$0.isEmpty && $0.utf8.count <= 255 && validLine($0) }) else { return nil } + // Once software runs, later keystrokes could reach that program instead + // of BASIC. Same-line loader chains remain one guest BASIC statement. + guard !lines.dropLast().contains(where: startsSoftware) else { return nil } + return lines + } + private static func statements(_ line: String) -> [String]? { + var result: [String] = [], current = "", quoted = false + for character in line { + if character == "\"" { quoted.toggle() } + if character == ":" && !quoted { result.append(current.trimmingCharacters(in: .whitespaces)); current = "" } + else { current.append(character) } + } + guard !quoted else { return nil } + result.append(current.trimmingCharacters(in: .whitespaces)); return result + } + private static func validLine(_ line: String) -> Bool { + guard let parts = statements(line) else { return false } + let number = "(?:[0-9]+|&H[0-9A-F]+)" + let filename = "\\\"[^\\\"\\\\]{1,64}\\\"" + let patterns = ["(?:CLOADM?|RUN)(?: *" + filename + ")?", "LOADM *" + filename, + "LOAD *" + filename + " *, *R", "LOAD +CHR\\$\\(42\\) *, *R", + "EXEC(?: *" + number + ")?", "DOS(?: +[0-9]+)?", "DIR(?: +[0-3])?", + "PCLEAR *[0-9]+", "CLEAR *" + number + "(?: *, *" + number + ")?", + "POKE *" + number + " *, *" + number, "NEW"] + return parts.allSatisfy { part in patterns.contains { part.range(of: "^(?:" + $0 + ")$", options: [.regularExpression, .caseInsensitive]) != nil } } + } + private static func startsSoftware(_ line: String) -> Bool { + guard let parts = statements(line.uppercased()) else { return false } + return parts.contains { $0.hasPrefix("RUN") || $0.hasPrefix("EXEC") || $0.hasPrefix("DOS") || ($0.hasPrefix("LOAD") && $0.range(of: ", *R$", options: .regularExpression) != nil) } + } +} diff --git a/platforms/macos/App/SoftwareLibraryLaunchView.swift b/platforms/macos/App/SoftwareLibraryLaunchView.swift new file mode 100644 index 0000000..532f375 --- /dev/null +++ b/platforms/macos/App/SoftwareLibraryLaunchView.swift @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI + +#if !VCC_COMPANION_CLIENT +struct SoftwareLibraryLaunchPreviewView: View { + let preview: LibraryLaunchPreview + let confirm: () -> Void + let cancel: () -> Void + private var plan: SoftwareLibraryLaunchPlan { preview.plan } + private var setupName: String { + switch plan.profile { + case .diskBasic: return "Disk BASIC" + case .romCartridge: return plan.cartridgeDevice == .orchestra90 ? "Orchestra-90" : "ROM Cartridge" + case .cocoSDC: return "CoCo SDC" + } + } + var body: some View { + VStack(alignment: .leading, spacing: 18) { + Label(plan.automaticallyStarts ? "Start Software" : "Set Up Software", systemImage: "play.rectangle") + .font(.title2.weight(.semibold)) + Text(plan.title).font(.title3.weight(.medium)) + ScrollView { + VStack(alignment: .leading, spacing: 14) { + LabeledContent("Machine", value: "Color Computer 3") + LabeledContent("Processor", value: plan.use6309 ? "Hitachi 6309" : "Motorola 6809") + LabeledContent("Memory", value: plan.ramKiB >= 1024 ? "\(plan.ramKiB / 1024) MB" : "\(plan.ramKiB) KB") + LabeledContent("Setup", value: setupName) + LabeledContent("Video", value: DisplayOutput(rawValue: preview.prepared.profile.videoOutput)?.label ?? "Current signal") + if let previous = preview.prepared.previousSetup { + ForEach([1, 0], id: \.self) { port in + if previous.input[port].source != preview.prepared.profile.input[port].source { + Text((port == 0 ? "Right" : "Left") + " joystick input will change for this title’s controls.") + .font(.callout).foregroundStyle(.secondary) + } + } + } + Divider() + if let cart = plan.cartridgeURL { + LabeledContent(plan.cartridgeDevice == .orchestra90 ? "Orchestra-90" : "ROM cartridge", value: cart.lastPathComponent) + } + if let tape = plan.cassetteURL { Label(tape.lastPathComponent, systemImage: "recordingtape") } + ForEach(plan.floppyURLs.keys.sorted(), id: \.self) { drive in + LabeledContent("FD\(drive)", value: plan.floppyURLs[drive]!.lastPathComponent) + } + if let folder = plan.sdcFolderURL { Label("SD card folder: " + folder.lastPathComponent, systemImage: "sdcard") } + if !plan.compatibilityNotes.isEmpty { + Text(plan.compatibilityNotes.joined(separator: "\n\n")).font(.callout).foregroundStyle(.secondary) + } + if !plan.automaticallyStarts { + Label("Manual loading", systemImage: "keyboard").font(.headline) + Text(plan.manualInstructions).font(.callout).textSelection(.enabled) + } else if !plan.commands.isEmpty { + DisclosureGroup("Loading commands") { + Text(plan.commands.joined(separator: "\n")).font(.system(.callout, design: .monospaced)).textSelection(.enabled) + } + } + }.frame(maxWidth: .infinity, alignment: .leading) + }.frame(maxHeight: 330) + Text("Starting this setup restarts the CoCo and clears its current program. Unsaved media must be saved first.") + .font(.callout).fixedSize(horizontal: false, vertical: true) + if preview.prepared.previousSetup == nil { + Text("The current setup could not be captured for return. Your installed files will remain available.").font(.caption).foregroundStyle(.secondary) + } + HStack { + Button("Cancel", role: .cancel, action: cancel).keyboardShortcut(.cancelAction).accessibilityIdentifier("library-cancel-play") + Spacer() + Button(plan.automaticallyStarts ? "Start" : "Set Up", action: confirm) + .buttonStyle(.borderedProminent).keyboardShortcut(.defaultAction).accessibilityIdentifier("library-confirm-play") + } + }.padding(24).frame(width: 490) + } +} + +#endif + +struct SoftwareLibraryMediaChoiceView: View { + let choice: LibraryMediaChoice + let choose: (String) -> Void + let cancel: () -> Void + @State private var selection: String? + var body: some View { + VStack(alignment: .leading, spacing: 16) { + Label("Choose Starting Media", systemImage: "externaldrive").font(.title2.weight(.semibold)) + Text("This collection has more than one possible starting file. Choose the one described by its loading instructions.") + .font(.callout) + List(selection: $selection) { + ForEach(choice.candidates, id: \.path) { candidate in + Text(candidate.path).tag(candidate.path) + } + }.frame(height: 240).accessibilityIdentifier("library-starting-media") + Text(choice.release.setup.instructions).font(.callout).foregroundStyle(.secondary).lineLimit(6) + HStack { + Button("Cancel", role: .cancel, action: cancel).keyboardShortcut(.cancelAction) + Spacer() + Button("Continue") { if let selection { choose(selection) } } + .disabled(selection == nil).keyboardShortcut(.defaultAction) + } + }.padding(24).frame(width: 520) + } +} diff --git a/platforms/macos/App/SoftwareLibraryManual.swift b/platforms/macos/App/SoftwareLibraryManual.swift new file mode 100644 index 0000000..824f8b0 --- /dev/null +++ b/platforms/macos/App/SoftwareLibraryManual.swift @@ -0,0 +1,258 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import PDFKit +import CryptoKit + +/// Original PDF and plain-text bytes are verified and retained separately from disposable art. +actor SoftwareLibraryManualCache { + static let shared = SoftwareLibraryManualCache() + static let maximumBytes: Int64 = 512 * 1024 * 1024 + enum Failure: LocalizedError { + case unavailable, response, changed + var errorDescription: String? { + switch self { + case .unavailable: return "This manual is not yet available in the reader." + case .response: return "The manual could not be downloaded. Please try again." + case .changed: return "The manual did not match the catalog’s saved copy. Please try again later." + } + } + } + private let session: URLSession + init(session: URLSession? = nil) { + if let session { self.session = session } + else { + let config = URLSessionConfiguration.ephemeral + config.timeoutIntervalForRequest = 30; config.timeoutIntervalForResource = 300 + config.urlCache = nil + self.session = URLSession(configuration: config, delegate: ManualRedirects(), delegateQueue: nil) + } + } + static func accepts(_ url: URL) -> Bool { + url.scheme == "https" && url.host == "vccplus.brianholman.com" && url.user == nil && url.password == nil + && (url.port == nil || url.port == 443) && url.query == nil && url.fragment == nil + && url.path.hasPrefix("/dl/software/CoCoLibrary/Documents/Manuals/") && ["pdf", "txt"].contains(url.pathExtension.lowercased()) + && !url.pathComponents.contains("..") && !url.pathComponents.contains(".") && !url.path.contains("\\") + } + static func fingerprint(_ url: URL) throws -> String { + let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } + var hash = SHA256() + while let block = try handle.read(upToCount: 1024 * 1024), !block.isEmpty { + try Task.checkCancellation(); hash.update(data: block) + } + return hash.finalize().map { String(format: "%02x", $0) }.joined() + } + func localCopy(for asset: SoftwareLibraryAsset, directory: URL) async throws -> URL { + try Task.checkCancellation() + guard asset.isManual, let url = asset.manualURL, Self.accepts(url), + let hash = asset.sha256, hash.count == 64, hash.allSatisfy({ $0.isHexDigit }), + let size = asset.byteSize, size > 0, size <= (url.pathExtension.lowercased() == "txt" ? 1024 * 1024 : Self.maximumBytes), directory.isFileURL else { throw Failure.unavailable } + let target = directory.appendingPathComponent(hash.lowercased() + "." + url.pathExtension.lowercased()) + if let values = try? target.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]), + values.isRegularFile == true, values.isSymbolicLink != true, values.fileSize == Int(size), + try Self.fingerprint(target) == hash.lowercased() { return target } + var request = URLRequest(url: url); request.setValue("VCCPlus/SoftwareLibrary-Manual", forHTTPHeaderField: "User-Agent") + let (temporary, response) = try await session.download(for: request) + defer { try? FileManager.default.removeItem(at: temporary) } + try Task.checkCancellation() + guard let http = response as? HTTPURLResponse, http.statusCode == 200, + let final = http.url, Self.accepts(final) else { throw Failure.response } + let actualSize = try temporary.resourceValues(forKeys: [.fileSizeKey]).fileSize + guard actualSize == Int(size), try Self.fingerprint(temporary) == hash.lowercased() else { throw Failure.changed } + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + guard !((try? target.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) ?? false) else { throw Failure.unavailable } + let staged = directory.appendingPathComponent(UUID().uuidString + ".partial") + defer { try? FileManager.default.removeItem(at: staged) } + try FileManager.default.copyItem(at: temporary, to: staged) + try Task.checkCancellation() + if FileManager.default.fileExists(atPath: target.path) { + _ = try FileManager.default.replaceItemAt(target, withItemAt: staged) + } else { try FileManager.default.moveItem(at: staged, to: target) } + return target + } +} +private final class ManualRedirects: NSObject, URLSessionTaskDelegate { + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { + completionHandler(request.url.map(SoftwareLibraryManualCache.accepts) == true ? request : nil) + } +} + +@MainActor +final class SoftwareLibraryManualModel: ObservableObject { + @Published private(set) var asset: SoftwareLibraryAsset? + @Published private(set) var loading = false + @Published private(set) var error: String? + @Published private(set) var document: PDFDocument? + @Published private(set) var text: String? + let textView = NSTextView() + static func decodeText(_ data: Data) throws -> String { + guard !data.isEmpty, data.count <= 1024 * 1024, + !data.contains(where: { $0 < 32 && ![9, 10, 12, 13, 26].contains($0) }), + let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) else { + throw SoftwareLibraryManualCache.Failure.response + } + return text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") + .replacingOccurrences(of: "\u{0C}", with: "\n\n").replacingOccurrences(of: "\u{1A}", with: "") + } + func findInText() { + let item = NSMenuItem(); item.tag = NSTextFinder.Action.showFindInterface.rawValue + textView.performFindPanelAction(item) + } + @Published var page = 1 + @Published var searchText = "" + @Published var searchMessage = "" + let pdfView = PDFView() + private var task: Task? + private var directory: URL? + private var companion: (any CompanionLibraryAccess)? + func open(_ asset: SoftwareLibraryAsset, directory: URL, companion: (any CompanionLibraryAccess)? = nil) { + if self.asset?.id == asset.id && (document != nil || text != nil) { return } + task?.cancel(); self.asset = asset; self.directory = directory; self.companion = companion + document = nil; pdfView.document = nil; text = nil; textView.string = ""; page = 1; searchText = ""; searchMessage = ""; error = nil; loading = true + task = Task { + do { + let local: URL + if let companion { + let response = try await companion.libraryRequest(.init(operation: .manual, assetID: asset.id)) + if let message = response.errorMessage { throw CompanionLibraryFailure(message: message) } + guard let shared = response.assetFileURL, shared.isFileURL, + shared.host.map({ $0.isEmpty || $0 == "localhost" }) != false, + shared.query == nil, shared.fragment == nil else { throw SoftwareLibraryManualCache.Failure.response } + try await Task.detached(priority: .userInitiated) { + let values = try shared.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) + guard values.isRegularFile == true, values.isSymbolicLink != true, + let size = values.fileSize, size > 0, size <= 64 * 1024 * 1024 else { throw SoftwareLibraryManualCache.Failure.response } + }.value + local = shared + } else { + local = try await SoftwareLibraryManualCache.shared.localCopy(for: asset, directory: directory) + } + try Task.checkCancellation() + if local.pathExtension == "txt" { + let bytes = try await Task.detached(priority: .userInitiated) { try Data(contentsOf: local) }.value + try Task.checkCancellation() + let decoded = try Self.decodeText(bytes) + text = decoded; textView.string = decoded + } else { + guard let loaded = PDFDocument(url: local), !loaded.isLocked, loaded.pageCount > 0 else { throw SoftwareLibraryManualCache.Failure.response } + document = loaded; pdfView.document = loaded; pdfView.autoScales = true + } + loading = false + } catch is CancellationError { } + catch { self.error = error.localizedDescription; loading = false } + } + } + func cancel() { task?.cancel(); loading = false } + func retry() { if let asset, let directory { open(asset, directory: directory, companion: companion) } } + func goToPage() { + guard let document else { return } + page = min(max(page, 1), document.pageCount) + if let target = document.page(at: page - 1) { pdfView.go(to: target) } + } + func findNext() { + guard let document, !searchText.isEmpty else { return } + let selection = document.findString(searchText, fromSelection: pdfView.currentSelection, withOptions: .caseInsensitive) + ?? document.findString(searchText, fromSelection: nil, withOptions: .caseInsensitive) + if let selection { pdfView.setCurrentSelection(selection, animate: false); pdfView.go(to: selection); searchMessage = "" } + else { searchMessage = "No matching text. Scanned pages may not contain searchable text." } + } +} + +struct SoftwareLibraryManualView: View { + @ObservedObject var model: SoftwareLibraryManualModel + @State private var showPages = false + var body: some View { + VStack(spacing: 0) { + HStack { + Label(model.asset?.name ?? "Software Manual", systemImage: "book.closed").font(.headline).lineLimit(2) + Spacer() + if model.text != nil { + Button { model.findInText() } label: { Label("Find", systemImage: "magnifyingglass") } + .accessibilityIdentifier("manual-text-find") + } + if model.document != nil { + Button { showPages.toggle() } label: { Image(systemName: "sidebar.left") }.help(showPages ? "Hide page thumbnails" : "Show page thumbnails").accessibilityLabel(showPages ? "Hide page thumbnails" : "Show page thumbnails") + Button { model.pdfView.zoomOut(nil) } label: { Image(systemName: "minus.magnifyingglass") }.help("Zoom out").accessibilityLabel("Zoom out") + Button { model.pdfView.zoomIn(nil) } label: { Image(systemName: "plus.magnifyingglass") }.help("Zoom in").accessibilityLabel("Zoom in") + Button("Fit Page") { model.pdfView.autoScales = true }.accessibilityIdentifier("manual-fit") + } + }.padding(12) + if let document = model.document { + HStack { + Button { model.pdfView.goToPreviousPage(nil) } label: { Image(systemName: "chevron.left") }.help("Previous page").accessibilityLabel("Previous page").disabled(model.page <= 1) + TextField("Page", value: $model.page, format: .number).frame(width: 45).onSubmit { model.goToPage() }.accessibilityLabel("Page number") + Text("of \(document.pageCount)").foregroundStyle(.secondary) + Button { model.pdfView.goToNextPage(nil) } label: { Image(systemName: "chevron.right") }.help("Next page").accessibilityLabel("Next page").disabled(model.page >= document.pageCount) + Spacer() + TextField("Find in manual", text: $model.searchText).frame(maxWidth: 230).onSubmit { model.findNext() }.accessibilityIdentifier("manual-search") + Button("Find Next") { model.findNext() }.disabled(model.searchText.isEmpty) + }.padding(.horizontal, 12).padding(.bottom, 10) + } + Divider() + if model.document != nil { + HStack(spacing: 0) { + if showPages { ManualPages(view: model.pdfView).frame(width: 115) } + ManualPDF(view: model.pdfView).accessibilityIdentifier("manual-pdf") + } + } else if model.text != nil { + ManualText(view: model.textView).accessibilityIdentifier("manual-text") + } else if model.loading { + VStack(spacing: 12) { ProgressView("Downloading manual…"); Button("Cancel") { model.cancel() } }.frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + VStack(spacing: 12) { + Image(systemName: "book.closed").font(.largeTitle) + Text(model.error ?? "Choose a manual from the Software Library.").multilineTextAlignment(.center) + if model.asset != nil { Button("Try Again") { model.retry() } } + }.padding().frame(maxWidth: .infinity, maxHeight: .infinity) + } + Divider() + VStack(alignment: .leading, spacing: 4) { + if !model.searchMessage.isEmpty { Text(model.searchMessage).foregroundStyle(.secondary) } + HStack { + Text(model.asset?.credit ?? "Manual preserved by Color Computer Archive").foregroundStyle(.secondary) + Spacer() + if let asset = model.asset { Link(asset.matchStatus == "project-owned" ? "Project source" : "Archive source", destination: asset.sourceURL) } + } + }.font(.caption).padding(10) + }.frame(minWidth: 620, minHeight: 480) + .onReceive(NotificationCenter.default.publisher(for: .PDFViewPageChanged, object: model.pdfView)) { _ in + if let page = model.pdfView.currentPage, let document = model.document { model.page = document.index(for: page) + 1 } + } + .onDisappear { model.cancel() } + } +} +private struct ManualPDF: NSViewRepresentable { + let view: PDFView + func makeNSView(context: Context) -> PDFView { + view.displayMode = .singlePageContinuous; view.displaysPageBreaks = true; view.backgroundColor = .windowBackgroundColor + return view + } + func updateNSView(_ nsView: PDFView, context: Context) { } +} +private struct ManualPages: NSViewRepresentable { + let view: PDFView + func makeNSView(context: Context) -> PDFThumbnailView { + let thumbnails = PDFThumbnailView(); thumbnails.pdfView = view; thumbnails.thumbnailSize = NSSize(width: 85, height: 110) + return thumbnails + } + func updateNSView(_ nsView: PDFThumbnailView, context: Context) { nsView.pdfView = view } +} + +private struct ManualText: NSViewRepresentable { + let view: NSTextView + func makeNSView(context: Context) -> NSScrollView { + let scroll = NSScrollView() + scroll.hasVerticalScroller = true; scroll.autohidesScrollers = true + view.isEditable = false; view.isSelectable = true; view.isRichText = false + view.font = .monospacedSystemFont(ofSize: 14, weight: .regular) + view.textColor = .textColor; view.backgroundColor = .textBackgroundColor + view.textContainerInset = NSSize(width: 18, height: 18) + view.isVerticallyResizable = true; view.isHorizontallyResizable = false + view.autoresizingMask = [.width]; view.textContainer?.widthTracksTextView = true + view.usesFindBar = true; view.isIncrementalSearchingEnabled = true + view.setAccessibilityLabel("Readme and instructions") + scroll.documentView = view + return scroll + } + func updateNSView(_ nsView: NSScrollView, context: Context) { } +} diff --git a/platforms/macos/App/SoftwareLibraryModel.swift b/platforms/macos/App/SoftwareLibraryModel.swift new file mode 100644 index 0000000..9048c4f --- /dev/null +++ b/platforms/macos/App/SoftwareLibraryModel.swift @@ -0,0 +1,705 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import Combine +import AppKit + +#if !VCC_COMPANION_CLIENT +/// Native review stays attached to its window and cannot strand shutdown on a +/// canceled download/launch task waiting for a modal response. +@MainActor +final class LibraryReviewSheet { + private let alert: NSAlert + private let parent: NSWindow + private var canceled = false + init(alert: NSAlert, parent: NSWindow) { self.alert = alert; self.parent = parent } + func present() async -> NSApplication.ModalResponse { + await withTaskCancellationHandler { + await withCheckedContinuation { done in + guard !Task.isCancelled, !canceled, parent.attachedSheet == nil else { + done.resume(returning: .cancel); return + } + alert.beginSheetModal(for: parent) { done.resume(returning: $0) } + } + } onCancel: { + Task { @MainActor in + self.canceled = true + if self.alert.window.sheetParent === self.parent { + self.parent.endSheet(self.alert.window, returnCode: .cancel) + } + } + } + } +} +#endif + +struct LibraryCategory: Identifiable, Sendable { + let id: String + let name: String + let children: [LibraryCategory]? + static func tree(_ paths: [String], prefix: String = "") -> [Self] { + let names = Set(paths.compactMap { path -> String? in + guard path.hasPrefix(prefix) else { return nil } + return path.dropFirst(prefix.count).split(separator: "/").first.map(String.init) + }) + return names.sorted().map { name in + let path = prefix + name + let descendants = tree(paths.filter { $0.hasPrefix(path + "/") }, prefix: path + "/") + return Self(id: path, name: name, children: descendants.isEmpty ? nil : descendants) + } + } +} + +struct LibraryBrowseQuery: Equatable, Sendable { + enum Scope: String, CaseIterable { case showcase, started, all, favorites, installed } + enum Sort: String, CaseIterable { case title = "Title", modified = "Last Modified", size = "Download Size" } + var scope: Scope = .started + var text = "" + var category = "" + var softwareType = "" + var media = "" + var system = "" + var evidence = "" + var sort: Sort = .title + var environment = "" + var processor = "" + var hardware = "" + var hardwareUse = "" + var displayFeature = "" + static let environmentLabels = ["basic": "BASIC", "disk-basic": "Disk BASIC", "os9": "OS-9 / NitrOS-9", "unknown": "Environment unspecified"] + static let processorLabels = ["6309": "Requires Hitachi 6309", "either": "Supports 6809 and 6309", "unknown": "Processor requirement unspecified"] + static let hardwareLabels = ["speech-sound": "Speech/Sound", "orchestra90": "Orchestra-90", "joystick": "Joystick"] + static let hardwareUseLabels = ["required": "Required", "optional": "Optional", "unspecified": "Requirement unspecified"] + static let displayLabels = ["semigraphics": "Semigraphics", "SG-8": "Semigraphics-8", "SG-12": "Semigraphics-12", "SG-24": "Semigraphics-24"] + var additionalFilterLabels: [String] { + [Self.environmentLabels[environment], Self.processorLabels[processor], + Self.hardwareLabels[hardware].map { label in + hardwareUse.isEmpty ? label : label + " — " + (Self.hardwareUseLabels[hardwareUse] ?? hardwareUse) + }, Self.displayLabels[displayFeature]].compactMap { $0 } + } + func matchesHardware(_ release: SoftwareLibraryRelease) -> Bool { + hardware.isEmpty || (release.hardwareSupport[hardware] != nil && + (hardwareUse.isEmpty || release.hardwareSupport[hardware] == hardwareUse)) + } + func matchesDisplay(_ release: SoftwareLibraryRelease) -> Bool { + displayFeature.isEmpty || (displayFeature == "semigraphics" ? !release.semigraphicsModes.isEmpty : release.semigraphicsModes.contains(displayFeature)) + } + // Getting Started is an explicit catalog choice, independent of runtime + // checks, provenance and former hard-coded starter selections. + static func isGettingStarted(_ release: SoftwareLibraryRelease) -> Bool { + release.gettingStarted + } + static func types(of release: SoftwareLibraryRelease, related: [SoftwareLibraryRelease] = []) -> [String] { + release.browseCategories.isEmpty ? [type(of: release, related: related)] : release.browseCategories + } + static func matchesCategory(_ category: String, release: SoftwareLibraryRelease) -> Bool { + if release.ownedGame != nil { return category.isEmpty || release.browseCategories.contains(category) } + return category.isEmpty || release.category == category || release.category.hasPrefix(category + "/") || + release.browseCategories.contains(category) + } + func matches(_ release: SoftwareLibraryRelease, titleName: String, related: [SoftwareLibraryRelease] = []) -> Bool { + guard softwareType.isEmpty || Self.types(of: release, related: related).contains(softwareType), + Self.matchesCategory(category, release: release), + media.isEmpty || release.mediaType == media, system.isEmpty || release.system == system else { return false } + guard environment.isEmpty || release.environment == environment, + processor.isEmpty || release.processorRequirement == processor, + matchesHardware(release), matchesDisplay(release) else { return false } + switch evidence { + case "checked": guard release.setup.status == "spot-checked" else { return false } + case "manual": guard release.setup.status == "manual-setup" else { return false } + case "notes": guard !release.setup.compatibilityNotes.isEmpty || !release.setup.configurationRequirements.isEmpty else { return false } + default: break + } + let haystack = titleName + " " + release.searchText + return text.split(whereSeparator: \.isWhitespace).allSatisfy { haystack.localizedStandardContains(String($0)) } + } + static func type(of release: SoftwareLibraryRelease, related: [SoftwareLibraryRelease] = []) -> String { + if let primary = release.primaryBrowseCategory { return primary } + func categoryType(_ release: SoftwareLibraryRelease) -> String? { + let components = release.category.split(separator: "/").map(String.init) + let names: Set = ["Applications", "Games", "Music", "Educational", "Demos", "Utilities", "Programming", "Magazines", "Books", "Pictures", "Hardware", "Operating Systems"] + // The first software category is authoritative; a game's demo is still a game. + if let name = components.first(where: names.contains) { return name } + if components.contains(where: { $0.hasPrefix("NitrOS-9") || $0.hasPrefix("OS-9 L2") }) { return "Operating Systems" } + if components.contains("Blank disks") || components.contains("Empty Hard Disk") { return "Blank Media" } + return nil + } + if let own = categoryType(release) { return own } + let types = Set(related.compactMap(categoryType)) + return types.count == 1 ? types.first! : "Other" + } + func apply(to titles: [SoftwareLibraryTitle], favorites: Set, installed: Set) -> [LibraryBrowseRow] { + var rows = titles.compactMap { title -> LibraryBrowseRow? in + if scope == .favorites && !favorites.contains(title.id) { return nil } + let matches = title.releases.filter { + (scope != .started || Self.isGettingStarted($0)) && + (scope != .showcase || $0.assets.contains(where: { SoftwareLibraryArtworkCache.canDisplay($0) })) && + (scope != .installed || installed.contains($0.id)) && self.matches($0, titleName: title.name, related: title.releases) + } + guard !matches.isEmpty else { return nil } + return LibraryBrowseRow(title: title, matchingReleases: matches) + } + rows.sort { a, b in + let featuredGrouping = !category.isEmpty || !softwareType.isEmpty + let aFeatured = featuredGrouping && a.categoryFeatured + let bFeatured = featuredGrouping && b.categoryFeatured + if aFeatured != bFeatured { return aFeatured } + switch aFeatured ? .title : sort { + case .modified: + let av = a.matchingReleases.compactMap(\.modifiedAt).max() ?? "" + let bv = b.matchingReleases.compactMap(\.modifiedAt).max() ?? "" + if av != bv { return av > bv } + case .size: + let av = a.matchingReleases.map(\.byteSize).max() ?? 0 + let bv = b.matchingReleases.map(\.byteSize).max() ?? 0 + if av != bv { return av > bv } + case .title: break + } + let order = a.title.name.localizedStandardCompare(b.title.name) + return order == .orderedSame ? a.id < b.id : order == .orderedAscending + } + return rows + } +} +struct LibraryBrowseRow: Identifiable, Sendable { + let title: SoftwareLibraryTitle + let matchingReleases: [SoftwareLibraryRelease] + var id: String { title.id } + var name: String { title.name } + var categoryFeatured: Bool { matchingReleases.contains(where: \.categoryFeatured) } + var formats: String { Set(matchingReleases.map(\.mediaLabel)).sorted().joined(separator: ", ") } + var modified: String { matchingReleases.compactMap(\.modifiedAt).max() ?? "Unknown" } + var size: String { ByteCountFormatter.string(fromByteCount: matchingReleases.map(\.byteSize).max() ?? 0, countStyle: .file) } +} + +#if !VCC_COMPANION_CLIENT +struct LibraryLaunchPreview: Identifiable { + let id = UUID() + let prepared: PreparedLibraryLaunch + var plan: SoftwareLibraryLaunchPlan { prepared.plan } +} +#endif +struct LibraryMediaChoice: Identifiable { + let id = UUID() + let release: SoftwareLibraryRelease + let receipt: SoftwareLibraryInstallationReceipt + let candidates: [CompanionLibraryDisk] +} + +@MainActor +final class SoftwareLibraryModel: ObservableObject { + let state: SoftwareLibraryState + let manual = SoftwareLibraryManualModel() + let artworkDirectory: URL + @Published private(set) var catalog: SoftwareLibraryCatalog? + @Published private(set) var rows: [LibraryBrowseRow] = [] + @Published private(set) var softwareTypes: [String] = [] + @Published private(set) var categories: [LibraryCategory] = [] + @Published private(set) var loading = false + @Published private(set) var filtering = false + @Published private(set) var error: String? + @Published var query = LibraryBrowseQuery() { didSet { if query != oldValue { filter() } } } + @Published var selection: String? + @Published var layout = "Shelf" + let companionAccess: (any CompanionLibraryAccess)? + private let insertCompanionDisk: ((URL) async throws -> Void)? + #if !VCC_COMPANION_CLIENT + let installer: SoftwareLibraryInstaller + let machine: MachineModel? + private let sourceImporter: SoftwareLibrarySourceImporter + private let sourceWorkspaceIdentity: (() -> UUID)? + private let openSourceProject: ((URL, UUID, String?) async throws -> Bool)? + @Published var launchPreview: LibraryLaunchPreview? + #endif + @Published var mediaChoice: LibraryMediaChoice? + @Published private(set) var launchBusy = false + @Published private(set) var launchError: String? + @Published private(set) var launchMessage: String? + #if !VCC_COMPANION_CLIENT + @Published private(set) var previousSetup: ConfigurationProfile? + #endif + @Published private(set) var machineFocusRequest = 0 + @Published private(set) var sourceFocusRequest = 0 + @Published private(set) var importingSourceID: String? + @Published private(set) var sourceImportMessage: String? + @Published private(set) var sourceImportError: String? + @Published private(set) var sourceImportFraction: Double? + @Published private(set) var importedSourceDirectory: URL? + @Published private(set) var sourceDetailsReleaseID: String? + private var sourceImportGeneration = UUID() + private var sourceImportTask: Task? + private var launchTask: Task? + @Published private(set) var installingReleaseID: String? + @Published private(set) var installProgress: SoftwareLibraryInstallProgress? + @Published private(set) var installationErrors: [String: String] = [:] + @Published private(set) var installationNotice: String? + @Published private(set) var recoveringInstallations = true + private var installationGeneration = UUID() + private var installationTask: Task? + private var task: Task? + private var generation = 0 + private var subscriptions: Set = [] + #if !VCC_COMPANION_CLIENT + init(state: SoftwareLibraryState, artworkDirectory: URL? = nil, machine: MachineModel? = nil, + sourceWorkspaceIdentity: (() -> UUID)? = nil, + openSourceProject: ((URL, UUID, String?) async throws -> Bool)? = nil) { + companionAccess = nil; insertCompanionDisk = nil + self.state = state + self.machine = machine + self.sourceWorkspaceIdentity = sourceWorkspaceIdentity; self.openSourceProject = openSourceProject + #if VCC_UI_TESTING + sourceImporter = SoftwareLibrarySourceImporter(cacheDirectory: state.directory.appendingPathComponent("SourcePackages"), + configuration: SoftwareLibraryInstallFixture.exclusiveEnabled ? SoftwareLibraryInstallFixture.sourceConfiguration : nil) + #else + sourceImporter = SoftwareLibrarySourceImporter(cacheDirectory: state.directory.appendingPathComponent("SourcePackages")) + #endif + #if VCC_UI_TESTING + installer = SoftwareLibraryInstallFixture.enabled ? SoftwareLibraryInstallFixture.installer(root: state.directory) : SoftwareLibraryInstaller(root: state.directory) + #else + installer = SoftwareLibraryInstaller(root: state.directory) + #endif + #if VCC_UI_TESTING + self.artworkDirectory = SoftwareLibraryInstallFixture.exclusiveEnabled ? state.directory.appendingPathComponent("FixtureArtwork") + : artworkDirectory ?? FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("com.brianholman.vccplus.oss.mac/SoftwareLibrary/Artwork") + if SoftwareLibraryInstallFixture.exclusiveEnabled { + do { try SoftwareLibraryInstallFixture.seedExclusiveAssets(manualDirectory: state.directory.appendingPathComponent("Manuals"), artworkDirectory: self.artworkDirectory) } + catch { self.error = error.localizedDescription } + } + #else + self.artworkDirectory = artworkDirectory ?? FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("com.brianholman.vccplus.oss.mac/SoftwareLibrary/Artwork") + #endif + state.objectWillChange.sink { [weak self] in + Task { @MainActor [weak self] in self?.objectWillChange.send(); self?.filter() } + }.store(in: &subscriptions) + } + #endif + init(companion: any CompanionLibraryAccess, onInsertDisk: @escaping (URL) async throws -> Void) { + companionAccess = companion; insertCompanionDisk = onInsertDisk + state = SoftwareLibraryState(companion: companion) + artworkDirectory = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCompanionPresentation") + #if !VCC_COMPANION_CLIENT + machine = nil; installer = SoftwareLibraryInstaller(root: state.directory) + sourceWorkspaceIdentity = nil; openSourceProject = nil + sourceImporter = SoftwareLibrarySourceImporter(cacheDirectory: state.directory.appendingPathComponent("SourcePackages")) + #endif + // A disk companion starts with all eligible software, including titles + // without cover art. Later snapshots preserve explicit scope choices. + query = LibraryBrowseQuery(scope: .all) + state.objectWillChange.sink { [weak self] in + Task { @MainActor [weak self] in self?.objectWillChange.send(); self?.filter() } + }.store(in: &subscriptions) + } + var isDiskCompanion: Bool { companionAccess != nil } + var canOpenSource: Bool { + #if !VCC_COMPANION_CLIENT + return !isDiskCompanion && sourceWorkspaceIdentity != nil && openSourceProject != nil + #else + return false + #endif + } + func chooseSourceDestination(_ release: SoftwareLibraryRelease) { + #if !VCC_COMPANION_CLIENT + guard canOpenSource, release.ownedGame != nil, importingSourceID == nil else { return } + let panel = NSSavePanel() + panel.title = "Save Source Project"; panel.prompt = "Download Source" + panel.message = "Choose a new personal project folder. Opening source does not build, run or change the CoCo." + panel.canCreateDirectories = true + panel.nameFieldStringValue = (selectedRow?.name ?? "CoCo") + " Source" + panel.begin { [weak self] response in + guard response == .OK, let directory = panel.url else { return } + self?.importSource(release, to: directory) + } + #endif + } + func importSource(_ release: SoftwareLibraryRelease, to directory: URL) { + #if !VCC_COMPANION_CLIENT + guard importingSourceID == nil, let source = release.ownedGame?.source, + let expected = sourceWorkspaceIdentity?(), let openSourceProject else { return } + importingSourceID = release.id; sourceImportMessage = "Downloading source…" + sourceDetailsReleaseID = release.id + let attempt = UUID(); sourceImportGeneration = attempt + sourceImportError = nil; sourceImportFraction = nil; importedSourceDirectory = nil + sourceImportTask = Task { + defer { importingSourceID = nil; sourceImportTask = nil; sourceImportFraction = nil } + do { + let result = try await sourceImporter.importProject(source, to: directory) { progress in + Task { @MainActor in + guard self.importingSourceID == release.id, self.sourceImportGeneration == attempt else { return } + self.sourceImportFraction = progress.fraction + switch progress.stage { + case .downloading: self.sourceImportMessage = "Downloading source…" + case .verifying: self.sourceImportMessage = "Verifying source…" + case .extracting: self.sourceImportMessage = "Preparing source files…" + case .checking: self.sourceImportMessage = "Checking the C project…" + case .complete: break + } + } + } + importedSourceDirectory = result.importedDirectory + try Task.checkCancellation() + let opened = try await openSourceProject(result.projectDirectory, expected, source.buildConfiguration) + sourceImportMessage = opened ? "Your source copy is open in C Development. Build when you are ready." + : "Your source copy is saved. The current C project is still open." + if opened { sourceFocusRequest += 1 } + } catch is CancellationError { + sourceImportMessage = importedSourceDirectory == nil ? "Source download canceled." : "Your source copy is saved." + } catch { sourceImportError = error.localizedDescription; sourceImportMessage = nil } + } + #endif + } + func cancelSourceImport() { sourceImportTask?.cancel() } + var canLaunch: Bool { + if insertCompanionDisk != nil { return true } + #if !VCC_COMPANION_CLIENT + return machine != nil + #else + return false + #endif + } + var hasPreviousSetup: Bool { + #if !VCC_COMPANION_CLIENT + return previousSetup != nil + #else + return false + #endif + } + var hasPendingLaunch: Bool { + #if !VCC_COMPANION_CLIENT + return launchPreview != nil || mediaChoice != nil + #else + return mediaChoice != nil + #endif + } + func launchLabel(_ release: SoftwareLibraryRelease, installed: Bool) -> String { + if isDiskCompanion { return installed ? "Insert Disk…" : "Download & Insert…" } + #if !VCC_COMPANION_CLIENT + if release.ownedGame?.firstPlayColdDOS == true { return installed ? "Play" : "Download & Play" } + return SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release) + ? (installed ? "Play…" : "Download & Play…") : (installed ? "Set Up…" : "Download & Set Up…") + #else + return "Insert Disk…" + #endif + } + func launchSymbol(_ release: SoftwareLibraryRelease) -> String { + if isDiskCompanion { return "externaldrive" } + #if !VCC_COMPANION_CLIENT + return SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release) ? "play.fill" : "desktopcomputer" + #else + return "externaldrive" + #endif + } + func focusDisplay() { + #if !VCC_COMPANION_CLIENT + machine?.focusDisplay() + #endif + } + func load(from url: URL? = SoftwareLibraryCatalog.bundledURL()) async { + guard catalog == nil, !loading else { return } + loading = true; error = nil + if let companionAccess { + defer { loading = false; recoveringInstallations = false } + do { + let response = try await companionAccess.libraryRequest(.init(operation: .snapshot)) + try acceptCompanion(response) + guard catalog != nil else { throw CompanionLibraryFailure(message: "VCC Plus did not return its disk catalog.") } + } catch { self.error = error.localizedDescription } + return + } + #if !VCC_COMPANION_CLIENT + await refreshInstallations() + #if VCC_UI_TESTING + if SoftwareLibraryInstallFixture.enabled { + catalog = SoftwareLibraryInstallFixture.catalog + categories = LibraryCategory.tree(catalog!.categories) + updateSoftwareTypes(catalog!) + query.scope = .all + filter(); loading = false; return + } + #endif + do { + guard let url else { throw SoftwareLibraryCatalog.Failure.missing } + let snapshot = try await SoftwareLibraryCatalog.load(from: url) + catalog = snapshot; categories = LibraryCategory.tree(snapshot.categories); updateSoftwareTypes(snapshot); filter() + } catch { self.error = error.localizedDescription } + loading = false + #endif + } + private func acceptCompanion(_ response: CompanionLibraryResponse) throws { + if let message = response.errorMessage { throw CompanionLibraryFailure(message: message) } + if let snapshot = response.snapshot { + // The service filters too; defend the UI and edition picker independently. + let filtered = snapshot.catalog.companionDisksOnly + catalog = filtered; categories = LibraryCategory.tree(filtered.categories) + updateSoftwareTypes(filtered); state.applyRemoteSnapshot(snapshot); filter() + } + } + var selectedRow: LibraryBrowseRow? { rows.first { $0.id == selection } } + var selectedRelease: SoftwareLibraryRelease? { + guard let row = selectedRow else { return nil } + if let preferred = state.preferredReleaseID(for: row.id), let release = row.matchingReleases.first(where: { $0.id == preferred }) { return release } + return row.matchingReleases.first + } + func chooseRelease(_ id: String) { + guard let title = selectedRow?.title, let chosen = title.releases.first(where: { $0.id == id }) else { return } + // Keep the user's context when another edition still matches it. Clear + // only constraints that would hide their explicit edition choice. + var next = query + if !next.softwareType.isEmpty && !LibraryBrowseQuery.types(of: chosen, related: title.releases).contains(next.softwareType) { next.softwareType = "" } + if !next.category.isEmpty && !LibraryBrowseQuery.matchesCategory(next.category, release: chosen) { next.category = "" } + if !next.media.isEmpty && chosen.mediaType != next.media { next.media = "" } + if !next.system.isEmpty && chosen.system != next.system { next.system = "" } + if !next.environment.isEmpty && chosen.environment != next.environment { next.environment = "" } + if !next.processor.isEmpty && chosen.processorRequirement != next.processor { next.processor = "" } + if !next.matchesHardware(chosen) { next.hardware = ""; next.hardwareUse = "" } + if !next.matchesDisplay(chosen) { next.displayFeature = "" } + if !LibraryBrowseQuery(scope: .all, evidence: next.evidence).matches(chosen, titleName: title.name) { next.evidence = "" } + if !LibraryBrowseQuery(scope: .all, text: next.text).matches(chosen, titleName: title.name) { next.text = "" } + if next.scope == .started && !LibraryBrowseQuery.isGettingStarted(chosen) { next.scope = .all } + if next.scope == .showcase && !chosen.assets.contains(where: { SoftwareLibraryArtworkCache.canDisplay($0) }) { next.scope = .all } + if next.scope == .installed && state.installedReleases[id] == nil { next.scope = .all } + state.selectRelease(id, for: title.id) + query = next + } + func browse(_ scope: LibraryBrowseQuery.Scope, category: String = "") { + var next = query + next.scope = scope; next.category = category; next.softwareType = "" + query = next + } + private func updateSoftwareTypes(_ catalog: SoftwareLibraryCatalog) { + softwareTypes = Array(Set(catalog.titles.flatMap { title in title.releases.flatMap { LibraryBrowseQuery.types(of: $0, related: title.releases) } })).sorted() + } + func browseType(_ type: String) { + var next = query + next.scope = .all; next.category = ""; next.softwareType = type + query = next + } + func clearFilters() { + var next = query + next.softwareType = ""; next.media = ""; next.system = ""; next.evidence = "" + next.environment = ""; next.processor = ""; next.hardware = ""; next.hardwareUse = ""; next.displayFeature = "" + query = next + } + func install(_ release: SoftwareLibraryRelease, playAfter: Bool = false) { + guard installingReleaseID == nil, !recoveringInstallations, !launchBusy, !hasPendingLaunch else { return } + if companionAccess != nil { installCompanion(release, insertAfter: playAfter); return } + #if !VCC_COMPANION_CLIENT + installationErrors[release.id] = nil; installationNotice = nil + installingReleaseID = release.id; installProgress = nil + let attempt = UUID(); installationGeneration = attempt + installationTask = Task { + do { + let receipt = try await installer.install(release) { progress in + Task { @MainActor in + guard self.installingReleaseID == release.id, self.installationGeneration == attempt else { return } + self.installProgress = progress + } + } + await refreshInstallations() + if playAfter, !Task.isCancelled { await prepareLaunch(release, receipt: receipt) } + } catch { + if Task.isCancelled || error is CancellationError { installationNotice = "Download canceled. You can try again whenever you’re ready." } + else { installationErrors[release.id] = error.localizedDescription } + } + installingReleaseID = nil; installProgress = nil; installationTask = nil + } + #endif + } + func cancelInstallation() { + installationTask?.cancel() + if let companionAccess, let id = installingReleaseID { + Task { _ = try? await companionAccess.libraryRequest(.init(operation: .cancelInstallation, releaseID: id)) } + } + } + func shutdown() async { + sourceImportTask?.cancel() + await sourceImportTask?.value + launchTask?.cancel() + await launchTask?.value + cancelInstallation() + await installationTask?.value + await state.flush() + } + func removeInstallation(_ id: String) async { + guard installingReleaseID == nil, !launchBusy, !hasPendingLaunch else { return } + if let companionAccess { + do { try acceptCompanion(try await companionAccess.libraryRequest(.init(operation: .removeInstallation, releaseID: id))) } + catch { installationErrors[id] = error.localizedDescription } + return + } + #if !VCC_COMPANION_CLIENT + do { + if let retained = try await installer.forgetInstallation(releaseID: id) { + installationNotice = "Removed from the Library. Your files are still in \(retained.path)." + } + await refreshInstallations() + } catch { installationErrors[id] = error.localizedDescription } + #endif + } + func play(_ release: SoftwareLibraryRelease) { + guard canLaunch else { return } + launchError = nil; launchMessage = nil + install(release, playAfter: true) + } + #if !VCC_COMPANION_CLIENT + private func prepareLaunch(_ release: SoftwareLibraryRelease, receipt: SoftwareLibraryInstallationReceipt, selectedMember: String? = nil) async { + guard let machine else { return } + launchBusy = true + defer { launchBusy = false } + do { + let plan = try await Task.detached(priority: .userInitiated) { + try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: receipt, selectedMember: selectedMember) + }.value + try Task.checkCancellation() + let prepared = try await machine.prepareLibraryLaunch(plan) + try Task.checkCancellation() + if plan.usesCuratedStartup { + let snapshot = await machine.mcpReadinessSnapshot() + try Task.checkCancellation() + if Self.needsCuratedRestartReview(snapshot, hasRAMDisk: machine.cartridgeAssignments.slots.contains(where: { $0.kind == .ramDisk })) { + let alert = NSAlert() + alert.messageText = "Restart the current CoCo to play “\(plan.title)â€�?" + alert.informativeText = "The current program and RAM disk contents will be cleared. Save any program you want to keep first. Writable disk changes are saved; unsaved temporary media or recordings block the restart." + alert.addButton(withTitle: "Restart & Play"); alert.addButton(withTitle: "Cancel") + guard let parent = NSApp.keyWindow else { throw ProfileFailure.message("Open the Software Library to review the current program before restarting.") } + let response = await LibraryReviewSheet(alert: alert, parent: parent).present() + guard response == .alertFirstButtonReturn else { return } + } + try Task.checkCancellation() + let result = try await machine.launchLibrary(prepared) + previousSetup = prepared.previousSetup + launchMessage = result.message ?? "Started " + plan.title + "." + machineFocusRequest += 1 + } else { launchPreview = LibraryLaunchPreview(prepared: prepared) } + } catch SoftwareLibraryLaunchPlan.Failure.needsSelection(let candidates) { + guard !Task.isCancelled else { return } + mediaChoice = LibraryMediaChoice(release: release, receipt: receipt, candidates: candidates.map { CompanionLibraryDisk(path: $0.path, mediaType: $0.mediaType) }) + } catch { + if !Task.isCancelled { launchError = error.localizedDescription } + } + } + static func needsCuratedRestartReview(_ snapshot: VCCMachineSnapshot, hasRAMDisk: Bool = false) -> Bool { + if hasRAMDisk { return true } + if snapshot.state == .empty { return false } + return snapshot.assistantEmptyBASIC?.boolValue != true || snapshot.assistantDirectPrompt?.boolValue != true + || snapshot.debuggerDevelopmentAttached || snapshot.basicDebugAttached || snapshot.debuggerAssemblyAttached + || snapshot.pasteRemaining > 0 + } + func confirmLaunch() { + guard let preview = launchPreview, let machine, !launchBusy else { return } + launchPreview = nil; launchBusy = true; launchError = nil; launchMessage = nil + launchTask = Task { + defer { launchBusy = false; launchTask = nil } + do { + let result = try await machine.launchLibrary(preview.prepared) + previousSetup = preview.prepared.previousSetup + launchMessage = result.message ?? (preview.plan.automaticallyStarts ? "Started " + preview.plan.title + "." : "The media is mounted. Follow the loading instructions to start the software.") + machineFocusRequest += 1 + } catch { launchError = error.localizedDescription } + } + } + func returnToPreviousSetup() { + guard let profile = previousSetup, let machine, !launchBusy, installingReleaseID == nil, launchPreview == nil, mediaChoice == nil else { return } + launchBusy = true; launchError = nil; launchMessage = nil + launchTask = Task { + defer { launchBusy = false; launchTask = nil } + do { + try await machine.returnLibrarySetup(profile) + previousSetup = nil; launchMessage = "Previous setup restored. Its prior running program and memory are not restored." + machineFocusRequest += 1 + } catch { launchError = error.localizedDescription } + } + } + private func refreshInstallations() async { + recoveringInstallations = true + defer { recoveringInstallations = false } + do { + let receipts = try await installer.recoverInstallations() + let warnings = await installer.recoveryWarnings + if !warnings.isEmpty { installationNotice = warnings.joined(separator: "\n") } + state.replaceInstallations(receipts.map { .init(releaseID: $0.releaseID, packageSHA256: $0.packageSHA256, installedAt: $0.installedAt, workingDirectory: $0.workingDirectory) }) + } catch { installationNotice = "Installed software could not be checked: " + error.localizedDescription } + } + #endif + func chooseLaunchMember(_ member: String, choice: LibraryMediaChoice) { + guard !launchBusy else { return } + mediaChoice = nil + if companionAccess != nil { + launchTask = Task { await prepareCompanionDisk(choice.release, selectedMember: member) } + return + } + #if !VCC_COMPANION_CLIENT + launchTask = Task { + await prepareLaunch(choice.release, receipt: choice.receipt, selectedMember: member) + launchTask = nil + } + #endif + } + func stopAutomaticLoading() { launchTask?.cancel(); cancelInstallation() } + #if VCC_COMPANION_CLIENT + func returnToPreviousSetup() { } + #endif + private func installCompanion(_ release: SoftwareLibraryRelease, insertAfter: Bool) { + guard let companionAccess, release.mediaType == "disk" else { return } + installationErrors[release.id] = nil; installationNotice = nil + installingReleaseID = release.id; installProgress = nil + let attempt = UUID(); installationGeneration = attempt + installationTask = Task { + defer { if installationGeneration == attempt { installingReleaseID = nil; installProgress = nil; installationTask = nil } } + do { + var response = try await companionAccess.libraryRequest(.init(operation: .install, releaseID: release.id)) + while true { + try Task.checkCancellation() + guard installationGeneration == attempt else { return } + try acceptCompanion(response); installProgress = response.progress + if !response.isInstalling { break } + try await Task.sleep(nanoseconds: 350_000_000) + response = try await companionAccess.libraryRequest(.init(operation: .installStatus, releaseID: release.id)) + } + guard state.installedReleases[release.id] != nil else { + throw CompanionLibraryFailure(message: "The installation did not complete. Your existing files have been preserved.") + } + if insertAfter { await prepareCompanionDisk(release) } + } catch { + if Task.isCancelled || error is CancellationError { installationNotice = "Download canceled. You can try again whenever you’re ready." } + else { installationErrors[release.id] = error.localizedDescription } + } + } + } + private func prepareCompanionDisk(_ release: SoftwareLibraryRelease, selectedMember: String? = nil) async { + guard let companionAccess, let insertCompanionDisk, release.mediaType == "disk" else { return } + launchBusy = true; launchError = nil; launchMessage = nil + defer { launchBusy = false } + do { + let response = try await companionAccess.libraryRequest(.init(operation: .diskMembers, releaseID: release.id)) + try acceptCompanion(response) + let candidates = response.disks ?? [] + let chosen: String + if let selectedMember, candidates.contains(where: { $0.path == selectedMember }) { chosen = selectedMember } + else if candidates.count == 1 { chosen = candidates[0].path } + else if candidates.count > 1 { + guard let receipt = response.receipt else { throw CompanionLibraryFailure(message: "VCC Plus did not return the installation record.") } + mediaChoice = LibraryMediaChoice(release: release, receipt: receipt, candidates: candidates) + return + } else { throw CompanionLibraryFailure(message: "This installation has no supported floppy disk image.") } + let exported = try await companionAccess.libraryRequest(.init(operation: .exportDisk, releaseID: release.id, memberPath: chosen)) + try acceptCompanion(exported); try Task.checkCancellation() + guard let url = exported.exportedDiskURL, url.isFileURL else { throw CompanionLibraryFailure(message: "VCC Plus did not return a disk copy.") } + try await insertCompanionDisk(url) + launchMessage = "The disk is inserted. Follow the loading instructions on your CoCo." + } catch { if !Task.isCancelled { launchError = error.localizedDescription } } + } + private func filter() { + guard let catalog else { return } + task?.cancel(); generation += 1; let version = generation + let query = query, favorites = state.favoriteTitleIDs, installed = Set(state.installedReleases.keys) + filtering = true + task = Task { + // Debounce typing without blocking the machine's UI or audio queues. + do { try await Task.sleep(nanoseconds: 90_000_000) } catch { return } + let worker = Task.detached(priority: .userInitiated) { query.apply(to: catalog.titles, favorites: favorites, installed: installed) } + let result = await worker.value + guard !Task.isCancelled, version == generation else { return } + rows = result; filtering = false + if !rows.contains(where: { $0.id == selection }) { selection = rows.first?.id } + } + } +} diff --git a/platforms/macos/App/SoftwareLibrarySourceImporter.swift b/platforms/macos/App/SoftwareLibrarySourceImporter.swift new file mode 100644 index 0000000..fe5c71a --- /dev/null +++ b/platforms/macos/App/SoftwareLibrarySourceImporter.swift @@ -0,0 +1,311 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import CryptoKit +import Darwin + +/// Downloads source only after an explicit action. It never opens a workspace, +/// executes Make, starts a compiler, or touches the emulator's media/state. +actor SoftwareLibrarySourceImporter { + static let maximumPackageBytes: Int64 = 64 * 1024 * 1024 + static let maximumExpandedBytes: UInt64 = 256 * 1024 * 1024 + static let maximumFileBytes: Int64 = 32 * 1024 * 1024 + static let maximumEntries: UInt = 8192 + + struct Progress: Sendable { + enum Stage: String, Sendable { case downloading, verifying, extracting, checking, complete } + let stage: Stage + let receivedBytes: Int64 + let totalBytes: Int64 + var fraction: Double? { + stage == .downloading && totalBytes > 0 ? min(1, Double(receivedBytes) / Double(totalBytes)) : nil + } + } + struct Result: Sendable { + let projectDirectory: URL + let importedDirectory: URL + let originalPackage: URL + let receiptURL: URL + } + enum Failure: LocalizedError { + case metadata, response, size, fingerprint, unsafeLocation, existingDestination, invalidProject, busy, insufficientSpace + var errorDescription: String? { + switch self { + case .metadata: "This source package has invalid download or project details." + case .response: "The source server did not return the expected download." + case .size: "The source download or expanded files exceed their expected size." + case .fingerprint: "The source download does not match its saved fingerprint." + case .unsafeLocation: "The source location contains an unexpected file or symbolic link. Existing files were preserved." + case .existingDestination: "That project folder already exists. Choose a new folder; existing projects are never replaced." + case .invalidProject: "The downloaded source does not contain its declared project, entry source and license files." + case .busy: "This project folder is already being prepared." + case .insufficientSpace: "There is not enough free space to prepare this source project." + } + } + } + + private let cacheDirectory: URL + private let configuration: URLSessionConfiguration + private var activeDestinations = Set() + private let manager = FileManager.default + + init(cacheDirectory: URL, configuration: URLSessionConfiguration? = nil) { + self.cacheDirectory = cacheDirectory.standardizedFileURL + let config = configuration?.copy() as? URLSessionConfiguration ?? .ephemeral + config.urlCache = nil + config.requestCachePolicy = .reloadIgnoringLocalCacheData + config.timeoutIntervalForRequest = 60 + config.timeoutIntervalForResource = 600 + self.configuration = config + } + + static func acceptsDownloadURL(_ url: URL) -> Bool { + url.scheme?.lowercased() == "https" && url.host?.lowercased() == "vccplus.brianholman.com" + && url.user == nil && url.password == nil && (url.port == nil || url.port == 443) + && url.query == nil && url.fragment == nil + && url.path.hasPrefix("/dl/software/CoCoLibrary/Sources/Exclusives/") + && url.pathExtension.lowercased() == "zip" && !url.path.contains("\\") + && !url.pathComponents.contains(where: { $0 == "." || $0 == ".." }) + && !url.path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + } + + private static func validRelative(_ path: String) -> Bool { + let components = path.split(separator: "/", omittingEmptySubsequences: false) + return !path.isEmpty && path.utf8.count <= 1024 && components.count <= 32 + && !path.contains("\\") && !path.contains(":") + && !path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + && !components.contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }) + } + private static func validate(_ source: SoftwareLibraryOwnedGame.Source) throws { + guard acceptsDownloadURL(source.package.url), source.package.byteSize > 0, + source.package.byteSize <= maximumPackageBytes, source.package.sha256.count == 64, + source.package.sha256.allSatisfy({ "0123456789abcdef".contains($0) }), + validRelative(source.projectDirectory), validRelative(source.entrySource), + source.entrySource.lowercased().hasSuffix(".c"), + source.configurationFile == source.projectDirectory + "/" + CMOCProject.configurationFilename, + !source.licenseFiles.isEmpty, source.licenseFiles.count <= 32, + source.licenseFiles.allSatisfy(validRelative), + Set(source.licenseFiles).count == source.licenseFiles.count else { throw Failure.metadata } + } + + func importProject(_ source: SoftwareLibraryOwnedGame.Source, to destination: URL, + progress: @escaping @Sendable (Progress) -> Void = { _ in }) async throws -> Result { + try Self.validate(source) + try Task.checkCancellation() + guard destination.isFileURL, destination.query == nil, destination.fragment == nil, + destination.host == nil || destination.host == "" || destination.host == "localhost", + Self.validRelative(destination.lastPathComponent), destination.lastPathComponent.utf8.count <= 255 else { + throw Failure.unsafeLocation + } + // Resolve the chosen parent once. The new leaf itself must never be a link + // or an existing file, even if the user's chosen parent has a Finder alias. + let parent = try CMOCProject.physicalURL(destination.deletingLastPathComponent()) + try checkDirectory(parent) + let target = parent.appendingPathComponent(destination.lastPathComponent, isDirectory: true) + guard !activeDestinations.contains(target.path) else { throw Failure.busy } + activeDestinations.insert(target.path) + defer { activeDestinations.remove(target.path) } + try requireAbsent(target) + let parentFD = open(parent.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) + guard parentFD >= 0 else { throw Failure.unsafeLocation } + defer { close(parentFD) } + var parentIdentity = stat() + guard fstat(parentFD, &parentIdentity) == 0 else { throw Failure.unsafeLocation } + if let available = (try? manager.attributesOfFileSystem(forPath: parent.path)[.systemFreeSize]) as? NSNumber, + available.uint64Value < Self.maximumExpandedBytes + UInt64(source.package.byteSize) { + throw Failure.insufficientSpace + } + + let cache = try prepareCache() + let retention = cache.appendingPathComponent(UUID().uuidString, isDirectory: true) + try manager.createDirectory(at: retention, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + let partial = retention.appendingPathComponent("Download.partial") + var verifiedOriginal = false + defer { + if verifiedOriginal { try? manager.removeItem(at: partial) } + else { try? manager.removeItem(at: retention) } + } + let original = retention.appendingPathComponent("Original.zip") + progress(.init(stage: .downloading, receivedBytes: 0, totalBytes: source.package.byteSize)) + do { try await download(source.package, to: partial, progress: progress) } + catch { + if Task.isCancelled { throw CancellationError() } + throw error + } + progress(.init(stage: .verifying, receivedBytes: source.package.byteSize, totalBytes: source.package.byteSize)) + try verify(partial, descriptor: source.package) + try Task.checkCancellation() + try manager.moveItem(at: partial, to: original) + guard chmod(original.path, 0o444) == 0 else { throw Failure.unsafeLocation } + verifiedOriginal = true + + // Extraction and promotion share the destination filesystem. Only this + // unique staging tree is removed on cancellation or validation failure. + let stageName = ".vcc-source-" + UUID().uuidString + guard mkdirat(parentFD, stageName, 0o700) == 0 else { throw Failure.unsafeLocation } + let stage = parent.appendingPathComponent(stageName, isDirectory: true) + defer { try? manager.removeItem(at: stage) } + let tree = stage.appendingPathComponent("Project", isDirectory: true) + progress(.init(stage: .extracting, receivedBytes: 0, totalBytes: 0)) + let files: [String] + do { + files = try VCCLibraryArchive.extractZIP(at: original, toNewDirectory: tree, + maximumExpandedBytes: Self.maximumExpandedBytes, maximumEntries: Self.maximumEntries, + shouldCancel: { Task.isCancelled }) + } catch { + if Task.isCancelled { throw CancellationError() } + throw error + } + try Task.checkCancellation() + progress(.init(stage: .checking, receivedBytes: 0, totalBytes: 0)) + try Self.validateExtractedProject(source, root: tree, files: files) + try Task.checkCancellation() + let receiptURL = retention.appendingPathComponent("Receipt.json") + let receipt = Receipt(version: 1, packageURL: source.package.url, + packageSHA256: source.package.sha256, packageByteSize: source.package.byteSize, + projectDirectory: source.projectDirectory, entrySource: source.entrySource, + licenseFiles: source.licenseFiles, files: files, verifiedAt: Date()) + try JSONEncoder().encode(receipt).write(to: receiptURL, options: .withoutOverwriting) + + var currentParent = stat() + guard lstat(parent.path, ¤tParent) == 0, currentParent.st_dev == parentIdentity.st_dev, + currentParent.st_ino == parentIdentity.st_ino, currentParent.st_mode & S_IFMT == S_IFDIR else { + throw Failure.unsafeLocation + } + // RENAME_EXCL closes the race between checking the destination and + // promotion. Never merge, remove or overwrite a late-created project. + guard renameatx_np(AT_FDCWD, tree.path, parentFD, target.lastPathComponent, UInt32(RENAME_EXCL)) == 0 else { + if errno == EEXIST || errno == ENOTEMPTY { throw Failure.existingDestination } + throw Failure.unsafeLocation + } + progress(.init(stage: .complete, receivedBytes: source.package.byteSize, totalBytes: source.package.byteSize)) + return Result(projectDirectory: target.appendingPathComponent(source.projectDirectory, isDirectory: true), + importedDirectory: target, originalPackage: original, receiptURL: receiptURL) + } + + private func download(_ descriptor: SoftwareLibraryOwnedGame.HostedFile, to path: URL, + progress: @escaping @Sendable (Progress) -> Void) async throws { + let delegate = SourceImportRedirects() + let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + defer { session.invalidateAndCancel() } + let request = URLRequest(url: descriptor.url) + let (bytes, response) = try await session.bytes(for: request) + guard let response = response as? HTTPURLResponse, response.statusCode == 200, + let finalURL = response.url, Self.acceptsDownloadURL(finalURL) else { throw Failure.response } + if response.expectedContentLength >= 0 && response.expectedContentLength != descriptor.byteSize { + throw Failure.size + } + let fd = open(path.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard fd >= 0 else { throw Failure.unsafeLocation } + let output = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + defer { try? output.close() } + var received: Int64 = 0 + var chunk = Data(); chunk.reserveCapacity(64 * 1024) + for try await byte in bytes { + try Task.checkCancellation() + received += 1 + guard received <= descriptor.byteSize else { throw Failure.size } + chunk.append(byte) + if chunk.count == 64 * 1024 { + try output.write(contentsOf: chunk); chunk.removeAll(keepingCapacity: true) + progress(.init(stage: .downloading, receivedBytes: received, totalBytes: descriptor.byteSize)) + } + } + try Task.checkCancellation() + guard received == descriptor.byteSize else { throw Failure.size } + if !chunk.isEmpty { try output.write(contentsOf: chunk) } + try output.synchronize() + progress(.init(stage: .downloading, receivedBytes: received, totalBytes: descriptor.byteSize)) + } + + private func verify(_ path: URL, descriptor: SoftwareLibraryOwnedGame.HostedFile) throws { + guard try Self.regularSize(path) == descriptor.byteSize else { throw Failure.size } + let input = try FileHandle(forReadingFrom: path); defer { try? input.close() } + var hash = SHA256() + while let data = try input.read(upToCount: 1024 * 1024), !data.isEmpty { + try Task.checkCancellation(); hash.update(data: data) + } + guard hash.finalize().map({ String(format: "%02x", $0) }).joined() == descriptor.sha256 else { throw Failure.fingerprint } + } + + /// Reusable authored-test seam: reads regular extracted files and parses the + /// declared project, without executing its Makefile or opening an editor. + static func validateExtractedProject(_ source: SoftwareLibraryOwnedGame.Source, root: URL, files: [String]) throws { + try validate(source) + guard !files.isEmpty, files.count <= maximumEntries, Set(files).count == files.count, + files.allSatisfy(validRelative) else { throw Failure.invalidProject } + var total: UInt64 = 0 + for path in files { + try Task.checkCancellation() + let components = path.split(separator: "/").map { $0.lowercased() } + guard !components.contains(where: { [".git", ".hg", ".svn", ".ds_store", "__macosx"].contains($0) }) else { + throw Failure.invalidProject + } + let size = try regularSize(root.appendingPathComponent(path)) + guard size <= maximumFileBytes else { throw Failure.size } + total += UInt64(size) + guard total <= maximumExpandedBytes else { throw Failure.size } + } + let known = Set(files) + guard known.contains(source.configurationFile), known.contains(source.projectDirectory + "/" + source.entrySource), + source.licenseFiles.allSatisfy(known.contains) else { throw Failure.invalidProject } + let projectURL = root.appendingPathComponent(source.projectDirectory, isDirectory: true) + let project = try CMOCProject.open(at: projectURL) + guard project.configuration.entrySource == source.entrySource else { throw Failure.invalidProject } + if let configuration = source.buildConfiguration { + guard project.configuration.configurations.contains(where: { $0.name == configuration }) else { throw Failure.invalidProject } + } + let canonicalRoot = try CMOCProject.physicalURL(root).path + for declared in project.configuration.buildSupportDirectories { + let support = try CMOCProject.physicalURL(projectURL.appendingPathComponent(declared, isDirectory: true)) + guard support.path.hasPrefix(canonicalRoot + "/") else { throw Failure.invalidProject } + var info = stat() + guard lstat(support.path, &info) == 0, info.st_mode & S_IFMT == S_IFDIR else { throw Failure.invalidProject } + } + } + + private func prepareCache() throws -> URL { + guard cacheDirectory.isFileURL else { throw Failure.unsafeLocation } + var info = stat() + if lstat(cacheDirectory.path, &info) == 0 { + guard info.st_mode & S_IFMT == S_IFDIR, info.st_uid == geteuid() else { throw Failure.unsafeLocation } + } else { + guard errno == ENOENT else { throw Failure.unsafeLocation } + try manager.createDirectory(at: cacheDirectory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) + } + let physical = try CMOCProject.physicalURL(cacheDirectory) + try checkDirectory(physical) + return physical + } + private func checkDirectory(_ url: URL) throws { + var info = stat() + guard lstat(url.path, &info) == 0, info.st_mode & S_IFMT == S_IFDIR, info.st_uid == geteuid() else { throw Failure.unsafeLocation } + } + private func requireAbsent(_ url: URL) throws { + var info = stat() + if lstat(url.path, &info) == 0 { throw Failure.existingDestination } + guard errno == ENOENT else { throw Failure.unsafeLocation } + } + private static func regularSize(_ url: URL) throws -> Int64 { + var info = stat() + guard lstat(url.path, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_size >= 0 else { throw Failure.unsafeLocation } + return info.st_size + } + private struct Receipt: Codable { + let version: Int + let packageURL: URL + let packageSHA256: String + let packageByteSize: Int64 + let projectDirectory: String + let entrySource: String + let licenseFiles: [String] + let files: [String] + let verifiedAt: Date + } +} + +private final class SourceImportRedirects: NSObject, URLSessionTaskDelegate { + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { + completionHandler(request.url.map(SoftwareLibrarySourceImporter.acceptsDownloadURL) == true ? request : nil) + } +} diff --git a/platforms/macos/App/SoftwareLibraryState.swift b/platforms/macos/App/SoftwareLibraryState.swift new file mode 100644 index 0000000..6beef5e --- /dev/null +++ b/platforms/macos/App/SoftwareLibraryState.swift @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import Combine + +// Catalog releases are immutable reference data. This independent, atomic file +// retains personal choices across catalog replacements, including IDs absent +// from a later catalog. Installation receipts are reconciled into it without editing SQLite. +@MainActor +final class SoftwareLibraryState: ObservableObject { + struct Installation: Codable, Equatable, Sendable { + let releaseID: String + let packageSHA256: String + let installedAt: Date + let workingDirectory: URL + } + private struct Document: Codable, Sendable { + var version = 1 + var favoriteTitleIDs: Set = [] + var preferredReleaseIDs: [String: String] = [:] + var installedReleases: [String: Installation] = [:] + } + @Published private(set) var favoriteTitleIDs: Set = [] + @Published private(set) var preferredReleaseIDs: [String: String] = [:] + @Published private(set) var installedReleases: [String: Installation] = [:] + @Published private(set) var saveError: String? + let directory: URL + private let fileURL: URL + private let queue = DispatchQueue(label: "com.brianholman.vccplus.library-state", qos: .utility) + private var companion: (any CompanionLibraryAccess)? + private var remoteSave: Task? + private var maySave = true + private var revision = 0 + + init(directory: URL) { + self.directory = directory + fileURL = directory.appendingPathComponent("LibraryState.json") + do { + guard FileManager.default.fileExists(atPath: fileURL.path) else { return } + let file = try FileHandle(forReadingFrom: fileURL) + defer { try? file.close() } + let data = try file.read(upToCount: 1_048_577) ?? Data() + guard data.count <= 1_048_576 else { throw StateFailure.invalid } + let document = try JSONDecoder().decode(Document.self, from: data) + guard document.version == 1, + document.favoriteTitleIDs.allSatisfy(Self.validID), + document.preferredReleaseIDs.allSatisfy({ Self.validID($0.key) && Self.validID($0.value) }), + document.installedReleases.allSatisfy({ key, entry in + key == entry.releaseID && Self.validID(key) && entry.packageSHA256.count == 64 + && entry.packageSHA256.allSatisfy(\.isHexDigit) && entry.workingDirectory.isFileURL + }) else { throw StateFailure.invalid } + favoriteTitleIDs = document.favoriteTitleIDs + preferredReleaseIDs = document.preferredReleaseIDs + installedReleases = document.installedReleases + } catch { + maySave = false // Preserve unreadable/newer state rather than overwriting it. + saveError = "Your saved Library choices could not be read. The original file has been preserved at \(fileURL.path). \(error.localizedDescription)" + } + } + /// In-memory presentation only. All persistence stays in VCC Plus. + init(companion: any CompanionLibraryAccess) { + self.companion = companion + directory = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCompanionPresentation", isDirectory: true) + fileURL = directory.appendingPathComponent("Unused.json") + } + func applyRemoteSnapshot(_ snapshot: CompanionLibrarySnapshot) { + favoriteTitleIDs = snapshot.favorites + preferredReleaseIDs = snapshot.preferredReleaseIDs + installedReleases = Dictionary(snapshot.installations.map { ($0.releaseID, $0) }, uniquingKeysWith: { _, last in last }) + saveError = nil + } + private func sendRemote(_ request: CompanionLibraryRequest) { + guard let companion else { return } + revision += 1 + let revision = revision, previous = remoteSave + remoteSave = Task { [weak self] in + await previous?.value + do { + let response = try await companion.libraryRequest(request) + if let message = response.errorMessage { throw CompanionLibraryFailure(message: message) } + guard let self, self.revision == revision else { return } + if let snapshot = response.snapshot { self.applyRemoteSnapshot(snapshot) } + } catch { + guard let self, self.revision == revision else { return } + self.saveError = error.localizedDescription + } + } + } + func isFavorite(_ titleID: String) -> Bool { favoriteTitleIDs.contains(titleID) } + func preferredReleaseID(for titleID: String) -> String? { preferredReleaseIDs[titleID] } + func toggleFavorite(_ titleID: String) { + guard maySave, Self.validID(titleID) else { return } + if favoriteTitleIDs.contains(titleID) { favoriteTitleIDs.remove(titleID) } + else { favoriteTitleIDs.insert(titleID) } + if companion != nil { + sendRemote(.init(operation: .setFavorite, titleID: titleID, enabled: favoriteTitleIDs.contains(titleID))) + } else { save() } + } + func selectRelease(_ releaseID: String, for titleID: String) { + guard maySave, Self.validID(titleID), Self.validID(releaseID), preferredReleaseIDs[titleID] != releaseID else { return } + preferredReleaseIDs[titleID] = releaseID + if companion != nil { sendRemote(.init(operation: .setPreferredRelease, releaseID: releaseID, titleID: titleID)) } + else { save() } + } + // Receipts are the authoritative installation record; personal choices stay separate. + func replaceInstallations(_ installations: [Installation]) { + let entries = Dictionary(installations.map { ($0.releaseID, $0) }, uniquingKeysWith: { _, latest in latest }) + guard entries != installedReleases else { return } + installedReleases = entries + if maySave && companion == nil { save() } + } + // Used at shutdown/testing to await all already-enqueued atomic writes. + func flush() async { + await remoteSave?.value + await withCheckedContinuation { continuation in queue.async { continuation.resume() } } + } + private static func validID(_ id: String) -> Bool { + !id.isEmpty && id.utf8.count <= 256 && !id.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + } + private func save() { + let document = Document(favoriteTitleIDs: favoriteTitleIDs, preferredReleaseIDs: preferredReleaseIDs, installedReleases: installedReleases) + revision += 1 + let revision = revision, destination = fileURL + queue.async { [weak self] in + let failure: String? + do { + let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys] + let data = try encoder.encode(document) + guard data.count <= 1_048_576 else { throw StateFailure.invalid } + try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: destination, options: .atomic) + failure = nil + } catch { failure = "Library choices could not be saved: \(error.localizedDescription)" } + Task { @MainActor [weak self] in + guard let self, self.revision == revision else { return } + self.saveError = failure + } + } + } + private enum StateFailure: LocalizedError { + case invalid + var errorDescription: String? { "The Library choices file is damaged or uses an unsupported version." } + } +} diff --git a/platforms/macos/App/SoftwareLibraryView.swift b/platforms/macos/App/SoftwareLibraryView.swift new file mode 100644 index 0000000..264c9f8 --- /dev/null +++ b/platforms/macos/App/SoftwareLibraryView.swift @@ -0,0 +1,644 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit + +struct SoftwareLibraryView: View { + @Environment(\.openWindow) private var openWindow + @ObservedObject var model: SoftwareLibraryModel + @State private var showManual = false + @State private var showFilters = false + @State private var showAdvancedFilters = false + @State private var confirmingReturn = false + @State private var removingRelease: SoftwareLibraryRelease? + var body: some View { + VStack(spacing: 0) { + header + Divider() + HSplitView { + sidebar.frame(minWidth: 170, idealWidth: 185, maxWidth: 235, maxHeight: .infinity, alignment: .top) + browser.frame(minWidth: 330, maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + detail.frame(minWidth: 320, idealWidth: 365, maxWidth: 460, maxHeight: .infinity, alignment: .top) + }.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + if let notice = model.installationNotice { + Text(notice).font(.caption).foregroundStyle(.secondary).textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 16).padding(.vertical, 6) + } + if let id = model.installingReleaseID, id != model.selectedRelease?.id { + HStack { + ProgressView().controlSize(.small) + Text("Installing " + (model.catalog?.releases.first { $0.id == id }?.metadata["title"].string ?? "software") + "…") + Spacer() + Button("Cancel", role: .cancel) { model.cancelInstallation() } + }.padding(12) + } + if let message = model.launchError ?? model.launchMessage { + HStack(alignment: .top) { + Image(systemName: model.launchError == nil ? "info.circle" : "exclamationmark.triangle") + Text(message).textSelection(.enabled).accessibilityIdentifier(model.launchError == nil ? "library-launch-message" : "library-launch-error") + }.font(.callout).foregroundStyle(model.launchError == nil ? Color.secondary : Color.orange) + .frame(maxWidth: .infinity, alignment: .leading).padding(12) + } + if model.launchBusy { + HStack { + ProgressView().controlSize(.small) + Text(model.isDiskCompanion ? "Preparing a disk for DriveWire…" : "Preparing and starting the CoCo…") + Spacer() + Button("Stop Automatic Loading") { model.stopAutomaticLoading() }.accessibilityIdentifier("library-stop-loading") + }.padding(12) + } + Divider() + HStack { + Text("Color Computer Archive software and VCC Plus-exclusive titles").font(.caption).foregroundStyle(.secondary) + Spacer() + if model.filtering { ProgressView().controlSize(.mini) } + Text(model.catalog.map { "\($0.titles.count.formatted()) titles · \($0.releaseCount.formatted()) editions" } ?? "") + .font(.caption).foregroundStyle(.secondary) + }.padding(.horizontal, 16).padding(.vertical, 9) + } + .frame(minWidth: 900, maxWidth: .infinity, minHeight: 570, maxHeight: .infinity, alignment: .top) + .task { await model.load() } + .onChange(of: model.machineFocusRequest) { _, _ in + if !model.isDiskCompanion { openWindow(id: "machine") } + DispatchQueue.main.async { model.focusDisplay() } + } + .onChange(of: model.sourceFocusRequest) { _, _ in + if !model.isDiskCompanion { openWindow(id: "c-development") } + } + .modifier(SoftwareLibraryLaunchPresentation(model: model)) + .environment(\.companionLibraryAccess, model.companionAccess) + .sheet(isPresented: $showManual) { + VStack(spacing: 0) { + SoftwareLibraryManualView(model: model.manual) + Divider() + HStack { Spacer(); Button("Done") { showManual = false }.keyboardShortcut(.defaultAction) }.padding(12) + }.frame(minWidth: 700, minHeight: 560) + } + .sheet(item: $model.mediaChoice) { choice in + SoftwareLibraryMediaChoiceView(choice: choice, choose: { model.chooseLaunchMember($0, choice: choice) }, cancel: { model.mediaChoice = nil }) + } + .alert("Return to Previous Setup?", isPresented: $confirmingReturn) { + Button("Cancel", role: .cancel) { } + Button("Restore Setup") { model.returnToPreviousSetup() }.accessibilityIdentifier("library-confirm-return") + } message: { + Text("This restarts the CoCo with the previous hardware and media assignments. It does not restore its previous program or memory. Unsaved media must be saved first.") + } + .onDisappear { Task { await model.state.flush() } } + .alert("Remove from Library?", isPresented: Binding(get: { removingRelease != nil }, set: { if !$0 { removingRelease = nil } }), presenting: removingRelease) { release in + Button("Cancel", role: .cancel) { removingRelease = nil } + Button("Remove from Library") { Task { await model.removeInstallation(release.id) }; removingRelease = nil } + } message: { _ in + Text("Your original download and working files will stay on this Mac, including any saved games or changes. Installing again creates a new working copy.") + } + } + private var header: some View { + HStack(spacing: 16) { + Label("Software Library", systemImage: "books.vertical.fill").font(.title2.weight(.semibold)) + Spacer(minLength: 10) + if model.hasPreviousSetup { + Button { confirmingReturn = true } label: { Image(systemName: "arrow.uturn.backward") } + .help("Return to Previous Setup…").accessibilityLabel("Return to Previous Setup…") + .accessibilityIdentifier("library-return-setup") + .disabled(model.launchBusy || model.installingReleaseID != nil) + } + HStack(spacing: 7) { + Image(systemName: "magnifyingglass").foregroundStyle(.secondary) + TextField("Search titles, authors, or keywords", text: $model.query.text) + .textFieldStyle(.plain).accessibilityLabel("Search software").accessibilityIdentifier("library-search") + if !model.query.text.isEmpty { + Button { model.query.text = "" } label: { Image(systemName: "xmark.circle.fill") } + .buttonStyle(.plain).help("Clear search").accessibilityLabel("Clear search") + } + }.padding(8).background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 8)) + .frame(minWidth: 230, idealWidth: 340, maxWidth: 420) + }.padding(16) + } + private var sidebar: some View { + VStack(alignment: .leading, spacing: 0) { + VStack(alignment: .leading, spacing: 4) { + Text("Discover").font(.caption.weight(.semibold)).foregroundStyle(.secondary) + scope("Cover Collection", icon: "rectangle.grid.2x2", scope: .showcase, id: "showcase") + scope("Getting Started", icon: "sparkles", scope: .started, id: "getting-started") + scope("All Software", icon: "books.vertical", scope: .all, id: "all") + Text("My Library").font(.caption.weight(.semibold)).foregroundStyle(.secondary).padding(.top, 8) + scope("Favorites", icon: "heart", scope: .favorites, id: "favorites") + scope("Installed", icon: "internaldrive", scope: .installed, id: "installed") + }.padding(14) + Divider() + List { + Section("Software Type") { + ForEach(model.softwareTypes, id: \.self) { type in + Button { model.browseType(type) } label: { + Label(type == "Educational" ? "Education" : type, systemImage: SoftwareLibraryCategoryStyle.symbol(for: type)) + .foregroundStyle(model.query.softwareType == type ? Color.accentColor : Color.primary) + .frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()) + }.buttonStyle(.plain).accessibilityIdentifier("library-type-" + type) + } + } + Section("Archive Folders") { + OutlineGroup(model.categories, children: \.children) { category in + Button { + model.browse(.all, category: category.id) + } label: { + Text(category.name).font(.callout).lineLimit(2) + .foregroundStyle(model.query.category == category.id ? Color.accentColor : Color.primary) + .frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()) + }.buttonStyle(.plain).help(category.id).accessibilityIdentifier("library-category-" + category.id) + } + } + }.listStyle(.sidebar).scrollContentBackground(.hidden) + }.background(Color(nsColor: .windowBackgroundColor)) + } + private func scope(_ title: String, icon: String, scope: LibraryBrowseQuery.Scope, id: String) -> some View { + Button { model.browse(scope) } label: { + Label(title, systemImage: icon).fontWeight(model.query.scope == scope && model.query.category.isEmpty && model.query.softwareType.isEmpty ? .semibold : .regular) + .foregroundStyle(model.query.scope == scope && model.query.category.isEmpty && model.query.softwareType.isEmpty ? Color.accentColor : Color.primary) + .frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 4).contentShape(Rectangle()) + }.buttonStyle(.plain).accessibilityIdentifier("library-scope-" + id) + } + private var heading: String { + if !model.query.softwareType.isEmpty { return SoftwareLibraryOwnedGame.categoryLabel(model.query.softwareType) } + if !model.query.category.isEmpty { return model.query.category.components(separatedBy: "/").last ?? "All Software" } + switch model.query.scope { + case .showcase: return "Cover Collection" + case .started: return "Getting Started" + case .all: return "All Software" + case .favorites: return "Favorites" + case .installed: return "Installed" + } + } + private var browser: some View { + VStack(alignment: .leading, spacing: 12) { + HStack { + VStack(alignment: .leading, spacing: 3) { + Text(heading).font(.title3.weight(.semibold)).accessibilityIdentifier("library-heading") + Text("\(model.rows.count.formatted()) \(model.rows.count == 1 ? "title" : "titles")").foregroundStyle(.secondary).font(.caption) + .accessibilityIdentifier("library-result-count") + } + Spacer() + Picker("Presentation", selection: Binding(get: { model.layout }, set: { value in + guard model.layout != value else { return } + Task { @MainActor in model.layout = value } + })) { + Image(systemName: "square.grid.2x2").tag("Shelf").help("Show software on the shelf").accessibilityLabel("Shelf") + Image(systemName: "list.bullet").tag("Table").help("Show software in a table").accessibilityLabel("Table") + }.pickerStyle(.segmented).labelsHidden().frame(width: 80).accessibilityIdentifier("library-layout") + Button { showFilters.toggle() } label: { Image(systemName: "line.3.horizontal.decrease.circle") } + .help("Filter and sort").accessibilityLabel("Filter and sort").accessibilityIdentifier("library-filters") + .popover(isPresented: $showFilters, arrowEdge: .bottom) { ScrollView { filters.padding(18) }.frame(width: 370, height: showAdvancedFilters ? 460 : 340) } + }.padding(.horizontal, 16).padding(.top, 14) + if model.query.scope == .showcase { + Text("Software with cover art, labels and screenshots.") + .font(.callout).foregroundStyle(.secondary).padding(.horizontal, 16) + } else if model.query.scope == .started { + Text("A first selection to explore your CoCo. More guided picks will join the collection.") + .font(.callout).foregroundStyle(.secondary).padding(.horizontal, 16) + } + if !model.query.category.isEmpty || !model.query.softwareType.isEmpty { + Text(model.query.sort == .title + ? "Curated titles appear first, alphabetically, followed by the alphabetical collection." + : "Curated titles appear first, alphabetically; the remaining titles use your selected sort.") + .font(.caption).foregroundStyle(.secondary).padding(.horizontal, 16) + } + if !activeFilters.isEmpty { + HStack(alignment: .top, spacing: 8) { + Text(activeFilters.joined(separator: " · ")).font(.caption).foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading).accessibilityIdentifier("library-active-filters") + Button("Clear filters") { model.clearFilters() }.controlSize(.small) + }.padding(.horizontal, 16) + } + if model.loading { + Spacer(); ProgressView("Opening the library…").frame(maxWidth: .infinity); Spacer() + } else if let error = model.error { + ContentUnavailableView { Label("Library unavailable", systemImage: "books.vertical") } description: { Text(error) } actions: { + Button("Try Again") { Task { await model.load() } } + } + } else if model.rows.isEmpty { + emptyState.frame(maxWidth: .infinity, maxHeight: .infinity) + } else if model.layout == "Table" { + Table(model.rows, selection: Binding(get: { model.selection }, set: { value in + // AppKit can report selection while SwiftUI installs/removes the table. + // Publish on the next main-actor turn, and ignore teardown callbacks. + guard model.selection != value else { return } + Task { @MainActor in + guard model.layout == "Table", value == nil || model.rows.contains(where: { $0.id == value }) else { return } + model.selection = value + } + })) { + TableColumn("Title", value: \.name).width(min: 140, ideal: 240) + TableColumn("Format", value: \.formats).width(min: 65, ideal: 95) + TableColumn("Size", value: \.size).width(55) + }.accessibilityLabel("Software titles") + } else { + ScrollView { + LazyVGrid(columns: [GridItem(.adaptive(minimum: 155, maximum: 215), spacing: 18)], alignment: .leading, spacing: 22) { + ForEach(model.rows) { row in shelfCard(row) } + }.padding(16) + }.background(Color.primary.opacity(0.018)) + } + } + } + private var activeFilters: [String] { + var labels: [String] = [] + if !model.query.softwareType.isEmpty { labels.append(SoftwareLibraryOwnedGame.categoryLabel(model.query.softwareType)) } + if !model.query.media.isEmpty { + labels.append(["cartridge": "Cartridge", "cassette": "Cassette", "disk": "Disk", "sdc": "SDC SD card", "hard-disk": "Hard disk"][model.query.media] ?? model.query.media) + } + if !model.query.system.isEmpty { labels.append(systemName(model.query.system)) } + if !model.query.evidence.isEmpty { + labels.append(["checked": "VCC Plus spot-checked", "manual": "Manual setup", "notes": "Has compatibility notes"][model.query.evidence] ?? model.query.evidence) + } + return labels + model.query.additionalFilterLabels + } + private var searchIsActive: Bool { !model.query.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } + private var narrowed: Bool { searchIsActive || !activeFilters.isEmpty || !model.query.category.isEmpty } + private var emptyState: some View { + ContentUnavailableView { + Label(!narrowed && model.query.scope == .installed ? "Your software will live here" : !narrowed && model.query.scope == .favorites ? "Keep your favorites close" : "No matching titles", systemImage: model.query.scope == .favorites ? "heart" : "books.vertical") + } description: { + if model.catalog?.releaseCount == 0 { Text("This development build has an empty catalog. Build with a prepared Software Library catalog to browse software.").accessibilityIdentifier("library-catalog-empty") } + else if narrowed { Text(searchIsActive ? "No titles match “\(model.query.text)â€� in this selection. Clear the search or adjust your filters." : "No titles match these filters. Try clearing them or choosing another category.") } + else if model.query.scope == .installed { Text("Choose a title and Install Only to keep a copy on your Mac. Your running CoCo session will stay as it is.") } + else if model.query.scope == .favorites { Text("Choose the heart beside a title to add it to your collection.") } + else { Text("Try a different search, category, or filter.") } + } actions: { + if searchIsActive { + Button("Clear Search") { model.query.text = "" }.accessibilityIdentifier("library-empty-clear-search") + } + Button("Browse All Titles") { model.query = LibraryBrowseQuery(scope: .all) } + } + } + private var filters: some View { + Form { + Picker("Software Type", selection: $model.query.softwareType) { + Text("All types").tag("") + ForEach(model.softwareTypes, id: \.self) { Text(SoftwareLibraryOwnedGame.categoryLabel($0)).tag($0) } + }.accessibilityIdentifier("library-filter-type") + if model.isDiskCompanion { + LabeledContent("Format") { Label("Disk images only", systemImage: "externaldrive") } + } else { + Picker("Format", selection: $model.query.media) { + Text("All formats").tag("") + Text("Cartridge").tag("cartridge"); Text("Cassette").tag("cassette"); Text("Disk").tag("disk") + Text("SDC SD card").tag("sdc"); Text("Hard disk").tag("hard-disk") + }.accessibilityIdentifier("library-filter-media") + } + Picker("System", selection: $model.query.system) { + Text("All systems").tag("") + ForEach(Array(Set(model.catalog?.releases.map(\.system) ?? [])).sorted(), id: \.self) { Text(systemName($0)).tag($0) } + }.accessibilityIdentifier("library-filter-system") + Picker("Environment", selection: $model.query.environment) { + Text("All environments").tag("") + ForEach(["basic", "disk-basic", "os9", "unknown"], id: \.self) { Text(LibraryBrowseQuery.environmentLabels[$0]!).tag($0) } + }.accessibilityIdentifier("library-filter-environment") + Picker("Setup", selection: $model.query.evidence) { + Text("All titles").tag(""); Text("VCC Plus spot-checked").tag("checked") + Text("Manual setup").tag("manual"); Text("Has compatibility notes").tag("notes") + }.accessibilityIdentifier("library-filter-evidence") + Picker("Sort by", selection: $model.query.sort) { + ForEach(LibraryBrowseQuery.Sort.allCases, id: \.self) { Text($0.rawValue).tag($0) } + }.accessibilityIdentifier("library-filter-sort") + DisclosureGroup("Advanced Filters", isExpanded: $showAdvancedFilters) { + Picker("Processor", selection: $model.query.processor) { + Text("Any processor").tag("") + ForEach(["6309", "either", "unknown"], id: \.self) { Text(LibraryBrowseQuery.processorLabels[$0]!).tag($0) } + }.accessibilityIdentifier("library-filter-processor") + Picker("Hardware", selection: Binding(get: { model.query.hardware }, set: { value in + var next = model.query; next.hardware = value; next.hardwareUse = ""; model.query = next + })) { + Text("Any hardware").tag("") + ForEach(["speech-sound", "orchestra90", "joystick"], id: \.self) { Text(LibraryBrowseQuery.hardwareLabels[$0]!).tag($0) } + }.accessibilityIdentifier("library-filter-hardware") + if !model.query.hardware.isEmpty { + Picker("Use", selection: $model.query.hardwareUse) { + Text("Any reported use").tag("") + ForEach(["required", "optional", "unspecified"], id: \.self) { Text(LibraryBrowseQuery.hardwareUseLabels[$0]!).tag($0) } + }.accessibilityIdentifier("library-filter-hardware-use") + } + Picker("Display", selection: $model.query.displayFeature) { + Text("Any display features").tag("") + ForEach(["semigraphics", "SG-8", "SG-12", "SG-24"], id: \.self) { Text(LibraryBrowseQuery.displayLabels[$0]!).tag($0) } + }.accessibilityIdentifier("library-filter-display") + Text("Based on catalog information. Missing details do not mean unsupported; reported hardware use may be optional.") + .font(.caption).foregroundStyle(.secondary) + } + }.formStyle(.grouped).fixedSize(horizontal: false, vertical: true) + } + private func shelfCard(_ row: LibraryBrowseRow) -> some View { + let release = row.matchingReleases.first! + let asset = release.assets.first { SoftwareLibraryArtworkCache.canDisplay($0) } + return Button { model.selection = row.id } label: { + VStack(alignment: .leading, spacing: 8) { + SoftwareLibraryArtworkView(asset: asset, cacheDirectory: model.artworkDirectory, + softwareType: LibraryBrowseQuery.type(of: release, related: row.title.releases)) + .frame(height: 180) + .overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(model.selection == row.id ? Color.accentColor : .clear, lineWidth: 3)) + .shadow(color: .black.opacity(0.1), radius: 3, y: 3) + HStack(alignment: .top, spacing: 4) { + Text(row.name).font(.callout.weight(.medium)).lineLimit(2).frame(maxWidth: .infinity, alignment: .leading) + if model.state.isFavorite(row.id) { Image(systemName: "heart.fill").font(.caption).foregroundStyle(.pink) } + } + Text(row.formats).font(.caption).foregroundStyle(.secondary).lineLimit(1) + }.padding(4).contentShape(Rectangle()) + }.buttonStyle(.plain).accessibilityIdentifier("library-title-" + row.id) + .accessibilityLabel(row.name + ", " + row.formats).help(row.name) + } + @ViewBuilder private var detail: some View { + if let row = model.selectedRow, let release = model.selectedRelease { + ScrollView { + VStack(alignment: .leading, spacing: 18) { + HStack(alignment: .top) { + Text(row.name).font(.title2.weight(.semibold)).textSelection(.enabled) + .accessibilityIdentifier("library-detail-title") + Spacer(minLength: 4) + Button { model.state.toggleFavorite(row.id) } label: { + Image(systemName: model.state.isFavorite(row.id) ? "heart.fill" : "heart") + .foregroundStyle(model.state.isFavorite(row.id) ? Color.pink : Color.secondary) + }.buttonStyle(.borderless).controlSize(.large) + .help(model.state.isFavorite(row.id) ? "Remove \(row.name) from favorites" : "Add \(row.name) to favorites").accessibilityLabel(model.state.isFavorite(row.id) ? "Remove Favorite" : "Add Favorite") + .accessibilityIdentifier("library-favorite") + } + if let error = model.state.saveError { Label(error, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.orange) } + SoftwareLibraryArtworkView( + asset: release.assets.first(where: { SoftwareLibraryArtworkCache.canDisplay($0) }), + cacheDirectory: model.artworkDirectory, + softwareType: LibraryBrowseQuery.type(of: release, related: row.title.releases)) + .frame(maxWidth: .infinity).frame(height: 200) + if let owned = release.ownedGame { + Label("VCC Plus-exclusive", systemImage: "sparkles").font(.headline) + .accessibilityIdentifier("library-exclusive") + Text("By " + owned.author).font(.callout) + Text("Part of the VCC Plus collection. Compatible real CoCo hardware can run this program too.") + .font(.caption).foregroundStyle(.secondary) + } + if let manual = release.primaryManualAsset { + Button { + model.manual.open(manual, directory: model.state.directory.appendingPathComponent("Manuals"), companion: model.companionAccess) + if model.isDiskCompanion { showManual = true } + else { openWindow(id: "software-manual") } + } label: { Label(manual.manualURL?.pathExtension.lowercased() == "txt" ? "Read Instructions" : "Read Manual", systemImage: "book") } + .accessibilityIdentifier("library-read-manual") + } + if row.title.releases.count > 1 { + Picker("Format / Edition", selection: Binding(get: { release.id }, set: model.chooseRelease)) { + ForEach(row.title.releases) { edition in + Text(edition.editionLabel).tag(edition.id) + .accessibilityIdentifier("library-release-" + edition.id) + } + }.accessibilityIdentifier("library-release-picker") + } else { Label(release.mediaLabel, systemImage: mediaIcon(release.mediaType)).foregroundStyle(.secondary) } + if !release.videoBadges.isEmpty { + ViewThatFits(in: .horizontal) { + HStack { videoBadges(release) } + VStack(alignment: .leading) { videoBadges(release) } + } + } + installationCard(release) + setupCard(release) + if let owned = release.ownedGame { + Link(destination: owned.onlineManualURL) { Label("Online Manual", systemImage: "book.pages") } + .accessibilityIdentifier("library-online-manual") + if model.canOpenSource { sourceCard(release, owned: owned) } + Link(destination: owned.projectURL) { Label("Visit Project", systemImage: "arrow.up.right.square") } + } + if !release.setup.compatibilityNotes.isEmpty || !release.setup.configurationRequirements.isEmpty { + VStack(alignment: .leading, spacing: 8) { + Label("Compatibility", systemImage: "info.circle").font(.headline) + Text((release.setup.compatibilityNotes + release.setup.configurationRequirements).joined(separator: "\n\n")) + .font(.callout).textSelection(.enabled).accessibilityIdentifier("library-compatibility-notes") + } + } + assetLinks(release) + DisclosureGroup("Edition & source details") { metadata(release, title: row.title).padding(.top, 10) } + .font(.callout) + if release.ownedGame == nil { + Link(destination: release.sourceURL.deletingLastPathComponent().appendingPathComponent("", isDirectory: true)) { Label("View on Color Computer Archive", systemImage: "arrow.up.right.square") } + } + Text(model.isDiskCompanion + ? "Insert Disk creates a separate writable copy for DriveWire. Choose its drive slot, then follow the loading instructions on your real CoCo." + : "Play previews the recommended setup before restarting. You can also use the Media menu to mount installed files yourself.") + .font(.caption).foregroundStyle(.secondary) + }.padding(18).frame(maxWidth: .infinity, alignment: .leading) + }.id(release.id) + } else { + ContentUnavailableView("Choose a title", systemImage: "book.closed", description: Text("Explore its editions, loading instructions, and manuals.")) + } + } + private func sourceCard(_ release: SoftwareLibraryRelease, owned: SoftwareLibraryOwnedGame) -> some View { + SecondaryCard { + Label("Learn from the source", systemImage: "curlybraces").font(.headline) + Text("Download an editable copy to a new folder and open it in C Development. Opening does not build, run or change the CoCo.") + .font(.callout).fixedSize(horizontal: false, vertical: true) + Button("Open Source…", systemImage: "arrow.down.document") { model.chooseSourceDestination(release) } + .disabled(model.importingSourceID != nil).accessibilityIdentifier("library-open-source") + if model.importingSourceID == release.id { + if let fraction = model.sourceImportFraction { ProgressView(value: fraction) } + else { ProgressView().controlSize(.small) } + Button("Cancel Source Download", role: .cancel) { model.cancelSourceImport() } + } + if model.sourceDetailsReleaseID == release.id { + if let message = model.sourceImportMessage { Text(message).font(.callout).textSelection(.enabled) } + if let error = model.sourceImportError { Label(error, systemImage: "exclamationmark.circle").foregroundStyle(.red).font(.callout).textSelection(.enabled) } + if let directory = model.importedSourceDirectory { + Button("Show Source Folder", systemImage: "folder") { NSWorkspace.shared.activateFileViewerSelecting([directory]) } + } + } + Link("Source Repository", destination: owned.sourceRepositoryURL).font(.callout) + ForEach(Array(owned.source.companionPackages.enumerated()), id: \.offset) { _, package in + Link("Download Corresponding Library Sources", destination: package.url).font(.callout) + } + } + } + @ViewBuilder private func installationCard(_ release: SoftwareLibraryRelease) -> some View { + SecondaryCard { + if model.installingReleaseID == release.id { + Label(progressTitle, systemImage: "arrow.down.circle").font(.headline) + .accessibilityIdentifier("library-install-status") + if let fraction = model.installProgress?.fraction { ProgressView(value: fraction) } + else { ProgressView().controlSize(.small) } + if let progress = model.installProgress, progress.stage == .downloading { + Text("\(ByteCountFormatter.string(fromByteCount: progress.receivedBytes, countStyle: .file)) of \(ByteCountFormatter.string(fromByteCount: progress.totalBytes, countStyle: .file))") + .font(.caption).foregroundStyle(.secondary) + } + Button("Cancel", role: .cancel) { model.cancelInstallation() }.accessibilityIdentifier("library-cancel-install") + } else if let installed = model.state.installedReleases[release.id] { + Label("Installed", systemImage: "checkmark.circle.fill").font(.headline).foregroundStyle(.green) + .accessibilityIdentifier("library-install-status") + if model.canLaunch { playButton(release, installed: true) } + Text("Your writable media is ready. The original files are kept separately.").font(.callout) + Button { NSWorkspace.shared.open(installed.workingDirectory) } label: { Label("Show Files in Finder", systemImage: "folder") } + .accessibilityIdentifier("library-reveal-install") + Button("Remove from Library…") { removingRelease = release } + .disabled(model.launchBusy || model.hasPendingLaunch || model.installingReleaseID != nil).accessibilityIdentifier("library-remove-install") + } else { + if model.canLaunch { playButton(release, installed: false) } + Button { model.install(release) } label: { Label(model.installationErrors[release.id] == nil ? "Install Only" : "Try Again", systemImage: "arrow.down.circle") } + .buttonStyle(.bordered) + .disabled(model.launchBusy || model.hasPendingLaunch || model.installingReleaseID != nil || model.recoveringInstallations || release.downloadURLs.isEmpty) + .accessibilityIdentifier(model.installationErrors[release.id] == nil ? "library-install" : "library-retry-install") + Text(ByteCountFormatter.string(fromByteCount: release.byteSize, countStyle: .file) + " download · Does not start the software") + .font(.caption).foregroundStyle(.secondary) + Text("Keeps the original files and creates your own writable copy. Expanded files may need considerably more space than the download.") + .font(.caption).foregroundStyle(.secondary) + } + if let error = model.installationErrors[release.id] { + Label(error, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.orange) + .accessibilityIdentifier("library-install-error").textSelection(.enabled) + } + } + } + private func playButton(_ release: SoftwareLibraryRelease, installed: Bool) -> some View { + Button { model.play(release) } label: { + Label(model.launchLabel(release, installed: installed), systemImage: model.launchSymbol(release)) + }.buttonStyle(.borderedProminent) + .disabled(model.launchBusy || model.hasPendingLaunch || model.installingReleaseID != nil || model.recoveringInstallations) + .accessibilityIdentifier("library-play") + } + private var progressTitle: String { + switch model.installProgress?.stage { + case .downloading: return "Downloading…" + case .verifying: return "Checking download…" + case .extracting: return "Unpacking…" + case .preparing: return "Preparing your copy…" + case .complete: return "Finishing installation…" + case nil: return "Preparing download…" + } + } + @ViewBuilder private func videoBadges(_ release: SoftwareLibraryRelease) -> some View { + ForEach(release.videoBadges, id: \.self) { badge in + Text(badge).font(.caption.weight(.medium)).padding(.horizontal, 8).padding(.vertical, 4) + .background(.quaternary, in: Capsule()) + .help(badge.hasPrefix("6847T1") ? "Archive reports support for the 6847T1 video chip. See this edition’s compatibility notes for VCC Plus checks." : "Uses a legacy CoCo semigraphics display mode.") + .accessibilityIdentifier("library-video-badge-" + badge) + } + } + private func setupCard(_ release: SoftwareLibraryRelease) -> some View { + SecondaryCard { + Label("Using this software", systemImage: "play.rectangle").font(.headline) + if let profile = release.setup.profile { + Text(profileName(profile)).font(.subheadline.weight(.medium)) + Text([release.setup.processor.map { $0 + " CPU" }, release.setup.ramKiB.map { $0 >= 1024 ? "\($0 / 1024) MB RAM" : "\($0) KB RAM" }].compactMap { $0 }.joined(separator: " · ")) + .font(.caption).foregroundStyle(.secondary) + } + Text(loadingInstructions(release)) + .font(.callout).textSelection(.enabled).accessibilityIdentifier("library-loading-instructions") + if let command = release.setup.command, !command.isEmpty { + Text(command.replacingOccurrences(of: "\r", with: "\n").trimmingCharacters(in: .whitespacesAndNewlines)) + .font(.system(.callout, design: .monospaced)).textSelection(.enabled) + .accessibilityIdentifier("library-loading-command") + .frame(maxWidth: .infinity, alignment: .leading).padding(10) + .background(.background, in: RoundedRectangle(cornerRadius: 6)) + } + if !release.setup.reasons.isEmpty { Text(release.setup.reasons.joined(separator: "\n")).font(.callout).foregroundStyle(.secondary) } + let controls = release.setup.controls.object + if !controls.isEmpty { + VStack(alignment: .leading, spacing: 6) { + Label("Controls", systemImage: "gamecontroller").font(.subheadline.weight(.medium)) + ForEach(controls.keys.sorted(), id: \.self) { key in + Text(release.setup.controlDescription(key, source: release.ownedGame == nil ? "the Archive" : "the project")).font(.callout).textSelection(.enabled) + .accessibilityIdentifier("library-controls-" + key) + } + } + } + } + } + @ViewBuilder private func assetLinks(_ release: SoftwareLibraryRelease) -> some View { + let manuals = release.assets.filter(\.isManual) + if !manuals.isEmpty { + VStack(alignment: .leading, spacing: 8) { + Text("Manuals").font(.headline) + ForEach(manuals) { manual in + if manual.manualURL != nil { + Button { + model.manual.open(manual, directory: model.state.directory.appendingPathComponent("Manuals"), companion: model.companionAccess) + if model.isDiskCompanion { showManual = true } + else { openWindow(id: "software-manual") } + } label: { Label(manual.name, systemImage: "book") } + .buttonStyle(.link).font(.callout).help("Read the manual in VCC Plus") + .accessibilityIdentifier("library-manual-" + manual.id) + } else { + Link(destination: manual.sourceURL) { Label(manual.name, systemImage: "arrow.up.right.square") } + .font(.callout).help(release.ownedGame == nil ? "Open this document on Color Computer Archive" : "Open this project document") + } + } + } + } + } + private func metadata(_ release: SoftwareLibraryRelease, title: SoftwareLibraryTitle) -> some View { + VStack(alignment: .leading, spacing: 9) { + Text(release.name).textSelection(.enabled) + LabeledContent("Software type", value: LibraryBrowseQuery.type(of: release, related: title.releases)) + LabeledContent("System", value: systemName(release.system)) + if let os = release.setup.configuration["os_hint"].string, os != "unknown" { LabeledContent("Operating system", value: os) } + if let environment = LibraryBrowseQuery.environmentLabels[release.environment], release.environment != "unknown" { LabeledContent("Loading environment", value: environment) } + if let processor = LibraryBrowseQuery.processorLabels[release.processorRequirement], release.processorRequirement != "unknown" { Text(processor) } + ForEach(release.hardwareSupport.keys.sorted(), id: \.self) { device in + if let label = LibraryBrowseQuery.hardwareLabels[device] { + LabeledContent(label, value: LibraryBrowseQuery.hardwareUseLabels[release.hardwareSupport[device] ?? ""] ?? "Requirement unspecified") + } + } + if let publisher = release.publisher { LabeledContent("Publisher", value: publisher) } + if let year = release.year { LabeledContent("Year", value: String(year)) } + LabeledContent("Download", value: ByteCountFormatter.string(fromByteCount: release.byteSize, countStyle: .file)) + if let owned = release.ownedGame { + LabeledContent("Author", value: owned.author) + LabeledContent("License", value: owned.license) + } + LabeledContent(release.ownedGame == nil ? "Archive modified" : "Project modified", value: release.modifiedAt ?? "Unknown") + if release.ownedGame == nil, release.modifiedAt != nil, release.modifiedTimezone == nil || release.modifiedTimezone == "unspecified" { + Text("Archive date; time zone not specified.").font(.caption).foregroundStyle(.secondary) + } + LabeledContent("Loading evidence", value: release.ownedGame == nil ? release.setup.statusLabel : "Project-provided loading instructions") + Text(release.setup.validationScope.map { "VCC Plus check: " + $0.replacingOccurrences(of: "-", with: " ") } ?? "Not individually tested in VCC Plus.") + if release.ownedGame == nil && title.releases.count > 1 && title.identityStatus == "suggested" { Text("Related editions are grouped from Archive names; their contents may differ.") } + if !release.videoModes.isEmpty { Text("Video: " + release.videoModes.joined(separator: ", ")) } + if let note = release.setup.curationNote { Text(note) } + if !release.assets.isEmpty { + Divider() + Text("Artwork & manual sources").fontWeight(.medium) + ForEach(release.assets) { asset in + VStack(alignment: .leading, spacing: 3) { + Link(asset.name, destination: asset.sourceURL) + Text(asset.credit).foregroundStyle(.secondary) + if asset.matchStatus == "candidate" { Text("Suggested match from Archive names; corrections are welcome.").font(.caption).foregroundStyle(.secondary) } + } + } + } + DisclosureGroup("File identity") { + Text(release.packageSHA256).font(.system(.caption, design: .monospaced)).textSelection(.enabled) + } + } + } + private func loadingInstructions(_ release: SoftwareLibraryRelease) -> String { + let instructions = release.setup.instructions + guard !instructions.isEmpty else { return "Loading instructions are not yet available for this edition." } + // The command has its own readable code block below, so don't repeat it + // as an internal recipe annotation in the surrounding guidance. + if let range = instructions.range(of: "Guest command:"), release.setup.command != nil { + return String(instructions[.. String { + switch value { case "coco3": return "Color Computer 3"; case "coco1-2", "coco1/2": return "Color Computer 1/2"; case "unknown": return "Not specified"; default: return value } + } + private func profileName(_ value: String) -> String { + switch value { case "rom-cartridge": return "ROM Cartridge"; case "disk-basic": return "Disk BASIC"; case "hard-drive-basic", "hard-basic": return "Hard Drive BASIC"; case "coco-sdc": return "CoCo SDC"; case "nitros9": return "NitrOS-9"; default: return value.replacingOccurrences(of: "-", with: " ").capitalized } + } + private func mediaIcon(_ value: String) -> String { + switch value { case "cartridge": return "memorychip"; case "cassette": return "recordingtape"; case "sdc": return "sdcard"; default: return "externaldrive" } + } +} + + +private struct SoftwareLibraryLaunchPresentation: ViewModifier { + @ObservedObject var model: SoftwareLibraryModel + func body(content: Content) -> some View { + #if VCC_COMPANION_CLIENT + content + #else + content.sheet(item: $model.launchPreview) { preview in + SoftwareLibraryLaunchPreviewView(preview: preview, confirm: model.confirmLaunch, cancel: { model.launchPreview = nil }) + } + #endif + } +} diff --git a/platforms/macos/App/SourceFind.swift b/platforms/macos/App/SourceFind.swift new file mode 100644 index 0000000..52eea34 --- /dev/null +++ b/platforms/macos/App/SourceFind.swift @@ -0,0 +1,303 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import SwiftUI + +/// Source editors keep a weak link to their window's finder. An inactive tab +/// may retain that link, so cancellation also checks the active editor identity. +@MainActor +protocol SourceFindEditor: AnyObject { + var sourceFind: SourceFind? { get set } +} + +/// Window-local search of the live source buffer. Commands resolve the editor again +/// after a tab change; they never edit the search field, disk file, or guest. +@MainActor +final class SourceFind: ObservableObject { + weak var editor: NSTextView? { + didSet { (editor as? SourceFindEditor)?.sourceFind = self } + } + @Published var query = "" { didSet { if !query.utf8.elementsEqual(oldValue.utf8) { selectMatch(includingSelection: true) } } } + @Published var matchCase = false { didSet { selectMatch(includingSelection: true) } } + @Published var replacement = "" + @Published private(set) var message: String? + @Published private(set) var visible = false + @Published private(set) var replacing = false + @Published private(set) var focusRequest = 0 + + private var cachedSource: String? + private var cachedQuery = "" + private var cachedCase = false + private var cachedRanges: [NSRange] = [] + + func matches(in source: String) -> [NSRange] { + if let cachedSource, source.utf8.elementsEqual(cachedSource.utf8), query.utf8.elementsEqual(cachedQuery.utf8), cachedCase == matchCase { return cachedRanges } + let text = source as NSString + var ranges: [NSRange] = [] + var start = 0 + let options: NSString.CompareOptions = matchCase ? [.literal] : [.literal, .caseInsensitive] + while !query.isEmpty && start < text.length { + let range = text.range(of: query, options: options, range: NSRange(location: start, length: text.length - start)) + guard range.location != NSNotFound, range.length > 0 else { break } + ranges.append(range) + start = NSMaxRange(range) + } + cachedSource = String(decoding: source.utf8, as: UTF8.self); cachedQuery = query; cachedCase = matchCase; cachedRanges = ranges + return ranges + } + + func show(replace: Bool = false) { + message = nil + visible = true; replacing = replace; focusRequest += 1 + } + func close() { + visible = false + if let editor { editor.window?.makeFirstResponder(editor) } + } + func cancel(from source: NSTextView) -> Bool { + guard visible, editor === source else { return false } + close() + return true + } + func useSelection() { + guard let editor, editor.selectedRange().length > 0 else { return } + query = (editor.string as NSString).substring(with: editor.selectedRange()) + show() + } + func selectMatch(backward: Bool = false, includingSelection: Bool = false) { + guard let editor else { return } + message = nil + if query.isEmpty { if !visible { show() }; return } + let ranges = matches(in: editor.string) + let selection = editor.selectedRange() + let range: NSRange? + if backward { + range = ranges.last(where: { NSMaxRange($0) <= selection.location }) ?? ranges.last + } else { + let start = includingSelection ? selection.location : NSMaxRange(selection) + range = ranges.first(where: { $0.location >= start }) ?? ranges.first + } + if let range { + editor.setSelectedRange(range) + editor.scrollRangeToVisible(range) + } + } + + func replace(all: Bool) { + guard let editor, editor.isEditable, !editor.hasMarkedText(), !query.isEmpty else { return } + let source = editor.string as NSString + let originalLength = source.length + message = nil + let ranges = matches(in: editor.string) + guard let first = ranges.first, let last = ranges.last else { return } + let range: NSRange + let newText: String + if all { + // One native edit gives the editor's existing size checks, debug + // invalidation, recovery and Undo one consistent document change. + range = NSUnionRange(first, last) + // The workspaces support 1 MiB source files. Check a potentially large + // expansion before constructing it (for example replacing each space + // in a large source with a pasted paragraph). + let sourceBytes = editor.string.utf8.count + let limit = max(sourceBytes, CMOCProject.maximumSourceBytes) + let (insertedBytes, overflow) = replacement.utf8.count.multipliedReportingOverflow(by: ranges.count) + if overflow || insertedBytes > limit { + message = "Replacement would exceed the source size limit." + return + } + let removedBytes = ranges.reduce(0) { $0 + source.substring(with: $1).utf8.count } + guard sourceBytes - removedBytes <= limit - insertedBytes else { + message = "Replacement would exceed the source size limit." + return + } + var pieces: [String] = [] + var cursor = first.location + for match in ranges { + pieces.append(source.substring(with: NSRange(location: cursor, length: match.location - cursor))) + pieces.append(replacement) + cursor = NSMaxRange(match) + } + newText = pieces.joined() + } else { + range = editor.selectedRange() + guard ranges.contains(range) else { selectMatch(includingSelection: true); return } + newText = replacement + } + if source.substring(with: range).utf8.elementsEqual(newText.utf8) { + if !all { selectMatch() } + return + } + editor.breakUndoCoalescing() + editor.insertText(newText, replacementRange: range) + editor.breakUndoCoalescing() + // The delegate can reject oversized edits. Don't rename an unrelated undo. + let result = editor.string as NSString + let inserted = NSRange(location: range.location, length: newText.utf16.count) + guard result.length == originalLength - range.length + inserted.length, + result.substring(with: inserted).utf8.elementsEqual(newText.utf8) else { return } + editor.window?.makeFirstResponder(editor) + editor.undoManager?.setActionName(all ? "Replace All in File" : "Replace") + if !all { selectMatch() } + } +} + +private struct SourceFindFocusKey: FocusedValueKey { typealias Value = SourceFind } +private struct ProjectSearchFocusKey: FocusedValueKey { typealias Value = () -> Void } +private struct EmulatorWindowFocusKey: FocusedValueKey { typealias Value = Bool } +extension FocusedValues { + var sourceFind: SourceFind? { + get { self[SourceFindFocusKey.self] } set { self[SourceFindFocusKey.self] = newValue } + } + var projectSearch: (() -> Void)? { + get { self[ProjectSearchFocusKey.self] } set { self[ProjectSearchFocusKey.self] = newValue } + } + var emulatorWindow: Bool? { + get { self[EmulatorWindowFocusKey.self] } set { self[EmulatorWindowFocusKey.self] = newValue } + } +} + +struct SourceFindCommands: Commands { + @FocusedValue(\.sourceFind) private var finder + @FocusedValue(\.manualPageFind) private var pageFind + @FocusedValue(\.projectSearch) private var projectSearch + var body: some Commands { + CommandGroup(after: .textEditing) { + if let finder { + Menu("Find") { + Button("Find…") { finder.show() }.keyboardShortcut("f") + Button("Find and Replace…") { finder.show(replace: true) }.keyboardShortcut("f", modifiers: [.command, .option]) + Divider() + Button("Find Next") { finder.selectMatch() }.keyboardShortcut("g") + Button("Find Previous") { finder.selectMatch(backward: true) }.keyboardShortcut("g", modifiers: [.command, .shift]) + Button("Use Selection for Find") { finder.useSelection() }.keyboardShortcut("e") + if let projectSearch { + Divider() + Button("Find in Project…", action: projectSearch).keyboardShortcut("f", modifiers: [.command, .shift]) + } + } + } else if let pageFind { + Menu("Find") { + Button("Find on This Page…") { pageFind.show() }.keyboardShortcut("f") + Button("Find Next") { pageFind.move() }.keyboardShortcut("g") + Button("Find Previous") { pageFind.move(backward: true) } + .keyboardShortcut("g", modifiers: [.command, .shift]) + } + } + } + } +} + +struct SourceFindButton: View { + let finder: SourceFind + var body: some View { + Button { finder.show() } label: { Image(systemName: "magnifyingglass") } + .help("Find text in the current file (⌘F)").accessibilityLabel("Find in File") + .accessibilityIdentifier("source.find.open") + } +} + +/// The search field owns Return/Shift-Return while its AppKit field editor is +/// active. Request focus after attachment, including when a menu opens the bar. +private struct SourceFindField: NSViewRepresentable { + @ObservedObject var finder: SourceFind + + final class Field: NSTextField { + var wantsSearchFocus = false + func requestSearchFocus() { + wantsSearchFocus = true + DispatchQueue.main.async { [weak self] in self?.applyFocus() } + } + private func applyFocus() { + guard wantsSearchFocus, let window, window.isKeyWindow else { return } + wantsSearchFocus = false + window.makeFirstResponder(self) + selectText(nil) + } + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + if wantsSearchFocus { requestSearchFocus() } + } + } + final class Coordinator: NSObject, NSTextFieldDelegate { + let finder: SourceFind + var focusRequest: Int? + init(_ finder: SourceFind) { self.finder = finder } + func controlTextDidChange(_ notification: Notification) { + guard let field = notification.object as? NSTextField else { return } + finder.query = field.stringValue + } + func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool { + switch selector { + case #selector(NSResponder.insertNewline(_:)), #selector(NSResponder.insertNewlineIgnoringFieldEditor(_:)), + #selector(NSResponder.insertLineBreak(_:)): + finder.selectMatch(backward: NSApp.currentEvent?.modifierFlags.contains(.shift) == true) + return true + case #selector(NSResponder.cancelOperation(_:)): + finder.close() + return true + default: return false + } + } + } + func makeCoordinator() -> Coordinator { Coordinator(finder) } + func makeNSView(context: Context) -> Field { + let field = Field() + field.placeholderString = "Find in File" + field.isBezeled = true; field.bezelStyle = .roundedBezel + field.controlSize = .small; field.font = .systemFont(ofSize: NSFont.smallSystemFontSize) + field.setContentHuggingPriority(.defaultLow, for: .horizontal) + field.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + field.setAccessibilityLabel("Find in File"); field.setAccessibilityIdentifier("source.find.query") + field.delegate = context.coordinator + return field + } + func updateNSView(_ field: Field, context: Context) { + if !field.stringValue.utf8.elementsEqual(finder.query.utf8) { field.stringValue = finder.query } + if context.coordinator.focusRequest != finder.focusRequest { + context.coordinator.focusRequest = finder.focusRequest + field.requestSearchFocus() + } + } +} + +struct SourceFindBar: View { + @ObservedObject var finder: SourceFind + let source: String + let readOnly: Bool + var body: some View { + if finder.visible { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 6) { + SourceFindField(finder: finder).frame(minWidth: 64) + let count = finder.matches(in: source).count + if !finder.query.isEmpty { + Text(count == 0 ? "No matches" : "\(count) \(count == 1 ? "match" : "matches")") + .font(.caption).foregroundStyle(.secondary).accessibilityIdentifier("source.find.count") + } + Button { finder.selectMatch(backward: true) } label: { Image(systemName: "chevron.up") } + .disabled(count == 0).help("Find previous occurrence (⇧⌘G)").accessibilityLabel("Find Previous") + Button { finder.selectMatch() } label: { Image(systemName: "chevron.down") } + .disabled(count == 0).help("Find next occurrence (⌘G)").accessibilityLabel("Find Next") + Toggle("Match Case", isOn: $finder.matchCase).toggleStyle(.checkbox) + Button(finder.replacing ? "Hide Replace" : "Show Replace") { finder.show(replace: !finder.replacing) } + Button("Done") { finder.close() }.keyboardShortcut(.escape, modifiers: []) + } + if let message = finder.message { + Text(message).font(.caption).foregroundStyle(.secondary) + } + if finder.replacing { + HStack(spacing: 6) { + TextField("Replace with", text: $finder.replacement) + .accessibilityLabel("Replace with").accessibilityIdentifier("source.find.replacement") + Group { + Button("Replace") { finder.replace(all: false) } + Button("Replace All in File") { finder.replace(all: true) } + }.disabled(readOnly || finder.matches(in: source).isEmpty) + } + } + }.textFieldStyle(.roundedBorder).controlSize(.small).padding(.horizontal, 10).padding(.vertical, 5) + .background(.bar) + .onExitCommand { finder.close() } + } + } +} diff --git a/platforms/macos/App/StartupDefaults.swift b/platforms/macos/App/StartupDefaults.swift new file mode 100644 index 0000000..8b7bad2 --- /dev/null +++ b/platforms/macos/App/StartupDefaults.swift @@ -0,0 +1,310 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import CryptoKit + +enum AppIdentity { + static let bundleID = "com.brianholman.vccplus.oss.mac" + // VCC Plus starts independently; no automatic import of legacy settings. + static var supportDirectory: URL { + supportDirectory(in: FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]) + } + static func supportDirectory(in parent: URL) -> URL { + parent.appendingPathComponent(bundleID, isDirectory: true) + } +} + +// Built-in definitions are separate from the editable profile library. +enum SystemProfile: String, CaseIterable, Identifiable, Sendable { + case diskBasic, hardDriveBasic, cocoSDC, nitros9 + var id: String { "system-" + rawValue } + var name: String { + switch self { case .diskBasic: return "Disk BASIC"; case .hardDriveBasic: return "Hard Drive BASIC"; case .nitros9: return "NitrOS-9 L2 V3.3.0"; case .cocoSDC: return "CoCo SDC" } + } + var diskROMName: String { self == .cocoSDC ? "sdcdos.rom" : self == .diskBasic ? "disk11.rom" : "rgbdos.rom" } + var summary: String { + switch self { + case .cocoSDC: return "Local SD card folder with Hello World mounted in drive 0" + case .diskBasic: return "Default disk and cassette loaded" + case .hardDriveBasic: return "Default hard disk and floppy loaded" + case .nitros9: return "Automatic OS-9 boot, with shared data disk in HD1" + } + } + var explanation: String { + switch self { + case .cocoSDC: return "6809, 512 KB, composite video, and CoCo SDC in Multi-Pak startup slot 4. A writable local SD card folder contains HELLO.DSK. Its startup.cfg mounts that disk as SDC0; the example does not load or run automatically. No floppy or hard-disk controller is needed." + case .diskBasic: return "The app's default setup: 6809, 512 KB, composite video, and the floppy controller in Multi-Pak slot 4. The Hello World floppy and stopped cassette are ready." + case .hardDriveBasic: return "6809, 512 KB, composite video, RGBDOS in Multi-Pak slot 4, and the hard-disk controller in slot 1. HD0 has 256 initialized BASIC volumes; volume 0 contains HELLO. FD0 holds the shared Hello World floppy. The cassette is ejected." + case .nitros9: return "6809, 512 KB, composite video, RGBDOS in slot 4 and the hard-disk controller in slot 1. HD0 holds the NitrOS-9 archive; HD1 is the same working disk used by Hard Drive BASIC. FD0 holds the shared Hello World floppy. Loading boots NitrOS-9 automatically." + } + } + var instructions: String { + switch self { + case .cocoSDC: return "Type DIR 0, then LOAD \"HELLO:0\" and RUN. To mount the starter disk again, type DRIVE 0,\"/HELLO.DSK\". Open the SD card folder in Finder from Cartridge Settings to add other images. Your local files are preserved when this profile is loaded again." + case .diskBasic: return "Disk: type LOAD\"HELLO\", then RUN. Tape: press Play in Cassette, type CLOAD\"HELLO\", then RUN." + case .hardDriveBasic: return "Hard disk: type LOAD\"HELLO\", then RUN. For the floppy, type DRIVE OFF before LOAD\"HELLO\". DRIVE ON returns to the hard disk. BASIC's drive numbers are virtual volumes within HD0, not the app's HD0/HD1 devices." + case .nitros9: return "At the OS-9 prompt, use dir /dd and dir /h1. Change folders with chd; list text files with list. The main window's Using your CoCo guide includes commands and archive links. Cold Restart opens the archive menu; select 6 (EXIT TO BASIC) and press Return. At BASIC, type DOS 255 to boot again." + } + } + +} + +// Optional private payload for development and distribution. ROMs never enter Git. +struct StarterKit: Sendable { + let directory: URL + static var bundled: Self? { + Bundle.main.url(forResource: "StarterKit", withExtension: nil).map { Self(directory: $0) } + } + private func romResource(_ name: String, in support: URL) throws -> (Data, URL) { + let source = directory.appendingPathComponent(name) + let bytes: Data + if name == "coco3.rom" { bytes = try ROMImage.read(source) } + else if name == "pic-7040-510.bin" { bytes = try DiskFiles.readSpeechChipROM(source, speech: false) } + else if name == "sp0256-al2.bin" { bytes = try DiskFiles.readSpeechChipROM(source, speech: true) } + else if name == "orch90.rom" { bytes = try DiskFiles.readOrchestraROM(source) } + else if name == "sdcdos.rom" { bytes = try DiskFiles.readSDCROM(source) } + else { bytes = try DiskFiles.readROM(source) } + let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() + // Content-addressed copies keep saved profiles valid when the .app moves + // or is upgraded. Never modify the signed bundle or an existing ROM. + return (bytes, support.appendingPathComponent("Bundled ROMs/\(digest)/\(name)")) + } + // Read-only identity lookup for contextual help; no seeding or preference changes. + func cachedROMURL(_ name: String, in support: URL) throws -> URL { + try romResource(name, in: support).1 + } + func rom(_ name: String, in support: URL) throws -> URL { + let (bytes, target) = try romResource(name, in: support) + if FileManager.default.fileExists(atPath: target.path) { + guard try Data(contentsOf: target) == bytes else { throw StartupStore.Failure.changedROM } + } else { + try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + try bytes.write(to: target, options: .withoutOverwriting) + } + return target + } + func seed(_ name: String, in support: URL) throws -> URL { + let source = directory.appendingPathComponent(name) + let target = support.appendingPathComponent("Starter Media/\(name)") + try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + if !FileManager.default.fileExists(atPath: target.path) { + try FileManager.default.copyItem(at: source, to: target) + } + return target + } + // Publish a complete card on first use. Existing cards, including files a + // user has edited or deliberately removed, are never reseeded or replaced. + func seedSDCCard(in support: URL) throws -> URL { + let target = support.appendingPathComponent("Starter Media/CoCo SDC", isDirectory: true) + if FileManager.default.fileExists(atPath: target.path) { + try DiskFiles.validateSDCFolder(target) + return target + } + let parent = target.deletingLastPathComponent() + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + let temporary = parent.appendingPathComponent(".sdc-starter-" + UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: temporary) } + try FileManager.default.copyItem(at: directory.appendingPathComponent("Hello World.dsk"), + to: temporary.appendingPathComponent("HELLO.DSK")) + try Data("0=HELLO.DSK\n".utf8).write(to: temporary.appendingPathComponent("startup.cfg"), options: .withoutOverwriting) + try FileManager.default.moveItem(at: temporary, to: target) + return target + } + // Two small authored volumes expand into the conventional RGBDOS layout. + // An authored empty OS-9 filesystem precedes the BASIC volumes. No OS is bundled here. + func os9Header() throws -> Data { + let bytes = try Data(contentsOf: directory.appendingPathComponent("Blank OS9 Header.bin")) + guard bytes.count == 8192, bytes.prefix(3) == Data([5, 160, 0]) else { + throw ProfileFailure.message("The bundled empty OS-9 template is invalid. Existing media has been kept.") + } + return bytes + } + func seedHardDisk(in support: URL) throws -> URL { + let target = support.appendingPathComponent("Starter Media/Hello World.vhd") + if FileManager.default.fileExists(atPath: target.path) { return target } + let hello = try Data(contentsOf: directory.appendingPathComponent("Hello Hard Disk.dsk")) + let blank = try Data(contentsOf: directory.appendingPathComponent("Blank Disk.dsk")) + guard hello.count == 161280, blank.count == 161280 else { throw StartupStore.Failure.invalid } + let parent = target.deletingLastPathComponent() + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + let temporary = parent.appendingPathComponent(".hard-starter-" + UUID().uuidString) + try Data().write(to: temporary, options: .withoutOverwriting) + defer { try? FileManager.default.removeItem(at: temporary) } + let file = try FileHandle(forWritingTo: temporary) + do { + try file.write(contentsOf: os9Header()) + try file.truncate(atOffset: 0x5a000 * 256) + try file.seekToEnd() + try file.write(contentsOf: hello) + for _ in 1..<256 { try file.write(contentsOf: blank) } + try file.synchronize(); try file.close() + } catch { try? file.close(); throw error } + // moveItem refuses to replace an existing working copy. + try FileManager.default.moveItem(at: temporary, to: target) + return target + } +} + +struct StartupStore: Sendable { + struct Selection: Codable, Equatable { + var version = 1 + var systemROM: URL? + var cassette: URL? + var bootNitros9: Bool? + // Only the built-in preset selection may establish this local startup provenance. + // Older selections and imported personal profiles have no network default. + var builtInNitros9: Bool? + func validate() throws { + guard version == 1 else { throw Failure.invalid } + let references: [URL] = [systemROM, cassette].compactMap { $0 } + for reference in references { + let host = reference.host ?? "" + guard reference.isFileURL, host.isEmpty || host == "localhost", reference.path.hasPrefix("/") else { throw Failure.invalid } + } + } + } + enum Failure: LocalizedError { + case invalid, changedROM, unavailable + var errorDescription: String? { + switch self { + case .unavailable: return "Bundled app defaults are unavailable in this build. Add the private development ROMs or choose your own system and disk ROMs." + case .invalid: return "The remembered startup selections are damaged. Choose your system ROM and cassette again. Existing media has been kept." + case .changedROM: return "A cached bundled ROM was changed. Choose a valid system or disk ROM; existing files have been kept." + } + } + } + let directory: URL + let kit: StarterKit? + var url: URL { directory.appendingPathComponent("Startup.json") } + func read() throws -> Selection? { + guard FileManager.default.fileExists(atPath: url.path) else { return nil } + let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } + let data = try handle.read(upToCount: 65537) ?? Data() + guard data.count <= 65536 else { throw Failure.invalid } + let value = try JSONDecoder().decode(Selection.self, from: data) + try value.validate(); return value + } + func save(_ selection: Selection) throws { + try selection.validate() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try JSONEncoder().encode(selection).write(to: url, options: .atomic) + } + // Used by both first launch and explicit recovery. Seed only absent example + // files; restoring configuration must never overwrite a user's saved work. + func appDefaults() throws -> ConfigurationProfile { try systemProfile(.diskBasic) } + + func unavailableReason(for kind: SystemProfile) -> String? { + guard let kit else { return Failure.unavailable.localizedDescription } + let names = ["coco3.rom", "Hello World.dsk"] + (kind == .cocoSDC ? ["sdcdos.rom"] : kind == .diskBasic + ? ["disk11.rom", "Hello World.cas"] : ["rgbdos.rom", "Blank Disk.dsk", "Hello Hard Disk.dsk", "Blank OS9 Header.bin"]) + + (kind == .nitros9 ? ["NitrOS-9 L2 V3.3.0.vhd"] : []) + let missing = names.filter { !FileManager.default.fileExists(atPath: kit.directory.appendingPathComponent($0).path) } + return missing.isEmpty ? nil : "This build is missing starter resources: " + missing.joined(separator: ", ") + } + + func systemProfile(_ kind: SystemProfile, freshMedia: Bool = false) throws -> ConfigurationProfile { + guard let kit else { throw Failure.unavailable } + if let reason = unavailableReason(for: kind) { throw ProfileFailure.message(reason) } + let support = freshMedia ? directory.appendingPathComponent("Starter Media Copies/" + UUID().uuidString) : directory + do { + var profile = ConfigurationProfile(name: kind.name) + profile.systemROM = try kit.rom("coco3.rom", in: directory) + var cartridges = CartridgeAssignments() + cartridges.multiPak = true; cartridges.mpiConfigured = true; cartridges.physicalSlot = 4 + if kind == .cocoSDC { + cartridges.slots[4] = .init(kind: .sdc, url: try kit.rom("sdcdos.rom", in: directory), + sdcFolderURL: try kit.seedSDCCard(in: support), sdcReadOnly: false) + } else { + profile.media.rom = try kit.rom(kind.diskROMName, in: directory) + profile.media.drives[0] = .init(url: try kit.seed("Hello World.dsk", in: support), writeProtected: false) + cartridges.slots[4].kind = .floppy + } + var hard = HardDiskAssignments() + if kind == .hardDriveBasic || kind == .nitros9 { + cartridges.slots[1].kind = .hardDisk + let shared = try kit.seedHardDisk(in: support) + hard.drives[kind == .nitros9 ? 1 : 0] = .init(url: shared, writeProtected: false) + if kind == .nitros9 { + hard.drives[0] = .init(url: try kit.seed("NitrOS-9 L2 V3.3.0.vhd", in: support), writeProtected: false) + profile.bootNitros9 = true + } + } else if kind == .diskBasic { + profile.cassette = try kit.seed("Hello World.cas", in: support) + } + profile.media.cartridges = cartridges; profile.media.hardDisks = hard + try profile.validate() + return profile + } catch { + if freshMedia { try? FileManager.default.removeItem(at: support) } + throw error + } + } + + // Only the app-owned shared data disk is eligible. Arbitrary imported HD1 + // images are never formatted. Nonzero partitions are always preserved. + func initializeSharedOS9(for profile: ConfigurationProfile) throws -> Bool { + guard profile.bootNitros9 == true, let kit, + let drive = profile.media.hardDisks?.drives[1], !drive.writeProtected, !drive.temporary else { return false } + let target = drive.url.standardizedFileURL + let expected = directory.appendingPathComponent("Starter Media/Hello World.vhd").standardizedFileURL + guard target == expected else { return false } // Fresh copies were formatted when seeded. + guard try target.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink != true else { return false } + let image = try HardDiskFiles.readImage(target) + guard !image.readOnly, image.data.count == 135659520 else { + throw ProfileFailure.message("The shared data disk cannot be initialized. Its contents were kept; check its size and write access.") + } + guard image.data.prefix(0x5a000 * 256).allSatisfy({ $0 == 0 }) else { return false } + let header = try kit.os9Header() + let backup = target.deletingLastPathComponent().appendingPathComponent("Before OS9 initialization " + UUID().uuidString + ".vhd") + try FileManager.default.copyItem(at: target, to: backup) + guard try HardDiskFiles.readImage(backup).digest == image.digest else { throw HardDiskFiles.Failure.changed } + var patches = Data() + for sector in 0..<(header.count / 256) { + var number = UInt32(sector).littleEndian + withUnsafeBytes(of: &number) { patches.append(contentsOf: $0) } + patches.append(header[(sector * 256)..<((sector + 1) * 256)]) + } + _ = try HardDiskFiles.saveAutomatically(patches, length: image.data.count, to: target, expected: image.digest) + return true + } + + func prepare(diskStore: DiskAssignmentStore) throws -> Selection? { + if let existing = try read() { return existing } + guard let kit else { return nil } + var selection = Selection(systemROM: try kit.rom("coco3.rom", in: directory)) + // Migrate existing installs without changing their topology or media. + // A completed marker prevents later ejections/deletions being reseeded. + if !FileManager.default.fileExists(atPath: diskStore.url.path) { + let profile = try appDefaults() + selection.cassette = profile.cassette + try diskStore.save(profile.media) + } + try save(selection) + return selection + } +} + +// Explicit native release QA uses the production startup path in an isolated +// temporary home for VCC's files. Normal launches never enter this mode. +@MainActor +final class StartupValidationContext { + let directory: URL + let defaults: UserDefaults + private let suite: String + init() throws { + guard StarterKit.bundled != nil else { throw StartupStore.Failure.invalid } + directory = FileManager.default.temporaryDirectory.appendingPathComponent("VCCStartupValidation-" + UUID().uuidString) + suite = "VCCStartupValidation-" + UUID().uuidString + defaults = UserDefaults(suiteName: suite)! + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + NSLog("VCC startup validation files: %@", directory.path) + } + func model() -> MachineModel { + MachineModel(diskStore: .init(url: directory.appendingPathComponent("DiskAssignments.json")), displayDefaults: defaults, + inputStore: .init(url: directory.appendingPathComponent("Input.json")), startupStore: .init(directory: directory, kit: .bundled)) + } + func cleanUp() { + defaults.removePersistentDomain(forName: suite) + try? FileManager.default.removeItem(at: directory) + } +} diff --git a/platforms/macos/App/SystemView.swift b/platforms/macos/App/SystemView.swift new file mode 100644 index 0000000..f5e1993 --- /dev/null +++ b/platforms/macos/App/SystemView.swift @@ -0,0 +1,464 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI + +enum SystemTarget: Hashable, Identifiable { + case computer, keyboard, joystick, cassette, printer, library, manuals, monitor, selector, slot(Int), sdc(Int), floppy(Int), hard(Int) + var id: String { String(describing: self) } + var title: String { + switch self { + case .manuals: return "Help — Manual Library" + case .library: return "Software Library" + case .monitor: return "Monitor video signal" + case .computer: return "Color Computer 3" + case .keyboard: return "Keyboard" + case .joystick: return "Joystick ports" + case .cassette: return "Cassette" + case .printer: return "Tandy TP-10 printer" + case .selector: return "Multi-Pak startup selector" + case .slot(let n): return "Multi-Pak slot \(n)" + case .sdc(let n): return "CoCo SDC in slot \(n)" + case .floppy(let n): return "Floppy FD\(n)" + case .hard(let n): return "Hard disk HD\(n)" + } + } + var action: String { + switch self { + case .manuals: return "Open the offline manual index" + case .library: return "Open the Software Library" + case .printer: return "Open Printer Output" + case .monitor: return "Choose the monitor video signal" + default: return "Show " + title + " controls" + } + } + var mediaDestination: MediaDestination? { + switch self { + case .computer: return .systemROM + case .cassette: return .cassette + case .slot(let n), .sdc(let n): return .cartridge(n) + case .floppy(let n): return .floppy(n) + case .hard(let n): return .hardDisk(n) + default: return nil + } + } + // Scene coordinates shared with runtime-system.svg. The slot targets follow + // the sockets and their numbered shelf, independent of cartridge occupancy. + var rect: CGRect { + switch self { + case .manuals: return CGRect(x: 453, y: 400, width: 58, height: 50.025) + case .library: return CGRect(x: 430, y: 19, width: 285, height: 115) + case .monitor: return CGRect(x: 54, y: 219, width: 272, height: 23) + case .computer: return CGRect(x: 52, y: 279, width: 284, height: 24) + case .keyboard: return CGRect(x: 49, y: 324, width: 284, height: 84) + case .joystick: return CGRect(x: -100, y: 354, width: 112, height: 94) + case .cassette: return CGRect(x: -111, y: 205, width: 150, height: 138) + case .printer: return CGRect(x: -113, y: 89, width: 159, height: 93) + case .selector: return CGRect(x: 367, y: 368, width: 195, height: 21) + case .sdc(let n): return SystemTarget.slot(n).rect + case .slot(let n): + return [CGRect(x: 366, y: 313, width: 173, height: 16), + CGRect(x: 358, y: 295, width: 170, height: 15), + CGRect(x: 352, y: 278, width: 166, height: 14), + CGRect(x: 349, y: 260, width: 158, height: 16)][n - 1] + case .floppy(let n): + return Self.driveFace(y: [339.966641, 308.442122, 268.911376, 237.386856][n]) + case .hard(let n): + return Self.driveFace(y: n == 0 ? 411.021906 : 379.497387) + } + } + private static func driveFace(y: Double) -> CGRect { + // Exact outer black face bounds after the SVG's vertical bay transform. + // Equal insets plus strokeBorder keep every highlight inside the face. + CGRect(x: 649.35728, y: y, width: 174.13544, height: 31.79139 * 0.96012592) + .insetBy(dx: 1.25, dy: 1.25) + } + +} + +struct MachineStage: View { + @Environment(\.openWindow) private var openWindow + @ObservedObject var machine: MachineModel + @ObservedObject var presentation: PresentationSettings + let system: Bool + let openManualIndex: () -> Void + @State private var target: SystemTarget? + @State private var list = false + @State private var hovered: SystemTarget? + @FocusState private var focused: SystemTarget? + private var targets: [SystemTarget] { + var result: [SystemTarget] = [.computer, .keyboard, .printer, .cassette, .joystick, .monitor, .library, .manuals] + if machine.hardware.values["mpi"] == "on" { result += [.selector] + (1...4).map { .slot($0) } } + if machine.hardware.values["floppyCase"] == "on" { result += (0..<4).map { .floppy($0) } } + if machine.hardware.values["hardCase"] == "on" { result += (0..<2).map { .hard($0) } } + return result + } + var body: some View { + GeometryReader { proxy in + let geometry = SystemGeometry(size: proxy.size, system: system, expanded: presentation.expanded, + contentBounds: HardwareArtwork.shared.layoutBounds(machine.hardware.values)) + ZStack(alignment: .topLeading) { + if system { + HardwareCanvas(values: machine.hardware.values, part: "scene") + .frame(width: geometry.scene.width, height: geometry.scene.height) + .position(x: geometry.scene.midX, y: geometry.scene.midY) + .opacity(presentation.expanded ? 0.20 : 1).accessibilityHidden(true).allowsHitTesting(false) + if let image = HardwareArtwork.shared.image("software-library-shelf.png") { + let shelf = geometry.rect(SystemGeometry.libraryArtwork) + Image(nsImage: image).resizable().scaledToFit() + .frame(width: shelf.width, height: shelf.height) + .position(x: shelf.midX, y: shelf.midY) + .opacity(presentation.expanded ? 0.20 : 1) + .accessibilityHidden(true).allowsHitTesting(false) + } + if let image = HardwareArtwork.shared.image("manual-help.pdf") { + let button = geometry.rect(SystemTarget.manuals.rect) + Image(nsImage: image).resizable().scaledToFit() + .frame(width: button.width, height: button.height) + .position(x: button.midX, y: button.midY) + .opacity(presentation.expanded ? 0.20 : 1) + .accessibilityHidden(true).allowsHitTesting(false) + } + if !presentation.expanded { + connectionOverlay(geometry) + ForEach(["floppy", "hard"], id: \.self) { kind in + if machine.hardware.values[kind + "Case"] == "on" && machine.hardware.values[kind] != "on" { + let r = geometry.rect(CGRect(x: 649, y: kind == "floppy" ? 300 : 400, width: 176, height: 20)) + Text("\(kind == "floppy" ? "Floppy" : "Hard-disk") controller disconnected") + .font(.caption).foregroundStyle(.black).padding(4) + .background(.white.opacity(0.9), in: RoundedRectangle(cornerRadius: 4)) + .position(x: r.midX, y: r.midY).allowsHitTesting(false) + } + } + ForEach(targets.filter { $0 != .monitor }) { item in + hotspot(item, frame: geometry.rect(item.rect)) + } + ForEach(1...4, id: \.self) { n in + if machine.hardware.values["mpi"] == "on", machine.hardware.values["slot\(n)"] == "sdc", + let rect = HardwareArtwork.shared.cartridgeHitRect(slot: n, values: machine.hardware.values) { + hotspot(.sdc(n), frame: geometry.rect(rect)) + } + } + } + HardwareCanvas(values: machine.hardware.values, part: "monitor") + .frame(width: geometry.monitor.width, height: geometry.monitor.height) + .position(x: geometry.monitor.midX, y: geometry.monitor.midY).accessibilityHidden(true).allowsHitTesting(false) + hotspot(.monitor, frame: geometry.monitorRect(SystemTarget.monitor.rect)) + } + // This representable occupies the same structural position in + // every presentation: one MTKView, one input owner, one session. + EmulatorDisplay(machine: machine, presentationToken: "\(system)-\(presentation.expanded)") + .frame(width: geometry.screen.width, height: geometry.screen.height) + .position(x: geometry.screen.midX, y: geometry.screen.midY) + if machine.pixels == nil { + VStack(spacing: 8) { + Text("VCC").font(.headline) + Text(machine.state == .empty ? "Open a CoCo 3 ROM to begin" : "Press Run to generate a frame") + .font(.callout).multilineTextAlignment(.center) + }.foregroundStyle(.white.opacity(0.85)) + .frame(width: geometry.screen.width, height: geometry.screen.height) + .position(x: geometry.screen.midX, y: geometry.screen.midY).allowsHitTesting(false) + } + if system { + HStack { + Button { list.toggle() } label: { Label("Devices", systemImage: "list.bullet") } + .popover(isPresented: $list) { + ScrollView { + VStack(alignment: .leading, spacing: 8) { + Text("System devices").font(.headline) + Text("All illustrated objects are available here, including obscured slots.").font(.caption).foregroundStyle(.secondary) + ForEach(targets) { item in + if item == .manuals { + Button { list = false; openManualIndex() } label: { + Label("Open Manual Library", systemImage: "books.vertical") + } + } else { + DisclosureGroup(item.title + " — " + description(item)) { + SystemDeviceControls(machine: machine, target: item).padding(.vertical, 8) + } + } + } + }.padding(16) + }.frame(width: 430, height: 520) + } + Toggle("Connections", isOn: $presentation.showConnections).toggleStyle(.button) + .help("Show which controller connects to each set of drives") + Spacer(minLength: 16) + Toggle("Show Clickable Areas", isOn: $presentation.showClickableAreas) + .toggleStyle(.checkbox).accessibilityIdentifier("show-clickable-areas") + .help("Outline available controls with dashed gray lines. Hover or focus highlights one in blue.") + }.controlSize(.small).environment(\.colorScheme, .light).padding(10) + } + } + .onChange(of: presentation.mode) { _, _ in target = nil; list = false; hovered = nil; focused = nil } + .onChange(of: presentation.expanded) { _, _ in target = nil; list = false; hovered = nil; focused = nil } + } + } + private func hotspot(_ item: SystemTarget, frame: CGRect) -> some View { + let active = focused == item || hovered == item + return Button { + if item == .manuals { target = nil; openManualIndex() } + else if item == .library { target = nil; openWindow(id: "software-library") } + else if item == .printer { target = nil; openWindow(id: "printer") } + else { target = item } + } label: { + RoundedRectangle(cornerRadius: 4).fill(Color.white.opacity(0.001)) + .contentShape(Rectangle()) + .overlay(alignment: .topTrailing) { + if unavailable(item) { Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.orange).font(.caption) } + } + .overlay { + RoundedRectangle(cornerRadius: 4) + .strokeBorder(active ? Color.accentColor : presentation.showClickableAreas ? Color.gray.opacity(0.7) : .clear, + style: StrokeStyle(lineWidth: active ? 2 : 1, dash: active ? [] : [4, 3])) + .allowsHitTesting(false) + } + }.buttonStyle(.plain) + // Do not grow narrow MPI rows into their neighbours at small sizes. + // Devices supplies a larger, accessible alternative for every target. + .frame(width: frame.width, height: frame.height) + .modifier(MediaDropTarget(machine: machine, destination: item.mediaDestination)) + .focused($focused, equals: item) + .onHover { hovered = $0 ? item : nil } + .accessibilityIdentifier("system-\(item.id)") + .accessibilityLabel(item.title).accessibilityValue(description(item)) + .help(item.action) + .popover(isPresented: Binding(get: { target == item }, set: { if !$0 && target == item { target = nil } })) { + SystemDeviceControls(machine: machine, target: item) + } + // Attach the popover to the device bounds, before scene positioning. + .position(x: frame.midX, y: frame.midY) + } + private func unavailable(_ item: SystemTarget) -> Bool { + switch item { + case .slot(let n), .sdc(let n): return machine.cartridgeAssignments.slots[n].kind != .empty && machine.cartridgeNames[n].isEmpty + case .floppy(let n): return machine.diskRestoreErrors[n] != nil + case .hard(let n): return machine.hardRestoreErrors[n] != nil + case .printer: return machine.printer.dropped > 0 + default: return false + } + } + private func description(_ item: SystemTarget) -> String { + switch item { + case .manuals: return "Offline books for VCC Plus" + case .library: return "Browse, install and play Color Computer software" + case .monitor: return machine.videoOutput.label + case .printer: return "\(machine.printer.enabled ? "Capturing" : "Capture stopped") · \(machine.printer.byteCount.formatted()) bytes\(machine.printer.unsaved ? " · Not saved" : "")" + case .computer: return "\(MachineSettings.memoryLabels[machine.settings.ram]), \(machine.use6309 ? "Hitachi 6309" : "Motorola 6809")" + case .cassette: return machine.tapeMounted ? machine.tapeName + " · " + machine.tapeTransportDescription : "Empty" + case .slot(let n), .sdc(let n): + let slot = machine.cartridgeAssignments.slots[n] + if slot.kind == .sdc, !machine.cartridgeNames[n].isEmpty { + return "CoCo SDC · \(slot.sdcFolderURL?.lastPathComponent ?? "No SD card folder") · \(machine.hardware.values["sdcActivity"] ?? "empty") · \(machine.sdcReadOnly ? "Read-only" : "Writable")" + } + return slot.kind == .empty ? "Empty" : machine.cartridgeNames[n].isEmpty ? "Unavailable — open controls to repair" : machine.cartridgeNames[n] + case .selector: return "Startup \(machine.cartridgeAssignments.physicalSlot); live ROM \(machine.romSlot), I/O \(machine.ioSlot)" + case .floppy(let n): return diskDescription(machine.disks, n, activity: n) + case .hard(let n): return diskDescription(machine.hardDisks, n, activity: n+4) + case .joystick: return "Assignments for both CoCo ports" + case .keyboard: return "Host key mappings and input help" + } + } + private func diskDescription(_ disks: [VCCDiskSnapshot], _ n: Int, activity: Int) -> String { + guard disks.indices.contains(n), disks[n].mounted else { + let error = activity < 4 ? machine.diskRestoreErrors[n] : machine.hardRestoreErrors[n] + return error == nil ? "Empty" : "Unavailable — open controls to repair the file location" + } + let d = disks[n] + return "\(d.name) · \(machine.hardware.activities[activity].rawValue)\(d.dirty ? " · Unsaved" : "")\(d.writeProtected ? " · Write protected" : "")" + } + @ViewBuilder private func connectionOverlay(_ geometry: SystemGeometry) -> some View { + let selection = focused ?? hovered ?? target + ForEach(1...4, id: \.self) { n in + let kind = machine.hardware.values["slot\(n)"] ?? "empty" + if (kind == "floppy" || kind == "hard") && (presentation.showConnections || selection == .slot(n)) { + let from = geometry.rect(SystemTarget.slot(n).rect) + let to = geometry.rect((kind == "floppy" ? SystemTarget.floppy(2) : SystemTarget.hard(1)).rect) + Path { p in + p.move(to: CGPoint(x: from.midX, y: from.minY)) + p.addCurve(to: CGPoint(x: to.minX, y: to.midY), control1: CGPoint(x: from.midX+30, y: from.minY-55), control2: CGPoint(x: to.minX-40, y: to.midY-50)) + }.stroke(Color.accentColor.opacity(0.65), style: StrokeStyle(lineWidth: 2, dash: [5,4])) + .allowsHitTesting(false).accessibilityHidden(true) + Text("Slot \(n) → \(kind == "floppy" ? "FD0–FD3" : "HD0–HD1")") + .font(.caption).padding(4).background(.regularMaterial, in: RoundedRectangle(cornerRadius: 4)) + .position(x: (from.midX+to.minX)/2, y: min(from.minY,to.minY)-22).allowsHitTesting(false) + } + } + } +} + +struct SystemDeviceControls: View { + @ObservedObject var machine: MachineModel + let target: SystemTarget + @Environment(\.openWindow) private var openWindow + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text(target.title).font(.headline) + controls + if let error = machine.fileError ?? machine.error { Text(error).foregroundStyle(.red).textSelection(.enabled) } + }.padding(16).frame(width: 375) + } + @ViewBuilder private var controls: some View { + switch target { + case .manuals: EmptyView() // Opens the reader directly. + case .library: + Text("Explore the software collection, read manuals, and choose something to play.") + Button { openWindow(id: "software-library") } label: { + Label("Open Software Library", systemImage: "books.vertical") + } + .accessibilityIdentifier("system-library-open") + case .printer: + SystemPrinterControls(printer: machine.printer) + case .monitor: + SystemVideoControls(machine: machine).equatable() + case .computer: + Text("Memory holds your working program. CPU or memory changes restart the computer and clear RAM.") + Text("\(MachineSettings.memoryLabels[machine.settings.ram]) · \(machine.use6309 ? "Hitachi 6309" : "Motorola 6809")") + Button("Machine Settings…") { openWindow(id: "machine-settings") } + case .keyboard, .joystick: + Text("Your Mac controller, mouse or keyboard can operate either CoCo joystick port. The pictured joystick's position does not assign a port.") + Text("Click the monitor to type. Escape is Break; Home is Clear. Leaving the display releases held keys and buttons.") + Button("Keyboard and Joysticks…") { openWindow(id: "input") } + case .cassette: + Text(machine.tapeName).textSelection(.enabled) + Text(machine.tapeTransportDescription) + Text("Play prepares the tape; the computer controls movement. Record creates a new tape in memory. Export keeps a recording on your Mac.").font(.callout).foregroundStyle(.secondary) + HStack { + Button("Play") { machine.tapeAction(1) }.disabled(!machine.tapeMounted || machine.tapeMode == 2) + Button("Stop") { machine.tapeAction(0) }.disabled(!machine.tapeMounted) + Button("Rewind") { machine.tapeAction(2) }.disabled(!machine.tapeMounted) + }.disabled(machine.busy || machine.state == .closed) + if machine.tapeDirty || machine.tapeMode == 2 { Label("Unsaved recording — export to keep", systemImage: "exclamationmark.circle").foregroundStyle(.orange) } + Button("Cassette Controls…") { openWindow(id: "cassette") } + case .selector: + Text("Startup selection takes effect with a cold restart and clears RAM. Software can route ROM and disk I/O independently afterward.").font(.callout) + Picker("Startup slot", selection: Binding(get: { machine.cartridgeAssignments.physicalSlot }, set: machine.selectPhysicalSlot)) { + ForEach(1...4,id: \.self) { Text("\($0)").tag($0) } + }.pickerStyle(.segmented).disabled(machine.busy || machine.diskSaving || machine.diskBusy) + Text("Live ROM slot \(machine.romSlot) · Disk I/O slot \(machine.ioSlot)").foregroundStyle(.secondary) + case .slot(let n), .sdc(let n): + let slot = machine.cartridgeAssignments.slots[n] + if slot.kind == .sdc { SystemSDCControls(machine: machine, slot: n) } else { + Text(slot.url?.lastPathComponent ?? (slot.kind == .floppy ? "Floppy controller (FD-502)" : slot.kind == .hardDisk ? "Virtual hard-disk controller" : slot.kind == .orchestra90 ? "Orchestra-90" : slot.kind == .speechSound ? "Speech/Sound Cartridge" : "Empty")) + .textSelection(.enabled) + Text(slot.kind == .speechSound ? "Speech/Sound adds speech and music for supporting programs. Both internal chip ROMs are required. It has no boot ROM; keep the disk controller as your startup slot." : slot.kind == .orchestra90 ? "Orchestra-90 provides stereo sound to supporting software. Its optional 8 KiB ROM adds the music program; choose it in Cartridge Settings and select this startup slot to boot it. Sound ports work independently of the live ROM selection." : slot.kind == .floppy ? "One controller serves FD0–FD3 in two enclosures. The FD-502 badges identify the emulated floppy controller." : slot.kind == .hardDisk ? "This separate virtual controller serves HD0–HD1. It has no boot ROM; use a compatible floppy ROM or OS-9 boot disk." : "A ROM cartridge contains a program. A storage controller connects the computer to disks; it does not contain the disks' files.").font(.callout).foregroundStyle(.secondary) + Text("Changing this slot cold-restarts the computer and clears its working program.").font(.caption) + VStack(alignment: .leading, spacing: 8) { + Button("Choose ROM…") { machine.openCartridgeROM(n) } + Button("Use Floppy Controller…") { machine.requestCartridge(.floppy, slot: n) }.disabled(slot.kind == .floppy) + Button("Use Hard-Disk Controller…") { machine.requestCartridge(.hardDisk, slot: n) }.disabled(slot.kind == .hardDisk) + Button("Use Speech/Sound…") { machine.requestCartridge(.speechSound, slot: n) }.disabled(slot.kind == .speechSound) + Button("Use Orchestra-90…") { machine.requestCartridge(.orchestra90, slot: n) }.disabled(slot.kind == .orchestra90) + Button("Use CoCo SDC…") { machine.requestCartridge(.sdc, slot: n) }.disabled(slot.kind == .sdc) + Button("Use RAM Disk…") { machine.requestCartridge(.ramDisk, slot: n) }.disabled(slot.kind == .ramDisk) + Button("Remove Cartridge…") { machine.requestCartridge(.empty, slot: n) }.disabled(slot.kind == .empty) + }.disabled(machine.busy || machine.diskSaving || machine.diskBusy || machine.state == .closed) + } + if let error = machine.cartridgeRestoreErrors[n] { Text(error).foregroundStyle(.orange) } + Button("All Cartridge Settings…") { openWindow(id: "cartridges") } + case .floppy(let n): + diskControls(n, hard: false) + case .hard(let n): + diskControls(n, hard: true) + } + } + @ViewBuilder private func diskControls(_ n: Int, hard: Bool) -> some View { + let disks = hard ? machine.hardDisks : machine.disks + if !(hard ? machine.hardDiskConnected : machine.diskConnected) { + Text("Controller disconnected. Retained media remains available here; connect the controller in Cartridges to use it.").foregroundStyle(.orange) + Button("Cartridges…") { openWindow(id: "cartridges") } + } + if disks.indices.contains(n) { + let disk = disks[n] + let remembered = hard ? machine.hardSettings.drives[n]?.url : machine.diskAssignments.drives[n]?.url + Text(disk.mounted ? disk.name : remembered.map { "Unavailable — " + $0.lastPathComponent } ?? "Empty").textSelection(.enabled) + if let error = hard ? machine.hardRestoreErrors[n] ?? machine.hardSaveErrors[n] : machine.diskRestoreErrors[n] ?? machine.diskSaveErrors[n] { + Text(error).foregroundStyle(.orange).textSelection(.enabled) + } + Text("\(hard ? "HD" : "FD")\(n) · \(machine.hardware.activities[hard ? n+4 : n].rawValue.capitalized)").foregroundStyle(.secondary) + if disk.dirty { Label("Unsaved changes", systemImage: "exclamationmark.circle").foregroundStyle(.orange) } + let temporary = hard ? machine.hardTemporary[n] : machine.diskTemporary[n] + Text(disk.writeProtected ? "Write protected" : temporary ? "Temporary changes — Save As to keep" : "Writable backed images save automatically") + .font(.callout).foregroundStyle(.secondary) + HStack { + Button("Insert…") { if hard { machine.openHardDisk(n) } else { machine.openDisk(n) } }.disabled(disk.dirty) + Button("Eject") { if hard { machine.ejectHardDisk(n) } else { machine.ejectDisk(n) } }.disabled(disk.dirty || !disk.mounted) + Button("Save As…") { if hard { machine.exportHardDisk(n) } else { machine.exportDisk(n) } }.disabled(!disk.mounted) + }.disabled(machine.busy || machine.diskSaving || (!hard && machine.diskBusy) || machine.state == .closed) + Text("The pictured medium is a file on your Mac. Insertion does not run its software. Media changes pause emulation.").font(.callout).foregroundStyle(.secondary) + } + Button("\(hard ? "Hard Disk" : "Floppy") Controls…") { openWindow(id: hard ? "hard-disks" : "disks") } + } +} + +// Keep a native signal picker stable while its surrounding popover refreshes. +private struct SystemVideoControls: View, Equatable { + @Environment(\.openWindow) private var openWindow + let machine: MachineModel + @ObservedObject private var menu: MachineMenuState + init(machine: MachineModel) { self.machine = machine; self.menu = machine.menuState } + static func == (lhs: Self, rhs: Self) -> Bool { lhs.machine === rhs.machine } + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Picker("Video Signal", selection: Binding(get: { menu.values.videoOutput }, set: machine.setVideoOutput)) { + ForEach(DisplayOutput.allCases, id: \.rawValue) { Text($0.label).tag($0) } + }.accessibilityIdentifier("monitor-video-signal") + .disabled(menu.values.busy || menu.values.state == .closed) + Text("Composite TV reproduces the artifact colors used by many CoCo games. Alternate Colors swaps their color phase. RGB gives a direct monitor signal.") + .font(.callout).foregroundStyle(.secondary) + Button("Display Settings…") { openWindow(id: "display-settings") } + Text("Changing the signal preserves the running session.").font(.caption).foregroundStyle(.secondary) + } + } +} + +// The accessible Devices alternative uses the same capture model and commands +// as the dedicated window. Paper feed on the illustration is not a second UI. +private struct SystemPrinterControls: View { + @ObservedObject var printer: PrinterModel + @Environment(\.openWindow) private var openWindow + var body: some View { + VStack(alignment: .leading, spacing: 10) { + Text("\(printer.byteCount.formatted()) captured bytes\(printer.unsaved ? " · Not saved" : "")") + Text("The power light shows capture is enabled. Marks on the paper show that output has been collected. Open Printer Output to read, save or print it.") + .font(.callout).foregroundStyle(.secondary) + HStack { + Button { printer.setCapture(!printer.enabled) } label: { + Label(printer.enabled ? "Stop Capture" : "Start Capture", systemImage: printer.enabled ? "stop.fill" : "record.circle") + }.disabled(printer.busy) + Button("Printer Output…") { openWindow(id: "printer") } + } + } + } +} + +// Shares the same queued commands and restart/media protections as Cartridges. +private struct SystemSDCControls: View { + @ObservedObject var machine: MachineModel + let slot: Int + var body: some View { + VStack(alignment: .leading, spacing: 8) { + Label("CoCo SDC", systemImage: "sdcard").font(.headline) + Text(machine.cartridgeAssignments.slots[slot].sdcFolderURL?.lastPathComponent ?? "No SD card folder") + .textSelection(.enabled) + if let folder = machine.cartridgeAssignments.slots[slot].sdcFolderURL { + Button { NSWorkspace.shared.activateFileViewerSelecting([folder]) } label: { Label("Show SD Card Folder in Finder", systemImage: "folder") } + } + Text(machine.sdcReadOnly ? "Read-only SD card" : "Writable SD card — changes save directly") + Text("Current folder: \(machine.sdcDirectory.isEmpty ? "/" : machine.sdcDirectory)").font(.callout) + ForEach(0..<2, id: \.self) { drive in + Text("SDC\(drive): \(machine.sdcDriveNames.indices.contains(drive) && !machine.sdcDriveNames[drive].isEmpty ? machine.sdcDriveNames[drive] : "No image mounted")") + .textSelection(.enabled) + } + Text("Transfers · Read \(machine.sdcReadCount) · Written \(machine.sdcWriteCount)") + .monospacedDigit().accessibilityIdentifier("system-sdc-transfers") + if let error = machine.sdcError { Text(error).foregroundStyle(.orange) } + Button { machine.openSDCFolder(slot) } label: { Label("Choose SD Card Folder…", systemImage: "folder") } + .disabled(machine.busy || machine.diskSaving || machine.diskBusy || machine.state == .closed) + Button { machine.openCartridgeROM(slot, kind: .sdc) } label: { Label("Choose SDC-DOS ROM…", systemImage: "memorychip") } + .disabled(machine.busy || machine.diskSaving || machine.diskBusy || machine.state == .closed) + Text("Changing the folder or ROM cold-restarts the CoCo. Use Cartridge Settings for write protection and slot changes.") + .font(.caption).foregroundStyle(.secondary) + Text("Green means an image is mounted; amber and red show actual reads and writes. Closing these controls keeps the session running.") + .font(.caption).foregroundStyle(.secondary) + } + } +} diff --git a/platforms/macos/App/TapeImage.swift b/platforms/macos/App/TapeImage.swift new file mode 100644 index 0000000..8815325 --- /dev/null +++ b/platforms/macos/App/TapeImage.swift @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +enum TapeImage { + static let limit = 64 * 1024 * 1024 + enum Failure: LocalizedError { + case notFile, tooLarge, extensionType + var errorDescription: String? { + switch self { + case .notFile: return "Choose a regular CAS or WAV tape image." + case .tooLarge: return "Tape images must be no larger than 64 MiB." + case .extensionType: return "Choose a .cas or .wav tape image." + } + } + } + static func read(_ url: URL) throws -> Data { + guard ["cas", "wav"].contains(url.pathExtension.lowercased()) else { throw Failure.extensionType } + guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw Failure.notFile } + let file = try FileHandle(forReadingFrom: url) + defer { try? file.close() } + var bytes = Data() + while bytes.count <= limit { + guard let chunk = try file.read(upToCount: min(1024 * 1024, limit + 1 - bytes.count)), !chunk.isEmpty else { break } + bytes.append(chunk) + } + guard bytes.count <= limit else { throw Failure.tooLarge } + return bytes + } +} diff --git a/platforms/macos/App/TraceModel.swift b/platforms/macos/App/TraceModel.swift new file mode 100644 index 0000000..08b78bb --- /dev/null +++ b/platforms/macos/App/TraceModel.swift @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import Combine + +@MainActor final class TraceModel: ObservableObject { + let machine: MachineModel + @Published private(set) var snapshot: VCCTraceSnapshot? + @Published var maximum = "10000" + @Published var starts = "" + @Published var stops = "" + @Published var screen = false + @Published var scheduler = false + @Published var firstExport = "1" + @Published var lastExport = "" + @Published var sampleText = "1" + @Published private(set) var selection: VCCTraceRecord? + @Published private(set) var markA: VCCTraceRecord? + @Published private(set) var markB: VCCTraceRecord? + @Published private(set) var pending = false + @Published var error: String? + @Published private(set) var saveMessage: String? + private var offset: UInt = 0 + private var request: UUID? + init(machine: MachineModel) { self.machine = machine } + var available: Bool { !pending && !machine.busy && !machine.diskSaving && (machine.state == .running || machine.state == .paused) } + static func addresses(_ text: String) -> [NSNumber]? { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { return [] } + let parts = trimmed.split(whereSeparator: { $0 == "," || $0.isWhitespace }) + guard parts.count <= 32 else { return nil } + let parsed = parts.compactMap { DebuggerModel.hexadecimal(String($0)).map { NSNumber(value: $0) } } + return parts.count == parsed.count ? parsed : nil + } + func poll() async { + defer { request = nil } + while !Task.isCancelled { + refresh() + do { try await Task.sleep(nanoseconds: 400_000_000) } catch { return } + } + } + func refresh() { + guard request == nil, !pending, !machine.busy else { return } + let token = UUID(); request = token + machine.readDebuggerTrace(offset: offset) { [weak self] value in + guard let self, self.request == token else { return } + self.request = nil + guard let value else { return } + if self.snapshot?.identifier != value.identifier { + self.selection = nil; self.markA = nil; self.markB = nil + self.offset = 0 + } + self.snapshot = value + } + } + private func command(_ operation: (@escaping () -> Void) -> Void) { + guard available else { return } + pending = true; request = nil; error = nil + operation { [weak self] in + guard let self else { return } + self.pending = false; self.error = self.machine.error; self.refresh() + } + } + func start() { + guard let limit = UInt(maximum), (1...100000).contains(limit), + let begins = Self.addresses(starts), let ends = Self.addresses(stops) else { + error = "Use 1–100,000 samples and up to 32 hexadecimal start/stop addresses separated by spaces or commas."; return + } + command { machine.startDebuggerTrace(maximum: limit, starts: begins, stops: ends, screen: screen, scheduler: scheduler, completion: $0) } + } + func stop() { command(machine.stopDebuggerTrace) } + func clear() { command(machine.clearDebuggerTrace) } + func choose(_ row: VCCTraceRecord) { selection = row } + func mark(_ first: Bool) { if first { markA = selection } else { markB = selection } } + var markDifference: String? { + guard let a = markA, let b = markB else { return nil } + let ticks = Int64(b.clock) - Int64(a.clock) + // CoCo master crystal: nominal 14.31818 MHz. Host playback pacing is separate. + return "B − A: \(ticks) master clocks · \(String(format: "%.3f", Double(ticks) / 14_318.18)) ms (emulated time)" + } + func page(_ forward: Bool) { + let total = snapshot?.total ?? 0 + if forward { guard offset + 256 < total else { return }; offset += 256 } + else { offset = offset >= 256 ? offset - 256 : 0 } + request = nil; refresh() + } + func go() { + guard let value = UInt(sampleText), value > 0, value <= (snapshot?.total ?? 0) else { error = "Enter a captured sample number."; return } + offset = ((value - 1) / 256) * 256; error = nil; request = nil; refresh() + } + func export(completion: @escaping (String?) -> Void) { + guard available, let snapshot, let first = UInt(firstExport), first > 0, + let last = lastExport.isEmpty ? snapshot.total : UInt(lastExport), last >= first, last <= snapshot.total else { + error = "Choose an inclusive sample range within the capture (blank end means the current last sample)."; completion(nil); return + } + pending = true; request = nil; error = nil; saveMessage = nil + machine.exportDebuggerTrace(first: first - 1, count: last - first + 1) { [weak self] text in + self?.pending = false; self?.error = self?.machine.error; completion(text) + } + } + func save(_ text: String, to url: URL) async { + pending = true; request = nil; error = nil; saveMessage = nil + defer { pending = false } + do { + try await Task.detached { + let access = url.startAccessingSecurityScopedResource() + defer { if access { url.stopAccessingSecurityScopedResource() } } + try text.write(to: url, atomically: true, encoding: .utf8) + }.value + saveMessage = "Saved trace to \(url.lastPathComponent)." + } catch { self.error = error.localizedDescription } + } + +} diff --git a/platforms/macos/App/TraceView.swift b/platforms/macos/App/TraceView.swift new file mode 100644 index 0000000..0f38a55 --- /dev/null +++ b/platforms/macos/App/TraceView.swift @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit +import UniformTypeIdentifiers + +struct TraceView: View { + @ObservedObject var model: TraceModel + var body: some View { + VStack(alignment: .leading, spacing: 0) { + controls.padding(12) + Divider() + HStack { + Text(model.snapshot?.status ?? "No trace").fontWeight(.semibold).accessibilityIdentifier("trace-status") + Text("\(model.snapshot?.total ?? 0) / \(model.snapshot?.limit ?? 0) samples").monospacedDigit().foregroundStyle(.secondary) + Spacer() + Button { model.page(false) } label: { Label("Previous", systemImage: "chevron.left") }.disabled((model.snapshot?.offset ?? 0) == 0) + Button { model.page(true) } label: { Label("Next", systemImage: "chevron.right") }.disabled((model.snapshot?.offset ?? 0) + 256 >= (model.snapshot?.total ?? 0)) + TextField("Sample", text: $model.sampleText).frame(width: 70).onSubmit(model.go) + .accessibilityLabel("Trace sample number").accessibilityIdentifier("trace-sample") + Button("Go", action: model.go) + }.padding(10) + Divider() + ScrollView([.vertical, .horizontal]) { + LazyVStack(alignment: .leading, spacing: 0) { + HStack(spacing: 12) { + Text("Sample").frame(width: 60, alignment: .leading) + Text("Master clock").frame(width: 110, alignment: .leading) + Text("Event").frame(width: 110, alignment: .leading) + Text("PC").frame(width: 48, alignment: .leading) + Text("Instruction / detail").frame(width: 310, alignment: .leading) + }.foregroundStyle(.secondary).padding(.vertical, 5) + ForEach(model.snapshot?.records ?? [], id: \.index) { row in + Button { model.choose(row) } label: { + HStack(spacing: 12) { + Text("\(row.index + 1)").frame(width: 60, alignment: .leading) + Text("\(row.clock)").frame(width: 110, alignment: .leading) + Text(row.kind).frame(width: 110, alignment: .leading) + Text(DebuggerModel.hex(row.address)).frame(width: 48, alignment: .leading) + Text(row.instruction.isEmpty ? row.detail : row.instruction).frame(width: 310, alignment: .leading) + }.padding(.vertical, 4).contentShape(Rectangle()) + }.buttonStyle(.plain) + .background(model.selection?.index == row.index ? Color.accentColor.opacity(0.16) : Color.clear) + .accessibilityIdentifier("trace-row-\(row.index)") + } + }.font(.system(size: 11, design: .monospaced)).padding(.horizontal, 12) + }.frame(minHeight: 100, maxHeight: .infinity).accessibilityIdentifier("trace-rows") + Divider() + VStack(alignment: .leading, spacing: 5) { + if let row = model.selection { + Text("Sample \(row.index + 1) · frame \(row.frame) · \(row.cycles) instruction cycles · \(row.detail)").font(.caption) + Text("Before: " + row.before).font(.system(size: 11, design: .monospaced)) + Text("After: " + row.after).font(.system(size: 11, design: .monospaced)) + } else { Text("Select a sample to inspect its before/after registers.").foregroundStyle(.secondary).font(.caption) } + HStack { + Button { model.mark(true) } label: { Label("Mark A", systemImage: "flag") }.disabled(model.selection == nil).accessibilityIdentifier("trace-mark-a") + Text(model.markA.map { "#\($0.index + 1)" } ?? "—") + Button { model.mark(false) } label: { Label("Mark B", systemImage: "flag.fill") }.disabled(model.selection == nil).accessibilityIdentifier("trace-mark-b") + Text(model.markB.map { "#\($0.index + 1)" } ?? "—") + if let difference = model.markDifference { Text(difference).font(.caption).accessibilityIdentifier("trace-difference") } + } + }.padding(10) + Divider() + HStack { + Text("Export samples").font(.caption) + TextField("First", text: $model.firstExport).frame(width: 65).accessibilityLabel("First trace sample to export") + Text("through").font(.caption) + TextField("Last", text: $model.lastExport).frame(width: 65).accessibilityLabel("Last trace sample to export, blank for all") + Button(action: export) { Label("Export CSV…", systemImage: "square.and.arrow.up") }.disabled(!model.available || (model.snapshot?.total ?? 0) == 0).accessibilityIdentifier("trace-export") + Spacer() + }.padding(10) + if let message = model.saveMessage { Text(message).font(.caption).foregroundStyle(.secondary).padding(10).accessibilityIdentifier("trace-save-message") } + if let error = model.error { Text(error).foregroundStyle(.red).font(.caption).padding(10).accessibilityIdentifier("trace-error") } + HStack { + Text("Start New replaces the previous capture; Clear removes it.") + .font(.caption).foregroundStyle(.secondary) + Spacer() + DebuggerHelpButton(title: "Execution trace", text: "Trace controls never resume or pause the machine. Start replaces the previous capture; Clear removes it. Addresses are logical hexadecimal. Captured bytes and states are historical.") + }.padding(.horizontal, 10).padding(.bottom, 8) + }.textFieldStyle(.roundedBorder).task { await model.poll() } + } + private var controls: some View { + VStack(alignment: .leading, spacing: 8) { + HStack { + Label("Capture", systemImage: "waveform.path").font(.headline) + Spacer() + Button(action: model.start) { Label("Start New", systemImage: "record.circle") }.disabled(!model.available).accessibilityIdentifier("trace-start") + Button(action: model.stop) { Label("Stop", systemImage: "stop.fill") }.disabled(!model.available || model.snapshot?.armed != true).accessibilityIdentifier("trace-stop") + Button(action: model.clear) { Label("Clear", systemImage: "xmark.circle") }.disabled(!model.available).accessibilityIdentifier("trace-clear") + } + HStack { + Text("Sample limit").font(.caption) + TextField("10000", text: $model.maximum).frame(width: 80).accessibilityLabel("Maximum trace samples").accessibilityIdentifier("trace-limit") + Toggle("Screen events", isOn: $model.screen).accessibilityIdentifier("trace-screen") + Toggle("Scheduler events", isOn: $model.scheduler).accessibilityIdentifier("trace-scheduler") + } + HStack { + Text("Start at").font(.caption) + TextField("Immediately (blank)", text: $model.starts).accessibilityLabel("Trace start addresses").accessibilityIdentifier("trace-start-addresses") + Text("Stop before").font(.caption) + TextField("Limit or Stop (blank)", text: $model.stops).accessibilityLabel("Trace stop addresses").accessibilityIdentifier("trace-stop-addresses") + } + } + } + private func export() { + model.export { text in + guard let text else { return } + let panel = NSSavePanel(); panel.title = "Export Execution Trace" + panel.allowedContentTypes = [.commaSeparatedText]; panel.nameFieldStringValue = "VCC Trace.csv" + panel.begin { response in + guard response == .OK, let url = panel.url else { return } + Task { await model.save(text, to: url) } + } + } + } +} diff --git a/platforms/macos/App/VCCMacApp.swift b/platforms/macos/App/VCCMacApp.swift new file mode 100644 index 0000000..9d147a2 --- /dev/null +++ b/platforms/macos/App/VCCMacApp.swift @@ -0,0 +1,574 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI +import AppKit +import Combine +import UniformTypeIdentifiers + +@MainActor +final class ApplicationDelegate: NSObject, NSApplicationDelegate, ObservableObject { + let machine: MachineModel + let presentation: PresentationSettings + lazy var development = CMOCDevelopmentModel(machine: machine) + private var openedAssemblyWorkspace: AssemblyDevelopmentModel? + var assemblyDevelopment: AssemblyDevelopmentModel { + if let workspace = openedAssemblyWorkspace { return workspace } + let workspace = AssemblyDevelopmentModel(machine: machine) + openedAssemblyWorkspace = workspace + return workspace + } + lazy var basicDevelopment = BASICDevelopmentModel(machine: machine, directory: profileStore.directory.deletingLastPathComponent().appendingPathComponent("BASICWorkspace")) + lazy var basicReference: Result = BASICReferenceCatalog.bundled.map { BASICReferenceModel(catalog: $0) } + lazy var manualReader = ManualReader() + private var basicExamples: [String: BASICDevelopmentModel] = [:] + func exampleWorkspace(_ id: String) -> BASICDevelopmentModel? { + if let existing = basicExamples[id] { return existing } + let source: String + let title: String + let directory = profileStore.directory.deletingLastPathComponent().appendingPathComponent("BASICExamples") + if id.hasPrefix("manual/") { + let path = String(id.dropFirst("manual/".count)) + guard let url = ManualLibraryContent.bundled?.exampleURL(for: path), + let (text, _) = try? BASICDevelopmentModel.readText(url) else { return nil } + source = text + title = url.lastPathComponent + } else { + guard let reference = try? basicReference.get(), + let example = reference.catalog.examples.first(where: { $0.id == id }) else { return nil } + source = example.source + title = example.title + } + let workspace = BASICDevelopmentModel(machine: machine, directory: directory.appendingPathComponent(id), + initialSource: source, title: title) + basicExamples[id] = workspace + return workspace + } + func archiveWorkspace(_ id: String) async throws -> BASICDevelopmentModel? { + if let workspace = basicExamples[id] { return workspace } + guard id.hasPrefix("archive/"), + let example = try await ArchiveLibraryCatalog.shared.basicExample(sourceSHA256: String(id.dropFirst("archive/".count))) else { return nil } + try Task.checkCancellation() + if let workspace = basicExamples[id] { return workspace } + let root = profileStore.directory.deletingLastPathComponent().appendingPathComponent("BASICExamples") + let workspace = BASICDevelopmentModel(machine: machine, directory: root.appendingPathComponent(id), + initialSource: example.source, title: example.title) + basicExamples[id] = workspace + return workspace + } + lazy var softwareLibrary = SoftwareLibraryModel(state: SoftwareLibraryState(directory: profileStore.directory.deletingLastPathComponent().appendingPathComponent("SoftwareLibrary")), artworkDirectory: profileStore.directory.deletingLastPathComponent().appendingPathComponent("SoftwareLibrary/ArtworkCache"), machine: machine, + sourceWorkspaceIdentity: { [weak self] in self?.development.assistantProjectID ?? UUID() }, + openSourceProject: { [weak self] directory, identity, configuration in + guard let self else { return false } + return try await self.development.openImportedProject(at: directory, expectedProjectID: identity, preferredConfiguration: configuration) + }) + let profileStore: ProfileStore + private let startupValidation: StartupValidationContext? + private let companionServiceLaunch: Bool + @Published private(set) var companionLaunchDeferred = false + private var companionService: VCCCompanionService? + private weak var deferredMachineWindow: NSWindow? + private var finishedLaunching = false + private static var isolatedCompanionLaunch: Bool { + #if VCC_UI_TESTING + return true + #else + return CommandLine.arguments.contains("--validate-startup") || CommandLine.arguments.contains("--interface-validation") + #endif + } + var windowTitle: String { + #if VCC_UI_TESTING + return "VCC UI Tests" + #else + return startupValidation == nil ? "VCC Plus OSS" : "VCC Startup Validation" + #endif + } + #if DEBUG + private var validation: InterfaceValidation? + #endif + override init() { + let serviceLaunch = CommandLine.arguments.contains("--companion-service") && !Self.isolatedCompanionLaunch + companionServiceLaunch = serviceLaunch + _companionLaunchDeferred = Published(initialValue: serviceLaunch) + var startupValidationRequested = CommandLine.arguments.contains("--validate-startup") + #if !DEBUG + // A release build has no InterfaceValidation type, but still fails closed. + startupValidationRequested = startupValidationRequested || CommandLine.arguments.contains("--interface-validation") + #endif + if startupValidationRequested { + do { startupValidation = try StartupValidationContext() } + catch { fatalError("Cannot initialize isolated startup validation: \(error)") } + } else { startupValidation = nil } + if let startupValidation { + machine = startupValidation.model() + presentation = PresentationSettings(defaults: startupValidation.defaults) + profileStore = ProfileStore(directory: startupValidation.directory.appendingPathComponent("Profiles")) + } else { + #if DEBUG + #if VCC_UI_TESTING + let isolatedInterface = true // Fail closed even if launched without arguments. + #else + let isolatedInterface = CommandLine.arguments.contains("--interface-validation") + #endif + if isolatedInterface { + // Fail closed rather than accidentally validating against personal settings. + let fixture: InterfaceValidation + do { fixture = try InterfaceValidation() } + catch { fatalError("Cannot create isolated interface validation: \(error)") } + validation = fixture; machine = fixture.makeModel(); presentation = PresentationSettings(defaults: fixture.defaults) + profileStore = ProfileStore(directory: fixture.directory.appendingPathComponent("Profiles")) + } else { machine = MachineModel(startupStore: StartupStore(directory: DiskAssignmentStore.standard.url.deletingLastPathComponent(), kit: .bundled), restoreMediaOnLaunch: !serviceLaunch); presentation = PresentationSettings(); profileStore = .standard } + #else + machine = MachineModel(startupStore: StartupStore(directory: DiskAssignmentStore.standard.url.deletingLastPathComponent(), kit: .bundled), restoreMediaOnLaunch: !serviceLaunch); presentation = PresentationSettings(); profileStore = .standard + #endif + } + super.init() + } + func applicationDidFinishLaunching(_ notification: Notification) { + #if VCC_UI_TESTING + // Per-process appearance for reproducible isolated UI inspection. This + // flag is absent from the shipping app and never changes Mac settings. + let testAppearances: [String: NSAppearance.Name] = [ + "light": .aqua, "dark": .darkAqua, + "light-high-contrast": .accessibilityHighContrastAqua, + "dark-high-contrast": .accessibilityHighContrastDarkAqua + ] + if let style = UserDefaults.standard.string(forKey: "VCCUITestAppearance"), + let appearance = testAppearances[style] { + NSApplication.shared.appearance = NSAppearance(named: appearance) + } + #endif + // Xcode's debugger launch can show a generic Dock tile even when Finder + // resolves CFBundleIconFile correctly. Load this build's bundled artwork + // directly instead of relying on the launch service's cached icon. + if let url = Bundle.main.url(forResource: "AppIcon", withExtension: "icns"), + let icon = NSImage(contentsOf: url) { + NSApplication.shared.applicationIconImage = icon + } + #if DEBUG + if let validation { + Task { @MainActor in + do { + let args = CommandLine.arguments + func directory(_ key: String) -> URL? { + guard let i = args.firstIndex(of: key), args.indices.contains(i + 1) else { return nil } + return URL(fileURLWithPath: args[i + 1]) + } + if let roms = directory("--mcp-rom-dir"), let c = directory("--mcp-c-validation-dir") { + for _ in 0..<500 where machine.busy { try await Task.sleep(for: .milliseconds(10)) } + try await MCPCMOC.shared.fixture(development, directory: c, roms: roms) + return + } + if let roms = directory("--mcp-rom-dir"), let assembly = directory("--mcp-assembly-fixture") { + for _ in 0..<500 where machine.busy { try await Task.sleep(for: .milliseconds(10)) } + try await MCPAssembly.shared.startFixture(assemblyDevelopment, directory: assembly, romDirectory: roms) + return + } + if args.contains("--mcp-edit-review"), args.contains("--mcp-rom-dir"), args.contains("--mcp-validation-dir") { + for _ in 0..<500 where machine.busy { try await Task.sleep(nanoseconds: 10_000_000) } + } else { + try await validation.install(in: machine) + validation.measure(machine, presentation: presentation) + } + if let index = args.firstIndex(of: "--mcp-validation-dir"), args.indices.contains(index + 1) { + let other = BASICDevelopmentModel(machine: machine, directory: validation.directory.appendingPathComponent("PrivateBASIC"), title: "Other document") + try await MCPAccess.shared.validate(model: basicDevelopment, other: other, in: URL(fileURLWithPath: args[index + 1])) + } + } + catch { NSLog("Interface validation failed: %@", error.localizedDescription) } + } + } + #endif + if CompanionValidation.enabled || (!Self.isolatedCompanionLaunch && !CompanionValidation.requested) { + do { + let configuration = try CompanionValidation.configuration(forVCCPlus: true) + companionService = try VCCCompanionService(library: softwareLibrary, configuration: configuration) + } catch { NSLog("Companion service unavailable: %@", error.localizedDescription) } + } + if companionLaunchDeferred { + for window in NSApp.windows { window.orderOut(nil) } + } + finishedLaunching = true + if !Self.isolatedCompanionLaunch && !CompanionValidation.requested { + // OSS releases are obtained manually; no update service is scheduled. + } + } + + func registerDeferredCompanionWindow(_ window: NSWindow) { + guard companionLaunchDeferred else { return } + deferredMachineWindow = window + window.isRestorable = false + window.orderOut(nil) + } + private func restoreCompanionMachineForForeground() { + guard companionLaunchDeferred else { return } + machine.restoreDeferredCompanionMachine() + companionLaunchDeferred = false + deferredMachineWindow?.isRestorable = true + deferredMachineWindow?.makeKeyAndOrderFront(nil) + } + func applicationDidBecomeActive(_ notification: Notification) { + guard finishedLaunching else { return } + restoreCompanionMachineForForeground() + } + func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { + if companionLaunchDeferred { + if sender.isActive { restoreCompanionMachineForForeground() } + return false + } + return true + } + func applicationShouldRestoreApplicationState(_ coder: NSCoder) -> Bool { !companionServiceLaunch } + func applicationShouldSaveApplicationState(_ coder: NSCoder) -> Bool { !companionLaunchDeferred } + + func application(_ sender: NSApplication, open urls: [URL]) { + restoreCompanionMachineForForeground() + guard urls.count == 1, let url = urls.first else { machine.reportMediaError("Open one media file at a time."); return } + Task { @MainActor in + for _ in 0..<200 { + if !machine.busy && !machine.diskSaving { machine.offerMedia(url); return } + try? await Task.sleep(nanoseconds: 50_000_000) + } + machine.reportMediaError("The machine is busy. Try File → Open Media after the current operation finishes.") + } + } + func applicationWillTerminate(_ notification: Notification) { + companionService?.stop() + startupValidation?.cleanUp() + #if DEBUG + validation?.cleanUp() + #endif + } + private var terminationPending = false + func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { + if companionLaunchDeferred { + guard !terminationPending else { return .terminateCancel } + terminationPending = true + companionService?.stop() + Task { @MainActor in + await softwareLibrary.shutdown() + machine.shutdown { sender.reply(toApplicationShouldTerminate: true) } + } + return .terminateLater + } + guard DiskImageEditorCoordinator.shared.prepareToQuit() else { return .terminateCancel } + if machine.busy || machine.printer.busy || machine.printer.saving || terminationPending { return .terminateCancel } + guard development.confirmDiscard(), basicDevelopment.confirmDiscard(), basicExamples.values.allSatisfy({ $0.confirmDiscard() }) else { return .terminateCancel } + guard openedAssemblyWorkspace?.prepareToQuit() != false else { return .terminateCancel } + development.cancelBuild() + terminationPending = true + // Refresh after pausing on the emulation queue: the last UI poll can be + // older than the guest's most recent disk write or cassette sample. + machine.prepareToQuit { [self] in + if machine.unsavedMedia || machine.printer.unsaved { + let alert = NSAlert() + alert.messageText = "Quit without saving?" + alert.informativeText = "Unsaved disk changes, cassette recordings or printer output will be lost. Choose Cancel, then save your disks, export your tape, or open Media → Printer Output and save the capture. The machine will remain paused." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Quit Without Saving") + if alert.runModal() != .alertSecondButtonReturn { + terminationPending = false; sender.reply(toApplicationShouldTerminate: false); return + } + } + development.flushDraftRecovery { [self] in + Task { @MainActor in + await MCPArchiveAccess.shared.revoke().value + MCPAssembly.shared.revoke() + await MCPCMOC.shared.revoke().value + await MCPAccess.shared.revoke().value + await softwareLibrary.shutdown() + machine.shutdown { sender.reply(toApplicationShouldTerminate: true) } + } + } + } + return .terminateLater + } +} + +@main +struct VCCMacApp: App { + @NSApplicationDelegateAdaptor(ApplicationDelegate.self) private var delegate + var body: some Scene { + Window(delegate.windowTitle, id: "machine") { + Group { + if delegate.companionLaunchDeferred { + VCCCompanionDeferredMachineView(onWindow: delegate.registerDeferredCompanionWindow) + } else { + MachineView(machine: delegate.machine, presentation: delegate.presentation, showManualHome: { delegate.manualReader.showHome() }) + .focusedSceneValue(\.emulatorWindow, true).rememberPlacement("machine", in: delegate.presentation.windows) + } + } + } + .defaultSize(width: 1100, height: 820) + .commands { MachineCommands(machine: delegate.machine, presentation: delegate.presentation, connectAssistant: { MCPAccess.shared.show(for: delegate.basicDevelopment) }); SourceFindCommands() } + Window("Manual Library", id: "manual-library") { + ManualLibraryView(reader: delegate.manualReader) + .rememberPlacement("manual-library", in: delegate.presentation.windows) + }.defaultSize(width: 1000, height: 780) + Window("Archive Library", id: "archive-library") { + ArchiveLibraryView().rememberPlacement("archive-library", in: delegate.presentation.windows) + }.defaultSize(width: 1180, height: 780) + Window("Software Library", id: "software-library") { + SoftwareLibraryView(model: delegate.softwareLibrary).rememberPlacement("software-library", in: delegate.presentation.windows) + }.defaultSize(width: 1180, height: 780) + Window("Software Manual", id: "software-manual") { + SoftwareLibraryManualView(model: delegate.softwareLibrary.manual) + }.defaultSize(width: 850, height: 850) + Window("Printer Output", id: "printer") { + PrinterOutputView(printer: delegate.machine.printer).rememberPlacement("printer", in: delegate.presentation.windows) + }.defaultSize(width: 820, height: 700) + Window("BASIC Development", id: "basic-development") { + BASICDevelopmentView(model: delegate.basicDevelopment, reference: try? delegate.basicReference.get()).onDisappear { MCPAccess.shared.closing(delegate.basicDevelopment) }.rememberPlacement("basic-development", in: delegate.presentation.windows) + }.defaultSize(width: 1050, height: 760) + Window("BASIC Quick Reference", id: "basic-reference") { + BASICReferenceHost(result: delegate.basicReference, machine: delegate.machine) { entry in + delegate.manualReader.showBASICTopic(entry) + } + .rememberPlacement("basic-reference", in: delegate.presentation.windows) + }.defaultSize(width: 960, height: 760) + WindowGroup("BASIC Example", id: "basic-example", for: String.self) { $identifier in + if let identifier, identifier.hasPrefix("archive/") { + ArchiveExampleWindow(identifier: identifier, delegate: delegate) + } else if let identifier, let workspace = delegate.exampleWorkspace(identifier) { + BASICDevelopmentView(model: workspace, reference: try? delegate.basicReference.get()) + .onDisappear { MCPAccess.shared.closing(workspace) } + } else { Text("This example is not available in the local reference.").padding() } + }.defaultSize(width: 1050, height: 760) + Window("C Development", id: "c-development") { + CMOCDevelopmentView(model: delegate.development).rememberPlacement("c-development", in: delegate.presentation.windows) + }.defaultSize(width: 1100, height: 780) + Window("Assembly Development", id: "assembly-development") { + AssemblyDevelopmentView(model: delegate.assemblyDevelopment) + .rememberPlacement("assembly-development", in: delegate.presentation.windows) + }.defaultSize(width: 1040, height: 740) + Window("Assembly Quick Reference", id: "assembly-reference") { + AssemblyReferenceWindow(model: delegate.assemblyDevelopment) + .rememberPlacement("assembly-reference", in: delegate.presentation.windows) + }.defaultSize(width: 960, height: 740) + Window("Debugger", id: "debugger") { + DebuggerView(machine: delegate.machine).rememberPlacement("debugger", in: delegate.presentation.windows) + }.defaultSize(width: 1120, height: 760) + Window("Release History", id: "release-history") { ReleaseHistoryView().rememberPlacement("release-history", in: delegate.presentation.windows) }.defaultSize(width: 760, height: 720) + Window("About VCC Plus OSS", id: "about") { AboutVCCView().rememberPlacement("about", in: delegate.presentation.windows) }.defaultSize(width: 760, height: 800) + Window("Licenses & Notices", id: "credits") { LicenseCreditsView().rememberPlacement("credits", in: delegate.presentation.windows) }.defaultSize(width: 760, height: 660) + Window("Display Settings", id: "display-settings") { DisplayControlsView(machine: delegate.machine).rememberPlacement("display-settings", in: delegate.presentation.windows) }.defaultSize(width: 600, height: 660) + Window("Keyboard & Shortcuts", id: "keyboard-help") { KeyboardHelpView().rememberPlacement("keyboard-help", in: delegate.presentation.windows) }.defaultSize(width: 760, height: 760) + Window("Configuration Profiles", id: "profiles") { + ProfileControlsView(machine: delegate.machine, store: delegate.profileStore).rememberPlacement("profiles", in: delegate.presentation.windows) + }.defaultSize(width: 820, height: 720) + Window("Machine Settings", id: "machine-settings") { + MachineSettingsView(machine: delegate.machine).rememberPlacement("machine-settings", in: delegate.presentation.windows) + }.defaultSize(width: 560, height: 660) + Window("Keyboard and Joysticks", id: "input") { + InputControlsView(input: delegate.machine.input).rememberPlacement("input", in: delegate.presentation.windows) + }.defaultSize(width: 700, height: 820) + Window("Virtual Hard Disks", id: "hard-disks") { + HardDiskControlsView(machine: delegate.machine).rememberPlacement("hard-disks", in: delegate.presentation.windows) + }.defaultSize(width: 780, height: 760) + Window("Cartridges", id: "cartridges") { + CartridgeControlsView(machine: delegate.machine).rememberPlacement("cartridges", in: delegate.presentation.windows) + }.defaultSize(width: 740, height: 660) + Window("Cassette", id: "cassette") { + CassetteControlsView(machine: delegate.machine).rememberPlacement("cassette", in: delegate.presentation.windows) + }.defaultSize(width: 800, height: 510) + Window("Floppy Disks", id: "disks") { + DiskControlsView(machine: delegate.machine).rememberPlacement("disks", in: delegate.presentation.windows) + }.defaultSize(width: 760, height: 650) + } +} + +private struct AssemblyReferenceWindow: View { + let model: AssemblyDevelopmentModel + @Environment(\.openWindow) private var openWindow + + var body: some View { + AssemblyReferenceView { example in + model.openExample(title: example.title, source: example.source, target6309: example.target6309) + openWindow(id: "assembly-development") + } + } +} + +// Observe only command-relevant values; routine frame/status polling must not +// rebuild the native View menu while the user is choosing an item. +struct MachineCommands: Commands { + @FocusedValue(\.emulatorWindow) private var emulatorWindow + let machine: MachineModel + @ObservedObject private var menu: MachineMenuState + @ObservedObject var presentation: PresentationSettings + let connectAssistant: () -> Void + init(machine: MachineModel, presentation: PresentationSettings, connectAssistant: @escaping () -> Void) { + self.connectAssistant = connectAssistant + self.presentation = presentation + self.machine = machine + self.menu = machine.menuState + } + @Environment(\.openWindow) private var openWindow + @CommandsBuilder + private var primaryCommands: some Commands { + CommandGroup(replacing: .appInfo) { + Button("About VCC Plus OSS") { openWindow(id: "about") } + } + CommandGroup(replacing: .help) { + Button("Manual Library…") { openWindow(id: "manual-library") } + Button("Archive Library…") { openWindow(id: "archive-library") } + Divider() + Button("BASIC Quick Reference…") { openWindow(id: "basic-reference") } + Button("Assembly Quick Reference…") { openWindow(id: "assembly-reference") } + Button("Keyboard & Shortcuts…") { openWindow(id: "keyboard-help") } + Button("Release History…") { openWindow(id: "release-history") } + Button("Licenses & Notices…") { openWindow(id: "credits") } + Button("About VCC Plus OSS") { openWindow(id: "about") } + } + CommandGroup(replacing: .appSettings) { + Button("Machine Settings…") { openWindow(id: "machine-settings") }.keyboardShortcut(",") + } + CommandMenu("Machine") { + Button("Configuration Profiles…") { openWindow(id: "profiles") } + .keyboardShortcut("p", modifiers: [.command, .shift]) + Button("Machine Settings…") { openWindow(id: "machine-settings") } + Button("Restore App Defaults…") { machine.confirmRestoreAppDefaults() } + .disabled(!machine.hasBundledROMs || menu.values.busy || menu.values.diskSaving || menu.values.state == .closed) + Divider() + FastForwardMenuItem(machine: machine, values: menu.values, emulatorFocused: emulatorWindow == true) + } + CommandMenu("Develop") { + Button("Connect to ChatGPT…") { + openWindow(id: "basic-development") + DispatchQueue.main.async { connectAssistant() } + } + Divider() + Button("BASIC Development…") { openWindow(id: "basic-development") } + Button("BASIC Quick Reference…") { openWindow(id: "basic-reference") } + Button("C Development…") { openWindow(id: "c-development") } + .keyboardShortcut("c", modifiers: [.command, .option]) + Button("Assembly Development…") { openWindow(id: "assembly-development") } + Button("Assembly Quick Reference…") { openWindow(id: "assembly-reference") } + } + CommandMenu("Debug") { + Button("Show Debugger") { openWindow(id: "debugger") } + .keyboardShortcut("d", modifiers: [.command, .option]) + Divider() + Button(menu.values.state == .running ? "Pause Execution" : "Continue Execution") { + if menu.values.state == .running { machine.debuggerPause {} } + else { machine.debuggerContinue {} } + } + .keyboardShortcut("r", modifiers: [.command, .option]) + .disabled(menu.values.busy || menu.values.diskSaving || !(menu.values.state == .running || menu.values.state == .paused)) + Button("Step Instruction") { machine.debuggerStep {} } + .keyboardShortcut("i", modifiers: [.command, .option]) + .disabled(menu.values.busy || menu.values.diskSaving || menu.values.state != .paused) + } + } + var body: some Commands { + primaryCommands + CommandMenu("Display") { + Picker("Presentation", selection: $presentation.mode) { + Text("Conventional Display").tag(PresentationSettings.Mode.display) + Text("Interactive System").tag(PresentationSettings.Mode.system) + }.pickerStyle(.inline) + Button(presentation.expanded ? "Return to System" : "Expand Monitor") { presentation.expanded.toggle() } + .keyboardShortcut("e", modifiers: [.command, .shift]) + .disabled(presentation.mode != .system) + Divider() + Picker("Video Output", selection: Binding(get: { menu.values.videoOutput }, set: machine.setVideoOutput)) { + ForEach(DisplayOutput.allCases, id: \.rawValue) { output in + Text(output.label).tag(output) + } + }.pickerStyle(.inline).disabled(menu.values.busy || menu.values.state == .closed) + Divider() + DisplayAppearanceControls(preferences: machine.displayPreferences) + Button("Display Settings…") { openWindow(id: "display-settings") } + Button("Save CoCo Screen…", action: machine.saveScreenshot) + .keyboardShortcut("s", modifiers: [.command, .shift]) + .disabled(menu.values.busy || !(menu.values.state == .running || menu.values.state == .paused)) + } + CommandGroup(after: .pasteboard) { + Divider() + Button("Copy CoCo Screen Text") { machine.copyScreenText() } + .keyboardShortcut("c", modifiers: [.command, .shift]) + .disabled(menu.values.busy || !(menu.values.state == .running || menu.values.state == .paused)) + Button("Paste Text into CoCo") { machine.pasteClipboard() } + .keyboardShortcut("v", modifiers: [.command, .shift]) + .disabled(!menu.values.canPaste) + Button("Paste BASIC — Merge…") { machine.pasteClipboard(.mergeBASIC) }.disabled(!menu.values.canPaste) + Button("Paste BASIC — Replace…") { machine.pasteClipboard(.newBASIC) }.disabled(!menu.values.canPaste) + Button("Cancel Paste") { machine.cancelPaste() }.disabled(!menu.values.pasting) + } + CommandMenu("Input") { + Button("Focus CoCo Display") { + openWindow(id: "machine") + DispatchQueue.main.async { machine.focusDisplay() } + }.keyboardShortcut("k", modifiers: [.command, .option]) + Button("Focus Mac Controls") { + openWindow(id: "machine") + DispatchQueue.main.async { presentation.focusControls() } + }.keyboardShortcut("u", modifiers: [.command, .option]) + Divider() + Button("Keyboard and Joysticks…") { openWindow(id: "input") } + } + CommandMenu("Cartridge") { + Button("Cartridges…") { openWindow(id: "cartridges") } + if menu.values.hardDiskConnected { + Button("Hard Drives…") { openWindow(id: "hard-disks") } + } + if menu.values.diskConnected { + Button("Floppy Drives…") { openWindow(id: "disks") } + } + } + CommandMenu("Media") { + Button("Software Library…") { openWindow(id: "software-library") } + .keyboardShortcut("l", modifiers: [.command, .shift]) + Divider() + Button("Printer Output…") { openWindow(id: "printer") } + Divider() + Button("Cassette…") { openWindow(id: "cassette") }.keyboardShortcut("t", modifiers: [.command, .shift]) + Button("Virtual Hard Disks…") { openWindow(id: "hard-disks") } + Button("Floppy Disks…") { openWindow(id: "disks") }.keyboardShortcut("d", modifiers: [.command, .shift]) + } + CommandGroup(replacing: .newItem) { + Button("Show Emulator") { + openWindow(id: "machine") + DispatchQueue.main.async { machine.focusDisplay() } + }.keyboardShortcut("1", modifiers: [.command]) + Divider() + Button("Software Library…") { openWindow(id: "software-library") } + Divider() + Button("Open Media…", action: machine.openMedia).keyboardShortcut("o") + .disabled(menu.values.busy || menu.values.diskSaving) + RecentMediaCommands(machine: machine, recent: machine.recentMedia, menu: menu) + Divider() + Button("Open ROM…", action: machine.openROM).keyboardShortcut("o", modifiers: [.command, .shift]) + .disabled(menu.values.busy) + Button("Load Binary…", action: machine.openBinary).keyboardShortcut("b", modifiers: [.command, .shift]) + .disabled(!menu.values.canQuickLoad) + } + } +} + +private struct ArchiveExampleWindow: View { + let identifier: String + let delegate: ApplicationDelegate + @State private var workspace: BASICDevelopmentModel? + @State private var message: String? + + var body: some View { + Group { + if let workspace { + BASICDevelopmentView(model: workspace, reference: try? delegate.basicReference.get()) + .onDisappear { MCPAccess.shared.closing(workspace) } + } else if let message { + Text(message).padding() + } else { + ProgressView("Opening example…") + } + } + .task(id: identifier) { + do { + workspace = try await delegate.archiveWorkspace(identifier) + if workspace == nil { message = "This example is unavailable in this Archive index." } + } catch is CancellationError { + return + } catch { + message = error.localizedDescription + } + } + } +} diff --git a/platforms/macos/App/WindowPlacement.swift b/platforms/macos/App/WindowPlacement.swift new file mode 100644 index 0000000..64c2083 --- /dev/null +++ b/platforms/macos/App/WindowPlacement.swift @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import SwiftUI + +// Host window geometry only: never guest memory, transport, or media state. +@MainActor +final class WindowPlacements { + private let defaults: UserDefaults + init(defaults: UserDefaults) { self.defaults = defaults } + private func key(_ id: String) -> String { "interface.window.\(id)" } + func saved(_ id: String) -> CGRect? { + guard let numbers = defaults.array(forKey: key(id)) as? [Double], numbers.count == 4 else { return nil } + let rect = CGRect(x: numbers[0], y: numbers[1], width: numbers[2], height: numbers[3]) + return Self.valid(rect) ? rect : nil + } + func save(_ frame: CGRect, id: String) { + guard Self.valid(frame) else { return } + defaults.set([frame.minX, frame.minY, frame.width, frame.height], forKey: key(id)) + } + private static func valid(_ r: CGRect) -> Bool { + [r.origin.x, r.origin.y, r.size.width, r.size.height].allSatisfy { $0.isFinite && abs($0) < 1_000_000 } + && r.size.width > 0 && r.size.height > 0 + } + // Use the screen with the greatest overlap; an unplugged display falls + // back to the main screen. Keep the title bar reachable even if a native + // form's minimum size exceeds a small screen's usable area. + static func reachable(_ frame: CGRect, screens: [CGRect], minimum: CGSize = .zero) -> CGRect { + guard valid(frame), let fallback = screens.first else { return frame } + func area(_ r: CGRect) -> CGFloat { r.isNull ? 0 : r.width * r.height } + let screen = screens.max { area(frame.intersection($0)) < area(frame.intersection($1)) } + .flatMap { area(frame.intersection($0)) > 0 ? $0 : nil } ?? fallback + let width = max(minimum.width, min(frame.width, screen.width)) + let height = max(minimum.height, min(frame.height, screen.height)) + return CGRect(x: max(screen.minX, min(frame.minX, screen.maxX - width)), + y: min(screen.maxY - height, max(frame.minY, screen.minY)), + width: width, height: height) + } +} + +// SwiftUI owns each window. Observe it rather than replacing its delegate or +// using global frame-autosave names, which would mix isolated test sessions. +struct RememberWindowPlacement: NSViewRepresentable { + let id: String + let placements: WindowPlacements + func makeCoordinator() -> Observer { Observer(id: id, placements: placements) } + func makeNSView(context: Context) -> Anchor { + let anchor = Anchor() + anchor.setAccessibilityElement(false) + anchor.attach = { [weak observer = context.coordinator] window in observer?.attach(window) } + return anchor + } + func updateNSView(_ view: Anchor, context: Context) {} + static func dismantleNSView(_ view: Anchor, coordinator: Observer) { coordinator.detach() } + final class Anchor: NSView { + var attach: ((NSWindow?) -> Void)? + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + // Wait for SwiftUI's initial window/default-size layout. + DispatchQueue.main.async { [weak self] in self?.attach?(self?.window) } + } + } + @MainActor final class Observer { + let id: String + let placements: WindowPlacements + private weak var window: NSWindow? + private var tokens: [NSObjectProtocol] = [] + private var restoring = false + private var fullScreenTransition = false + init(id: String, placements: WindowPlacements) { self.id = id; self.placements = placements } + deinit { for token in tokens { NotificationCenter.default.removeObserver(token) } } + private var screens: [CGRect] { + let ordered = [NSScreen.main].compactMap { $0 } + NSScreen.screens.filter { $0 !== NSScreen.main } + return ordered.map(\.visibleFrame) + } + func attach(_ window: NSWindow?) { + guard let window, self.window !== window else { return } + detach(); self.window = window + if let saved = placements.saved(id) { restore(saved) } + for name in [NSWindow.didMoveNotification, NSWindow.didResizeNotification, + NSWindow.didEndLiveResizeNotification, NSWindow.willCloseNotification] { + observe(name, object: window) { $0.save() } + } + observe(NSWindow.willEnterFullScreenNotification, object: window) { + $0.save(); $0.fullScreenTransition = true + } + observe(NSWindow.willExitFullScreenNotification, object: window) { $0.fullScreenTransition = true } + observe(NSWindow.didExitFullScreenNotification, object: window) { + $0.fullScreenTransition = false; $0.recoverScreen(); $0.save() + } + observe(NSApplication.didChangeScreenParametersNotification, object: nil) { $0.recoverScreen() } + } + private func observe(_ name: Notification.Name, object: Any?, action: @escaping (Observer) -> Void) { + tokens.append(NotificationCenter.default.addObserver(forName: name, object: object, queue: .main) { [weak self] _ in + guard let self else { return }; action(self) + }) + } + func save() { + guard let window, !restoring, !fullScreenTransition, !window.styleMask.contains(.fullScreen), !window.isMiniaturized else { return } + placements.save(window.frame, id: id) + } + private func restore(_ frame: CGRect) { + guard let window else { return } + restoring = true + let minimum = window.frameRect(forContentRect: CGRect(origin: .zero, size: window.contentMinSize)).size + window.setFrame(WindowPlacements.reachable(frame, screens: screens, minimum: minimum), display: true) + restoring = false + } + private func recoverScreen() { + guard let window, window.isVisible, !fullScreenTransition, !window.styleMask.contains(.fullScreen) else { return } + restore(window.frame); save() + } + func detach() { + save() + for token in tokens { NotificationCenter.default.removeObserver(token) } + tokens.removeAll(); window = nil + } + } +} + +extension View { + func rememberPlacement(_ id: String, in placements: WindowPlacements) -> some View { + background(RememberWindowPlacement(id: id, placements: placements).frame(width: 0, height: 0).accessibilityHidden(true)) + } +} diff --git a/platforms/macos/Bridge/DiskImageEditorBackend.h b/platforms/macos/Bridge/DiskImageEditorBackend.h new file mode 100644 index 0000000..676447c --- /dev/null +++ b/platforms/macos/Bridge/DiskImageEditorBackend.h @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import + +NS_ASSUME_NONNULL_BEGIN +/// Synchronous, bounded operations on caller-owned private working images. +/// Call off the main thread. Internal serialization protects retained C code. +@interface VCCDiskImageEditorBackend : NSObject +/// Discover validated volumes in a raw floppy/hard-drive image. IDs encode the +/// filesystem, byte offset and extent; all regions outside the selected volume +/// remain opaque and are never reformatted or inferred as free space. ++ (nullable NSArray *> *)discoverVolumesAtURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(discoverVolumes(at:)); ++ (BOOL)extractVolume:(NSString *)volumeID imageURL:(NSURL *)imageURL outputURL:(NSURL *)outputURL error:(NSError **)error NS_SWIFT_NAME(extractVolume(_:imageURL:outputURL:)); ++ (BOOL)replaceVolume:(NSString *)volumeID imageURL:(NSURL *)imageURL volumeURL:(NSURL *)volumeURL error:(NSError **)error NS_SWIFT_NAME(replaceVolume(_:imageURL:volumeURL:)); ++ (nullable NSDictionary *)inspectImageAtURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(inspectImage(at:)); ++ (nullable NSArray *> *)listDirectory:(NSString *)directory imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(listDirectory(_:imageURL:)); ++ (nullable NSData *)readFile:(NSString *)path imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(readFile(_:imageURL:)); ++ (nullable NSString *)identifyFile:(NSString *)path imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(identifyFile(_:imageURL:)); ++ (BOOL)importData:(NSData *)data named:(NSString *)name directory:(NSString *)directory imageURL:(NSURL *)imageURL fileType:(NSInteger)fileType ascii:(BOOL)ascii replace:(BOOL)replace error:(NSError **)error NS_SWIFT_NAME(importData(_:named:directory:imageURL:fileType:ascii:replace:)); ++ (BOOL)makeDirectory:(NSString *)name inDirectory:(NSString *)directory imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(makeDirectory(_:in:imageURL:)); ++ (BOOL)renameEntry:(NSString *)path toName:(NSString *)name imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(renameEntry(_:to:imageURL:)); ++ (BOOL)deleteEntry:(NSString *)path directory:(BOOL)directory imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(deleteEntry(_:directory:imageURL:)); +/// Relink regular files within one OS-9 image without copying their data or +/// replacing descriptors. The empty destination path denotes the root. ++ (BOOL)moveFiles:(NSArray *)paths toDirectory:(NSString *)directory imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(moveFiles(_:toDirectory:imageURL:)); +/// OS-9's two-byte owner is represented as high-byte group / low-byte user. +/// Permissions are owner/public rwx and single access (0...127); type is kept. ++ (BOOL)setOS9MetadataForPath:(NSString *)path imageURL:(NSURL *)imageURL ownerUser:(NSInteger)ownerUser ownerGroup:(NSInteger)ownerGroup permissions:(NSInteger)permissions error:(NSError **)error NS_SWIFT_NAME(setOS9Metadata(for:imageURL:ownerUser:ownerGroup:permissions:)); +@end +NS_ASSUME_NONNULL_END diff --git a/platforms/macos/Bridge/DiskImageEditorBackend.mm b/platforms/macos/Bridge/DiskImageEditorBackend.mm new file mode 100644 index 0000000..3e7b4bd --- /dev/null +++ b/platforms/macos/Bridge/DiskImageEditorBackend.mm @@ -0,0 +1,697 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import "DiskImageEditorBackend.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +extern "C" { +#include "decbpath.h" +#include "os9path.h" +#include "os9module.h" +} + +namespace { +constexpr size_t limit = 512 * 1024 * 1024; +constexpr size_t fileLimit = 16 * 1024 * 1024; +constexpr size_t sectorSize = 256; +constexpr size_t rawTrackBytes = 18 * sectorSize; +constexpr size_t decbVolumeBytes = 35 * rawTrackBytes; +std::recursive_mutex backendMutex; +using Bytes = std::vector; +[[noreturn]] void fail(const std::string& message) { throw std::runtime_error(message); } +uint32_t be(const Bytes& bytes, size_t offset, size_t count) { + if (offset > bytes.size() || count > bytes.size() - offset) fail("The disk image contains a truncated structure."); + uint32_t value = 0; for (size_t i = 0; i < count; ++i) value = (value << 8) | bytes[offset + i]; return value; +} +std::string lower(std::string value) { for (char& c : value) c = char(std::tolower(static_cast(c))); return value; } +std::string string(NSString *value) { + const char *bytes = value.UTF8String; if (!bytes) fail("This name is not valid UTF-8."); return bytes; +} +NSString *text(const std::string& value) { return [[NSString alloc] initWithBytes:value.data() length:value.size() encoding:NSUTF8StringEncoding] ?: @""; } +std::string name(std::string value, bool decb, bool allowDots = false) { + if (value.empty() || value.size() > (decb ? 12 : 29) || (!allowDots && (value == "." || value == ".."))) + fail(decb ? "Use a Disk BASIC name of up to eight characters and a three-character extension." : "Use an OS-9 name of 1–29 ASCII characters."); + for (unsigned char c : value) if (c < 32 || c > 126 || c == '/' || c == '\\' || c == ',' || c == ':' || c == '@') + fail("The image name contains an unsupported character."); + if (decb) { + const auto dot = value.find('.'); + if (dot == 0 || (dot != std::string::npos && (dot > 8 || dot + 1 == value.size() || value.size() - dot - 1 > 3 || value.find('.', dot + 1) != std::string::npos)) || (dot == std::string::npos && value.size() > 8)) + fail("Use a Disk BASIC name of up to eight characters and a three-character extension."); + for (char& c : value) c = char(std::toupper(static_cast(c))); + } + return value; +} +std::string imagePath(NSString *input, bool decb, bool rootAllowed = false) { + const auto path = string(input); + if (path.empty()) { if (rootAllowed) return path; fail("Select a file or directory within the image."); } + if (path.size() > 1024 || path.front() == '/' || path.back() == '/') fail("Use a relative path inside the image."); + std::string out; size_t start = 0, components = 0; + while (start < path.size()) { + const auto end = path.find('/', start); + const auto part = name(path.substr(start, end == std::string::npos ? end : end - start), decb); + if (++components > 32 || (decb && components > 1)) fail("The image path is too deep for this filesystem."); + if (!out.empty()) out += '/'; out += part; + if (end == std::string::npos) break; start = end + 1; + } + return out; +} +Bytes load(NSURL *url) { + if (!url.isFileURL || [url.path containsString:@","]) fail("Choose a local private working image with no comma in its path."); + const int fd = open(url.fileSystemRepresentation, O_RDONLY | O_NOFOLLOW); + if (fd < 0) fail("The working disk image could not be opened."); + struct stat info{}; + if (fstat(fd, &info) != 0 || !S_ISREG(info.st_mode) || info.st_size < 256 || info.st_size > off_t(limit)) { close(fd); fail("Choose a regular disk image between 256 bytes and 512 MiB."); } + Bytes bytes(size_t(info.st_size)); size_t offset = 0; + while (offset < bytes.size()) { const ssize_t got = read(fd, bytes.data() + offset, bytes.size() - offset); if (got <= 0) { close(fd); fail("The disk image could not be read completely."); } offset += size_t(got); } + uint8_t extra; const auto additional = read(fd, &extra, 1); close(fd); + if (additional != 0) fail("The working image changed while it was being read."); + return bytes; +} +struct Node { + std::string path, parent, name; bool directory = false; + size_t size = 0, descriptorSector = 0; unsigned type = 0, ascii = 0, attributes = 0, owner = 0, group = 0; + id modified = NSNull.null; Bytes content; std::vector dataSectors; +}; +struct Image { + Bytes bytes; bool decb = false; size_t capacity = 0, free = 0, unit = 0; + std::map nodes; + const Node& find(const std::string& path) const { + auto found = nodes.find(lower(path)); if (found == nodes.end()) fail("The selected image entry no longer exists."); return found->second; + } +}; +std::string padded(const Bytes& b, size_t offset, size_t size) { + std::string value(reinterpret_cast(b.data() + offset), size); + while (!value.empty() && value.back() == ' ') value.pop_back(); return value; +} +void validateDECB(Image& image) { + auto& b = image.bytes; + if (b.size() < decbVolumeBytes || b.size() % rawTrackBytes != 0) + fail("Disk BASIC editing requires a complete 35-track raw filesystem, optionally followed by whole supplementary tracks. Other image layouts are preserved but cannot be edited here."); + // Disk BASIC's 68-granule filesystem occupies only the first 35 tracks. + // Supplementary tracks are opaque application data, never free granules. + image.decb = true; image.unit = 2304; image.capacity = 68 * image.unit; + constexpr size_t fat = (17 * 18 + 1) * 256, directory = (17 * 18 + 2) * 256; + auto chain = [&](unsigned first) { + std::vector result; std::set visited; unsigned current = first; + for (;;) { + if (current >= 68 || !visited.insert(current).second) fail("The Disk BASIC allocation chain is out of range or cyclic."); + result.push_back(current); const unsigned next = b[fat + current]; + if (next >= 0xc0 && next <= 0xc9) return result; + if (next >= 68) fail("The Disk BASIC allocation chain has an invalid terminator."); current = next; + } + }; + for (unsigned i = 0; i < 68; ++i) { if (b[fat + i] == 255) image.free += image.unit; else (void)chain(i); } + Node root; root.directory = true; image.nodes.emplace("", root); + std::set claimed; + for (unsigned i = 0; i < 72; ++i) { + const auto offset = directory + i * 32; if (b[offset] == 255 || b[offset] == 0) continue; + Node n; n.name = padded(b, offset, 8); const auto ext = padded(b, offset + 8, 3); if (!ext.empty()) n.name += '.' + ext; + n.path = name(n.name, true); n.name = n.path; n.type = b[offset + 11]; n.ascii = b[offset + 12]; + if (n.type > 3 || (n.ascii != 0 && n.ascii != 255)) fail("The Disk BASIC file has unsupported type or encoding metadata."); + const auto allocated = chain(b[offset + 13]); const auto last = b[fat + allocated.back()] & 0x3f; const auto lastBytes = be(b, offset + 14, 2); + if (lastBytes > 256 || (last == 0 && lastBytes != 0)) fail("The Disk BASIC last-sector length is invalid."); + n.size = (allocated.size() - 1) * 2304 + (last > 0 ? last - 1 : 0) * 256 + lastBytes; + for (unsigned granule : allocated) { + if (!claimed.insert(granule).second) fail("Two Disk BASIC files share an allocation granule."); + const size_t sector = size_t(granule / 2 + (granule >= 34 ? 1 : 0)) * 18 + (granule % 2) * 9; + n.content.insert(n.content.end(), b.begin() + sector * 256, b.begin() + sector * 256 + 2304); + } + if (n.size > n.content.size()) fail("The Disk BASIC file length exceeds its allocation."); n.content.resize(n.size); + if (!image.nodes.emplace(lower(n.path), std::move(n)).second) fail("The Disk BASIC directory has duplicate names."); + } +} +id modifiedTime(const Bytes& b, size_t offset) { + const unsigned year = b[offset] + 1900, month = b[offset + 1], day = b[offset + 2], hour = b[offset + 3], minute = b[offset + 4]; + if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59) return NSNull.null; + NSDateComponents *parts = [NSDateComponents new]; parts.year = year; parts.month = month; parts.day = day; parts.hour = hour; parts.minute = minute; + NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; + NSDate *date = [calendar dateFromComponents:parts]; return date ? @([date timeIntervalSince1970]) : NSNull.null; +} +void validateOS9(Image& image) { + auto& b = image.bytes; const size_t sectors = be(b, 0, 3), mapBytes = be(b, 4, 2), cluster = be(b, 6, 2), rootFD = be(b, 8, 3); + const auto declaredSectorSize = be(b, offsetof(lsn0_sect, dd_lsnsize), 2); + const auto sectorsPerTrack = be(b, offsetof(lsn0_sect, dd_spt), 2); + const bool osk = be(b, offsetof(lsn0_sect, dd_sync), 4) == 0x4372757a; + const auto track0 = be(b, osk ? offsetof(lsn0_sect, dd_opt.m68k.pd_t0s) : offsetof(lsn0_sect, dd_opt.m6809.pd_t0s), 2); + // The upstream raw reader uses the first byte of dd_lsnsize; historical + // writers also store 1 in the low byte. Both spellings still mean 256. + if (!sectors || sectors * 256 != b.size() || cluster == 0 || cluster > 256 || (cluster & (cluster - 1)) || !rootFD || rootFD >= sectors || (declaredSectorSize != 0 && declaredSectorSize != 1 && declaredSectorSize != 256) || !sectorsPerTrack || (track0 && track0 != sectorsPerTrack)) + fail("The OS-9 geometry is invalid or is not a supported raw 256-byte-sector image."); + const size_t clusters = (sectors + cluster - 1) / cluster, mapSectors = (mapBytes + 255) / 256; + if (mapBytes < (clusters + 7) / 8 || mapBytes > b.size() - 256 || mapSectors + 1 >= sectors) fail("The OS-9 allocation bitmap is truncated."); + auto allocated = [&](size_t sector) { const auto bit = sector / cluster; return (b[256 + bit / 8] & (0x80 >> (bit % 8))) != 0; }; + const size_t bootStart = be(b, offsetof(lsn0_sect, dd_bt), 3), bootBytes = be(b, offsetof(lsn0_sect, dd_bsz), 2); + if (bootStart) { + // A zero byte length can designate the fragmented-boot descriptor. + // At minimum its pointed sector must remain within allocated space. + const size_t bootSectors = bootBytes ? (bootBytes + sectorSize - 1) / sectorSize : 1; + if (bootStart >= sectors || bootSectors > sectors - bootStart) fail("The OS-9 boot extent is outside the volume."); + for (size_t sector = bootStart; sector < bootStart + bootSectors; ++sector) + if (!allocated(sector)) fail("An OS-9 boot sector is marked free in the allocation bitmap."); + if (!bootBytes) { + const size_t descriptor = bootStart * sectorSize; size_t allocation = 0; + for (size_t i = 0; i < 48; ++i) { + const size_t segment = descriptor + 16 + i * 5, start = be(b, segment, 3), count = be(b, segment + 3, 2); + if (!count) { if (start) fail("The fragmented OS-9 boot segment is invalid."); continue; } + if (!start || start >= sectors || count > sectors - start) fail("The fragmented OS-9 boot segment is outside the volume."); + for (size_t sector = start; sector < start + count; ++sector) + if (!allocated(sector)) fail("A fragmented OS-9 boot sector is marked free."); + allocation += count * sectorSize; + } + if (be(b, descriptor + 9, 4) > allocation) fail("The fragmented OS-9 boot file is shorter than its descriptor."); + } + } else if (bootBytes) fail("The OS-9 boot extent has no starting sector."); + image.capacity = sectors * 256; image.unit = cluster * 256; + for (size_t c = 0; c < clusters; ++c) if (!allocated(c * cluster)) image.free += std::min(cluster, sectors - c * cluster) * 256; + std::vector owners(sectors, 0); + for (size_t s = 0; s <= mapSectors; ++s) { if (!allocated(s)) fail("OS-9 reserved sectors are marked free."); owners[s] = size_t(-1); } + std::set directories, activeDirectories, claimedFDs; size_t materializedBytes = 0; + std::function visit; + visit = [&](size_t fd, std::string path, std::string parent, unsigned depth) { + if (fd >= sectors || !fd || depth > 32 || image.nodes.size() >= 4096) fail("The OS-9 directory tree exceeds safe bounds."); + const size_t offset = fd * 256; Node n; n.descriptorSector = fd; n.path = path; n.parent = parent; n.name = path.substr(path.rfind('/') == std::string::npos ? 0 : path.rfind('/') + 1); + n.attributes = b[offset]; n.directory = (n.attributes & 0x80) != 0; n.owner = b[offset + 2]; n.group = b[offset + 1]; n.modified = modifiedTime(b, offset + 3); n.size = be(b, offset + 9, 4); + if (n.size > b.size() || b[offset + 8] == 0) fail("The OS-9 descriptor has invalid length or link count."); + if (n.size > limit * 2 - materializedBytes) fail("The OS-9 tree contains too many aliased file bytes."); + const bool firstFD = claimedFDs.insert(fd).second; + if (firstFD) { if (owners[fd] || !allocated(fd)) fail("The OS-9 descriptor overlaps another allocation or is marked free."); owners[fd] = fd; } + std::set localSectors; + for (unsigned i = 0; i < 48; ++i) { + const size_t pos = offset + 16 + i * 5, start = be(b, pos, 3), count = be(b, pos + 3, 2); + if (!count) { if (start) fail("The OS-9 segment has no length."); continue; } + if (start == 0 || start >= sectors || count > sectors - start) fail("The OS-9 file segment is outside the image."); + for (size_t s = start; s < start + count; ++s) { + if (!localSectors.insert(s).second || !allocated(s) || (firstFD && owners[s])) fail("The OS-9 file allocation is cross-linked or marked free."); + if (firstFD) owners[s] = fd; + n.dataSectors.push_back(s); + } + if (count * sectorSize > limit * 2 - materializedBytes) fail("The OS-9 tree contains too many aliased allocation bytes."); + materializedBytes += count * sectorSize; + const size_t needed = std::min(count * sectorSize, n.size - std::min(n.size, n.content.size())); + n.content.insert(n.content.end(), b.begin() + start * sectorSize, b.begin() + start * sectorSize + needed); + } + if (n.size > n.content.size()) fail("The OS-9 file is shorter than its descriptor claims."); n.content.resize(n.size); + if (!image.nodes.emplace(lower(path), n).second) fail("The OS-9 directory contains duplicate names."); + if (!n.directory) return; + if (!activeDirectories.insert(fd).second || !directories.insert(fd).second || n.size % 32) fail("The OS-9 directory is cyclic or has an invalid size."); + for (size_t i = 0; i < n.content.size(); i += 32) { + if (n.content[i] == 0) continue; + std::string child; bool terminated = false; + for (size_t j = 0; j < 29; ++j) { const auto c = n.content[i + j]; child += char(c & 127); if (c & 128) { terminated = true; break; } } + if (!terminated) fail("An OS-9 directory name is not terminated."); + const size_t childFD = be(n.content, i + 29, 3); + if (!childFD || childFD >= sectors) fail("An OS-9 directory entry points outside the image."); + if (child == "." || child == "..") continue; + child = name(child, false); visit(childFD, path.empty() ? child : path + '/' + child, path, depth + 1); + } + activeDirectories.erase(fd); + }; + visit(rootFD, "", "", 0); + if (!image.find("").directory) fail("The OS-9 root descriptor is not a directory."); + std::map clusterOwners; + for (size_t sector = mapSectors + 1; sector < sectors; ++sector) { + if (!owners[sector] || owners[sector] == size_t(-1)) continue; + const auto prior = clusterOwners.emplace(sector / cluster, owners[sector]); + if (!prior.second && prior.first->second != owners[sector]) fail("OS-9 files share an allocation cluster."); + } +} +Image inspect(NSURL *url) { + Image image; image.bytes = load(url); + diskimage_format format = DISKIMAGE_UNKNOWN; + if (_diskimage_identify(url.fileSystemRepresentation, &format) || format != DISKIMAGE_RAW) + fail("The editor currently supports raw disk images. Other image containers are preserved but cannot be edited here."); + if (image.bytes.size() % 256 == 0 && be(image.bytes, 0, 3) == image.bytes.size() / 256) validateOS9(image); + else validateDECB(image); + return image; +} +struct ByteRange { size_t offset, length; }; +std::vector externalBootRanges(const Bytes& bytes, size_t filesystemBytes) { + const size_t start = be(bytes, offsetof(lsn0_sect, dd_bt), 3), length = be(bytes, offsetof(lsn0_sect, dd_bsz), 2); + if (!start || start < filesystemBytes / sectorSize) return {}; + const size_t sectors = bytes.size() / sectorSize; + auto range = [&](size_t first, size_t count) { + if (!count || first >= sectors || count > sectors - first || first < filesystemBytes / sectorSize) + fail("The external OS-9 boot extent is outside the hard-drive image or crosses its filesystem boundary."); + return ByteRange{first * sectorSize, count * sectorSize}; + }; + if (length) return {range(start, (length + sectorSize - 1) / sectorSize)}; + std::vector protectedRanges{range(start, 1)}; + const size_t descriptor = start * sectorSize; size_t allocatedBytes = 0; + if ((bytes[descriptor] & 0x80) || !bytes[descriptor + 8]) fail("The external fragmented OS-9 boot descriptor is invalid."); + for (size_t i = 0; i < 48; ++i) { + const size_t segment = descriptor + 16 + i * 5, first = be(bytes, segment, 3), count = be(bytes, segment + 3, 2); + if (!count) { if (first) fail("The external fragmented OS-9 boot segment has no length."); continue; } + protectedRanges.push_back(range(first, count)); allocatedBytes += count * sectorSize; + } + if (be(bytes, descriptor + 9, 4) > allocatedBytes) fail("The external fragmented OS-9 boot file is shorter than its descriptor."); + return protectedRanges; +} +void clearExternalBootPointer(Bytes& bytes) { + std::fill_n(bytes.begin() + offsetof(lsn0_sect, dd_bt), 5, 0); +} +struct Volume { std::string id, format, name; size_t offset, length, index; }; +std::vector discover(const Bytes& bytes) { + if (bytes.size() % sectorSize) fail("A raw hard-drive image must contain complete 256-byte sectors."); + std::vector volumes; std::vector protectedBoot; size_t hdbStart = 0; + // An RBF volume may occupy a prefix of a combined OS-9/HDB-DOS image. + // Only its declared extent is inspected; no heuristic sector scanning. + const size_t extent = be(bytes, 0, 3) * sectorSize; + const size_t cluster = be(bytes, 6, 2); + const bool rbfHeader = be(bytes, 4, 2) != 0 && cluster != 0 && cluster <= 256 && !(cluster & (cluster - 1)) && be(bytes, 8, 3) != 0; + if (rbfHeader) { + if (extent < 3 * sectorSize || extent > bytes.size()) fail("The OS-9 declared volume extent is outside the image."); + protectedBoot = externalBootRanges(bytes, extent); + Image image; image.bytes.assign(bytes.begin(), bytes.begin() + extent); + if (!protectedBoot.empty()) clearExternalBootPointer(image.bytes); + validateOS9(image); + std::string volumeName; + for (size_t i = 31; i < 63; ++i) { const auto c = bytes[i]; if (!c) break; volumeName += char(c & 127); if (c & 128) break; } + volumes.push_back({"os9:0:" + std::to_string(extent), "os9", volumeName.empty() ? "OS-9 volume" : "OS-9 — " + volumeName, 0, extent, 0}); + hdbStart = extent; + } + const size_t slots = (bytes.size() - hdbStart) / decbVolumeBytes; + for (size_t index = 0; index < slots; ++index) { + const size_t offset = hdbStart + index * decbVolumeBytes; + bool bootOverlap = false; + for (const auto& range : protectedBoot) if (offset < range.offset + range.length && range.offset < offset + decbVolumeBytes) bootOverlap = true; + if (bootOverlap) continue; // bootstrap storage is never a writable BASIC disk + Image image; image.bytes.assign(bytes.begin() + offset, bytes.begin() + offset + decbVolumeBytes); + try { validateDECB(image); } + catch (const std::exception&) { continue; } // unformatted/foreign slots remain opaque + const bool hard = hdbStart != 0 || slots > 1; + volumes.push_back({"decb:" + std::to_string(offset) + ":" + std::to_string(decbVolumeBytes), "decb", + hard ? "HDB-DOS disk " + std::to_string(index) : "Disk BASIC", offset, decbVolumeBytes, index}); + } + if (volumes.empty()) fail("No supported OS-9 or Disk BASIC volume was found. Unformatted and foreign regions are preserved without modification."); + return volumes; +} +const Volume& selected(const std::vector& volumes, NSString *identifier) { + const auto id = string(identifier); + for (const auto& volume : volumes) if (volume.id == id) return volume; + fail("The selected volume no longer matches this image. Reopen the editor and choose it again."); +} +std::vector toolPath(NSURL *url, const std::string& path) { const auto full = std::string(url.fileSystemRepresentation) + ',' + path; std::vector result(full.begin(), full.end()); result.push_back(0); return result; } +void check(error_code error, const char *operation) { if (error) fail(std::string(operation) + " failed (ToolShed error " + std::to_string(error) + ")."); } +struct OpenPath { + bool decb; decb_path_id d = nullptr; os9_path_id o = nullptr; + OpenPath(bool value) : decb(value) {} + ~OpenPath() { if (d) _decb_close(d); if (o) _os9_close(o); } + void open(NSURL *url, const std::string& path, int mode = FAM_READ) { + auto p = toolPath(url, path); + if (decb) { decb_path_id opened = nullptr; check(_decb_open(&opened,p.data(),mode),"Open image file"); d = opened; } + else { os9_path_id opened = nullptr; check(_os9_open(&opened,p.data(),mode),"Open image file"); o = opened; } + } + void close() { if (d) { const auto result = _decb_close(d); d = nullptr; check(result, "Close image file"); } if (o) { const auto result = _os9_close(o); o = nullptr; check(result, "Close image file"); } } +}; +NSData *readEntry(NSURL *url, const Image& image, const std::string& path) { + const auto& n = image.find(path); if (n.directory) fail("Choose a file to export or inspect."); + if (n.size > fileLimit) fail("Export or inspect files no larger than 16 MiB."); + if (!image.decb && image.unit > sectorSize) return [NSData dataWithBytes:n.content.data() length:n.content.size()]; + OpenPath file(image.decb); file.open(url, n.path); Bytes out(n.size); size_t offset = 0; + while (offset < out.size()) { + u_int count = u_int(out.size() - offset); const auto result = image.decb ? _decb_read(file.d, out.data() + offset, &count) : _os9_read(file.o, out.data() + offset, &count); + if (count > out.size() - offset || !count || (result && result != EOS_EOF)) fail("The file could not be read completely."); offset += count; + } + file.close(); if (out != n.content) fail("The filesystem reader disagrees with the validated file allocation."); + return [NSData dataWithBytes:out.data() length:out.size()]; +} +// OS-9 directory entries are 32-byte records aligned within 256-byte sectors. +// Relinking them leaves every file descriptor and data allocation untouched. +size_t directoryOffset(const Node& directory, size_t logical) { + if (!directory.directory || logical % 32 || logical / sectorSize >= directory.dataSectors.size()) + fail("The OS-9 directory entry is outside its allocation."); + return directory.dataSectors[logical / sectorSize] * sectorSize + logical % sectorSize; +} +size_t findDirectoryEntry(const Image& image, const Node& directory, const Node& node) { + for (size_t i = 0; i < directory.size; i += 32) { + if (!directory.content[i]) continue; + std::string entryName; + for (size_t j = 0; j < 29; ++j) { + const auto c = directory.content[i + j]; entryName += char(c & 127); + if (c & 128) break; + } + if (lower(entryName) == lower(node.name) && be(directory.content, i + 29, 3) == node.descriptorSector) + return directoryOffset(directory, i); + } + fail("The selected file's directory entry changed. Refresh and select it again."); +} +void putBigEndian(Bytes& bytes, size_t offset, size_t length, size_t value) { + if (offset > bytes.size() || length > bytes.size() - offset || (length < sizeof(size_t) && value >> (length * 8))) + fail("The OS-9 directory metadata exceeds its supported bounds."); + for (size_t i = 0; i < length; ++i) { bytes[offset + length - i - 1] = uint8_t(value); value >>= 8; } +} +void growDirectory(Bytes& bytes, Node& directory) { + const size_t sectors = bytes.size() / sectorSize; + const size_t cluster = be(bytes, 6, 2); + size_t freeSector = 0; + for (size_t s = cluster; s + cluster <= sectors; s += cluster) if (!(bytes[sectorSize + (s / cluster) / 8] & (0x80 >> ((s / cluster) % 8)))) { freeSector = s; break; } + if (!freeSector) fail("The destination directory needs another sector, but the OS-9 disk is full."); + const size_t fd = directory.descriptorSector * sectorSize; + size_t freeSegment = size_t(-1), lastSegment = size_t(-1); + for (size_t i = 0; i < 48; ++i) { + const size_t segment = fd + 16 + i * 5; + if (be(bytes, segment + 3, 2)) lastSegment = segment; + else if (freeSegment == size_t(-1)) freeSegment = segment; + } + // RBF on the 6x09 keeps a segment within one allocation-map sector + // (2048 single-sector clusters). Prefer adjacent legal growth first. + if (lastSegment != size_t(-1)) { + const size_t start = be(bytes, lastSegment, 3), count = be(bytes, lastSegment + 3, 2), adjacent = start + count; + if (count + cluster <= 65535 && adjacent + cluster <= sectors && adjacent % cluster == 0 && adjacent / cluster / 2048 == start / cluster / 2048 && + !(bytes[sectorSize + (adjacent / cluster) / 8] & (0x80 >> ((adjacent / cluster) % 8)))) freeSector = adjacent; + } + if (lastSegment != size_t(-1) && be(bytes, lastSegment, 3) + be(bytes, lastSegment + 3, 2) == freeSector && + freeSector / cluster / 2048 == be(bytes, lastSegment, 3) / cluster / 2048 && be(bytes, lastSegment + 3, 2) + cluster <= 65535) { + putBigEndian(bytes, lastSegment + 3, 2, be(bytes, lastSegment + 3, 2) + cluster); + } else { + // Append after the last occupied segment so logical directory offsets + // remain stable even when an input descriptor contains segment holes. + const size_t appended = lastSegment == size_t(-1) ? fd + 16 : lastSegment + 5; + // Match the retained allocator: leave its final descriptor segment + // empty, although inspection accepts existing 48-segment images. + if (freeSegment == size_t(-1) || appended >= fd + 16 + 47 * 5) + fail("The destination directory has no room for another allocation segment."); + putBigEndian(bytes, appended, 3, freeSector); putBigEndian(bytes, appended + 3, 2, cluster); + } + bytes[sectorSize + (freeSector / cluster) / 8] |= uint8_t(0x80 >> ((freeSector / cluster) % 8)); + std::fill(bytes.begin() + freeSector * sectorSize, bytes.begin() + (freeSector + cluster) * sectorSize, 0); + for (size_t s = freeSector; s < freeSector + cluster; ++s) directory.dataSectors.push_back(s); +} +// The retained allocator scans sector counts as bitmap bits for multi-sector +// clusters. Keep those volumes on this bounded, cluster-aware transaction path +// rather than passing them to allocator entry points that can overrun the map. +size_t clusterSize(const Bytes& bytes) { return be(bytes, 6, 2); } +void markCluster(Bytes& bytes, size_t sector, bool allocated) { + const size_t bit = sector / clusterSize(bytes), byte = sectorSize + bit / 8; + if (byte >= sectorSize + be(bytes, 4, 2)) fail("The OS-9 allocation bit is outside its bitmap."); + const uint8_t mask = uint8_t(0x80 >> (bit % 8)); + if (allocated) bytes[byte] |= mask; else bytes[byte] &= uint8_t(~mask); +} +size_t allocateCluster(Bytes& bytes) { + const size_t cluster = clusterSize(bytes), sectors = bytes.size() / sectorSize; + for (size_t sector = cluster; sector + cluster <= sectors; sector += cluster) { + const size_t bit = sector / cluster; + if (!(bytes[sectorSize + bit / 8] & (0x80 >> (bit % 8)))) { + markCluster(bytes, sector, true); + std::fill(bytes.begin() + sector * sectorSize, bytes.begin() + (sector + cluster) * sectorSize, 0); + return sector; + } + } + fail("The OS-9 volume has no free complete allocation cluster."); +} +void appendSegment(Bytes& bytes, Node& node, size_t start, size_t count) { + const size_t descriptor = node.descriptorSector * sectorSize, cluster = clusterSize(bytes); + size_t last = size_t(-1), slot = 0; + for (; slot < 47; ++slot) { + const size_t entry = descriptor + 16 + slot * 5; + if (!be(bytes, entry + 3, 2)) break; + last = entry; + } + if (last != size_t(-1) && be(bytes, last, 3) + be(bytes, last + 3, 2) == start && + be(bytes, last + 3, 2) + count <= 65535 && be(bytes, last, 3) / cluster / 2048 == (start + count - 1) / cluster / 2048) { + putBigEndian(bytes, last + 3, 2, be(bytes, last + 3, 2) + count); + } else { + if (slot >= 47) fail("The OS-9 file has no room for another allocation segment."); + putBigEndian(bytes, descriptor + 16 + slot * 5, 3, start); + putBigEndian(bytes, descriptor + 19 + slot * 5, 2, count); + } + for (size_t sector = start; sector < start + count; ++sector) node.dataSectors.push_back(sector); +} +std::array directoryEntry(const std::string& name, size_t descriptor) { + std::array entry{}; + std::copy(name.begin(), name.end(), entry.begin()); entry[name.size() - 1] |= 0x80; + entry[29] = uint8_t(descriptor >> 16); entry[30] = uint8_t(descriptor >> 8); entry[31] = uint8_t(descriptor); + return entry; +} +void insertEntry(Bytes& bytes, Node& parent, const std::string& name, size_t descriptor) { + size_t logical = 0; + while (logical < parent.content.size() && parent.content[logical]) logical += 32; + if (logical == parent.content.size()) { + if (logical + 32 > parent.dataSectors.size() * sectorSize) growDirectory(bytes, parent); + parent.content.resize(logical + 32, 0); parent.size = parent.content.size(); + putBigEndian(bytes, parent.descriptorSector * sectorSize + 9, 4, parent.size); + } + const auto entry = directoryEntry(name, descriptor); const size_t offset = directoryOffset(parent, logical); + std::copy(entry.begin(), entry.end(), bytes.begin() + offset); + std::copy(entry.begin(), entry.end(), parent.content.begin() + logical); +} +void deleteClusterEntry(Bytes& bytes, const Image& image, const Node& node) { + const size_t entry = findDirectoryEntry(image, image.find(node.parent), node); + std::fill_n(bytes.begin() + entry, 32, 0); + const size_t descriptor = node.descriptorSector * sectorSize; + if (--bytes[descriptor + 8]) return; + const size_t cluster = clusterSize(bytes); + std::set owned{node.descriptorSector / cluster}; + for (const size_t sector : node.dataSectors) owned.insert(sector / cluster); + const size_t mapSectors = (be(bytes, 4, 2) + sectorSize - 1) / sectorSize; + for (const size_t index : owned) { + if (index * cluster <= mapSectors) fail("A removed entry shares a reserved filesystem cluster."); + markCluster(bytes, index * cluster, false); + } +} +Bytes createClusterEntry(const Image& image, const Node& parentInput, const std::string& filename, const uint8_t *data, size_t length, bool directory, bool replace) { + Bytes bytes = image.bytes; Node parent = parentInput; + const auto path = parent.path.empty() ? filename : parent.path + '/' + filename; + auto existing = image.nodes.find(lower(path)); + if (existing != image.nodes.end()) { + if (!replace || existing->second.directory) fail("An entry already has that name."); + deleteClusterEntry(bytes, image, existing->second); + const size_t offset = findDirectoryEntry(image, parent, existing->second); + for (size_t logical = 0; logical < parent.content.size(); logical += 32) + if (directoryOffset(parent, logical) == offset) std::fill_n(parent.content.begin() + logical, 32, 0); + } + const size_t cluster = clusterSize(bytes), descriptor = allocateCluster(bytes); + Node node; node.descriptorSector = descriptor; node.directory = directory; + const size_t base = descriptor * sectorSize; + bytes[base] = directory ? 0xbf : 0x0b; bytes[base + 8] = 1; + NSDateComponents *now = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:NSDate.date]; + bytes[base + 3] = uint8_t(now.year - 1900); bytes[base + 4] = uint8_t(now.month); bytes[base + 5] = uint8_t(now.day); bytes[base + 6] = uint8_t(now.hour); bytes[base + 7] = uint8_t(now.minute); + std::copy_n(bytes.begin() + base + 3, 3, bytes.begin() + base + 13); + if (cluster > 1) appendSegment(bytes, node, descriptor + 1, cluster - 1); + Bytes directoryData; + if (directory) { + directoryData.resize(64); const auto dot = directoryEntry(".", descriptor), up = directoryEntry("..", parent.descriptorSector); + std::copy(dot.begin(), dot.end(), directoryData.begin()); std::copy(up.begin(), up.end(), directoryData.begin() + 32); + data = directoryData.data(); length = directoryData.size(); + } + while (node.dataSectors.size() * sectorSize < length) appendSegment(bytes, node, allocateCluster(bytes), cluster); + for (size_t logical = 0; logical < length; ++logical) bytes[node.dataSectors[logical / sectorSize] * sectorSize + logical % sectorSize] = data[logical]; + putBigEndian(bytes, base + 9, 4, length); insertEntry(bytes, parent, filename, descriptor); + return bytes; +} + +Bytes movedOS9Files(const Image& image, NSArray *paths, NSString *destination) { + if (image.decb) fail("Moving files between folders is available only for OS-9 images."); + if (paths.count == 0 || paths.count > 4096) fail("Select from one to 4096 regular files to move."); + Node target = image.find(imagePath(destination, false, true)); + if (!target.directory) fail("Choose an OS-9 destination folder."); + struct Move { const Node *node; size_t offset; std::array entry; }; + std::vector moves; std::set sources, names; + for (NSString *path in paths) { + if (![path isKindOfClass:NSString.class]) fail("Select valid image paths to move."); + const auto& node = image.find(imagePath(path, false)); + if (node.directory) fail("Move regular files only. Folders are destinations and cannot be moved."); + if (!sources.insert(lower(node.path)).second) fail("A file was selected more than once. Refresh the selection."); + if (lower(node.parent) == lower(target.path)) fail("The selected file is already in that folder. Choose a different destination."); + const auto dest = target.path.empty() ? node.name : target.path + '/' + node.name; + if (!names.insert(lower(node.name)).second || image.nodes.count(lower(dest))) + fail("A destination name already exists or repeats within the selection. No files were moved; choose another folder."); + const size_t offset = findDirectoryEntry(image, image.find(node.parent), node); + Move move{&node, offset, {}}; std::copy_n(image.bytes.begin() + offset, 32, move.entry.begin()); moves.push_back(move); + } + Bytes next = image.bytes; + for (const auto& move : moves) { + size_t slot = 0; + while (slot < target.content.size() && target.content[slot]) slot += 32; + if (slot == target.content.size()) { + if (slot + 32 > target.dataSectors.size() * sectorSize) growDirectory(next, target); + target.content.resize(slot + 32, 0); target.size = target.content.size(); + putBigEndian(next, target.descriptorSector * sectorSize + 9, 4, target.size); + } + const size_t offset = directoryOffset(target, slot); + std::copy(move.entry.begin(), move.entry.end(), next.begin() + offset); + std::copy(move.entry.begin(), move.entry.end(), target.content.begin() + slot); + } + // A plan is complete before any source entry is removed or any file is + // written. Failure at any point leaves the caller's working image intact. + for (const auto& move : moves) std::fill_n(next.begin() + move.offset, 32, 0); + for (const auto& move : moves) { + const size_t descriptor = move.node->descriptorSector * sectorSize; + if (!std::equal(image.bytes.begin() + descriptor, image.bytes.begin() + descriptor + sectorSize, next.begin() + descriptor)) + fail("A move changed a file descriptor; no changes were kept."); + for (const size_t sector : move.node->dataSectors) + if (!std::equal(image.bytes.begin() + sector * sectorSize, image.bytes.begin() + (sector + 1) * sectorSize, next.begin() + sector * sectorSize)) + fail("A move changed file data; no changes were kept."); + } + return next; +} +void setError(NSError **error, const std::exception& value) { if (error) *error = [NSError errorWithDomain:@"VCCDiskImageEditor" code:1 userInfo:@{NSLocalizedDescriptionKey:text(value.what())}]; } +void restore(NSURL *url, const Bytes& bytes) { NSError *error = nil; if (![[NSData dataWithBytes:bytes.data() length:bytes.size()] writeToURL:url options:NSDataWritingAtomic error:&error]) fail("A working-image operation failed and its private copy could not be restored. Close the editor and reopen the original image."); } +template BOOL mutate(NSURL *url, Operation operation, NSError **error) { + std::lock_guard lock(backendMutex); + try { + auto image = inspect(url); + try { + operation(image); + const auto after = load(url); + if (after.size() != image.bytes.size() || + (image.decb && !std::equal(image.bytes.begin() + decbVolumeBytes, image.bytes.end(), after.begin() + decbVolumeBytes))) + fail("The filesystem operation changed the image size or protected supplementary tracks. The private working image has been restored."); + (void)inspect(url); + } + catch (...) { restore(url, image.bytes); throw; } + return YES; + } catch (const std::exception& value) { setError(error, value); return NO; } +} +NSString *attributes(unsigned bits) { + NSMutableArray *items = [NSMutableArray array]; + for (const auto& item : std::array,8>{{{0x80,"d"},{0x40,"s"},{1,"r"},{2,"w"},{4,"e"},{8,"pr"},{16,"pw"},{32,"pe"}}}) if (bits & item.first) [items addObject:@(item.second)]; + return [items componentsJoinedByString:@" "]; +} +} + +@implementation VCCDiskImageEditorBackend ++ (NSArray *> *)discoverVolumesAtURL:(NSURL *)imageURL error:(NSError **)error { + std::lock_guard lock(backendMutex); + try { + diskimage_format format = DISKIMAGE_UNKNOWN; + if (_diskimage_identify(imageURL.fileSystemRepresentation, &format) || format != DISKIMAGE_RAW) + fail("The editor supports raw floppy and hard-drive images; other containers are preserved without conversion."); + const auto bytes = load(imageURL); const auto volumes = discover(bytes); + NSMutableArray *rows = [NSMutableArray array]; + for (const auto& volume : volumes) [rows addObject:@{@"id":text(volume.id), @"format":text(volume.format), @"name":text(volume.name), @"offset_bytes":@(volume.offset), @"byte_count":@(volume.length), @"index":@(volume.index)}]; + return rows; + } catch (const std::exception& value) { setError(error, value); return nil; } +} ++ (BOOL)extractVolume:(NSString *)volumeID imageURL:(NSURL *)imageURL outputURL:(NSURL *)outputURL error:(NSError **)error { + std::lock_guard lock(backendMutex); + try { const auto bytes = load(imageURL); const auto volumes = discover(bytes); const auto volume = selected(volumes, volumeID); + if ([imageURL.URLByResolvingSymlinksInPath isEqual:outputURL.URLByResolvingSymlinksInPath]) fail("Extract a volume to a separate private working file."); + Bytes part(bytes.begin() + volume.offset, bytes.begin() + volume.offset + volume.length); + if (volume.format == "os9" && !externalBootRanges(bytes, volume.length).empty()) clearExternalBootPointer(part); + restore(outputURL, part); return YES; + } catch (const std::exception& value) { setError(error, value); return NO; } +} ++ (BOOL)replaceVolume:(NSString *)volumeID imageURL:(NSURL *)imageURL volumeURL:(NSURL *)volumeURL error:(NSError **)error { + std::lock_guard lock(backendMutex); + try { auto bytes = load(imageURL); const auto volumes = discover(bytes); const auto volume = selected(volumes, volumeID); const auto part = inspect(volumeURL); + if (part.bytes.size() != volume.length || part.decb != (volume.format == "decb")) fail("The edited volume changed its size or filesystem type. No changes were applied."); + const bool externalBoot = volume.format == "os9" && !externalBootRanges(bytes, volume.length).empty(); + std::array pointer{}; + if (externalBoot) std::copy_n(bytes.begin() + offsetof(lsn0_sect, dd_bt), 5, pointer.begin()); + std::copy(part.bytes.begin(), part.bytes.end(), bytes.begin() + volume.offset); + if (externalBoot) std::copy(pointer.begin(), pointer.end(), bytes.begin() + offsetof(lsn0_sect, dd_bt)); + (void)discover(bytes); // validate the original boot pointer in its full container context + restore(imageURL, bytes); return YES; + } catch (const std::exception& value) { setError(error, value); return NO; } +} ++ (NSDictionary *)inspectImageAtURL:(NSURL *)imageURL error:(NSError **)error { + std::lock_guard lock(backendMutex); + try { const auto image = inspect(imageURL); return @{@"format":image.decb ? @"decb" : @"os9", @"format_name":image.decb ? @"Disk BASIC" : @"OS-9 RBF", @"byte_count":@(image.bytes.size()), @"writable":@YES, @"capacity_bytes":@(image.capacity), @"used_bytes":@(image.capacity - image.free), @"free_bytes":@(image.free), @"allocation_unit_bytes":@(image.unit), @"protected_suffix_bytes":@(image.decb ? image.bytes.size() - decbVolumeBytes : 0)}; } + catch (const std::exception& value) { setError(error, value); return nil; } +} ++ (NSArray *> *)listDirectory:(NSString *)directory imageURL:(NSURL *)imageURL error:(NSError **)error { + std::lock_guard lock(backendMutex); + try { + const auto image = inspect(imageURL); const auto path = imagePath(directory, image.decb, true); const auto& folder = image.find(path); if (!folder.directory) fail("This entry is not a directory."); + NSMutableArray *rows = [NSMutableArray array]; + for (const auto& pair : image.nodes) { const auto& n = pair.second; if (n.path.empty() || lower(n.parent) != lower(folder.path)) continue; + NSString *type = image.decb ? @[@"BASIC program",@"BASIC data",@"Machine language",@"Text"][n.type] : n.directory ? @"Folder" : @"OS-9 file"; + [rows addObject:@{@"name":text(n.name),@"path":text(n.path),@"size":@(n.size),@"is_directory":@(n.directory),@"type":type,@"file_type":image.decb ? @(n.type) : NSNull.null,@"encoding":image.decb ? (n.ascii ? @"ASCII" : @"Binary") : @"",@"ascii":@(n.ascii != 0),@"attributes":image.decb ? @"" : attributes(n.attributes),@"permissions":image.decb ? NSNull.null : @(n.attributes & 0x7f),@"owner":@(n.owner),@"group":@(n.group),@"modified":n.modified}]; } + return rows; + } catch (const std::exception& value) { setError(error, value); return nil; } +} ++ (NSData *)readFile:(NSString *)path imageURL:(NSURL *)imageURL error:(NSError **)error { + std::lock_guard lock(backendMutex); + try { const auto image = inspect(imageURL); return readEntry(imageURL, image, imagePath(path, image.decb)); } + catch (const std::exception& value) { setError(error, value); return nil; } +} ++ (NSString *)identifyFile:(NSString *)path imageURL:(NSURL *)imageURL error:(NSError **)error { + std::lock_guard lock(backendMutex); + try { + const auto image = inspect(imageURL); NSData *data = readEntry(imageURL, image, imagePath(path, image.decb)); const auto *begin = static_cast(data.bytes); Bytes bytes(begin, begin + data.length); + NSMutableArray *modules = [NSMutableArray array]; size_t offset = 0; + while (offset < bytes.size()) { + const bool os9 = bytes.size() - offset >= OS9_HEADER_SIZE && be(bytes, offset, 2) == 0x87cd; + const bool osk = bytes.size() - offset >= OSK_HEADER_SIZE && be(bytes, offset, 2) == 0x4afc; + if (!os9 && !osk) fail("The selected file does not contain a complete supported OS-9 module."); + const size_t header = os9 ? OS9_HEADER_SIZE : OSK_HEADER_SIZE, size = be(bytes, offset + (os9 ? 2 : 4), os9 ? 2 : 4), nameOffset = be(bytes, offset + (os9 ? 4 : 12), os9 ? 2 : 4); + if (size < header + 3 || size > bytes.size() - offset || nameOffset >= size - 3) fail("The OS-9 module has a truncated or invalid header."); + std::string moduleName; bool ended = false; + for (size_t i = nameOffset; i < size - 3 && moduleName.size() < 255; ++i) { const auto c = bytes[offset + i]; if ((c & 127) < 32 || (c & 127) > 126) fail("The OS-9 module name is invalid."); moduleName += char(c & 127); if (c & 128) { ended = true; break; } } + if (!ended) fail("The OS-9 module name is not terminated."); + u_char crc[3] = {255,255,255}; const bool good = _os9_crc_compute(bytes.data() + offset, u_int(size), crc) != 0; + [modules addObject:[NSString stringWithFormat:@"%@ module: %@\nOffset: %zu bytes\nSize: %zu bytes\nCRC: %@",os9 ? @"OS-9/6809" : @"OS-9/68K",text(moduleName),offset,size,good ? @"Valid" : @"Mismatch"]]; + offset += size; + } + if (!modules.count) fail("The selected file is empty."); return [modules componentsJoinedByString:@"\n\n"]; + } catch (const std::exception& value) { setError(error, value); return nil; } +} ++ (BOOL)importData:(NSData *)data named:(NSString *)filename directory:(NSString *)directory imageURL:(NSURL *)imageURL fileType:(NSInteger)fileType ascii:(BOOL)ascii replace:(BOOL)replace error:(NSError **)error { + return mutate(imageURL, [&](const Image& image) { + if (data.length > fileLimit || fileType < 0 || fileType > 3) fail("Choose a supported file type and a file no larger than 16 MiB."); + const auto dir = imagePath(directory, image.decb, true); const auto& parent = image.find(dir); if (!parent.directory) fail("The import destination is not a directory."); + const auto base = name(string(filename), image.decb); const auto dest = parent.path.empty() ? base : parent.path + '/' + base; + const auto existing = image.nodes.find(lower(dest)); if (existing != image.nodes.end() && (!replace || existing->second.directory)) fail(existing->second.directory ? "A directory already has that name." : "A file already has that name. Confirm replacement or use a different name."); + if (data.length > image.capacity) fail("This file is larger than the disk's usable capacity."); + if (!image.decb && image.unit > sectorSize) { restore(imageURL, createClusterEntry(image, parent, base, static_cast(data.bytes), data.length, false, replace)); return; } + OpenPath file(image.decb); auto path = toolPath(imageURL, dest); + if (image.decb) { decb_path_id opened = nullptr; check(_decb_create(&opened,path.data(),FAM_WRITE | (replace ? 0 : FAM_NOCREATE),int(fileType),ascii ? 255 : 0),"Create image file"); file.d = opened; } + else { os9_path_id opened = nullptr; check(_os9_create(&opened,path.data(),FAM_WRITE | (replace ? 0 : FAM_NOCREATE),FAP_READ|FAP_WRITE|FAP_PREAD),"Create image file"); file.o = opened; } + size_t offset = 0; const auto *bytes = static_cast(data.bytes); + while (offset < data.length) { u_int count = u_int(data.length - offset); const auto result = image.decb ? _decb_write(file.d,const_cast(bytes + offset),&count) : _os9_write(file.o,const_cast(bytes + offset),&count); check(result,"Write image file"); if (!count || count > data.length - offset) fail("The image writer did not complete the file."); offset += count; } + file.close(); + }, error); +} ++ (BOOL)makeDirectory:(NSString *)filename inDirectory:(NSString *)directory imageURL:(NSURL *)imageURL error:(NSError **)error { + return mutate(imageURL, [&](const Image& image) { if (image.decb) fail("Disk BASIC images do not support folders."); const auto dir = imagePath(directory,false,true); const auto& parent = image.find(dir); if (!parent.directory) fail("The destination is not a directory."); const auto base = name(string(filename),false); const auto dest = parent.path.empty() ? base : parent.path + '/' + base; if (image.nodes.count(lower(dest))) fail("An entry already has that name."); if (image.unit > sectorSize) { restore(imageURL, createClusterEntry(image, parent, base, nullptr, 0, true, false)); return; } auto path = toolPath(imageURL,dest); check(_os9_makdir(path.data()),"Create OS-9 directory"); }, error); +} ++ (BOOL)renameEntry:(NSString *)entry toName:(NSString *)filename imageURL:(NSURL *)imageURL error:(NSError **)error { + return mutate(imageURL, [&](const Image& image) { const auto& node = image.find(imagePath(entry,image.decb)); const auto base = name(string(filename),image.decb); const auto dest = node.parent.empty() ? base : node.parent + '/' + base; if (image.nodes.count(lower(dest))) fail("An entry already has that name."); if (!image.decb && image.unit > sectorSize) { auto bytes = image.bytes; const size_t offset = findDirectoryEntry(image, image.find(node.parent), node); const auto entry = directoryEntry(base, node.descriptorSector); std::copy(entry.begin(), entry.end(), bytes.begin() + offset); restore(imageURL, bytes); return; } auto path = toolPath(imageURL,node.path); std::vector newName(base.begin(),base.end());newName.push_back(0); check(image.decb ? _decb_rename(path.data(),newName.data()) : _os9_rename(path.data(),newName.data()),"Rename image entry"); }, error); +} ++ (BOOL)deleteEntry:(NSString *)entry directory:(BOOL)directory imageURL:(NSURL *)imageURL error:(NSError **)error { + return mutate(imageURL, [&](const Image& image) { const auto& node = image.find(imagePath(entry,image.decb)); if (node.directory != bool(directory)) fail("The selected entry changed type. Refresh the directory."); if (node.directory) for (const auto& pair : image.nodes) if (!pair.second.path.empty() && lower(pair.second.parent) == lower(node.path)) fail("Delete the folder's contents before deleting the folder."); if (!image.decb && image.unit > sectorSize) { auto bytes = image.bytes; deleteClusterEntry(bytes, image, node); restore(imageURL, bytes); return; } auto path = toolPath(imageURL,node.path); check(image.decb ? _decb_kill(path.data()) : node.directory ? _os9_delete_directory(path.data()) : _os9_delete(path.data()),"Delete image entry"); }, error); +} ++ (BOOL)moveFiles:(NSArray *)paths toDirectory:(NSString *)directory imageURL:(NSURL *)imageURL error:(NSError **)error { + return mutate(imageURL, [&](const Image& image) { restore(imageURL, movedOS9Files(image, paths, directory)); }, error); +} ++ (BOOL)setOS9MetadataForPath:(NSString *)entry imageURL:(NSURL *)imageURL ownerUser:(NSInteger)ownerUser ownerGroup:(NSInteger)ownerGroup permissions:(NSInteger)permissions error:(NSError **)error { + return mutate(imageURL, [&](const Image& image) { + if (image.decb) fail("Disk BASIC entries do not have OS-9 ownership or permission attributes."); + if (ownerUser < 0 || ownerUser > 255 || ownerGroup < 0 || ownerGroup > 255 || permissions < 0 || permissions > 127) + fail("Use owner user and group values from 0 to 255 and permission bits from 0 to 127. The directory type cannot be changed."); + const auto& node = image.find(imagePath(entry, false, true)); + // Host disk maintenance deliberately does not impersonate a guest UID. + // A raw RBF path can repair even an entry with no guest access bits, + // without changing it temporarily or bypassing host write protection. + if (image.unit > sectorSize) { auto bytes = image.bytes; const size_t offset = node.descriptorSector * sectorSize; bytes[offset] = uint8_t((bytes[offset] & 0x80) | permissions); bytes[offset + 1] = uint8_t(ownerGroup); bytes[offset + 2] = uint8_t(ownerUser); restore(imageURL, bytes); return; } + OpenPath raw(false); raw.open(imageURL, "@", FAM_WRITE); + fd_stats descriptor{}; + check(_os9_lsn_get(raw.o, int(node.descriptorSector), 0, &descriptor, sizeof(descriptor)), "Read OS-9 descriptor"); + const size_t offset = node.descriptorSector * sectorSize; + const auto *actual = reinterpret_cast(&descriptor); + if (!std::equal(actual, actual + sizeof(descriptor), image.bytes.begin() + offset)) + fail("The OS-9 descriptor changed while its metadata was being edited."); + descriptor.fd_att = static_cast((descriptor.fd_att & FAP_DIR) | permissions); + descriptor.fd_own[0] = static_cast(ownerGroup); + descriptor.fd_own[1] = static_cast(ownerUser); + check(_os9_lsn_put(raw.o, int(node.descriptorSector), 0, &descriptor, sizeof(descriptor)), "Write OS-9 metadata"); + raw.close(); + auto expected = image.bytes; + expected[offset] = descriptor.fd_att; + expected[offset + 1] = descriptor.fd_own[0]; + expected[offset + 2] = descriptor.fd_own[1]; + if (load(imageURL) != expected) fail("The metadata edit changed bytes outside the entry's attributes and owner. The private working image has been restored."); + }, error); +} +@end diff --git a/platforms/macos/Bridge/DriveWireCoWin.h b/platforms/macos/Bridge/DriveWireCoWin.h new file mode 100644 index 0000000..49cb8ba --- /dev/null +++ b/platforms/macos/Bridge/DriveWireCoWin.h @@ -0,0 +1,106 @@ +#pragma once + +#include +#include +#include +#include + +namespace VCC::Mac { + +using TerminalGrid = std::array, 24>; + +// Encode an addressed terminal screen for the stock NitrOS-9 telnet client's +// output path, which passes ordinary bytes straight through to CoWin. +class DriveWireTerminalOutput { +public: + static constexpr std::size_t maxDrawBytes = 2010; + + void draw(const TerminalGrid& cells, int x, int y, bool cursorVisible, + bool clear, std::vector& out) { + const auto start = out.size(); + if (clear || !known) { + out.push_back(0x0c); + for (auto& row : painted) row.fill(' '); + cursorX = cursorY = -1; + visibilityKnown = false; + known = true; + } + + constexpr int bottom = 23; + for (int row = 0; row < bottom - 1; ++row) { + paintRow(row, cells[row], out); + } + + // GRFDRV wraps immediately after the last column. To write the + // bottom-right cell without scrolling away the first line, prepare + // the last row one line up and move it down with CoWin's insert-line. + // Ordinary changes elsewhere on the bottom row avoid that extra work. + if (glyph(cells[bottom].back()) != painted[bottom].back()) { + paintRow(bottom - 1, cells[bottom], out); + position(0, bottom - 1, out); + out.insert(out.end(), {0x1f, 0x30}); + painted[bottom] = painted[bottom - 1]; + painted[bottom - 1].fill(' '); + } else { + paintRow(bottom, cells[bottom], out); + } + paintRow(bottom - 1, cells[bottom - 1], out); + + // CoWin may move the cursor on a write, including automatic wrapping. + // Reposition it even when the logical position itself didn't change. + x = std::clamp(x, 0, 79); + y = std::clamp(y, 0, 23); + if (out.size() != start || x != cursorX || y != cursorY) { + position(x, y, out); + cursorX = x; + cursorY = y; + } + if (!visibilityKnown || visible != cursorVisible) { + out.insert(out.end(), {0x05, static_cast(cursorVisible ? 0x21 : 0x20)}); + visible = cursorVisible; + visibilityKnown = true; + } + } + +private: + using Row = TerminalGrid::value_type; + TerminalGrid painted{}; + int cursorX = -1, cursorY = -1; + bool known = false, visibilityKnown = false, visible = true; + + static char glyph(char ch) { + const auto byte = static_cast(ch); + return byte >= 0x20 && byte <= 0x7e ? ch : '?'; + } + + static void position(int x, int y, std::vector& out) { + out.insert(out.end(), {0x02, static_cast(0x20 + x), + static_cast(0x20 + y)}); + } + + void paintRow(int row, const Row& desired, std::vector& out) { + auto& current = painted[row]; + std::size_t x = 0; + while (x < desired.size()) { + if (current[x] == glyph(desired[x])) { + ++x; + continue; + } + const auto first = x; + position(static_cast(x), row, out); + auto lastChange = x; + // Repaint short gaps: an absolute cursor move costs three bytes. + // Even an alternating pattern costs at most 83 bytes per row. + while (x < desired.size() && x - lastChange <= 4) { + if (current[x] != glyph(desired[x])) lastChange = x; + ++x; + } + for (auto column = first; column <= lastChange; ++column) { + current[column] = glyph(desired[column]); + out.push_back(static_cast(current[column])); + } + } + } +}; + +} // namespace VCC::Mac diff --git a/platforms/macos/Bridge/DriveWireEndpoint.h b/platforms/macos/Bridge/DriveWireEndpoint.h new file mode 100644 index 0000000..a48f884 --- /dev/null +++ b/platforms/macos/Bridge/DriveWireEndpoint.h @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include "DriveWireShell.h" +#include "../../../src/devices/DriveWireTransport.h" +#include + +namespace VCC::Mac { +inline std::unique_ptr openDriveWireEndpoint( + DriveWireShell& shell, const std::string& host, uint16_t port) { + // This name exists only inside the emulator. Never send it to DNS or + // redirect normal localhost connections to a privileged command prompt. + if (strcasecmp(host.c_str(), "macshell") == 0) + return port == 2323 ? shell.connect() : nullptr; + return Devices::makeDriveWireTCPConnection(host, port); +} +} diff --git a/platforms/macos/Bridge/DriveWireShell.h b/platforms/macos/Bridge/DriveWireShell.h new file mode 100644 index 0000000..0a18b16 --- /dev/null +++ b/platforms/macos/Bridge/DriveWireShell.h @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include "devices/DriveWireTransport.h" +#include +#include + +namespace VCC::Mac { +// An explicit, one-use invitation for this emulator's guest. No network listener. +class DriveWireShell { +public: + enum class StartupFiles { user, isolatedTest }; + explicit DriveWireShell(StartupFiles files = StartupFiles::user); + ~DriveWireShell(); + void arm(); + std::uint64_t requestID() const; + bool decide(std::uint64_t id, bool allow); + void stop(); + std::string status() const; + std::unique_ptr connect(); +private: + struct Impl; + std::unique_ptr impl; +}; +} diff --git a/platforms/macos/Bridge/DriveWireShell.mm b/platforms/macos/Bridge/DriveWireShell.mm new file mode 100644 index 0000000..915139d --- /dev/null +++ b/platforms/macos/Bridge/DriveWireShell.mm @@ -0,0 +1,368 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include "DriveWireShell.h" +#include "DriveWireTerminal.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace VCC::Mac { +namespace { +using Transport = Devices::DriveWireTransport; +using State = Transport::State; +using namespace std::chrono_literals; +constexpr std::size_t queueLimit = 65536; + +struct Child { + pid_t pid = -1; + int master = -1; + ~Child() { + if (master >= 0) ::close(master); + } +}; + +// Spawn directly into a fresh session. The child gets only its three tty +// descriptors and a small interactive environment. No login helper, command +// string, or user-supplied executable path is involved. +bool spawnShell(Child& child, DriveWireShell::StartupFiles startup) { + passwd record{}, *user = nullptr; + std::array account{}; + if (::getpwuid_r(::getuid(), &record, account.data(), account.size(), &user) || !user) return false; + std::string home = record.pw_dir, shell = record.pw_shell, name = record.pw_name; + if (home.empty() || home.front() != '/' || shell.empty() || shell.front() != '/') return false; + + int slave = -1; + winsize size{24, 80, 0, 0}; + char tty[PATH_MAX]{}; + if (::openpty(&child.master, &slave, tty, nullptr, &size) != 0) return false; + if (::fcntl(child.master, F_SETFD, FD_CLOEXEC) < 0 || ::fcntl(slave, F_SETFD, FD_CLOEXEC) < 0 || + ::fcntl(child.master, F_SETFL, O_NONBLOCK) < 0) { + ::close(slave); + return false; + } + termios modes{}; + if (::tcgetattr(slave, &modes) == 0) { + modes.c_cc[VERASE] = 8; // CoCo backspace + ::tcsetattr(slave, TCSANOW, &modes); + } + std::string term = "TERM=vt100", path = "PATH=/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"; + std::string dir = "HOME=" + home, login = "LOGNAME=" + name, uid = "USER=" + name, sh = "SHELL=" + shell; + std::string locale = "LANG=en_US.UTF-8", prompt = "PS1=$ ", history = "HISTFILE=/dev/null"; + // Ordinary sessions use the account's interactive login shell. Only + // the integration tests suppress personal startup scripts and history. + auto base = shell.substr(shell.find_last_of('/') + 1); + bool isolated = startup == DriveWireShell::StartupFiles::isolatedTest; + if (isolated && base != "zsh" && base != "bash") { shell = "/bin/sh"; sh = "SHELL=" + shell; base = "sh"; } + std::vector options{isolated ? base : "-" + base}; + if (isolated && base == "zsh") options.insert(options.end(), {"-f", "-o", "no_zle"}); + if (isolated && base == "bash") options.insert(options.end(), {"--noprofile", "--norc", "--noediting"}); + options.emplace_back("-i"); + std::vector args; + for (auto& option : options) args.push_back(option.data()); + args.push_back(nullptr); + std::vector env{dir.data(), login.data(), uid.data(), sh.data(), term.data(), path.data(), locale.data()}; + if (isolated) { env.push_back(prompt.data()); env.push_back(history.data()); } + env.push_back(nullptr); + // These pointers and limits are computed before fork. The child of the + // multithreaded Mac app uses only descriptor/signal syscalls and execve. + auto executable = shell.c_str(); + auto directory = home.c_str(); + auto arguments = args.data(); + auto environment = env.data(); + const int maxFD = static_cast(::sysconf(_SC_OPEN_MAX)); + int handshake[2]{}; + if (maxFD < 3 || ::pipe(handshake) < 0) { ::close(slave); return false; } + if (::fcntl(handshake[0], F_SETFD, FD_CLOEXEC) < 0 || ::fcntl(handshake[1], F_SETFD, FD_CLOEXEC) < 0) { + ::close(slave); ::close(handshake[0]); ::close(handshake[1]); return false; + } + sigset_t mask; + sigemptyset(&mask); + struct sigaction defaults{}; + defaults.sa_handler = SIG_DFL; + sigemptyset(&defaults.sa_mask); + child.pid = ::fork(); + if (child.pid == 0) { + ::close(handshake[0]); + bool ok = ::setsid() >= 0 && ::ioctl(slave, TIOCSCTTY, 0) == 0; + for (int fd = 0; ok && fd < 3; ++fd) + ok = ::dup2(slave, fd) >= 0 && ::fcntl(fd, F_SETFD, 0) == 0; + for (int fd = 3; fd < maxFD; ++fd) if (fd != handshake[1]) ::close(fd); + for (int signal = 1; signal < NSIG; ++signal) { + if (signal != SIGKILL && signal != SIGSTOP) ::sigaction(signal, &defaults, nullptr); + } + ::sigprocmask(SIG_SETMASK, &mask, nullptr); + if (ok && ::chdir(directory) == 0) ::execve(executable, arguments, environment); + const char failed = 1; + (void)::write(handshake[1], &failed, 1); + _exit(127); + } + ::close(slave); + ::close(handshake[1]); + char failure; + ssize_t result; + do { result = ::read(handshake[0], &failure, 1); } while (result < 0 && errno == EINTR); + ::close(handshake[0]); + if (child.pid < 0) return false; + if (result == 0) return true; + while (::waitpid(child.pid, nullptr, 0) < 0 && errno == EINTR) {} + return false; +} + +void hangup(Child& child) { + // Closing a controlling tty sends HUP to its foreground group. Also signal + // the shell's own group when a foreground job has taken control. Keep its + // pid unreaped until sending signals is finished to avoid pid reuse. + pid_t foreground = ::tcgetpgrp(child.master); + if (foreground > 0 && foreground != child.pid && ::getsid(foreground) == child.pid) { + ::kill(-foreground, SIGHUP); + ::kill(-foreground, SIGCONT); + // Explicit revocation must also stop a foreground program that traps + // terminal hangups. Limit the signal to the shell's own session. + if (::getsid(foreground) == child.pid) ::kill(-foreground, SIGKILL); + } + ::kill(-child.pid, SIGHUP); + ::kill(-child.pid, SIGCONT); + ::close(child.master); + child.master = -1; + for (unsigned i = 0; i < 20; ++i) { + int status = 0; + pid_t done = ::waitpid(child.pid, &status, WNOHANG); + if (done == child.pid || (done < 0 && errno == ECHILD)) return; + std::this_thread::sleep_for(10ms); + } + ::kill(child.pid, SIGKILL); + while (::waitpid(child.pid, nullptr, 0) < 0 && errno == EINTR) {} +} + +// Option (the CoCo Alt key) distinguishes cursor keys from OS-9 editing +// characters. The stock telnet client sends the corresponding high-bit codes. +char cursorDirection(std::uint8_t key) { + switch (key) { + case 0x8c: return 'A'; // up + case 0x8a: return 'B'; // down + case 0x89: return 'C'; // right + case 0x88: return 'D'; // left + default: return 0; + } +} +class Terminal { +public: + std::atomic state{State::connecting}; + std::atomic stopped{false}; + std::atomic launched{false}; + const std::chrono::steady_clock::time_point expires = std::chrono::steady_clock::now() + 2min; + + bool waiting() const { + return !launched && !stopped && state == State::connecting && std::chrono::steady_clock::now() < expires; + } + + State transportState() const { + if (!launched && !waiting()) return State::failed; + return stopped ? State::closed : state.load(); + } + void cancel() { + std::lock_guard lock(mutex); + stopped = true; + incoming.clear(); + outgoing.clear(); + } + + std::size_t read(std::uint8_t* bytes, std::size_t count) { + std::lock_guard lock(mutex); + if (stopped) return 0; + count = std::min(count, incoming.size()); + std::copy_n(incoming.begin(), count, bytes); + incoming.erase(incoming.begin(), incoming.begin() + count); + return count; + } + bool write(const std::uint8_t* bytes, std::size_t count) { + std::lock_guard lock(mutex); + if (stopped || state != State::connected || count > queueLimit - outgoing.size()) return false; + // The stock OS-9 telnet client sends its abort byte for CoCo Break + // (Mac Escape). Backspace and Tab also double as left/right on the + // wire; keep their normal shell meanings. + const auto arrows = std::count_if(bytes, bytes + count, cursorDirection); + if (count + 2 * arrows > queueLimit - outgoing.size()) return false; + for (std::size_t i = 0; i < count; ++i) { + if (auto direction = cursorDirection(bytes[i])) { + outgoing.push_back(0x1b); + outgoing.push_back(applicationKeys ? 'O' : '['); + outgoing.push_back(direction); + } else { + outgoing.push_back(bytes[i] == 0x05 ? 0x1b : bytes[i]); + } + } + return true; + } + + void run(DriveWireShell::StartupFiles startup) { + Child child; + if (stopped || !spawnShell(child, startup)) { state = State::failed; return; } + state = State::connected; + bool reaped = false; + DriveWireTerminal terminal; + std::vector display; + std::size_t displayOffset = 0; + while (!stopped) { + std::array data{}; + std::size_t room, pending; + { + std::lock_guard lock(mutex); + // One PTY read can expand into a screen redraw. Drain that redraw + // in order before consuming more output, even after shell exit. + auto transfer = std::min(display.size() - displayOffset, queueLimit - incoming.size()); + incoming.insert(incoming.end(), display.begin() + displayOffset, + display.begin() + displayOffset + transfer); + displayOffset += transfer; + room = displayOffset == display.size() && incoming.size() < queueLimit ? data.size() : 0; + pending = std::min(data.size(), outgoing.size()); + } + if (!reaped) { + pid_t result = ::waitpid(child.pid, nullptr, WNOHANG); + reaped = result == child.pid || (result < 0 && errno == ECHILD); + } + pollfd descriptor{child.master, short((room ? POLLIN : 0) | (pending ? POLLOUT : 0)), 0}; + if (!room && !pending) { std::this_thread::sleep_for(10ms); continue; } + int result = ::poll(&descriptor, 1, 10); + if (result < 0 && errno == EINTR) continue; + if (result < 0) break; + if (pending && (descriptor.revents & POLLOUT)) { + std::lock_guard lock(mutex); + if (stopped) break; + std::copy_n(outgoing.begin(), pending, data.begin()); + auto sent = ::write(child.master, data.data(), pending); // non-blocking PTY + if (sent > 0) outgoing.erase(outgoing.begin(), outgoing.begin() + sent); + else if (sent < 0 && errno != EINTR && errno != EAGAIN) break; + } + if (room && (descriptor.revents & (POLLIN | POLLHUP | POLLERR))) { + auto n = ::read(child.master, data.data(), room); + if (n > 0) { + display = terminal.consume(data.data(), static_cast(n)); + displayOffset = 0; + auto replies = terminal.takeReply(); + std::lock_guard lock(mutex); + applicationKeys = terminal.applicationCursor(); + if (stopped || replies.size() > queueLimit - outgoing.size()) break; + outgoing.insert(outgoing.end(), replies.begin(), replies.end()); + continue; // collect any final output before reporting EOF + } + if (n < 0 && errno == EINTR) continue; + if (n <= 0 && (n == 0 || errno != EAGAIN || reaped)) break; + } + if (reaped && room) break; + } + if (!reaped) hangup(child); + state = State::closed; + } +private: + std::mutex mutex; + std::deque incoming, outgoing; + bool applicationKeys = false; // guarded by mutex +}; + +class ShellChannel final : public Transport { +public: + explicit ShellChannel(std::shared_ptr terminal) : terminal(std::move(terminal)) {} + ~ShellChannel() override { terminal->cancel(); } + State state() override { return terminal->transportState(); } + std::size_t read(std::uint8_t* bytes, std::size_t count) override { return terminal->read(bytes, count); } + bool write(const std::uint8_t* bytes, std::size_t count) override { return terminal->write(bytes, count); } +private: + std::shared_ptr terminal; +}; +} + +struct DriveWireShell::Impl { + explicit Impl(StartupFiles startup) : startup(startup) {} + StartupFiles startup; + mutable std::mutex mutex; + std::chrono::steady_clock::time_point readyUntil{}; + std::weak_ptr active; + std::uint64_t sequence = 0, pendingID = 0; + + void clear() { + readyUntil = {}; + pendingID = 0; + if (auto current = active.lock()) current->cancel(); + active.reset(); + } + void start(const std::shared_ptr& live) { + live->launched = true; + try { + std::thread([live, files = startup]{ live->run(files); }).detach(); + } catch (const std::system_error&) { + live->state = State::failed; + } + } +}; + +DriveWireShell::DriveWireShell(StartupFiles files) : impl(std::make_unique(files)) {} +DriveWireShell::~DriveWireShell() { stop(); } +void DriveWireShell::arm() { + std::lock_guard lock(impl->mutex); + impl->clear(); + impl->readyUntil = std::chrono::steady_clock::now() + 2min; +} +void DriveWireShell::stop() { + std::lock_guard lock(impl->mutex); + impl->clear(); +} +std::string DriveWireShell::status() const { + std::lock_guard lock(impl->mutex); + if (std::chrono::steady_clock::now() < impl->readyUntil) return "ready"; + if (auto live = impl->active.lock()) { + if (live->waiting()) return "requested"; + auto state = live->transportState(); + if (state == State::connecting || state == State::connected) return "connected"; + } + return "idle"; +} +std::uint64_t DriveWireShell::requestID() const { + std::lock_guard lock(impl->mutex); + auto live = impl->active.lock(); + return live && live->waiting() ? impl->pendingID : 0; +} +bool DriveWireShell::decide(std::uint64_t id, bool allow) { + std::lock_guard lock(impl->mutex); + auto live = impl->active.lock(); + if (!id || id != impl->pendingID || !live || !live->waiting()) return false; + impl->pendingID = 0; + if (allow) impl->start(live); + else live->state = State::failed; + return true; +} +std::unique_ptr DriveWireShell::connect() { + std::lock_guard lock(impl->mutex); + if (auto live = impl->active.lock()) { + auto state = live->transportState(); + if (state == State::connecting || state == State::connected) return {}; + } + auto live = std::make_shared(); + auto channel = std::make_unique(live); + impl->active = live; + if (std::chrono::steady_clock::now() < impl->readyUntil) { + impl->readyUntil = {}; + impl->pendingID = 0; + impl->start(live); + } else { + if (!++impl->sequence) ++impl->sequence; + impl->pendingID = impl->sequence; + } + return channel; +} +} diff --git a/platforms/macos/Bridge/DriveWireTCP.mm b/platforms/macos/Bridge/DriveWireTCP.mm new file mode 100644 index 0000000..32203c0 --- /dev/null +++ b/platforms/macos/Bridge/DriveWireTCP.mm @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include "devices/DriveWireTransport.h" +#import + +#include +#include +#include +#include + +namespace VCC::Devices { +namespace { + +using State = DriveWireTransport::State; +constexpr size_t bufferLimit = 64 * 1024; +constexpr size_t receiveChunk = 8192; + +class Stream : public std::enable_shared_from_this { +public: + explicit Stream(nw_connection_t connection) : connection(connection) {} + + void start() { + auto weak = weak_from_this(); + nw_connection_set_queue(connection, queue); + nw_connection_set_state_changed_handler(connection, ^(nw_connection_state_t state, nw_error_t) { + auto stream = weak.lock(); + if (!stream) return; + switch (state) { + case nw_connection_state_ready: + { + std::lock_guard lock(stream->mutex); + if (stream->status != State::connecting) return; + stream->status = State::connected; + } + stream->receive(); + break; + case nw_connection_state_failed: + case nw_connection_state_waiting: + stream->finish(State::failed); + break; + default: + break; + } + }); + nw_connection_start(connection); + } + + void finish(State reason) { + { + std::lock_guard lock(mutex); + if (status == State::closed || status == State::failed) return; + status = reason; + outgoing.clear(); + } + nw_connection_force_cancel(connection); + } + + State state() { + std::lock_guard lock(mutex); + return status; + } + + size_t read(uint8_t* bytes, size_t capacity) { + std::lock_guard lock(mutex); + size_t count = std::min(capacity, incoming.size()); + if (!count) return 0; + bool wasFull = incoming.size() == bufferLimit; + std::copy_n(incoming.begin(), count, bytes); + incoming.erase(incoming.begin(), incoming.begin() + count); + if (wasFull && status == State::connected) { + auto weak = weak_from_this(); + dispatch_async(queue, ^{ if (auto stream = weak.lock()) stream->receive(); }); + } + return count; + } + + bool write(const uint8_t* bytes, size_t count) { + std::lock_guard lock(mutex); + if (status != State::connected || count > bufferLimit - outgoing.size() - inFlight) return false; + if (!count) return true; + outgoing.insert(outgoing.end(), bytes, bytes + count); + if (!sending) { + sending = true; + auto weak = weak_from_this(); + dispatch_async(queue, ^{ if (auto stream = weak.lock()) stream->send(); }); + } + return true; + } + +private: + // Only the private serial network queue calls receive() and send(). + void receive() { + size_t room; + { + std::lock_guard lock(mutex); + room = bufferLimit - incoming.size(); + if (receiving || !room || status != State::connected) return; + receiving = true; + } + auto weak = weak_from_this(); + nw_connection_receive(connection, 1, static_cast(std::min(room, receiveChunk)), + ^(dispatch_data_t data, nw_content_context_t, bool complete, nw_error_t error) { + auto stream = weak.lock(); + if (!stream) return; + stream->receiving = false; + if (data) { + std::lock_guard lock(stream->mutex); + dispatch_data_apply(data, ^bool(dispatch_data_t, size_t, const void* buffer, size_t size) { + const auto* first = static_cast(buffer); + stream->incoming.insert(stream->incoming.end(), first, first + size); + return true; + }); + } + if (error || complete) stream->finish(error ? State::failed : State::closed); + else stream->receive(); + }); + } + + void send() { + std::vector batch; + { + std::lock_guard lock(mutex); + if (status != State::connected || outgoing.empty()) { + sending = false; + return; + } + batch.swap(outgoing); + inFlight = batch.size(); + } + // The default destructor copies our temporary batch into the dispatch data. + auto data = dispatch_data_create(batch.data(), batch.size(), nullptr, DISPATCH_DATA_DESTRUCTOR_DEFAULT); + auto weak = weak_from_this(); + nw_connection_send(connection, data, NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, ^(nw_error_t error) { + auto stream = weak.lock(); + if (!stream) return; + { + std::lock_guard lock(stream->mutex); + stream->inFlight = 0; + } + if (error) stream->finish(State::failed); + else stream->send(); + }); + } + + nw_connection_t connection; + dispatch_queue_t queue = dispatch_queue_create("com.brianholman.vccplus.drivewire.tcp", DISPATCH_QUEUE_SERIAL); + std::mutex mutex; + State status = State::connecting; + std::deque incoming; + std::vector outgoing; + size_t inFlight = 0; + bool sending = false; + bool receiving = false; +}; + +class TCPTransport final : public DriveWireTransport { +public: + explicit TCPTransport(std::shared_ptr stream) : stream(std::move(stream)) {} + ~TCPTransport() override { stream->finish(State::closed); } + State state() override { return stream->state(); } + size_t read(uint8_t* bytes, size_t capacity) override { return stream->read(bytes, capacity); } + bool write(const uint8_t* bytes, size_t count) override { return stream->write(bytes, count); } +private: + std::shared_ptr stream; +}; + +} // namespace + +std::unique_ptr makeDriveWireTCPConnection(const std::string& host, uint16_t port) { + if (host.empty() || host.find('\0') != std::string::npos || !port) return {}; + auto endpoint = nw_endpoint_create_host(host.c_str(), std::to_string(port).c_str()); + auto parameters = nw_parameters_create_secure_tcp(NW_PARAMETERS_DISABLE_PROTOCOL, ^(nw_protocol_options_t tcp) { + nw_tcp_options_set_connection_timeout(tcp, 10); + nw_tcp_options_set_no_delay(tcp, true); + }); + auto connection = nw_connection_create(endpoint, parameters); + if (!connection) return {}; + auto stream = std::make_shared(connection); + stream->start(); + return std::make_unique(std::move(stream)); +} + +} // namespace VCC::Devices diff --git a/platforms/macos/Bridge/DriveWireTerminal.h b/platforms/macos/Bridge/DriveWireTerminal.h new file mode 100644 index 0000000..8bf5294 --- /dev/null +++ b/platforms/macos/Bridge/DriveWireTerminal.h @@ -0,0 +1,349 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include "DriveWireCoWin.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace VCC::Mac { + +// A PTY advertises an 80x24 VT-style terminal. The historical OS-9 telnet +// client writes the received bytes straight to its CoWin window. Keep shell +// output relative until a program takes ownership of the screen so connecting +// does not erase the guest's login transcript. +class DriveWireTerminal { +public: + std::vector consume(const std::uint8_t* bytes, std::size_t count) { + std::vector output; + for (std::size_t i = 0; i < count; ++i) parse(bytes[i], output); + if (managed) { + auto& s = screen(); + // A guest can quit telnet at any time. Leave its native cursor + // visible even when a Mac program requests an invisible cursor. + renderer.draw(s.cells, s.x, s.y, true, invalidate, output); + invalidate = false; + if (returnToTranscript) { + managed = false; + returnToTranscript = false; + } + } + return output; + } + + bool applicationCursor() const { return applicationKeys; } + std::string takeReply() { return std::exchange(replies, {}); } + +private: + using Bytes = std::vector; + static constexpr int width = 80, height = 24; + struct Screen { + TerminalGrid cells; + int x = 0, y = 0, savedX = 0, savedY = 0, top = 0, bottom = height-1; + bool pendingWrap = false; + Screen() { for (auto& line : cells) line.fill(' '); } + }; + Screen normal, alternate; + DriveWireTerminalOutput renderer; + bool inAlternate = false, managed = false, invalidate = false, returnToTranscript = false; + bool origin = false, autoWrap = true, insert = false, applicationKeys = false; + bool g0Graphics = false, g1Graphics = false, shifted = false, selectG1 = false; + std::array tabs = [] { + std::array stops{}; + for (int x = 8; x < width; x += 8) stops[x] = true; + return stops; + }(); + + enum class State { plain, escape, charset, intermediate, csi, string, stringEscape }; + State state = State::plain; + std::array args{}; + std::size_t argument = 0; + bool privateMode = false, ignoredSequence = false; + int utfRemaining = 0; + std::string replies; + + Screen& screen() { return inAlternate ? alternate : normal; } + int param(std::size_t i, int fallback = 1) const { + return i <= argument && args[i] != 0 ? args[i] : fallback; + } + void reply(const std::string& value) { + if (replies.size() + value.size() <= 128) replies += value; + } + void beginScreen() { + if (!managed) invalidate = true; + managed = true; + returnToTranscript = false; + } + void direct(Bytes& out, std::uint8_t ch, int repeat = 1) const { + if (!managed) out.insert(out.end(), repeat, ch); + } + void scroll(int top, int bottom, int number, bool down) { + auto& lines = screen().cells; + const int n = std::min(number, bottom-top+1); + if (n <= 0) return; + if (down) { + std::move_backward(lines.begin()+top, lines.begin()+bottom+1-n, lines.begin()+bottom+1); + for (int row = top; row < top+n; ++row) lines[row].fill(' '); + } else { + std::move(lines.begin()+top+n, lines.begin()+bottom+1, lines.begin()+top); + for (int row = bottom+1-n; row <= bottom; ++row) lines[row].fill(' '); + } + } + void index(bool reverse) { + auto& s = screen(); + s.pendingWrap = false; + if (reverse && s.y == s.top) scroll(s.top, s.bottom, 1, true); + else if (!reverse && s.y == s.bottom) scroll(s.top, s.bottom, 1, false); + else s.y = std::clamp(s.y + (reverse ? -1 : 1), 0, height-1); + } + void move(int x, int y) { + auto& s = screen(); + s.x = std::clamp(x, 0, width-1); + s.y = std::clamp(y, origin ? s.top : 0, origin ? s.bottom : height-1); + s.pendingWrap = false; + } + void horizontal(int x, Bytes& out) { + auto& s = screen(); + int target = std::clamp(x, 0, width-1); + if (target == 0) direct(out, 13); + else if (target != s.x) direct(out, target < s.x ? 8 : 6, std::abs(target-s.x)); + move(target, s.y); + } + void save() { auto& s = screen(); s.savedX = s.x; s.savedY = s.y; } + void restore() { auto& s = screen(); move(s.savedX, s.savedY); } + void alternateMode(bool enable, int mode) { + if (enable == inAlternate) return; + beginScreen(); + if (enable && mode == 1049) save(); + if (enable && mode != 47) alternate = Screen{}; + inAlternate = enable; + if (!enable && mode == 1049) restore(); + returnToTranscript = !enable; + } + void put(char ch, Bytes& out) { + auto& s = screen(); + if (s.pendingWrap) { index(false); s.x = 0; } + auto& line = s.cells[s.y]; + if (insert) std::move_backward(line.begin()+s.x, line.end()-1, line.end()); + line[s.x] = ch; + direct(out, ch); + if (s.x < width-1) ++s.x; + else s.pendingWrap = autoWrap; + } + static char graphic(char ch) { + switch (ch) { + case 'q': case 'o': case 'p': case 'r': case 's': return '-'; + case 'x': return '|'; + case 'j': case 'k': case 'l': case 'm': case 'n': + case 't': case 'u': case 'v': case 'w': return '+'; + default: return ch; + } + } + void tab(bool back) { + auto& s = screen(); + int x = s.x; + do { x += back ? -1 : 1; } while (x > 0 && x < width-1 && !tabs[x]); + move(x, s.y); + } + void control(std::uint8_t ch, Bytes& out) { + auto& s = screen(); + switch (ch) { + case 7: out.push_back(ch); break; + case 8: if (s.x > 0) direct(out, ch); move(s.x-1, s.y); break; + case 9: { + int oldX = s.x; + tab(false); + direct(out, 6, s.x-oldX); + break; + } + case 10: case 11: case 12: index(false); direct(out, 10); break; + case 13: move(0, s.y); direct(out, 13); break; + case 14: shifted = true; break; + case 15: shifted = false; break; + } + } + void eraseLine(int mode, Bytes& out) { + auto& s = screen(); + auto& line = s.cells[s.y]; + if (mode == 0) { + std::fill(line.begin()+s.x, line.end(), ' '); + direct(out, 4); + } else if (mode == 1) { + beginScreen(); + std::fill(line.begin(), line.begin()+s.x+1, ' '); + } else if (mode == 2) { + line.fill(' '); + // Some CoWin erase-line paths also move the cursor. + if (!managed) { direct(out, 13); direct(out, 4); direct(out, 6, s.x); } + } + } + void eraseDisplay(int mode, Bytes& out) { + auto& s = screen(); + if (mode == 3) return; // discard saved scrollback only + if (mode == 0) { + eraseLine(0, out); + for (int y = s.y+1; y < height; ++y) s.cells[y].fill(' '); + direct(out, 11); + } else if (mode == 1 || mode == 2) { + beginScreen(); + for (int y = 0; y < (mode == 2 ? height : s.y); ++y) s.cells[y].fill(' '); + if (mode == 1) eraseLine(1, out); + } + } + void modes(bool on) { + for (std::size_t i = 0; i <= argument; ++i) { + if (!privateMode) { + if (args[i] == 4) { insert = on; if (on) beginScreen(); } + continue; + } + switch (args[i]) { + case 1: applicationKeys = on; break; + case 6: origin = on; beginScreen(); move(0, on ? screen().top : 0); break; + case 7: autoWrap = on; screen().pendingWrap = false; break; + case 47: case 1047: case 1049: alternateMode(on, args[i]); break; + case 1048: if (on) save(); else { beginScreen(); restore(); } break; + } + } + } + void csi(std::uint8_t final, Bytes& out) { + auto& s = screen(); + const int n = param(0), mode = args[0]; + if (final == 'h' || final == 'l') { modes(final == 'h'); return; } + if (privateMode) return; + switch (final) { + case 'A': case 'B': case 'e': { + const int oldY = s.y; + move(s.x, s.y + (final == 'A' ? -n : n)); + direct(out, final == 'A' ? 9 : 10, std::abs(oldY-s.y)); + break; + } + case 'C': case 'a': horizontal(s.x+n, out); break; + case 'D': horizontal(s.x-n, out); break; + case 'E': case 'F': beginScreen(); move(0, s.y + (final == 'E' ? n : -n)); break; + case 'G': case '`': horizontal(n-1, out); break; + case 'd': beginScreen(); move(s.x, n-1 + (origin ? s.top : 0)); break; + case 'H': case 'f': beginScreen(); move(param(1)-1, n-1 + (origin ? s.top : 0)); break; + case 'K': eraseLine(mode, out); break; + case 'J': eraseDisplay(mode, out); break; + case 's': save(); break; + case 'u': beginScreen(); restore(); break; + case 'r': { + int top = n-1, bottom = param(1,height)-1; + if (top >= bottom || bottom >= height) break; + beginScreen(); + s.top = top; s.bottom = bottom; + move(0, origin ? top : 0); + break; + } + case 'L': case 'M': + if (s.y >= s.top && s.y <= s.bottom) { + beginScreen(); scroll(s.y, s.bottom, n, final == 'L'); + } + break; + case 'S': case 'T': beginScreen(); scroll(s.top, s.bottom, n, final == 'T'); break; + case '@': case 'P': case 'X': { + beginScreen(); + auto& line = s.cells[s.y]; + auto pos = line.begin()+s.x; + const int count = std::min(n,width-s.x); + if (final == '@') std::move_backward(pos, line.end()-count, line.end()); + if (final == 'P') { + std::move(pos+count, line.end(), pos); + std::fill(line.end()-count,line.end(),' '); + } else std::fill(pos,pos+count,' '); + break; + } + case 'I': case 'Z': { + int oldX = s.x; + for (int i = 0; i < std::min(n,width); ++i) tab(final == 'Z'); + direct(out, final == 'Z' ? 8 : 6, std::abs(s.x-oldX)); + break; + } + case 'g': if (mode == 0) tabs[s.x] = false; else if (mode == 3) tabs.fill(false); break; + case 'c': if (mode == 0) reply("\x1b[?1;0c"); break; + case 'n': + if (mode == 5) reply("\x1b[0n"); + if (mode == 6) reply("\x1b[" + std::to_string(s.y+1-(origin ? s.top : 0)) + + ";" + std::to_string(s.x+1) + "R"); + break; + } + } + void startCSI() { + state = State::csi; + args.fill(0); + argument = 0; + ignoredSequence = false; + privateMode = false; + } + void escape(std::uint8_t ch, Bytes& out) { + state = State::plain; + switch (ch) { + case '[': startCSI(); break; + case ']': case 'P': case '^': case '_': case 'X': state = State::string; break; + case '(': case ')': selectG1 = ch == ')'; state = State::charset; break; + case '7': save(); break; + case '8': beginScreen(); restore(); break; + case 'D': index(false); direct(out, 10); break; + case 'E': control(13, out); control(10, out); break; + case 'M': beginScreen(); index(true); break; + case 'H': tabs[screen().x] = true; break; + case 'Z': reply("\x1b[?1;0c"); break; + case 'c': + *this = DriveWireTerminal{}; + beginScreen(); + break; + default: + if (ch >= 0x20 && ch <= 0x2f) state = State::intermediate; + } + } + static int continuationCount(std::uint8_t ch) { + return ch < 0xc2 || ch > 0xf4 ? 0 : ch < 0xe0 ? 1 : ch < 0xf0 ? 2 : 3; + } + void parse(std::uint8_t ch, Bytes& out) { + if (ch == 0x18 || ch == 0x1a) { state = State::plain; utfRemaining = 0; return; } + if (state == State::string || state == State::stringEscape) { + // A UTF-8 continuation byte in an OSC title can equal C1 ST. + if (utfRemaining && (ch & 0xc0) == 0x80) { --utfRemaining; return; } + utfRemaining = continuationCount(ch); + if (ch == 7 || ch == 0x9c || (state == State::stringEscape && ch == '\\')) state = State::plain; + else state = ch == 27 ? State::stringEscape : State::string; + return; + } + if (ch == 27) { state = State::escape; utfRemaining = 0; return; } + if (ch < 32) { control(ch, out); return; } + if (state == State::escape) { escape(ch, out); return; } + if (state == State::charset) { + if (selectG1) g1Graphics = ch == '0'; + else g0Graphics = ch == '0'; + state = State::plain; + return; + } + if (state == State::intermediate) { if (ch >= 0x30) state = State::plain; return; } + if (state == State::csi) { + if (ch >= '0' && ch <= '9') args[argument] = std::min(9999, 10*args[argument]+ch-'0'); + else if (ch == ';') { + if (argument+1 < args.size()) ++argument; + else ignoredSequence = true; + } else if (ch == '?' && argument == 0 && !args[0]) privateMode = true; + else if (ch >= 0x40 && ch <= 0x7e) { + if (!ignoredSequence) csi(ch, out); + state = State::plain; + } else ignoredSequence = true; + return; + } + if (utfRemaining && (ch & 0xc0) == 0x80) { --utfRemaining; return; } + utfRemaining = 0; + if (ch == 0x9b) { startCSI(); return; } + if (ch == 0x90 || ch == 0x98 || ch == 0x9d || ch == 0x9e || ch == 0x9f) { state = State::string; return; } + if (ch >= 0xc0) { + utfRemaining = continuationCount(ch); + put('?', out); + } else if (ch >= 32 && ch < 127) put((shifted ? g1Graphics : g0Graphics) ? graphic(ch) : ch, out); + } +}; +} diff --git a/platforms/macos/Bridge/MacAudioOutput.h b/platforms/macos/Bridge/MacAudioOutput.h new file mode 100644 index 0000000..0b5544e --- /dev/null +++ b/platforms/macos/Bridge/MacAudioOutput.h @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include "../../../src/core/AudioBuffer.h" +#include +namespace VCC::Mac { +// All methods except the internal render callback belong to the machine queue. +class MacAudioOutput { +public: + MacAudioOutput(); + ~MacAudioOutput(); + void start(); // throws a user-visible error; never opens an input device + void stop(); // stops callback before clearing queued samples + bool running() const; + std::uint64_t starts() const; + bool needsRestart() const; + AudioBuffer& buffer(); +private: + struct Impl; + std::unique_ptr impl; +}; +} diff --git a/platforms/macos/Bridge/MacAudioOutput.mm b/platforms/macos/Bridge/MacAudioOutput.mm new file mode 100644 index 0000000..cda0ee3 --- /dev/null +++ b/platforms/macos/Bridge/MacAudioOutput.mm @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import +#include "MacAudioOutput.h" +#include +#include +namespace VCC::Mac { +struct MacAudioOutput::Impl { + std::shared_ptr ring = std::make_shared(); + std::shared_ptr> changed = std::make_shared>(false); + AVAudioEngine *engine = nil; + id observer = nil; + std::uint64_t starts = 0; + ~Impl() { stop(); } + void stop() { + if(observer) { [[NSNotificationCenter defaultCenter] removeObserver:observer]; observer=nil; } + [engine stop]; engine=nil; ring->clear(); changed->store(false); + } +}; +MacAudioOutput::MacAudioOutput() : impl(std::make_unique()) {} +MacAudioOutput::~MacAudioOutput() = default; +AudioBuffer& MacAudioOutput::buffer() { return *impl->ring; } +std::uint64_t MacAudioOutput::starts() const { return impl->starts; } +bool MacAudioOutput::running() const { return impl->engine.isRunning; } +bool MacAudioOutput::needsRestart() const { return impl->changed->load() || (impl->engine && !impl->engine.isRunning); } +void MacAudioOutput::stop() { impl->stop(); } +void MacAudioOutput::start() { + if(running()) return; + // A new graph follows the current default output device and its sample rate. + impl->engine = [AVAudioEngine new]; + AVAudioFormat *format = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:44100 channels:2]; + auto ring=impl->ring; + AVAudioSourceNode *source = [[AVAudioSourceNode alloc] initWithFormat:format renderBlock: + ^OSStatus(BOOL *silence, const AudioTimeStamp *, AVAudioFrameCount frames, AudioBufferList *list) { + if(list->mNumberBuffers != 2) return kAudio_ParamError; + ring->read(static_cast(list->mBuffers[0].mData),static_cast(list->mBuffers[1].mData),frames); + *silence=NO; return noErr; + }]; + [impl->engine attachNode:source]; + [impl->engine connect:source to:impl->engine.mainMixerNode format:format]; + auto changed=impl->changed; + impl->observer=[[NSNotificationCenter defaultCenter] addObserverForName:AVAudioEngineConfigurationChangeNotification + object:impl->engine queue:nil usingBlock:^(NSNotification*) { changed->store(true); }]; + NSError *error=nil; + if(![impl->engine startAndReturnError:&error]) { + const std::string message=error.localizedDescription.UTF8String ?: "Unable to start Mac audio output"; + impl->stop(); throw std::runtime_error(message); + } + ++impl->starts; +} +} diff --git a/platforms/macos/Bridge/VCCLibraryArchive.h b/platforms/macos/Bridge/VCCLibraryArchive.h new file mode 100644 index 0000000..a34fa82 --- /dev/null +++ b/platforms/macos/Bridge/VCCLibraryArchive.h @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import +NS_ASSUME_NONNULL_BEGIN +FOUNDATION_EXPORT NSErrorDomain const VCCLibraryArchiveErrorDomain; +typedef NS_ERROR_ENUM(VCCLibraryArchiveErrorDomain, VCCLibraryArchiveError) { + VCCLibraryArchiveErrorInvalid = 1, + VCCLibraryArchiveErrorUnsupported, + VCCLibraryArchiveErrorUnsafePath, + VCCLibraryArchiveErrorCollision, + VCCLibraryArchiveErrorLimit, + VCCLibraryArchiveErrorCancelled, + VCCLibraryArchiveErrorIO +}; +@interface VCCLibraryArchive : NSObject +// Synchronous worker API: call off the main thread. The destination must not +// exist; on failure only the new directory created by this call is removed. +// Returns regular-file relative paths. No links, executable permissions, or +// archive ownership/timestamps are restored. ZIP64/multi-volume ZIPs are rejected. ++ (nullable NSArray *)extractZIPAtURL:(NSURL *)archiveURL + toNewDirectory:(NSURL *)destinationURL + maximumExpandedBytes:(uint64_t)maximumExpandedBytes + maximumEntries:(NSUInteger)maximumEntries + shouldCancel:(BOOL (^ _Nullable)(void))shouldCancel + error:(NSError **)error + NS_SWIFT_NAME(extractZIP(at:toNewDirectory:maximumExpandedBytes:maximumEntries:shouldCancel:)); +@end +NS_ASSUME_NONNULL_END diff --git a/platforms/macos/Bridge/VCCLibraryArchive.mm b/platforms/macos/Bridge/VCCLibraryArchive.mm new file mode 100644 index 0000000..d9493b1 --- /dev/null +++ b/platforms/macos/Bridge/VCCLibraryArchive.mm @@ -0,0 +1,266 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import "VCCLibraryArchive.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// A narrow adapter for the stable system libarchive ABI. Apple's SDK exports +// these functions in libarchive.tbd but does not supply libarchive headers. +// No external program, Homebrew installation, or bundled library is required. +extern "C" { +struct archive; +struct archive_entry; +struct archive *archive_read_new(void); +int archive_read_support_format_zip_seekable(struct archive *); +int archive_read_open_fd(struct archive *, int, size_t); +int archive_read_next_header(struct archive *, struct archive_entry **); +ssize_t archive_read_data(struct archive *, void *, size_t); +int archive_read_close(struct archive *); +int archive_read_free(struct archive *); +const char *archive_error_string(struct archive *); +const char *archive_entry_pathname_utf8(struct archive_entry *); +const char *archive_entry_pathname(struct archive_entry *); +const char *archive_entry_symlink(struct archive_entry *); +const char *archive_entry_hardlink(struct archive_entry *); +mode_t archive_entry_filetype(struct archive_entry *); +int64_t archive_entry_size(struct archive_entry *); +int archive_entry_size_is_set(struct archive_entry *); +int archive_entry_is_encrypted(struct archive_entry *); +} +NSErrorDomain const VCCLibraryArchiveErrorDomain = @"com.brianholman.vccplus.library.archive"; +namespace { +constexpr int archiveOK = 0, archiveEOF = 1; +struct Descriptor { + int fd = -1; + explicit Descriptor(int value = -1): fd(value) {} + ~Descriptor() { if (fd >= 0) close(fd); } + Descriptor(const Descriptor &) = delete; + Descriptor &operator=(const Descriptor &) = delete; + void reset(int value) { if (fd >= 0) close(fd); fd = value; } +}; +struct Reader { + struct archive *value = archive_read_new(); + ~Reader() { if (value) archive_read_free(value); } +}; +bool fail(NSError **error, VCCLibraryArchiveError code, NSString *message) { + if (error) *error = [NSError errorWithDomain:VCCLibraryArchiveErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey:message}]; + return false; +} +bool cancelled(BOOL (^check)(void), NSError **error) { + return check && check() ? !fail(error, VCCLibraryArchiveErrorCancelled, @"Installation was cancelled.") : false; +} +NSString *archiveMessage(struct archive *value, NSString *fallback) { + const char *text = archive_error_string(value); + return text ? [NSString stringWithFormat:@"%@: %s", fallback, text] : fallback; +} +uint16_t u16(const uint8_t *p) { return uint16_t(p[0]) | uint16_t(p[1]) << 8; } +uint32_t u32(const uint8_t *p) { return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24; } +bool readAt(int fd, uint64_t offset, void *buffer, size_t count) { + size_t done = 0; + while (done < count) { + ssize_t n = pread(fd, (uint8_t *)buffer + done, count - done, (off_t)(offset + done)); + if (n < 0 && errno == EINTR) continue; + if (n <= 0) return false; + done += (size_t)n; + } + return true; +} +// Require the complete central directory. A streaming unzip reader can otherwise +// accept a truncated ZIP with intact local headers. Inspect raw names too: C APIs +// cannot expose embedded NULs, and ZIP readers may normalize Windows separators. +bool checkContainer(int fd, uint64_t fileSize, NSUInteger maxEntries, BOOL (^check)(void), uint64_t &entryCount, NSError **error) { + if (fileSize < 22) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP file is truncated or invalid."); + size_t tailSize = (size_t)MIN(fileSize, uint64_t(65557)); + std::vector tail(tailSize); + if (!readAt(fd, fileSize - tailSize, tail.data(), tailSize)) return fail(error, VCCLibraryArchiveErrorIO, @"The ZIP file could not be read."); + int64_t end = -1; + for (int64_t i = (int64_t)tailSize - 22; i >= 0; --i) { + if (u32(tail.data() + i) == 0x06054b50 && (uint64_t)i + 22 + u16(tail.data() + i + 20) == tailSize) { end = i; break; } + } + if (end < 0) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP file has no complete end-of-directory record."); + const uint8_t *e = tail.data() + end; + uint64_t count = u16(e + 10), centralSize = u32(e + 12), centralOffset = u32(e + 16); + if (u16(e + 4) || u16(e + 6) || u16(e + 8) != count || count == 65535 || centralSize == UINT32_MAX || centralOffset == UINT32_MAX) + return fail(error, VCCLibraryArchiveErrorUnsupported, @"Multi-volume and ZIP64 packages are not supported by this installer."); + if (count > maxEntries) return fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP file contains too many entries."); + const uint64_t endOffset = fileSize - tailSize + (uint64_t)end; + if (centralOffset > endOffset || centralSize != endOffset - centralOffset) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP central directory is incomplete or inconsistent."); + uint64_t offset = centralOffset; + for (uint64_t index = 0; index < count; ++index) { + if (cancelled(check, error)) return false; + uint8_t header[46]; + if (offset > endOffset || endOffset - offset < sizeof(header) || !readAt(fd, offset, header, sizeof(header)) || u32(header) != 0x02014b50) + return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP central directory contains a damaged entry."); + const uint64_t nameLength = u16(header + 28), extraLength = u16(header + 30), commentLength = u16(header + 32); + uint64_t length = sizeof(header) + nameLength + extraLength + commentLength; + if (length > endOffset - offset || nameLength == 0 || nameLength > 4096) + return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP file contains an invalid filename."); + if ((u16(header + 8) & 1) || (u16(header + 8) & 0x40)) return fail(error, VCCLibraryArchiveErrorUnsupported, @"Encrypted ZIP packages are not supported."); + // Some readers normalize unsupported Unix entry kinds into regular + // files. Reject those kinds from the original central attributes too. + const mode_t storedType = (mode_t)((u32(header + 38) >> 16) & S_IFMT); + if (storedType && storedType != S_IFREG && storedType != S_IFDIR) + return fail(error, VCCLibraryArchiveErrorUnsupported, @"ZIP packages containing links or special files cannot be installed."); + if (u16(header + 34) || u32(header + 20) == UINT32_MAX || u32(header + 24) == UINT32_MAX || u32(header + 42) == UINT32_MAX) + return fail(error, VCCLibraryArchiveErrorUnsupported, @"Multi-volume and ZIP64 packages are not supported by this installer."); + std::vector name((size_t)nameLength); + if (!readAt(fd, offset + sizeof(header), name.data(), name.size())) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP filename is truncated."); + for (auto byte : name) if (byte == 0 || byte == '\\' || byte == ':') + return fail(error, VCCLibraryArchiveErrorUnsafePath, @"The ZIP file contains an unsafe filename."); + // Ensure local and central names agree, before the reader chooses one. + uint8_t local[30]; const uint64_t localOffset = u32(header + 42); + if (localOffset > centralOffset || centralOffset - localOffset < sizeof(local) || !readAt(fd, localOffset, local, sizeof(local)) || u32(local) != 0x04034b50 || u16(local + 26) != nameLength) + return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP local header does not match its directory entry."); + const uint64_t dataStart = localOffset + sizeof(local) + nameLength + u16(local + 28); + if (dataStart > centralOffset || u32(header + 20) > centralOffset - dataStart || u16(local + 6) != u16(header + 8) || u16(local + 8) != u16(header + 10)) + return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP entry extends beyond its stored data."); + std::vector localName((size_t)nameLength); + if (!readAt(fd, localOffset + sizeof(local), localName.data(), localName.size()) || localName != name) + return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP filename differs between its headers."); + offset += length; + } + if (offset != endOffset) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP directory length does not match its entries."); + entryCount = count; + return true; +} +NSArray *pathComponents(NSString *path, bool directory, NSError **error) { + if (directory && [path hasSuffix:@"/"]) path = [path substringToIndex:path.length - 1]; + if (!path.length || [path hasPrefix:@"/"] || [path rangeOfString:@"\\"].location != NSNotFound || [path rangeOfString:@":"].location != NSNotFound || [path rangeOfCharacterFromSet:NSCharacterSet.controlCharacterSet].location != NSNotFound) { + fail(error, VCCLibraryArchiveErrorUnsafePath, @"The ZIP file contains an unsafe path."); return nil; + } + NSArray *parts = [path componentsSeparatedByString:@"/"]; + if (parts.count > 64) { fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP directory nesting is too deep."); return nil; } + for (NSString *part in parts) { + if (!part.length || [part isEqualToString:@"."] || [part isEqualToString:@".."] || [part lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 255) { + fail(error, VCCLibraryArchiveErrorUnsafePath, @"The ZIP file contains an unsafe or unsupported path component."); return nil; + } + } + return parts; +} +NSString *collisionKey(NSString *path) { + return [[path precomposedStringWithCanonicalMapping] stringByFoldingWithOptions:NSCaseInsensitiveSearch locale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]]; +} +bool writeAll(int fd, const void *bytes, size_t size) { + size_t done = 0; + while (done < size) { + ssize_t n = write(fd, (const uint8_t *)bytes + done, size - done); + if (n < 0 && errno == EINTR) continue; + if (n <= 0) return false; + done += (size_t)n; + } + return true; +} +} +@implementation VCCLibraryArchive ++ (NSArray *)extractZIPAtURL:(NSURL *)archiveURL toNewDirectory:(NSURL *)destinationURL maximumExpandedBytes:(uint64_t)maximumExpandedBytes maximumEntries:(NSUInteger)maximumEntries shouldCancel:(BOOL (^)(void))shouldCancel error:(NSError **)error { + if (error) *error = nil; + if (!archiveURL.isFileURL || !destinationURL.isFileURL || !maximumEntries || !maximumExpandedBytes) { + fail(error, VCCLibraryArchiveErrorInvalid, @"A local ZIP file, new local destination, and positive extraction limits are required."); return nil; + } + if (cancelled(shouldCancel, error)) return nil; + Descriptor source(open(archiveURL.fileSystemRepresentation, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)); + struct stat sourceInfo; + if (source.fd < 0 || fstat(source.fd, &sourceInfo) != 0 || !S_ISREG(sourceInfo.st_mode) || sourceInfo.st_size < 0) { + fail(error, VCCLibraryArchiveErrorIO, @"The downloaded ZIP is not a readable regular file."); return nil; + } + uint64_t expectedEntries = 0; + if (!checkContainer(source.fd, (uint64_t)sourceInfo.st_size, maximumEntries, shouldCancel, expectedEntries, error)) return nil; + if (mkdir(destinationURL.fileSystemRepresentation, 0700) != 0) { + fail(error, VCCLibraryArchiveErrorIO, @"The extraction destination already exists or could not be created."); return nil; + } + bool success = false; + @try { + Descriptor root(open(destinationURL.fileSystemRepresentation, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)); + Reader reader; + if (root.fd < 0 || !reader.value || archive_read_support_format_zip_seekable(reader.value) != archiveOK || archive_read_open_fd(reader.value, source.fd, 65536) != archiveOK) { + fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP package could not be opened."); return nil; + } + std::map paths; + std::set explicitEntries; + NSMutableArray *files = [NSMutableArray array]; + uint64_t total = 0, count = 0; + struct archive_entry *entry = nullptr; + int status; + while ((status = archive_read_next_header(reader.value, &entry)) == archiveOK) { + if (cancelled(shouldCancel, error)) return nil; + if (++count > maximumEntries) { fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP file contains too many entries."); return nil; } + mode_t type = archive_entry_filetype(entry); + bool directory = type == S_IFDIR; + if ((type != S_IFREG && !directory) || archive_entry_symlink(entry) || archive_entry_hardlink(entry)) { + fail(error, VCCLibraryArchiveErrorUnsupported, @"ZIP packages containing links or special files cannot be installed."); return nil; + } + if (archive_entry_is_encrypted(entry)) { fail(error, VCCLibraryArchiveErrorUnsupported, @"Encrypted ZIP packages are not supported."); return nil; } + const char *utf8 = archive_entry_pathname_utf8(entry); + if (!utf8) utf8 = archive_entry_pathname(entry); + NSString *path = utf8 ? [[NSString alloc] initWithUTF8String:utf8] : nil; + if (!path) { fail(error, VCCLibraryArchiveErrorUnsupported, @"A ZIP filename cannot be represented safely on this Mac."); return nil; } + NSArray *parts = pathComponents(path, directory, error); + if (!parts) return nil; + NSString *relative = [parts componentsJoinedByString:@"/"]; + std::string fullKey(collisionKey(relative).UTF8String); + if (!explicitEntries.insert(fullKey).second) { fail(error, VCCLibraryArchiveErrorCollision, @"The ZIP file contains duplicate or conflicting filenames."); return nil; } + NSString *prefix = @""; + for (NSString *part in parts) { + prefix = prefix.length ? [prefix stringByAppendingFormat:@"/%@", part] : part; + std::string key(collisionKey(prefix).UTF8String), original(prefix.UTF8String); + auto prior = paths.find(key); + if (prior != paths.end() && prior->second != original) { fail(error, VCCLibraryArchiveErrorCollision, @"ZIP paths differ only by letter case or Unicode spelling and would collide on a Mac."); return nil; } + paths[key] = original; + } + int64_t declared = archive_entry_size(entry); + if (!archive_entry_size_is_set(entry) || declared < 0 || (uint64_t)declared > maximumExpandedBytes - total || (directory && declared != 0)) { + fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP package exceeds the expanded-size limit or has an invalid entry size."); return nil; + } + Descriptor parent(dup(root.fd)); + if (parent.fd < 0) { fail(error, VCCLibraryArchiveErrorIO, @"The extraction directory could not be opened."); return nil; } + NSUInteger directories = directory ? parts.count : parts.count - 1; + for (NSUInteger i = 0; i < directories; ++i) { + const char *name = parts[i].fileSystemRepresentation; + if (mkdirat(parent.fd, name, 0755) != 0 && errno != EEXIST) { fail(error, VCCLibraryArchiveErrorIO, @"A ZIP directory could not be created."); return nil; } + int child = openat(parent.fd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + if (child < 0) { fail(error, VCCLibraryArchiveErrorCollision, @"A ZIP path conflicts with an existing file or link."); return nil; } + parent.reset(child); + if (fchmod(parent.fd, 0755) != 0) { fail(error, VCCLibraryArchiveErrorIO, @"The extracted directory permissions could not be set."); return nil; } + } + Descriptor output; + if (!directory) { + output.reset(openat(parent.fd, parts.lastObject.fileSystemRepresentation, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600)); + if (output.fd < 0) { fail(error, VCCLibraryArchiveErrorCollision, @"A ZIP output path already exists or could not be created."); return nil; } + } + uint8_t buffer[65536]; uint64_t written = 0; + while (true) { + if (cancelled(shouldCancel, error)) return nil; + ssize_t bytes = archive_read_data(reader.value, buffer, sizeof(buffer)); + if (bytes < 0) { fail(error, VCCLibraryArchiveErrorInvalid, archiveMessage(reader.value, @"A ZIP entry is damaged or uses unsupported compression")); return nil; } + if (!bytes) break; + if (directory || (uint64_t)bytes > maximumExpandedBytes - total || (uint64_t)bytes > (uint64_t)declared - written) { + fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP expanded data exceeds its declared size or the installation limit."); return nil; + } + if (!writeAll(output.fd, buffer, (size_t)bytes)) { fail(error, VCCLibraryArchiveErrorIO, @"The ZIP data could not be saved. Check available disk space."); return nil; } + written += (uint64_t)bytes; total += (uint64_t)bytes; + } + if (written != (uint64_t)declared) { fail(error, VCCLibraryArchiveErrorInvalid, @"A ZIP entry is truncated."); return nil; } + if (!directory) { + if (fchmod(output.fd, 0644) != 0) { fail(error, VCCLibraryArchiveErrorIO, @"The extracted file permissions could not be set."); return nil; } + [files addObject:relative]; + } + } + if (status != archiveEOF || count != expectedEntries || archive_read_close(reader.value) != archiveOK) { + fail(error, VCCLibraryArchiveErrorInvalid, archiveMessage(reader.value, @"The ZIP package is incomplete or damaged")); return nil; + } + if (cancelled(shouldCancel, error)) return nil; + if (fchmod(root.fd, 0755) != 0) { fail(error, VCCLibraryArchiveErrorIO, @"The extraction directory permissions could not be set."); return nil; } + success = true; + return files; + } @finally { + if (!success) [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:nil]; + } +} +@end diff --git a/platforms/macos/Bridge/VCCMac-Bridging-Header.h b/platforms/macos/Bridge/VCCMac-Bridging-Header.h new file mode 100644 index 0000000..82ca48c --- /dev/null +++ b/platforms/macos/Bridge/VCCMac-Bridging-Header.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import "VCCMachineController.h" +#import "VCCLibraryArchive.h" +#import "DiskImageEditorBackend.h" diff --git a/platforms/macos/Bridge/VCCMachineController.h b/platforms/macos/Bridge/VCCMachineController.h new file mode 100644 index 0000000..3bf4721 --- /dev/null +++ b/platforms/macos/Bridge/VCCMachineController.h @@ -0,0 +1,369 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import +#import +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, VCCMachineState) { + VCCMachineStateEmpty, VCCMachineStatePaused, VCCMachineStateRunning, VCCMachineStateClosed +}; +typedef NS_ENUM(NSInteger, VCCFloppyFormat) { + VCCFloppyFormatStandard, VCCFloppyFormatTrackDMK, VCCFloppyFormatSectorVDK +}; +typedef NS_ENUM(NSInteger, VCCDiskInsertionReset) { + VCCDiskInsertionResetNone, VCCDiskInsertionResetSoftReset, VCCDiskInsertionResetColdRestart +}; +// Immutable copies only; no borrowed RAM or rendering pointers cross the queue. +@interface VCCDiskSnapshot : NSObject +@property(nonatomic, readonly) BOOL mounted, dirty, writeProtected, sourceReadOnly; +@property(nonatomic, readonly) NSString *name; +@property(nonatomic, readonly, nullable) NSString *floppyExtension; +@property(nonatomic, readonly) BOOL formatWriteProtected; +@property(nonatomic, readonly) NSUInteger tracks, sides, byteCount; +@property(nonatomic, readonly) uint64_t readEvents, writeEvents; +@end + +// Immutable mounted-image snapshot held by one controller-owned edit lease. +@interface VCCDiskEditCapture : NSObject +@property(nonatomic, readonly) NSData *data; +@property(nonatomic, readonly) NSString *name; +@property(nonatomic, readonly) uint64_t token; +@property(nonatomic, readonly) NSInteger drive; +@property(nonatomic, readonly) BOOL canApply; +@end + +@interface VCCHardDiskSave : NSObject +@property(nonatomic, readonly) NSData *data; // full export, or packed [LSN little-endian UInt32, 256 bytes] records +@property(nonatomic, readonly) uint64_t token; +@property(nonatomic, readonly) NSUInteger byteCount; +@end + +// Raw, immutable printer bytes captured at one emulation-queue boundary. +@interface VCCPrinterOutput : NSObject +@property(nonatomic, readonly) NSData *bytes; +@property(nonatomic, readonly) uint64_t revision, droppedBytes; +@property(nonatomic, readonly) NSUInteger capacity; +@property(nonatomic, readonly) BOOL enabled; +@end + +// A native grant can invalidate its owner while an emulator operation is queued. +@interface VCCCompiledRunLease : NSObject +@property(nonatomic, readonly, getter=isValid) BOOL valid; +- (void)invalidate; +@end + +// Immutable input values copied from the same core snapshot as state/frame identity. +// Ports are ordered right (0), left (1); no hardware identities or typed keys. +@interface VCCJoystickInputSnapshot : NSObject +@property(nonatomic, readonly) NSUInteger x, y, buttons, mode; +@end + +@interface VCCMachineSnapshot : NSObject +@property(nonatomic, readonly) VCCMachineState state; +@property(nonatomic, readonly) uint64_t generation; +@property(nonatomic, readonly) uint64_t debuggerProgramRevision, debuggerMappingFingerprint, assistantMediaRevision; +@property(nonatomic, readonly) BOOL debuggerDevelopmentAttached, debuggerAssemblyAttached, debuggerSourceStepping; +@property(nonatomic, readonly) BOOL debuggerBankedDevelopment; +@property(nonatomic, readonly) BOOL basicDebugAttached, assistantCompiledReturned; +@property(nonatomic, readonly) NSArray *assistantDeviceBlockers; +@property(nonatomic, readonly, nullable) NSNumber *assistantDirectPrompt, *assistantEmptyBASIC; // On-demand readiness observation. +@property(nonatomic, readonly, nullable) NSString *assistantLoadedSource; // Only the guarded transfer completion. +@property(nonatomic, readonly) NSInteger basicStoppedLine; // -1 unless stopped before a BASIC statement +@property(nonatomic, readonly) NSInteger basicSourceOffset; +@property(nonatomic, readonly) NSUInteger basicSourceLength; +@property(nonatomic, readonly) BOOL basicStepping, basicCanStepOut; +@property(nonatomic, readonly) NSInteger basicErrorLine; +@property(nonatomic, readonly) NSString *basicErrorCode; +@property(nonatomic, readonly) NSString *basicDebugStatus; +@property(nonatomic, readonly) uint64_t frames; +@property(nonatomic, readonly, copy) NSArray *joystickInputs; +@property(nonatomic, readonly) BOOL keyboardInputHeld; +@property(nonatomic, readonly) NSUInteger pasteRemaining; +@property(nonatomic, readonly) BOOL printerEnabled; +@property(nonatomic, readonly) uint64_t printerRevision, printerDroppedBytes; +@property(nonatomic, readonly) NSUInteger printerByteCount; +@property(nonatomic, readonly) uint64_t cycles; +@property(nonatomic, readonly) uint16_t programCounter; +@property(nonatomic, readonly) CGRect activeVideoRect; // Bounds belonging to pixels, not the latest register state. +@property(nonatomic, readonly, nullable) NSData *pixels; // 640x480, little-endian 0x00RRGGBB +@property(nonatomic, readonly, nullable) NSString *errorMessage; +@property(nonatomic, readonly) BOOL use6309, fastForward; +@property(nonatomic, readonly) NSUInteger ramConfiguration, cpuOverclock, frameInterval; +@property(nonatomic, readonly) uint64_t presentedFrame; // Completed guest rasters at publication. +@property(nonatomic, readonly) uint64_t pixelRevision; // Includes redraws between rasters at a BASIC stop. +@property(nonatomic, readonly) NSInteger videoOutput; // 0 RGB, 1 composite, 2 alternate composite phase +@property(nonatomic, readonly) BOOL audioEnabled; +@property(nonatomic, readonly) BOOL driveWireEnabled; +@property(nonatomic, readonly, copy) NSString *macShellStatus; +@property(nonatomic, readonly) uint64_t macShellRequestID; +@property(nonatomic, readonly) uint64_t audioUnderruns, audioOverruns, audioConsumed; +// Lifetime totals except current occupancy (audioBuffered) and maximum fields. +// Nonzero signal is counted before gain; reset/pause do not clear diagnostics. +@property(nonatomic, readonly) uint64_t audioSubmitted, audioSignalSamples, audioBuffered, audioStarts; +@property(nonatomic, readonly) uint64_t audioMaximumRequest, audioMaximumRefillGapNanoseconds; +@property(nonatomic, readonly) BOOL tapeMounted, tapeMotor, tapeDirty, tapeFast, tapeWAV; +@property(nonatomic, readonly) NSInteger tapeMode; +@property(nonatomic, readonly) uint64_t tapePosition, tapeLength; +@property(nonatomic, readonly) uint64_t tapeReadEvents, tapeWriteEvents; +@property(nonatomic, readonly) BOOL diskEnabled, diskBusy, diskMotor, diskConnected, diskEditorLocked; +@property(nonatomic, readonly) BOOL hardDiskConnected, hardClockEnabled, hardClockReadOnly; +@property(nonatomic, readonly) NSUInteger hardSelectedDrive, hardSector, hardStatus; +@property(nonatomic, readonly) uint64_t hardFlushRequests; +@property(nonatomic, readonly) NSArray *hardDisks; // two drives +@property(nonatomic, readonly) BOOL sdcReadOnly; +@property(nonatomic, readonly) NSArray *sdcDriveNames; +@property(nonatomic, readonly) NSString *sdcDirectory; +@property(nonatomic, readonly, nullable) NSString *sdcError; +@property(nonatomic, readonly) uint64_t sdcReadCount, sdcWriteCount; +@property(nonatomic, readonly) BOOL multiPakEnabled; +@property(nonatomic, readonly) NSUInteger physicalSlot, romSlot, ioSlot; +@property(nonatomic, readonly) NSArray *cartridgeKinds; +@property(nonatomic, readonly) NSArray *cartridgeNames; // single then slots 1...4 +@property(nonatomic, readonly) NSString *diskROMName; +@property(nonatomic, readonly) NSInteger diskSelectedDrive; +@property(nonatomic, readonly) NSUInteger diskTrack, diskSector, diskSide; +@property(nonatomic, readonly) NSArray *disks; // always four drives +@end + +// Owned, validated payload for a complete profile switch. Image indices 0...3 +// are floppies and 4...5 are hard disks; empty image data denotes no medium. +@interface VCCMachineProfile : NSObject +@property(nonatomic) BOOL use6309, fastForward, sound, multiPak, clockEnabled, clockReadOnly, cassetteWAV, fastCassette; +@property(nonatomic) NSInteger ram, overclock, frameInterval, videoOutput, physicalSlot; +@property(nonatomic) float volume; +@property(nonatomic, copy, nullable) NSData *systemROM, *diskROM, *cassette; +@property(nonatomic, copy) NSString *diskROMName; +@property(nonatomic, copy) NSArray *kinds, *readOnly, *protectedImages; +@property(nonatomic, copy) NSArray *cartridgeROMs, *images; +@property(nonatomic, copy) NSArray *cartridgeNames, *imageNames; +@property(nonatomic, copy) NSArray *sdcFolders; +@property(nonatomic, copy) NSArray *sdcReadOnly; +@end + +typedef void (^VCCMachineCompletion)(VCCMachineSnapshot *snapshot); + +// Debugger data is captured on the same queue and at the same boundary as +// machine state. Unavailable I/O bytes are marked separately, never read. +@interface VCCDebugInstruction : NSObject +@property(nonatomic, readonly) uint16_t address; +@property(nonatomic, readonly) NSData *bytes; +@property(nonatomic, readonly) NSString *mnemonic, *operand; +@property(nonatomic, readonly) BOOL valid; +@end +@interface VCCDebugMemoryCapture : NSObject +@property(nonatomic, readonly) VCCMachineSnapshot *machine; +@property(nonatomic, readonly) uint32_t address, capacity; +@property(nonatomic, readonly) NSData *bytes, *available; +@property(nonatomic, readonly) NSArray *instructions; +// Parallel offsets distinguish physical locations from assumed logical PCs. +@property(nonatomic, readonly) NSArray *instructionOffsets; +@end +// Pixel coordinates use the captured source resolution, before display zoom. +// Addresses are in the same space as the enclosing capture. +@interface VCCDebugGraphicsPixel : NSObject +@property(nonatomic, readonly) uint32_t address; +@property(nonatomic, readonly) uint8_t value, mask; +@property(nonatomic, readonly, nullable) NSNumber *attributeAddress, *attributeValue; // attributed text cells +@property(nonatomic, readonly) BOOL available; +@end +@interface VCCDebugGraphicsCapture : NSObject +@property(nonatomic, readonly) VCCMachineSnapshot *machine; +@property(nonatomic, readonly, nullable) NSString *errorMessage; +@property(nonatomic, readonly) NSString *modeName; +@property(nonatomic, readonly) NSInteger width, height; +@property(nonatomic, readonly) uint32_t address; +@property(nonatomic, readonly) BOOL physical; +@property(nonatomic, readonly) NSData *rgba; // R, G, B, A; four bytes per pixel, rows top-down. +- (nullable VCCDebugGraphicsPixel *)pixelAtX:(NSInteger)x y:(NSInteger)y NS_SWIFT_NAME(pixel(x:y:)); +- (BOOL)hasSameLayoutAs:(VCCDebugGraphicsCapture *)other NS_SWIFT_NAME(hasSameLayout(as:)); +@end +@interface VCCMemoryMapping : NSObject +@property(nonatomic, readonly) uint16_t page; +@property(nonatomic, readonly) uint32_t ramAddress, sourceAddress; +@property(nonatomic, readonly) NSInteger source; // 0 RAM, 1 internal ROM, 2 cartridge ROM +@end +@interface VCCMMUSnapshot : NSObject +@property(nonatomic, readonly) BOOL enabled, ramVectors, allRAM; +@property(nonatomic, readonly) NSUInteger activeTask, romMap, prefix; +@property(nonatomic, readonly) uint32_t ramByteCount, vectorRAMAddress; +@property(nonatomic, readonly) NSArray *task0, *task1; +// Eight logical 8 KiB banks, before FE00/vector and FF00/I/O overrides. +@property(nonatomic, readonly) NSArray *effective; +@end +@interface VCCDebuggerSnapshot : NSObject +@property(nonatomic, readonly) VCCMachineSnapshot *machine; +@property(nonatomic, readonly) NSDictionary *registers; +@property(nonatomic, readonly) NSArray *instructions; +@property(nonatomic, readonly) NSArray *breakpoints, *disabledBreakpoints; +@property(nonatomic, readonly) uint16_t memoryAddress; +@property(nonatomic, readonly) NSData *memory, *memoryAvailable; +// Full logical memory and availability captured atomically with registers. +@property(nonatomic, readonly) NSData *logicalMemory, *logicalMemoryAvailable; +@property(nonatomic, readonly) NSString *stopReason; +@property(nonatomic, readonly) VCCMMUSnapshot *mmu; +@property(nonatomic, readonly) uint32_t physicalAddress; +@property(nonatomic, readonly) NSData *physicalMemory; // Raw RAM, never overlaid ROM/I/O; read-only. +@end +// Commands are asynchronous and ordered on a private serial queue. Completions +// are delivered on the main queue. One process-wide machine may be loaded. +// Shutdown is terminal; deallocation also drains work and releases the core. +@interface VCCTraceRecord : NSObject +@property(nonatomic, readonly) NSUInteger index; +@property(nonatomic, readonly) uint64_t clock, frame; +@property(nonatomic, readonly) NSInteger cycles; +@property(nonatomic, readonly) uint16_t address; +@property(nonatomic, readonly) NSString *kind, *instruction, *detail, *before, *after; +@end +@interface VCCTraceSnapshot : NSObject +@property(nonatomic, readonly) BOOL armed, capturing; +@property(nonatomic, readonly) uint64_t identifier; +@property(nonatomic, readonly) NSUInteger total, limit, offset; +@property(nonatomic, readonly) NSString *status; +@property(nonatomic, readonly) NSArray *records; +@end + +@interface VCCMachineController : NSObject +// Capture starts disabled. Toggling or clearing never pauses/resets the machine. +// Closing a UI window has no effect; reset/profile replacement retain output. +- (void)setPrinterEnabled:(BOOL)enabled completion:(VCCMachineCompletion)completion; +- (void)clearPrinterOutputWithCompletion:(VCCMachineCompletion)completion; +- (void)printerOutputWithCompletion:(void (^)(VCCPrinterOutput *, VCCMachineSnapshot *))completion; +- (void)debuggerSnapshotAtAddress:(uint16_t)address followPC:(BOOL)followPC memoryAddress:(uint16_t)memoryAddress completion:(void (^)(VCCDebuggerSnapshot *))completion NS_SWIFT_NAME(debuggerSnapshot(address:followPC:memoryAddress:completion:)); +- (void)debuggerSnapshotAtAddress:(uint16_t)address followPC:(BOOL)followPC memoryAddress:(uint16_t)memoryAddress physicalAddress:(uint32_t)physicalAddress physicalMemory:(BOOL)physicalMemory completion:(void (^)(VCCDebuggerSnapshot *))completion NS_SWIFT_NAME(debuggerSnapshot(address:followPC:memoryAddress:physicalAddress:physicalMemory:completion:)); +// Mode for an address preview: SG4, PMODE 0–4, then HSCREEN 1–4 (0–9). +// Current page derives the interpretation, palette and physical address from the machine. +- (void)debuggerGraphicsCurrentPage:(BOOL)currentPage address:(uint32_t)address physical:(BOOL)physical mode:(NSInteger)mode alternatePalette:(BOOL)alternatePalette completion:(void (^)(VCCDebugGraphicsCapture *))completion NS_SWIFT_NAME(debuggerGraphics(currentPage:address:physical:mode:alternatePalette:completion:)); +- (void)debuggerStepWithCompletion:(VCCMachineCompletion)completion; +// mode: 0 into, 1 over, 2 out. Completion acknowledges start; poll machine state +// for the eventual pause. pauseWithCompletion cancels a pending source step. +- (void)debuggerStepSource:(NSInteger)mode addresses:(NSArray *)addresses locations:(NSArray *)locations bytes:(NSArray *)bytes generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(debuggerStepSource(mode:addresses:locations:bytes:generation:programRevision:mappingFingerprint:programCounter:completion:)); +- (void)debuggerStepBankedSource:(NSInteger)mode addresses:(NSArray *)addresses locations:(NSArray *)locations bytes:(NSArray *)bytes moduleIdentifiers:(NSArray *)moduleIdentifiers generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(debuggerStepBankedSource(mode:addresses:locations:bytes:moduleIdentifiers:generation:programRevision:mappingFingerprint:programCounter:completion:)); +- (void)debuggerMemoryAtAddress:(uint32_t)address count:(uint32_t)count physical:(BOOL)physical logicalAddress:(uint16_t)logicalAddress os9:(BOOL)os9 decode:(BOOL)decode completion:(void (^)(VCCDebugMemoryCapture *))completion NS_SWIFT_NAME(debuggerMemory(address:count:physical:logicalAddress:os9:decode:completion:)); +- (void)debuggerSetPC:(uint16_t)address completion:(VCCMachineCompletion)completion; +- (void)debuggerSetBreakpoints:(NSArray *)addresses completion:(VCCMachineCompletion)completion; +- (void)debuggerConfigureBreakpoints:(NSArray *)enabled disabled:(NSArray *)disabled completion:(VCCMachineCompletion)completion; +- (void)debuggerStartTrace:(NSUInteger)maximum starts:(NSArray *)starts stops:(NSArray *)stops screen:(BOOL)screen scheduler:(BOOL)scheduler completion:(VCCMachineCompletion)completion; +- (void)debuggerStopTraceWithCompletion:(VCCMachineCompletion)completion; +- (void)debuggerClearTraceWithCompletion:(VCCMachineCompletion)completion; +- (void)debuggerTraceAtOffset:(NSUInteger)offset completion:(void (^)(VCCTraceSnapshot *, VCCMachineSnapshot *))completion NS_SWIFT_NAME(debuggerTrace(offset:completion:)); +- (void)debuggerExportTraceFrom:(NSUInteger)first count:(NSUInteger)count completion:(void (^)(NSString * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(debuggerExportTrace(first:count:completion:)); +// Direct BASIC transfers are serialized with emulation; no synthetic key events. +// Scoped BASIC operations validate machine identity, mounted devices and guest program on its owner queue. +- (void)assistantReadinessWithCompletion:(VCCMachineCompletion)completion NS_SWIFT_NAME(assistantReadiness(completion:)); +- (void)assistantLoadSource:(NSString *)source breakpoints:(NSArray *)lines expected:(VCCMachineSnapshot *)expected existing:(NSString *)existing completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(assistantLoad(source:breakpoints:expected:existing:completion:)); +- (void)assistantPaste:(NSArray *)chords runID:(NSString *)runID direct:(BOOL)direct expected:(VCCMachineSnapshot *)expected source:(NSString *)source completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(assistantPaste(chords:runID:direct:expected:source:completion:)); +- (void)cancelAssistantPaste:(NSString *)runID; +- (void)compiledGuest:(VCCCompiledRunLease *)lease runID:(NSString *)runID expected:(VCCMachineSnapshot *)expected assembly:(BOOL)assembly key:(nullable NSNumber *)key readScreen:(BOOL)readScreen finalScreen:(BOOL)finalScreen completion:(void (^)(NSString * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(compiledGuest(lease:runID:expected:assembly:key:readScreen:finalScreen:completion:)); +- (void)checkReviewedBASIC:(VCCMachineSnapshot *)expected source:(NSString *)source completion:(VCCMachineCompletion)completion; +- (void)assistantScreen:(VCCMachineSnapshot *)expected source:(NSString *)source completion:(void (^)(NSDictionary * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(assistantScreen(expected:source:completion:)); +- (void)basicLoadSource:(NSString *)source run:(BOOL)run completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(basicLoadSource(_:run:completion:)); +- (void)basicLoadSource:(NSString *)source run:(BOOL)run breakpoints:(NSArray *)lines completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(basicLoadSource(_:run:breakpoints:completion:)); +- (void)basicSetBreakpoints:(NSArray *)lines source:(NSString *)source completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(basicSetBreakpoints(_:source:completion:)); +- (void)basicContinueSource:(NSString *)source completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(basicContinue(source:completion:)); +- (void)basicStepSource:(NSString *)source over:(BOOL)over completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(basicStep(source:over:completion:)); +- (void)basicStepOutSource:(NSString *)source completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(basicStepOut(source:completion:)); +- (void)basicClearDebugWithCompletion:(VCCMachineCompletion)completion; +- (void)basicExportSource:(NSString *)source name:(NSString *)name cassette:(BOOL)cassette completion:(void (^)(NSData * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(basicExportSource(_:name:cassette:completion:)); +- (void)basicInspectSource:(NSString *)source completion:(void (^)(NSArray *> * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(basicInspect(source:completion:)); +- (void)basicReadSourceWithCompletion:(void (^)(NSString * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(basicReadSource(completion:)); +- (void)debuggerWriteMemoryAtAddress:(uint16_t)address data:(NSData *)data completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(debuggerWriteMemory(address:data:completion:)); +// Stages/validates all devices first, rejects dirty media, then cold-loads paused. +// applied distinguishes a committed setup from a preflight rejection, including +// the unlikely case of a core allocation failure after media installation. +- (void)applyProfile:(VCCMachineProfile*)profile completion:(void (^)(BOOL applied, VCCMachineSnapshot *snapshot))completion NS_SWIFT_NAME(applyProfile(_:completion:)); +- (void)configureMachineWith6309:(BOOL)use6309 ram:(NSInteger)ram overclock:(NSInteger)overclock frameInterval:(NSInteger)interval fastForward:(BOOL)fastForward completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(configureMachine(use6309:ram:overclock:frameInterval:fastForward:completion:)); +- (void)setVideoOutput:(NSInteger)output completion:(VCCMachineCompletion)completion; +- (void)loadDiagnosticWithCompletion:(VCCMachineCompletion)completion; +- (void)loadDiagnosticWith6309:(BOOL)use6309 completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(loadDiagnostic(use6309:completion:)); +- (void)loadROM:(NSData *)rom use6309:(BOOL)use6309 completion:(VCCMachineCompletion)completion; +// Fire-and-forget input shares the command queue; no frame copy per key event. +- (void)setJoystick:(NSUInteger)port x:(NSUInteger)x y:(NSUInteger)y buttons:(NSUInteger)buttons mode:(NSUInteger)mode; +- (void)pasteChords:(NSArray *)chords completion:(VCCMachineCompletion)completion; +- (void)cancelPasteWithCompletion:(VCCMachineCompletion)completion; +- (void)copyScreenTextWithCompletion:(void (^)(NSString * _Nullable, VCCMachineSnapshot *))completion; +// Read-only discovery for loading automation; graphics screens return nil without setting a user-visible error. +- (void)inspectScreenTextWithCompletion:(void (^)(NSString * _Nullable, VCCMachineSnapshot *))completion; +- (void)setKeyboardMask:(uint64_t)keys; +- (void)launchAssembly:(NSData *)binary points:(NSArray *)points addresses:(NSArray *)addresses bytes:(NSArray *)bytes pauseAtEntry:(BOOL)pauseAtEntry requires6309:(BOOL)requires6309 generation:(uint64_t)generation revision:(uint64_t)revision mapping:(uint64_t)mapping completion:(VCCMachineCompletion)completion; +- (void)launchAssembly:(NSData *)binary points:(NSArray *)points addresses:(NSArray *)addresses bytes:(NSArray *)bytes pauseAtEntry:(BOOL)pauseAtEntry requires6309:(BOOL)requires6309 generation:(uint64_t)generation revision:(uint64_t)revision mapping:(uint64_t)mapping shared:(BOOL)shared completion:(VCCMachineCompletion)completion; +- (void)pauseAssembly:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion; +- (void)controlAssembly:(BOOL)step expected:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion; +- (void)updateAssembly:(NSArray *)points expected:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion; +- (void)clearAssembly:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion; +- (void)startReviewedC:(NSData *)binary disk:(nullable NSData *)disk name:(NSString *)name stop:(uint16_t)stop expected:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion; +- (void)continueReviewedC:(VCCMachineSnapshot *)expected name:(NSString *)name stop:(uint16_t)stop bytes:(NSData *)bytes completion:(VCCMachineCompletion)completion; +- (void)ejectReviewedCDisk:(NSString *)name completion:(VCCMachineCompletion)completion; +- (void)debuggerLoadBinary:(NSData *)binary breakpoint:(uint16_t)breakpoint completion:(VCCMachineCompletion)completion; +- (void)debuggerLoadBinary:(NSData *)binary breakpoints:(NSArray *)breakpoints completion:(VCCMachineCompletion)completion; +- (void)debuggerArmDevelopmentBreakpoints:(NSArray *)breakpoints guardAddresses:(NSArray *)guardAddresses guardBytes:(NSArray *)guardBytes completion:(VCCMachineCompletion)completion; +// Module dictionaries: id:String, pages:[{logicalPage:Number,physicalPage:Number}], +// addresses:[Number], bytes:[Data], optional breakpoints:[Number]. An explicit +// breakpoint array qualifies stops to this module; empty retains only code evidence. +// Pages identify actual installed 8 KiB RAM. +- (void)debuggerArmBankedDevelopmentBreakpoints:(NSArray *)breakpoints modules:(NSArray *> *)modules completion:(VCCMachineCompletion)completion; +- (void)debuggerClearDevelopmentBreakpointsWithCompletion:(VCCMachineCompletion)completion; +- (void)quickLoadBinary:(NSData *)binary completion:(VCCMachineCompletion)completion; +- (void)requestNitros9BootWithCompletion:(VCCMachineCompletion)completion; +- (void)resumeWithCompletion:(VCCMachineCompletion)completion; +- (void)pauseWithCompletion:(VCCMachineCompletion)completion; +- (void)softResetWithCompletion:(VCCMachineCompletion)completion; +- (void)resetWithCompletion:(VCCMachineCompletion)completion; +- (void)startMacShellWithCompletion:(VCCMachineCompletion)completion NS_SWIFT_NAME(startMacShell(completion:)); +- (void)stopMacShellWithCompletion:(VCCMachineCompletion)completion NS_SWIFT_NAME(stopMacShell(completion:)); +- (void)decideMacShellRequest:(uint64_t)requestID allow:(BOOL)allow completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(decideMacShellRequest(_:allow:completion:)); +- (void)setDriveWireEnabled:(BOOL)enabled completion:(VCCMachineCompletion)completion; +- (void)setAudioEnabled:(BOOL)enabled volume:(float)volume completion:(VCCMachineCompletion)completion; +- (void)mountTape:(NSData *)data wav:(BOOL)wav completion:(VCCMachineCompletion)completion; +// 0 stop, 1 play, 2 rewind, 3 eject, 4 record CAS, 5 record WAV. +- (void)tapeAction:(NSInteger)action completion:(VCCMachineCompletion)completion; +- (void)seekTape:(uint64_t)position completion:(VCCMachineCompletion)completion; +- (void)setTapeFast:(BOOL)enabled completion:(VCCMachineCompletion)completion; +- (void)exportTapeWithCompletion:(void (^)(NSData * _Nullable, VCCMachineSnapshot *))completion; +- (void)discardTapeWithCompletion:(VCCMachineCompletion)completion; +- (void)markTapeSavedWithCompletion:(VCCMachineCompletion)completion; +// Atomic layout change; kinds: 0 empty, 1 raw ROM, 2 FD-502, 3 virtual hard disk, 4 RAM disk, 5 Orchestra-90 (optional 8 KiB ROM), 6 Speech/Sound (PIC + speech payload, or empty), 7 CoCo SDC (8/16 KiB ROM). +// Empty ROM data for kind 1 represents an unavailable remembered file. +// Changes pause and cold reset; disk contents and save acknowledgements survive. +- (void)configureCartridges:(NSArray *)kinds roms:(NSArray *)roms names:(NSArray *)names multiPak:(BOOL)enabled physicalSlot:(NSInteger)slot completion:(VCCMachineCompletion)completion; +// SDC folders are explicit host roots, never guest paths. Writes are opt-in. +- (void)configureCartridges:(NSArray *)kinds roms:(NSArray *)roms names:(NSArray *)names multiPak:(BOOL)enabled physicalSlot:(NSInteger)slot sdcFolders:(NSArray *)folders sdcReadOnly:(NSArray *)readOnly completion:(VCCMachineCompletion)completion; +// Disk changes pause execution and reject in-progress controller commands. +- (void)pauseForDiskChangeWithCompletion:(VCCMachineCompletion)completion; +- (void)loadDiskROM:(NSData *)rom name:(NSString *)name completion:(VCCMachineCompletion)completion; +- (void)disableDisksWithCompletion:(VCCMachineCompletion)completion; +- (void)mountDisk:(NSData *)data drive:(NSInteger)drive name:(NSString *)name readOnly:(BOOL)readOnly completion:(VCCMachineCompletion)completion; +// Validate the complete replacement and media guards before resetting; reset and +// mount share one serialized transaction. Reset does not execute the new disk. +- (void)mountDisk:(NSData *)data drive:(NSInteger)drive name:(NSString *)name readOnly:(BOOL)readOnly reset:(VCCDiskInsertionReset)reset completion:(VCCMachineCompletion)completion; +- (void)createDiskInDrive:(NSInteger)drive completion:(VCCMachineCompletion)completion; +- (void)createDiskInDrive:(NSInteger)drive format:(VCCFloppyFormat)format completion:(VCCMachineCompletion)completion; +- (void)ejectDiskInDrive:(NSInteger)drive discard:(BOOL)discard completion:(VCCMachineCompletion)completion; +- (void)setDiskWriteProtected:(BOOL)enabled drive:(NSInteger)drive completion:(VCCMachineCompletion)completion; +// Export freezes execution and returns immutable bytes and a one-use token. +// Acknowledge only after a successful host write; stale tokens never clear dirty state. +- (void)exportDiskInDrive:(NSInteger)drive completion:(void (^)(NSData * _Nullable, uint64_t, VCCMachineSnapshot *))completion; +// Copy completed in-memory bytes on the worker queue without pausing execution, +// changing media/dirty state, or consuming an export/save acknowledgement token. +- (void)snapshotDiskCopyInDrive:(NSInteger)drive completion:(void (^)(NSData * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(snapshotDiskCopy(inDrive:completion:)); +- (void)markDiskSavedInDrive:(NSInteger)drive token:(uint64_t)token name:(NSString *)name completion:(VCCMachineCompletion)completion; +// Acquiring a lease pauses at an idle disk boundary. All execution/media +// mutations are refused until cancel or a confirmed edited-image commit. +- (void)beginDiskEditorInDrive:(NSInteger)drive completion:(void (^)(VCCDiskEditCapture * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(beginDiskEditor(inDrive:completion:)); +- (void)beginHardDiskEditorInDrive:(NSInteger)drive completion:(void (^)(VCCDiskEditCapture * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(beginHardDiskEditor(inDrive:completion:)); +- (void)prepareDiskEditorToken:(uint64_t)token data:(NSData *)data completion:(void (^)(BOOL, VCCMachineSnapshot *))completion NS_SWIFT_NAME(prepareDiskEditor(token:data:completion:)); +- (void)commitDiskEditorToken:(uint64_t)token restartConfirmed:(BOOL)restartConfirmed sourceSaved:(BOOL)sourceSaved completion:(void (^)(BOOL, VCCMachineSnapshot *))completion NS_SWIFT_NAME(commitDiskEditor(token:restartConfirmed:sourceSaved:completion:)); +- (void)cancelDiskEditorToken:(uint64_t)token completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(cancelDiskEditor(token:completion:)); +- (void)snapshotWithCompletion:(VCCMachineCompletion)completion; +// Background saving neither pauses the CPU nor restarts audio. Nil means no +// eligible completed write. A stale acknowledgement leaves newer writes dirty. +- (void)captureDiskForSavingInDrive:(NSInteger)drive completion:(void (^)(NSData * _Nullable, uint64_t, VCCMachineSnapshot *))completion; +- (void)acknowledgeDiskSaveInDrive:(NSInteger)drive token:(uint64_t)token completion:(VCCMachineCompletion)completion; +- (void)mountHardDisk:(NSData *)data drive:(NSInteger)drive name:(NSString *)name readOnly:(BOOL)readOnly completion:(VCCMachineCompletion)completion; +- (void)createHardDiskInDrive:(NSInteger)drive size:(NSUInteger)size completion:(VCCMachineCompletion)completion; +// 0 eject, 1 discard/eject, 2 protect, 3 allow writes. +- (void)hardDiskAction:(NSInteger)action drive:(NSInteger)drive completion:(VCCMachineCompletion)completion; +- (void)configureHardClock:(BOOL)enabled readOnly:(BOOL)readOnly completion:(VCCMachineCompletion)completion; +- (void)captureHardDiskInDrive:(NSInteger)drive full:(BOOL)full completion:(void (^)(VCCHardDiskSave * _Nullable, VCCMachineSnapshot *))completion; +- (void)acknowledgeHardDiskInDrive:(NSInteger)drive token:(uint64_t)token name:(NSString * _Nullable)name completion:(VCCMachineCompletion)completion; +- (void)shutdownWithCompletion:(VCCMachineCompletion)completion; +@end +NS_ASSUME_NONNULL_END diff --git a/platforms/macos/Bridge/VCCMachineController.mm b/platforms/macos/Bridge/VCCMachineController.mm new file mode 100644 index 0000000..902fe1e --- /dev/null +++ b/platforms/macos/Bridge/VCCMachineController.mm @@ -0,0 +1,2218 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#import "VCCMachineController.h" +#include "../../../src/core/MachineSession.h" +#include "../../../src/core/DebugDisassembler.h" +#include "MacAudioOutput.h" +#include "DriveWireEndpoint.h" +#include "../../../src/core/FramePacing.h" +#include "../../../src/devices/FD502/Fd502Device.h" +#include "../../../src/devices/RomCartridge.h" +#include "../../../src/devices/RamDiskDevice.h" +#include "../../../src/devices/Orchestra90Device.h" +#include "../../../src/devices/SpeechSoundDevice.h" +#include "../../../src/devices/SDCDevice.h" +#include "../../../src/devices/HardDisk/HardDiskDevice.h" +#include "../../../src/core/BinaryImage.h" +#include +#include +#include +#include +#include +#include +#include +#include + +@interface VCCTraceRecord () +@property(nonatomic, readwrite) NSUInteger index; +@property(nonatomic, readwrite) uint64_t clock, frame; +@property(nonatomic, readwrite) NSInteger cycles; +@property(nonatomic, readwrite) uint16_t address; +@property(nonatomic, readwrite, copy) NSString *kind, *instruction, *detail, *before, *after; +@end +@implementation VCCTraceRecord +@end +@interface VCCTraceSnapshot () +@property(nonatomic, readwrite) BOOL armed, capturing; +@property(nonatomic, readwrite) uint64_t identifier; +@property(nonatomic, readwrite) NSUInteger total, limit, offset; +@property(nonatomic, readwrite, copy) NSString *status; +@property(nonatomic, readwrite, copy) NSArray *records; +@end +@implementation VCCTraceSnapshot +@end +static NSString* TraceRegisters(const VCC::CPUState& state, bool extended) { + auto common = [NSString stringWithFormat:@"PC %04X A %02X B %02X X %04X Y %04X U %04X S %04X DP %02X CC %02X", state.PC, state.A, state.B, state.X, state.Y, state.U, state.S, state.DP, state.CC]; + return extended ? [common stringByAppendingFormat:@" E %02X F %02X V %04X MD %02X", state.E, state.F, state.V, state.MD] : common; +} +static NSString* TraceKind(VCC::TraceEvent event) { + switch (event) { + case VCC::TraceEvent::Instruction: return @"Instruction"; + case VCC::TraceEvent::IRQRequested: return @"IRQ requested"; + case VCC::TraceEvent::IRQMasked: return @"IRQ masked"; + case VCC::TraceEvent::IRQServicing: return @"IRQ servicing"; + case VCC::TraceEvent::IRQExecuting: return @"IRQ vector"; + case VCC::TraceEvent::ScreenHSYNCLow: return @"HSYNC low"; + case VCC::TraceEvent::ScreenHSYNCHigh: return @"HSYNC high"; + case VCC::TraceEvent::ScreenVSYNCLow: return @"VSYNC low"; + case VCC::TraceEvent::ScreenVSYNCHigh: return @"VSYNC high"; + case VCC::TraceEvent::ScreenReg: return @"Video register"; + case VCC::TraceEvent::ScreenTopBorder: return @"Top border"; + case VCC::TraceEvent::ScreenRender: return @"Active display"; + case VCC::TraceEvent::ScreenBottomBorder: return @"Bottom border"; + case VCC::TraceEvent::EmulatorCycle: return @"Scheduler"; + default: return @"Event"; + } +} +static std::vector DebugAddresses(NSArray* values, unsigned maximum) { + if (values.count > maximum) throw std::invalid_argument("Too many debugger addresses"); + std::vector result; + for (NSNumber* value in values) { + const double n = value.doubleValue; + if (!std::isfinite(n) || n < 0 || n > 65535 || n != std::floor(n)) throw std::invalid_argument("Use logical addresses from 0000 to FFFF"); + result.push_back(uint16_t(n)); + } + return result; +} +@interface VCCDebugInstruction () +@property(nonatomic, readwrite) uint16_t address; +@property(nonatomic, readwrite, copy) NSData *bytes; +@property(nonatomic, readwrite, copy) NSString *mnemonic, *operand; +@property(nonatomic, readwrite) BOOL valid; +@end +@implementation VCCDebugInstruction +@end +@interface VCCDebugMemoryCapture () +@property(nonatomic, readwrite) VCCMachineSnapshot *machine; +@property(nonatomic, readwrite) uint32_t address, capacity; +@property(nonatomic, readwrite, copy) NSData *bytes, *available; +@property(nonatomic, readwrite, copy) NSArray *instructions; +@property(nonatomic, readwrite, copy) NSArray *instructionOffsets; +@end +@implementation VCCDebugMemoryCapture +@end +@interface VCCDebugGraphicsPixel () +@property(nonatomic, readwrite) uint32_t address; +@property(nonatomic, readwrite) uint8_t value, mask; +@property(nonatomic, readwrite) BOOL available; +@property(nonatomic, readwrite) NSNumber *attributeAddress, *attributeValue; +@end +@implementation VCCDebugGraphicsPixel +@end + +@interface VCCDebugGraphicsCapture () +@property(nonatomic, readwrite) VCCMachineSnapshot *machine; +@property(nonatomic, readwrite, copy) NSString *errorMessage; +- (void)takePreview:(VCC::Mac::DebugGraphicsPreview&)preview; +@end +@implementation VCCDebugGraphicsCapture { + VCC::Mac::DebugGraphicsPreview _source; + NSData *_rgba; + NSString *_modeName; +} +- (void)takePreview:(VCC::Mac::DebugGraphicsPreview&)preview { + _modeName = [NSString stringWithUTF8String:preview.modeName.c_str()]; + NSMutableData *rgba = [NSMutableData dataWithLength:preview.pixels.size() * 4]; + auto* out = static_cast(rgba.mutableBytes); + for (const auto rgb : preview.pixels) { + *out++ = uint8_t(rgb >> 16); + *out++ = uint8_t(rgb >> 8); + *out++ = uint8_t(rgb); + *out++ = 255; + } + _rgba = rgba; + // Keep only the packed RGBA buffer and source-byte metadata after publication. + std::vector().swap(preview.pixels); + _source = std::move(preview); +} +- (NSString *)modeName { return _modeName ?: @""; } +- (NSData *)rgba { return _rgba ?: [NSData data]; } +- (NSInteger)width { return _source.width; } +- (NSInteger)height { return _source.height; } +- (uint32_t)address { return _source.address; } +- (BOOL)physical { return _source.physical; } +- (VCCDebugGraphicsPixel *)pixelAtX:(NSInteger)x y:(NSInteger)y { + if (!_rgba || x < 0 || y < 0 || x >= self.width || y >= self.height) return nil; + const auto selection = _source.pixelInfo(unsigned(x), unsigned(y)); + const auto i = selection.byteIndex; + auto result = [VCCDebugGraphicsPixel new]; + result.address = _source.byteAddresses[i]; + result.available = _source.available[i] != 0; + result.value = _source.bytes[i]; + result.mask = selection.mask; + if (_source.bytesPerCell == 2) { + result.attributeAddress = @(_source.byteAddresses[i + 1]); + if (_source.available[i + 1]) result.attributeValue = @(_source.bytes[i + 1]); + } + return result; +} +- (BOOL)hasSameLayoutAs:(VCCDebugGraphicsCapture *)other { + if (!_rgba || !other->_rgba || self.machine.generation != other.machine.generation) return NO; + const auto& otherSource = other->_source; + return (_source.physical || self.machine.debuggerMappingFingerprint == other.machine.debuggerMappingFingerprint) + && _source.physical == otherSource.physical && _source.address == otherSource.address + && _source.width == otherSource.width && _source.height == otherSource.height + && _source.modeName == otherSource.modeName && _source.bytesPerCell == otherSource.bytesPerCell + && _source.pixelsPerByte == otherSource.pixelsPerByte && _source.linesPerRow == otherSource.linesPerRow + && _source.rowByteOffsets == otherSource.rowByteOffsets && _source.byteAddresses == otherSource.byteAddresses; +} +@end +@interface VCCMemoryMapping () +@property(nonatomic, readwrite) uint16_t page; +@property(nonatomic, readwrite) uint32_t ramAddress, sourceAddress; +@property(nonatomic, readwrite) NSInteger source; +@end +@implementation VCCMemoryMapping +@end +@interface VCCMMUSnapshot () +@property(nonatomic, readwrite) BOOL enabled, ramVectors, allRAM; +@property(nonatomic, readwrite) NSUInteger activeTask, romMap, prefix; +@property(nonatomic, readwrite) uint32_t ramByteCount, vectorRAMAddress; +@property(nonatomic, readwrite, copy) NSArray *task0, *task1; +@property(nonatomic, readwrite, copy) NSArray *effective; +@end +@implementation VCCMMUSnapshot +@end +@interface VCCDebuggerSnapshot () +@property(nonatomic, readwrite) VCCMachineSnapshot *machine; +@property(nonatomic, readwrite, copy) NSDictionary *registers; +@property(nonatomic, readwrite, copy) NSArray *instructions; +@property(nonatomic, readwrite, copy) NSArray *breakpoints, *disabledBreakpoints; +@property(nonatomic, readwrite) uint16_t memoryAddress; +@property(nonatomic, readwrite, copy) NSData *memory, *memoryAvailable; +@property(nonatomic, readwrite, copy) NSData *logicalMemory, *logicalMemoryAvailable; +@property(nonatomic, readwrite, copy) NSString *stopReason; +@property(nonatomic, readwrite) VCCMMUSnapshot *mmu; +@property(nonatomic, readwrite) uint32_t physicalAddress; +@property(nonatomic, readwrite, copy) NSData *physicalMemory; +@end +@implementation VCCDebuggerSnapshot +@end + +@implementation VCCMachineProfile +- (instancetype)init { + if ((self = [super init])) { + _ram = 1; _overclock = _frameInterval = 1; _physicalSlot = 4; _videoOutput = 1; + _volume = 0.5; _sound = _clockEnabled = _clockReadOnly = YES; + _diskROMName = @""; + _kinds = @[@0,@0,@0,@0,@0]; + _cartridgeROMs = @[[NSData data],[NSData data],[NSData data],[NSData data],[NSData data]]; + _cartridgeNames = @[@"",@"",@"",@"",@""]; + _sdcFolders = @[@"",@"",@"",@"",@""]; _sdcReadOnly = @[@YES,@YES,@YES,@YES,@YES]; + _images = @[[NSData data],[NSData data],[NSData data],[NSData data],[NSData data],[NSData data]]; + _imageNames = @[@"",@"",@"",@"",@"",@""]; + _readOnly = _protectedImages = @[@NO,@NO,@NO,@NO,@NO,@NO]; + } + return self; +} +- (id)copyWithZone:(NSZone*)zone { + auto value = [[VCCMachineProfile allocWithZone:zone] init]; + value.use6309 = self.use6309; + value.fastForward = self.fastForward; + value.sound = self.sound; + value.multiPak = self.multiPak; + value.clockEnabled = self.clockEnabled; + value.clockReadOnly = self.clockReadOnly; + value.cassetteWAV = self.cassetteWAV; + value.fastCassette = self.fastCassette; + value.ram = self.ram; + value.overclock = self.overclock; + value.frameInterval = self.frameInterval; + value.videoOutput = self.videoOutput; + value.physicalSlot = self.physicalSlot; + value.volume = self.volume; + value.systemROM = self.systemROM; + value.diskROM = self.diskROM; + value.cassette = self.cassette; + value.diskROMName = self.diskROMName; + value.kinds = [[NSArray alloc] initWithArray:self.kinds copyItems:YES]; + value.readOnly = [[NSArray alloc] initWithArray:self.readOnly copyItems:YES]; + value.protectedImages = [[NSArray alloc] initWithArray:self.protectedImages copyItems:YES]; + value.cartridgeROMs = [[NSArray alloc] initWithArray:self.cartridgeROMs copyItems:YES]; + value.images = [[NSArray alloc] initWithArray:self.images copyItems:YES]; + value.cartridgeNames = [[NSArray alloc] initWithArray:self.cartridgeNames copyItems:YES]; + value.imageNames = [[NSArray alloc] initWithArray:self.imageNames copyItems:YES]; + value.sdcFolders = [[NSArray alloc] initWithArray:self.sdcFolders copyItems:YES]; + value.sdcReadOnly = [[NSArray alloc] initWithArray:self.sdcReadOnly copyItems:YES]; + return value; +} +@end + +@interface VCCDiskSnapshot () +@property(nonatomic, readwrite) BOOL mounted, dirty, writeProtected, sourceReadOnly; +@property(nonatomic, readwrite, copy) NSString *name; +@property(nonatomic, readwrite, copy) NSString *floppyExtension; +@property(nonatomic, readwrite) BOOL formatWriteProtected; +@property(nonatomic, readwrite) NSUInteger tracks, sides, byteCount; +@property(nonatomic, readwrite) uint64_t readEvents, writeEvents; +@end +@implementation VCCDiskSnapshot +@end + +@interface VCCDiskEditCapture () +@property(nonatomic, readwrite, copy) NSData *data; +@property(nonatomic, readwrite, copy) NSString *name; +@property(nonatomic, readwrite) uint64_t token; +@property(nonatomic, readwrite) NSInteger drive; +@property(nonatomic, readwrite) BOOL canApply; +@end +@implementation VCCDiskEditCapture +@end + +@interface VCCHardDiskSave () +@property(nonatomic, readwrite, copy) NSData *data; +@property(nonatomic, readwrite) uint64_t token; +@property(nonatomic, readwrite) NSUInteger byteCount; +@end +@implementation VCCHardDiskSave +@end + +@interface VCCPrinterOutput () +@property(nonatomic, readwrite, copy) NSData *bytes; +@property(nonatomic, readwrite) uint64_t revision, droppedBytes; +@property(nonatomic, readwrite) NSUInteger capacity; +@property(nonatomic, readwrite) BOOL enabled; +@end +@implementation VCCPrinterOutput +@end + +@interface VCCJoystickInputSnapshot () +@property(nonatomic, readwrite) NSUInteger x, y, buttons, mode; +@end +@implementation VCCJoystickInputSnapshot +@end + +@interface VCCMachineSnapshot () +@property(nonatomic, readwrite) NSUInteger pasteRemaining; +@property(nonatomic, readwrite) BOOL printerEnabled; +@property(nonatomic, readwrite) uint64_t printerRevision, printerDroppedBytes; +@property(nonatomic, readwrite) NSUInteger printerByteCount; +@property(nonatomic, readwrite) VCCMachineState state; +@property(nonatomic, readwrite) uint64_t generation, frames, cycles; +@property(nonatomic, readwrite, copy) NSArray *joystickInputs; +@property(nonatomic, readwrite) BOOL keyboardInputHeld; +@property(nonatomic, readwrite) uint64_t debuggerProgramRevision, debuggerMappingFingerprint, assistantMediaRevision; +@property(nonatomic, readwrite) BOOL debuggerDevelopmentAttached, debuggerAssemblyAttached, debuggerSourceStepping; +@property(nonatomic, readwrite) BOOL debuggerBankedDevelopment; +@property(nonatomic, readwrite) BOOL basicDebugAttached, assistantCompiledReturned; +@property(nonatomic, readwrite, nullable) NSNumber *assistantDirectPrompt, *assistantEmptyBASIC; +@property(nonatomic, readwrite, copy, nullable) NSString *assistantLoadedSource; +@property(nonatomic, readwrite) NSInteger basicStoppedLine; +@property(nonatomic, readwrite) NSInteger basicSourceOffset; +@property(nonatomic, readwrite) NSUInteger basicSourceLength; +@property(nonatomic, readwrite) BOOL basicStepping, basicCanStepOut; +@property(nonatomic, readwrite) NSInteger basicErrorLine; +@property(nonatomic, readwrite, copy) NSString *basicErrorCode; +@property(nonatomic, readwrite, copy) NSString *basicDebugStatus; +@property(nonatomic, readwrite) uint16_t programCounter; +@property(nonatomic, readwrite) CGRect activeVideoRect; +@property(nonatomic, readwrite, copy, nullable) NSData *pixels; +@property(nonatomic, readwrite, copy, nullable) NSString *errorMessage; +@property(nonatomic, readwrite) BOOL use6309, fastForward; +@property(nonatomic, readwrite) NSUInteger ramConfiguration, cpuOverclock, frameInterval; +@property(nonatomic, readwrite) uint64_t presentedFrame, pixelRevision; +@property(nonatomic, readwrite) NSInteger videoOutput; +@property(nonatomic, readwrite) BOOL audioEnabled; +@property(nonatomic, readwrite) BOOL driveWireEnabled; +@property(nonatomic, readwrite, copy) NSString *macShellStatus; +@property(nonatomic, readwrite) uint64_t macShellRequestID; +@property(nonatomic, readwrite) uint64_t audioUnderruns, audioOverruns, audioConsumed; +@property(nonatomic, readwrite) uint64_t audioSubmitted, audioSignalSamples, audioBuffered, audioStarts; +@property(nonatomic, readwrite) uint64_t audioMaximumRequest, audioMaximumRefillGapNanoseconds; +@property(nonatomic, readwrite) BOOL tapeMounted, tapeMotor, tapeDirty, tapeFast, tapeWAV; +@property(nonatomic, readwrite) NSInteger tapeMode; +@property(nonatomic, readwrite) uint64_t tapePosition, tapeLength; +@property(nonatomic, readwrite) uint64_t tapeReadEvents, tapeWriteEvents; +@property(nonatomic, readwrite) BOOL diskEnabled, diskBusy, diskMotor, diskConnected, diskEditorLocked; +@property(nonatomic, readwrite) BOOL hardDiskConnected, hardClockEnabled, hardClockReadOnly; +@property(nonatomic, readwrite) NSUInteger hardSelectedDrive, hardSector, hardStatus; +@property(nonatomic, readwrite) uint64_t hardFlushRequests; +@property(nonatomic, readwrite, copy) NSArray *hardDisks; +@property(nonatomic, readwrite) BOOL sdcReadOnly; +@property(nonatomic, readwrite, copy) NSArray *sdcDriveNames; +@property(nonatomic, readwrite, copy) NSString *sdcDirectory; +@property(nonatomic, readwrite, copy, nullable) NSString *sdcError; +@property(nonatomic, readwrite) uint64_t sdcReadCount, sdcWriteCount; +@property(nonatomic, readwrite) BOOL multiPakEnabled; +@property(nonatomic, readwrite) NSUInteger physicalSlot, romSlot, ioSlot; +@property(nonatomic, readwrite, copy) NSArray *cartridgeKinds; +@property(nonatomic, readwrite, copy) NSArray *cartridgeNames; +@property(nonatomic, readwrite, copy) NSString *diskROMName; +@property(nonatomic, readwrite) NSInteger diskSelectedDrive; +@property(nonatomic, readwrite) NSUInteger diskTrack, diskSector, diskSide; +@property(nonatomic, readwrite, copy) NSArray *disks; +@end +@implementation VCCCompiledRunLease { + std::atomic _valid; +} +- (instancetype)init { if ((self = [super init])) _valid.store(true); return self; } +- (BOOL)isValid { return _valid.load(); } +- (void)invalidate { _valid.store(false); } +@end + +@implementation VCCMachineSnapshot +- (NSArray *)assistantDeviceBlockers { + NSMutableArray *reasons = [NSMutableArray array]; + if (self.driveWireEnabled || ![self.macShellStatus isEqualToString:@"idle"]) + [reasons addObject:@"Disable DriveWire networking and end Mac shell access before running a shared program."]; + if (self.tapeMounted || self.tapeMode == 2) + [reasons addObject:@"Eject the cassette and end recording before running a shared program."]; + for (VCCDiskSnapshot *drive in [self.disks arrayByAddingObjectsFromArray:self.hardDisks]) + if (drive.mounted && !drive.writeProtected) { + [reasons addObject:@"Eject writable disks or enable write protection before running a shared program."]; + break; + } + for (NSNumber *kind in self.cartridgeKinds) + if (kind.integerValue != 0 && kind.integerValue != 2) { + [reasons addObject:@"Choose a BASIC setup with only a floppy controller before running a shared program."]; + break; + } + return reasons; +} +@end + +namespace { +struct Worker { + VCC::Mac::DriveWireShell shell; + uint64_t shellGeneration = 0, mediaRevision = 0; + std::string assistantPasteRun; + VCCCompiledRunLease *compiledKeyLease = nil; + VCCMachineSnapshot *compiledKeyExpected = nil; + bool compiledKeyAssembly = false; + std::optional> assistantProgram; + + VCC::Mac::MachineSession machine; + VCC::Mac::MacAudioOutput audio; + bool audioEnabled = false, fastForward = false; + VCC::Mac::FramePacer pacer; + VCC::Mac::AudioProgress audioProgress; + std::chrono::steady_clock::time_point previousAudioTick{}; + uint64_t maximumAudioGap = 0; + std::shared_ptr capturedFrame; + NSData* capturedPixels = nil; + uint64_t pixelRevision = 0; + bool closed = false; + std::string error; + std::string diskROMName; + struct Export { uint64_t token; std::vector bytes; }; + std::array, 4> exports; + std::array diskNames; + std::array readOnly{}; + uint64_t nextExport = 0; + struct DiskEdit { + uint64_t token, generation, mediaRevision; + unsigned drive; + std::vector original; + std::optional prepared; + bool hardDisk = false; + std::optional preparedHard; + }; + std::optional diskEdit; + uint64_t nextDiskEdit = 0; + void requireNoDiskEditor() const { + if (diskEdit) throw std::logic_error("Close the Disk Image Editor before running, resetting or changing the CoCo and its media."); + } + DiskEdit& requireDiskEditor(uint64_t token) { + if (!diskEdit || diskEdit->token != token) throw std::logic_error("This disk edit session has ended. Reopen the disk to edit it."); + auto& edit = *diskEdit; + const auto* floppyImage = !edit.hardDisk && floppy() ? floppy()->image(edit.drive) : nullptr; + const auto* hardImage = edit.hardDisk ? hardDevice->image(edit.drive) : nullptr; + const bool unchanged = edit.hardDisk ? hardImage && hardImage->bytes() == edit.original : + floppyImage && floppyImage->bytes() == edit.original; + if (closed || machine.snapshot().generation != edit.generation || mediaRevision != edit.mediaRevision || + !unchanged || (floppy() && floppy()->snapshot().busy)) + throw std::logic_error("The mounted disk or machine changed. Keep your edited copy and reopen the disk."); + return edit; + } + + std::shared_ptr hardDevice = std::make_shared(); + struct HardExport { uint64_t token; VCC::Devices::HardDiskImage::Save saved; }; + std::array,2> hardExports; + std::array hardNames; + std::array hardReadOnly{}; + void clearHardDrive(unsigned drive) { ++mediaRevision; hardExports[drive].reset(); hardNames[drive].clear(); hardReadOnly[drive] = false; } + std::shared_ptr diskDevice; + std::shared_ptr ramDevice; + std::array cartridgeKinds{2, 0, 0, 0, 0}; + VCC::Devices::CartridgeBus::Slots cartridgeDevices; + std::array cartridgeNames; + void applyLayout(bool enabled, unsigned physical) { + shell.stop(); + for (unsigned i = 0; i < 5; ++i) + if (cartridgeKinds[i] == 2) cartridgeDevices[i] = diskDevice; + machine.cartridges().configure(cartridgeDevices, enabled, physical); + } + VCC::Devices::Fd502Device* floppy() { return diskDevice.get(); } + VCC::Devices::Fd502Device& requireFloppy() { + auto* disk = floppy(); + if (!disk) throw std::logic_error("Choose a disk ROM to enable the floppy controller"); + return *disk; + } + void pauseForDisks() { + if (auto* disk = floppy(); disk && disk->snapshot().busy) + throw std::logic_error("Disk operation in progress. Press Run to let it finish, or reset the machine before changing disks."); + machine.pause(); + } + void clearDrive(unsigned drive) { ++mediaRevision; exports[drive].reset(); diskNames[drive].clear(); readOnly[drive] = false; } +}; +unsigned HardDriveIndex(NSInteger value) { + if (value < 0 || value > 1) throw std::invalid_argument("Hard disk drive must be 0 or 1"); + return static_cast(value); +} +unsigned DriveIndex(NSInteger value) { + if (value < 0 || value > 3) throw std::invalid_argument("Floppy drive must be 0 through 3"); + return static_cast(value); +} +std::vector OwnedBytes(NSData* data, NSUInteger limit) { + if (data.length > limit) throw std::invalid_argument("Selected file is too large"); + if (!data.length) return {}; + const auto* begin = static_cast(data.bytes); + return {begin, begin + data.length}; +} +std::vector CodeGuards(NSArray *addresses, NSArray *bytes) { + if (addresses.count != bytes.count || bytes.count > 65536) + throw std::invalid_argument("Code guard addresses and bytes must have matching bounded counts"); + auto parsed = DebugAddresses(addresses, 65536); + std::vector guards; + std::size_t total = 0; + for (NSUInteger i = 0; i < bytes.count; ++i) { + if (bytes[i].length > 65536 - total) throw std::invalid_argument("Code guards exceed address space"); + total += bytes[i].length; + guards.push_back({parsed[i], OwnedBytes(bytes[i], 65536)}); + } + return guards; +} +std::vector BankedModules(NSArray *> *modules) { + if (!modules || !modules.count || modules.count > 256) + throw std::invalid_argument("Supply 1 to 256 banked modules"); + std::vector result; + for (NSDictionary *module in modules) { + if (![module isKindOfClass:NSDictionary.class]) throw std::invalid_argument("Invalid banked module"); + NSString *identifier = module[@"id"]; + NSArray *pages = module[@"pages"], *addresses = module[@"addresses"], *bytes = module[@"bytes"]; + if (![identifier isKindOfClass:NSString.class] || ![pages isKindOfClass:NSArray.class] || + ![addresses isKindOfClass:NSArray.class] || ![bytes isKindOfClass:NSArray.class]) + throw std::invalid_argument("Banked modules require id, pages, addresses and bytes"); + for (id address in addresses) + if (![address isKindOfClass:NSNumber.class]) throw std::invalid_argument("Invalid banked code address"); + for (id data in bytes) + if (![data isKindOfClass:NSData.class]) throw std::invalid_argument("Invalid banked instruction bytes"); + VCC::Mac::DebugBankedModule parsed; + parsed.identifier = identifier.UTF8String; + parsed.guards = CodeGuards(addresses, bytes); + if (id qualified = module[@"breakpoints"]) { + if (![qualified isKindOfClass:NSArray.class]) throw std::invalid_argument("Module breakpoints must be an array"); + for (id point in qualified) + if (![point isKindOfClass:NSNumber.class] || CFGetTypeID((__bridge CFTypeRef)point) == CFBooleanGetTypeID()) + throw std::invalid_argument("Module breakpoints require logical integer addresses"); + parsed.breakpointAddresses = DebugAddresses(qualified, 1024); + } + if (!pages.count || pages.count > 8) throw std::invalid_argument("Supply 1 to 8 page mappings per module"); + for (NSDictionary *page in pages) { + if (![page isKindOfClass:NSDictionary.class]) throw std::invalid_argument("Invalid banked page mapping"); + NSNumber *logical = page[@"logicalPage"], *physical = page[@"physicalPage"]; + if (![logical isKindOfClass:NSNumber.class] || ![physical isKindOfClass:NSNumber.class]) + throw std::invalid_argument("Banked pages require logicalPage and physicalPage"); + const double l = logical.doubleValue, p = physical.doubleValue; + if (!std::isfinite(l) || !std::isfinite(p) || l < 0 || l > 7 || l != std::floor(l) || + p < 0 || p > 1023 || p != std::floor(p)) + throw std::invalid_argument("Invalid logical or physical RAM page"); + parsed.pages.push_back({static_cast(l), static_cast(p)}); + } + result.push_back(std::move(parsed)); + } + return result; +} +VCC::Mac::Snapshot AssemblyIdentity(VCCMachineSnapshot *snapshot) { + VCC::Mac::Snapshot expected; + expected.generation = snapshot.generation; + expected.debuggerProgramRevision = snapshot.debuggerProgramRevision; + expected.debuggerMappingFingerprint = snapshot.debuggerMappingFingerprint; + expected.cpu.PC = snapshot.programCounter; + expected.cycles = snapshot.cycles; + return expected; +} +VCC::Devices::DiskImage LoadFloppyImage(NSData *data, NSString *name, bool protect) { + using namespace VCC::Devices; + auto image = DiskImage::load(OwnedBytes(data, DiskImage::maxBytes), protect); + NSString *ext = name.pathExtension.lowercaseString; + if (([ext isEqualToString:@"dmk"] && image.format() != DiskFormat::DMK) || + ([ext isEqualToString:@"vdk"] && image.format() != DiskFormat::VDK)) + throw std::invalid_argument("The disk contents do not match the selected image format"); + return image; +} +VCCMachineSnapshot *Capture(Worker& worker) { + const auto value = worker.machine.snapshot(); + auto result = [VCCMachineSnapshot new]; + result.diskEditorLocked = worker.diskEdit.has_value(); + auto joystickInputs = [NSMutableArray arrayWithCapacity:2]; + for (const auto& port : value.joysticks) { + auto input = [VCCJoystickInputSnapshot new]; + input.x = port.x; input.y = port.y; input.buttons = port.buttons; input.mode = port.mode; + [joystickInputs addObject:input]; + } + result.joystickInputs = joystickInputs; + result.keyboardInputHeld = value.keyboardHeld; + switch (value.state) { + case VCC::Mac::RunState::Empty: result.state = VCCMachineStateEmpty; break; + case VCC::Mac::RunState::Paused: result.state = VCCMachineStatePaused; break; + case VCC::Mac::RunState::Running: result.state = VCCMachineStateRunning; break; + } + result.pasteRemaining = worker.machine.pasteRemaining(); + const auto& printer = worker.machine.printer(); + result.printerEnabled = printer.enabled(); result.printerRevision = printer.revision(); + result.printerDroppedBytes = printer.droppedBytes(); result.printerByteCount = printer.bytes().size(); + result.use6309 = value.configuration.processor == VCC::Mac::Processor::HD6309; + result.ramConfiguration = value.configuration.ram; + result.cpuOverclock = value.configuration.overclock; + result.frameInterval = value.configuration.frameInterval; + result.fastForward = worker.fastForward; + result.presentedFrame = value.frame ? value.frame->number : 0; + result.videoOutput = static_cast(value.videoOutput); + result.audioEnabled = worker.audioEnabled; + result.driveWireEnabled = worker.machine.driveWireEnabled(); + if (worker.shellGeneration != value.generation) { + worker.shell.stop(); + worker.shellGeneration = value.generation; + } + result.macShellStatus = [NSString stringWithUTF8String:worker.shell.status().c_str()]; + result.macShellRequestID = worker.shell.requestID(); + result.audioConsumed = worker.audio.buffer().consumed.load(); + result.audioSubmitted = worker.audio.buffer().submitted.load(); + result.audioSignalSamples = worker.audio.buffer().signalSamples.load(); + result.audioBuffered = worker.audio.buffer().size(); + result.audioStarts = worker.audio.starts(); + result.audioMaximumRequest = worker.audio.buffer().maximumRequest.load(); + result.audioMaximumRefillGapNanoseconds = worker.maximumAudioGap; + result.audioUnderruns = worker.audio.buffer().underruns.load(); + result.audioOverruns = worker.audio.buffer().overruns.load(); + const auto tape = worker.machine.cassette().snapshot(); + result.tapeMounted=tape.mounted; result.tapeMotor=tape.motor; result.tapeDirty=tape.dirty; + result.tapeFast=tape.fast; result.tapeWAV=tape.format==VCC::Mac::TapeFormat::WAV; + result.tapeMode=static_cast(tape.mode); result.tapePosition=tape.position; result.tapeLength=tape.length; + result.tapeReadEvents = tape.readEvents; result.tapeWriteEvents = tape.writeEvents; + auto& bus = worker.machine.cartridges(); + result.multiPakEnabled = bus.multiPak(); result.physicalSlot = bus.physicalSlot(); + result.romSlot = bus.romSlot(); result.ioSlot = bus.ioSlot(); + result.sdcDriveNames = @[@"", @""]; result.sdcDirectory = @""; result.sdcReadOnly = YES; + auto names = [NSMutableArray arrayWithCapacity:5]; + for (unsigned i = 0; i < 5; ++i) { + [names addObject:bus.at(i) ? (worker.cartridgeKinds[i] == 2 ? @"Floppy controller" : worker.cartridgeKinds[i] == 3 ? @"Virtual hard disk" : worker.cartridgeKinds[i] == 4 ? @"RAM disk (512 KB)" : worker.cartridgeKinds[i] == 5 ? @"Orchestra-90" : worker.cartridgeKinds[i] == 6 ? @"Speech/Sound Cartridge" : worker.cartridgeKinds[i] == 7 ? @"CoCo SDC" : [NSString stringWithUTF8String:worker.cartridgeNames[i].c_str()]) : @""]; + if (auto* sdc = dynamic_cast(bus.at(i)); sdc && (bus.multiPak() ? i > 0 : i == 0)) { + const auto status = sdc->snapshot(); + result.sdcDriveNames = @[[NSString stringWithUTF8String:status.drives[0].name.c_str()], [NSString stringWithUTF8String:status.drives[1].name.c_str()]]; + result.sdcDirectory = [NSString stringWithUTF8String:status.currentDirectory.c_str()]; + result.sdcReadOnly = status.writeProtected; + result.sdcReadCount = status.drives[0].reads + status.drives[1].reads; + result.sdcWriteCount = status.drives[0].writes + status.drives[1].writes; + if (!status.error.empty()) result.sdcError = [NSString stringWithUTF8String:status.error.c_str()]; + } + if (bus.at(i) == worker.hardDevice.get() && (bus.multiPak() ? i > 0 : i == 0)) result.hardDiskConnected = YES; + if (bus.at(i) && bus.at(i) == worker.floppy() && (bus.multiPak() ? i > 0 : i == 0)) result.diskConnected = YES; + } + result.cartridgeNames = names; + auto kinds = [NSMutableArray arrayWithCapacity:5]; + for (unsigned i = 0; i < 5; ++i) [kinds addObject:@(worker.cartridgeKinds[i])]; + result.cartridgeKinds = kinds; + result.diskROMName = [NSString stringWithUTF8String:worker.diskROMName.c_str()]; + result.diskSelectedDrive = -1; + auto* floppy = worker.floppy(); + result.diskEnabled = floppy != nullptr; + if (floppy) { + const auto disk = floppy->snapshot(); + result.diskBusy = disk.busy; result.diskMotor = disk.motor; + result.diskSelectedDrive = disk.drive; result.diskTrack = disk.head; + result.diskSector = disk.sector; result.diskSide = disk.side; + } + auto drives = [NSMutableArray arrayWithCapacity:4]; + for (unsigned i = 0; i < 4; ++i) { + auto disk = [VCCDiskSnapshot new]; + disk.name = [NSString stringWithUTF8String:worker.diskNames[i].c_str()]; + disk.sourceReadOnly = worker.readOnly[i]; + disk.readEvents = floppy ? floppy->readEvents(i) : 0; disk.writeEvents = floppy ? floppy->writeEvents(i) : 0; + if (const auto* image = floppy ? floppy->image(i) : nullptr) { + disk.mounted = YES; disk.dirty = image->dirty(); disk.writeProtected = image->writeProtected(); + switch (image->format()) { + case VCC::Devices::DiskFormat::DMK: disk.floppyExtension = @"dmk"; break; + case VCC::Devices::DiskFormat::VDK: disk.floppyExtension = @"vdk"; break; + default: { + NSString *ext = disk.name.pathExtension.lowercaseString; + disk.floppyExtension = [@[@"dsk", @"os9", @"jvc"] containsObject:ext] ? ext : @"dsk"; + } + } + disk.formatWriteProtected = image->formatWriteProtected(); + disk.tracks = image->geometry().tracks; disk.sides = image->geometry().sides; + disk.byteCount = image->bytes().size(); + } + [drives addObject:disk]; + } + result.disks = drives; + auto hardDrives = [NSMutableArray arrayWithCapacity:2]; + for (unsigned i = 0; i < 2; ++i) { + auto disk = [VCCDiskSnapshot new]; disk.name = [NSString stringWithUTF8String:worker.hardNames[i].c_str()]; + disk.sourceReadOnly = worker.hardReadOnly[i]; + disk.readEvents = worker.hardDevice->readEvents(i); disk.writeEvents = worker.hardDevice->writeEvents(i); + if (auto* image = worker.hardDevice->image(i)) { + disk.mounted = YES; disk.dirty = image->dirty(); disk.writeProtected = image->writeProtected(); disk.byteCount = image->bytes().size(); + } + [hardDrives addObject:disk]; + } + result.hardDisks = hardDrives; result.hardSelectedDrive = worker.hardDevice->selectedDrive(); + result.hardSector = worker.hardDevice->selectedSector(); result.hardStatus = worker.hardDevice->result(); + result.hardClockEnabled = worker.hardDevice->isClockEnabled(); result.hardClockReadOnly = worker.hardDevice->isClockReadOnly(); + result.hardFlushRequests = worker.hardDevice->flushRequests(); + if (worker.closed) result.state = VCCMachineStateClosed; + result.generation = value.generation; result.frames = value.frames; + result.debuggerProgramRevision = value.debuggerProgramRevision; result.debuggerMappingFingerprint = value.debuggerMappingFingerprint; + result.debuggerDevelopmentAttached = value.debuggerDevelopmentAttached; + result.debuggerBankedDevelopment = value.debuggerBankedDevelopment; + result.debuggerAssemblyAttached = value.debuggerAssemblyAttached; + result.assistantMediaRevision = worker.mediaRevision; + result.assistantCompiledReturned = worker.machine.sharedCompiledCallReturned(); + result.debuggerSourceStepping = value.debuggerSourceStepping; + result.basicDebugAttached = value.basicDebugAttached; result.basicStoppedLine = value.basicStoppedLine; + result.basicSourceOffset = value.basicSourceOffset; result.basicSourceLength = value.basicSourceLength; + result.basicStepping = value.basicStepping; + result.basicCanStepOut = value.basicCanStepOut; + result.basicErrorLine = value.basicErrorLine; + result.basicErrorCode = [NSString stringWithUTF8String:value.basicErrorCode.c_str()]; + result.basicDebugStatus = [NSString stringWithUTF8String:value.basicDebugStatus.c_str()]; + result.cycles = value.cycles; result.programCounter = value.cpu.PC; + if (value.frame != worker.capturedFrame) { + worker.capturedPixels = value.frame ? [NSData dataWithBytes:value.frame->pixels.data() + length:value.frame->pixels.size() * sizeof(std::uint32_t)] : nil; + worker.capturedFrame = value.frame; + ++worker.pixelRevision; + } + result.pixelRevision = worker.pixelRevision; + result.pixels = worker.capturedPixels; + const auto area = value.frame ? value.frame->activeArea : VCC::VideoRect{0, 0, 640, 480}; + result.activeVideoRect = CGRectMake(area.x, area.y, area.width, area.height); + if (!worker.error.empty()) result.errorMessage = [NSString stringWithUTF8String:worker.error.c_str()]; + return result; +} +void CheckAssistantGuestDevices(VCCMachineSnapshot *current) { + NSString *reason = current.assistantDeviceBlockers.firstObject; + if (reason) throw std::logic_error(reason.UTF8String); +} +void CheckCompiledRun(Worker& worker, VCCCompiledRunLease *lease, VCCMachineSnapshot *expected, bool assembly, bool finalScreen = false) { + if (!lease.valid) throw std::logic_error("stale_run"); + auto current = Capture(worker); + if (!worker.assistantProgram || *worker.assistantProgram != std::make_pair(current.generation, current.debuggerProgramRevision) || + current.generation != expected.generation || current.debuggerProgramRevision != expected.debuggerProgramRevision || + current.debuggerMappingFingerprint != expected.debuggerMappingFingerprint || current.use6309 != expected.use6309 || + !current.debuggerDevelopmentAttached || bool(current.debuggerAssemblyAttached) != assembly || + (current.state != VCCMachineStateRunning && current.state != VCCMachineStatePaused)) + throw std::logic_error("stale_run"); + CheckAssistantGuestDevices(current); + if (expected.assistantMediaRevision != current.assistantMediaRevision) + throw std::logic_error("media_changed"); + if (finalScreen) { + if (!worker.machine.sharedCompiledCallReturned()) throw std::logic_error("run_not_finished"); + return; + } + if (!worker.machine.sharedCompiledCallActive()) + throw std::logic_error(worker.machine.sharedCompiledCallReturned() ? "run_finished" : "unverified_program_entry"); +} +void AdvanceWorker(Worker& worker) { + if (worker.compiledKeyLease) { + if (worker.machine.pasteRemaining()) { + try { + CheckCompiledRun(worker, worker.compiledKeyLease, worker.compiledKeyExpected, worker.compiledKeyAssembly); + } catch (const std::exception&) { worker.machine.cancelPaste(); } + } + if (!worker.machine.pasteRemaining()) { + worker.compiledKeyLease = nil; + worker.compiledKeyExpected = nil; + } + } + worker.machine.advance(); +} +// Called inside the emulator queue before every assistant load, observation or key. +void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSString *source, + const char *sourceChanged = "The program in BASIC memory changed. Review it before continuing.") { + auto current = Capture(worker); + if (current.generation != expected.generation || current.debuggerProgramRevision != expected.debuggerProgramRevision) + throw std::logic_error("The CoCo or its loaded program changed. Start a new reviewed run."); + if (current.assistantMediaRevision != expected.assistantMediaRevision) + throw std::logic_error("The mounted media changed. Start a new reviewed run."); + if (current.state != VCCMachineStateRunning && current.state != VCCMachineStatePaused) + throw std::logic_error("Start a supported CoCo BASIC system before running."); + CheckAssistantGuestDevices(current); + if (worker.machine.basicReadSource() != [source UTF8String]) + throw std::logic_error(sourceChanged); +} + +} +@implementation VCCMachineController { + dispatch_queue_t _queue; + dispatch_source_t _timer; + std::shared_ptr _worker; +} +- (instancetype)init { + if ((self = [super init])) { + _worker = std::make_shared(); + // Audio production has a short deadline even when the window is inactive. + // Keep it off the main thread, with interactive scheduling priority. + auto attributes = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INTERACTIVE, 0); + _queue = dispatch_queue_create("com.brianholman.vccplus.mac.machine", attributes); + _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _queue); + // Refill on the owner queue; the real-time callback only consumes samples. + dispatch_source_set_timer(_timer, dispatch_time(DISPATCH_TIME_NOW, 0), 2*NSEC_PER_MSEC, NSEC_PER_MSEC/2); + auto worker = _worker; + dispatch_source_set_event_handler(_timer, ^{ + if (worker->closed) return; + try { + if (worker->machine.snapshot().state != VCC::Mac::RunState::Running) { + if (worker->audio.running()) worker->audio.stop(); + worker->pacer.reset(); worker->audioProgress.reset(); return; + } + if (worker->fastForward) { + // Yield after at most four frames or eight milliseconds so + // input, pause, and automatic media saves keep getting turns. + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(8); + for (unsigned i = 0; i < 4; ++i) { + AdvanceWorker(*worker); worker->machine.takeAudio(); + if (std::chrono::steady_clock::now() >= deadline) break; + } + } else if (worker->audioEnabled) { + const auto tick = std::chrono::steady_clock::now(); + if (worker->audio.running() && worker->previousAudioTick.time_since_epoch().count()) + worker->maximumAudioGap = std::max(worker->maximumAudioGap, uint64_t(std::chrono::duration_cast(tick - worker->previousAudioTick).count())); + worker->previousAudioTick = tick; + if(worker->audio.needsRestart()) { worker->audio.stop(); worker->audioProgress.reset(); } + // Roughly 100 ms ahead, at most four frames per queue turn. + // The physical audio clock paces production; guest clocks stay fixed. + for(unsigned i=0;i<4 && worker->audio.buffer().size()machine.takeAudio(); + worker->audio.buffer().write(samples.data(), samples.size()); + if (worker->machine.snapshot().state != VCC::Mac::RunState::Running) break; + } + if (worker->machine.snapshot().state != VCC::Mac::RunState::Running) { + worker->audio.stop(); worker->pacer.reset(); worker->audioProgress.reset(); return; + } + const bool starting = !worker->audio.running(); + if (!starting || worker->audio.buffer().size() >= VCC::Mac::audioTargetSamples) { + worker->audio.start(); + // Graph creation precedes consumption; start both timing + // measurements only after the output graph is running. + if (starting) { + worker->previousAudioTick = std::chrono::steady_clock::now(); + worker->audioProgress.reset(); + } + } + if (worker->audioProgress.stalled(std::chrono::steady_clock::now(), worker->audio.buffer().consumed.load())) + throw std::runtime_error("Audio output stopped consuming samples. Emulation continues without sound; turn Sound on to retry."); + } else { + if (worker->pacer.ready(std::chrono::steady_clock::now())) { + AdvanceWorker(*worker); worker->machine.takeAudio(); + } + } + } catch (const std::exception& error) { + worker->error=error.what(); worker->audio.stop(); worker->audioEnabled=false; + worker->pacer.reset(); worker->audioProgress.reset(); + } + }); + dispatch_resume(_timer); + } + return self; +} +- (void)perform:(void (^)(Worker&))operation completion:(VCCMachineCompletion)completion { + [self performAllowingDiskEditor:NO operation:operation completion:completion]; +} +- (void)inspect:(void (^)(Worker&))operation completion:(VCCMachineCompletion)completion { + [self performAllowingDiskEditor:YES operation:operation completion:completion]; +} +- (void)performAllowingDiskEditor:(BOOL)allow operation:(void (^)(Worker&))operation completion:(VCCMachineCompletion)completion { + auto worker = _worker; + dispatch_async(_queue, ^{ + try { if (!allow) worker->requireNoDiskEditor(); operation(*worker); } + catch (const std::exception& error) { worker->error = error.what(); } + VCCMachineSnapshot *snapshot = Capture(*worker); + dispatch_async(dispatch_get_main_queue(), ^{ completion(snapshot); }); + }); +} +- (void)command:(void (^)(Worker&))operation completion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.error.clear(); worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); operation(worker); + } completion:completion]; +} +- (void)applyProfile:(VCCMachineProfile*)profile completion:(void (^)(BOOL, VCCMachineSnapshot*))completion { + VCCMachineProfile* p = [profile copy]; + __block BOOL applied = NO; + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + if (p.ram < 0 || p.ram > 3 || p.overclock < 1 || p.overclock > 16 || p.frameInterval < 1 || p.frameInterval > 6 || + p.videoOutput < 0 || p.videoOutput > 2 || p.physicalSlot < 1 || p.physicalSlot > 4 || + !std::isfinite(p.volume) || p.volume < 0 || p.volume > 1 || + p.kinds.count != 5 || p.cartridgeROMs.count != 5 || p.cartridgeNames.count != 5 || + p.sdcFolders.count != 5 || p.sdcReadOnly.count != 5 || + p.images.count != 6 || p.imageNames.count != 6 || p.readOnly.count != 6 || p.protectedImages.count != 6) + throw std::invalid_argument("Invalid profile configuration"); + auto systemROM = OwnedBytes(p.systemROM, 32768); + if (p.systemROM && systemROM.size() != 32768) throw std::invalid_argument("A 32 KiB system ROM is required"); + // Build disconnected replacements. Parsing failures leave the current + // CPU, media, dirty flags and save acknowledgement tokens untouched. + std::shared_ptr floppy; + if (p.diskROM) floppy = std::make_shared(OwnedBytes(p.diskROM, 16384)); + auto hard = std::make_shared(); + hard->configureClock(p.clockEnabled, p.clockReadOnly); + for (unsigned i = 0; i < 6; ++i) { + if (![p.images[i] length]) continue; + const bool protect = [p.readOnly[i] boolValue] || [p.protectedImages[i] boolValue]; + if (i < 4) { + if (!floppy) throw std::invalid_argument("A floppy image requires a floppy ROM"); + floppy->mount(i, LoadFloppyImage(p.images[i], p.imageNames[i], protect)); + } else hard->mount(i - 4, VCC::Devices::HardDiskImage(OwnedBytes(p.images[i], VCC::Devices::HardDiskImage::maxBytes), protect)); + } + VCC::Mac::CassetteDeck tape; + if (p.cassette) tape.mount(OwnedBytes(p.cassette, VCC::Mac::CassetteDeck::maxBytes), + p.cassetteWAV ? VCC::Mac::TapeFormat::WAV : VCC::Mac::TapeFormat::CAS); + tape.setFast(p.fastCassette); + VCC::Devices::CartridgeBus::Slots slots; + std::array kinds; std::array names; + unsigned floppyCount = 0, hardCount = 0, ramCount = 0, orchestraCount = 0, speechCount = 0, sdcCount = 0; + std::shared_ptr ram; + for (unsigned i = 0; i < 5; ++i) { + kinds[i] = [p.kinds[i] intValue]; names[i] = [p.cartridgeNames[i] UTF8String]; + switch (kinds[i]) { + case 0: break; + case 1: slots[i] = std::make_shared(OwnedBytes(p.cartridgeROMs[i], 262144)); break; + case 2: slots[i] = floppy; if (i) ++floppyCount; break; + case 3: slots[i] = hard; if (i) ++hardCount; break; + case 4: + if (!ram) ram = std::make_shared(); + slots[i] = ram; if (i) ++ramCount; break; + case 7: + if ([p.cartridgeROMs[i] length]) slots[i] = std::make_shared( + OwnedBytes(p.cartridgeROMs[i], 16384), [p.sdcFolders[i] UTF8String], [p.sdcReadOnly[i] boolValue]); + if (i) ++sdcCount; break; + case 6: + slots[i] = std::make_shared(OwnedBytes(p.cartridgeROMs[i], 6144)); + if (i) ++speechCount; break; + case 5: + slots[i] = std::make_shared(OwnedBytes(p.cartridgeROMs[i], 8192)); + if (i) ++orchestraCount; break; + default: throw std::invalid_argument("Unknown profile cartridge device"); + } + } + if (floppyCount > 1 || hardCount > 1 || ramCount > 1 || orchestraCount > 1 || speechCount > 1 || sdcCount > 1) throw std::invalid_argument("Duplicate Multi-Pak devices"); + auto* oldFloppy = worker.floppy(); + if (oldFloppy && oldFloppy->snapshot().busy) throw std::logic_error("Finish the floppy operation before loading a profile"); + for (unsigned i = 0; i < 4; ++i) + if (oldFloppy && oldFloppy->image(i) && oldFloppy->image(i)->dirty()) + throw std::logic_error("Save or discard modified floppy images before loading a profile"); + for (unsigned i = 0; i < 2; ++i) + if (worker.hardDevice->image(i) && worker.hardDevice->image(i)->dirty()) + throw std::logic_error("Save or discard modified hard disks before loading a profile"); + const auto oldTape = worker.machine.cassette().snapshot(); + if (oldTape.dirty || oldTape.mode == VCC::Mac::TapeMode::Recording) + throw std::logic_error("Stop and export or discard the cassette recording before loading a profile"); + worker.error.clear(); worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); worker.previousAudioTick = {}; + worker.machine.shutdown(); + worker.diskDevice = std::move(floppy); worker.hardDevice = std::move(hard); + worker.ramDevice = std::move(ram); + worker.cartridgeDevices = std::move(slots); worker.cartridgeKinds = kinds; worker.cartridgeNames = std::move(names); + worker.diskROMName = p.diskROMName.UTF8String; + for (unsigned i = 0; i < 4; ++i) { + worker.clearDrive(i); worker.diskNames[i] = [p.imageNames[i] UTF8String]; worker.readOnly[i] = [p.readOnly[i] boolValue]; + } + for (unsigned i = 0; i < 2; ++i) { + worker.clearHardDrive(i); worker.hardNames[i] = [p.imageNames[i+4] UTF8String]; worker.hardReadOnly[i] = [p.readOnly[i+4] boolValue]; + } + worker.machine.cassette() = std::move(tape); + worker.applyLayout(p.multiPak, unsigned(p.physicalSlot)); + VCC::Mac::MachineConfiguration config; + config.processor = p.use6309 ? VCC::Mac::Processor::HD6309 : VCC::Mac::Processor::MC6809; + config.ram = unsigned(p.ram); config.overclock = unsigned(p.overclock); config.frameInterval = unsigned(p.frameInterval); + worker.machine.configure(config); worker.machine.setVideoOutput(static_cast(p.videoOutput)); + worker.fastForward = p.fastForward; worker.audioEnabled = p.sound; worker.audio.buffer().gain.store(p.volume); + applied = YES; + if (p.systemROM) worker.machine.load(systemROM, config.processor); + } completion:^(VCCMachineSnapshot* snapshot) { completion(applied, snapshot); }]; +} +- (void)configureMachineWith6309:(BOOL)use6309 ram:(NSInteger)ram overclock:(NSInteger)overclock frameInterval:(NSInteger)interval fastForward:(BOOL)fastForward completion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + // Reject before touching audio, RAM, preferences, or media. + if (ram < 0 || ram > 3 || overclock < 1 || overclock > 16 || interval < 1 || interval > 6) + throw std::invalid_argument("Unsupported machine settings"); + VCC::Mac::MachineConfiguration value; + value.processor = use6309 ? VCC::Mac::Processor::HD6309 : VCC::Mac::Processor::MC6809; + value.ram = unsigned(ram); value.overclock = unsigned(overclock); value.frameInterval = unsigned(interval); + const auto previous = worker.machine.snapshot().configuration; + const bool restart = previous.processor != value.processor || previous.ram != value.ram; + if (restart) { + if (auto* disk = worker.floppy(); disk && disk->snapshot().busy) + throw std::logic_error("Wait for the disk operation to finish before changing CPU or memory."); + if (worker.machine.cassette().snapshot().mode == VCC::Mac::TapeMode::Recording) + throw std::logic_error("Stop the cassette recording before changing CPU or memory."); + } + if (restart || worker.fastForward != bool(fastForward)) { + worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); + worker.previousAudioTick = {}; + } + worker.machine.configure(value); + worker.fastForward = fastForward; worker.error.clear(); + } completion:completion]; +} +- (void)setVideoOutput:(NSInteger)output completion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + if (output < 0 || output > 2) throw std::invalid_argument("Unsupported video output"); + worker.machine.setVideoOutput(static_cast(output)); + worker.error.clear(); + } completion:completion]; +} +- (void)loadDiagnosticWithCompletion:(VCCMachineCompletion)completion { + [self loadDiagnosticWith6309:NO completion:completion]; +} +- (void)loadDiagnosticWith6309:(BOOL)use6309 completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { + worker.machine.loadDiagnostic(use6309 ? VCC::Mac::Processor::HD6309 : VCC::Mac::Processor::MC6809); + } completion:completion]; +} +- (void)loadROM:(NSData *)rom use6309:(BOOL)use6309 completion:(VCCMachineCompletion)completion { + NSData *owned = [rom copy]; + [self command:^(Worker& worker) { + if (owned.length != 0x8000) throw std::invalid_argument("A 32 KiB CoCo 3 ROM image is required"); + const auto *begin = static_cast(owned.bytes); + worker.machine.load({begin, begin + owned.length}, use6309 ? VCC::Mac::Processor::HD6309 : VCC::Mac::Processor::MC6809); + } completion:completion]; +} +- (void)setJoystick:(NSUInteger)port x:(NSUInteger)x y:(NSUInteger)y buttons:(NSUInteger)buttons mode:(NSUInteger)mode { + auto worker = _worker; + dispatch_async(_queue, ^{ if (!worker->closed && !worker->diskEdit) worker->machine.setJoystick((unsigned)port, (unsigned)MIN(x, 16383), (unsigned)MIN(y, 16383), (unsigned)buttons, (unsigned)mode); }); +} +- (void)pasteChords:(NSArray *)chords completion:(VCCMachineCompletion)completion { + NSArray *owned = [chords copy]; + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.error.clear(); + if (owned.count > 65536) throw std::invalid_argument("Paste is too large"); + std::vector keys; + for (NSNumber* value in owned) keys.push_back(value.unsignedLongLongValue); + worker.machine.paste(keys); + worker.assistantPasteRun.clear(); + worker.compiledKeyLease = nil; worker.compiledKeyExpected = nil; + } completion:completion]; +} +- (void)assistantPaste:(NSArray *)chords runID:(NSString *)runID direct:(BOOL)direct expected:(VCCMachineSnapshot *)expected source:(NSString *)source completion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { + worker.error.clear(); + CheckAssistantMachine(worker, expected, source); + if (worker.machine.pasteRemaining()) throw std::logic_error("Guest keyboard input is pending."); + if (worker.machine.snapshot().state != VCC::Mac::RunState::Running || chords.count < 1 || chords.count > 8 || + (direct ? !worker.machine.basicAtDirectPrompt() : !worker.machine.basicExecutingStoredSource())) + throw std::logic_error("The guest is not at the expected BASIC input state."); + std::vector keys; + for (NSNumber *value in chords) keys.push_back(value.unsignedLongLongValue); + worker.machine.paste(keys); + worker.assistantPasteRun = runID.UTF8String; + worker.compiledKeyLease = nil; worker.compiledKeyExpected = nil; + } completion:completion]; +} +- (void)cancelAssistantPaste:(NSString *)runID { + auto worker = _worker; + dispatch_async(_queue, ^{ + if (worker->assistantPasteRun == runID.UTF8String) { + worker->machine.cancelPaste(); + worker->assistantPasteRun.clear(); + } + }); +} +- (void)compiledGuest:(VCCCompiledRunLease *)lease runID:(NSString *)runID expected:(VCCMachineSnapshot *)expected assembly:(BOOL)assembly key:(NSNumber *)key readScreen:(BOOL)readScreen finalScreen:(BOOL)finalScreen completion:(void (^)(NSString *, VCCMachineSnapshot *))completion { + __block NSString *text = nil; + [self perform:^(Worker& worker) { + worker.error.clear(); + CheckCompiledRun(worker, lease, expected, assembly, finalScreen); + if (finalScreen) { + if (const auto *saved = worker.machine.sharedCompiledReturnScreen()) + text = [NSString stringWithUTF8String:saved->c_str()]; + return; + } + if (readScreen) text = [NSString stringWithUTF8String:worker.machine.copyScreenText().c_str()]; + if (key) { + if (worker.machine.snapshot().state != VCC::Mac::RunState::Running) throw std::logic_error("run_paused"); + if (worker.machine.pasteRemaining()) throw std::logic_error("input_busy"); + worker.machine.pasteSharedCompiledKey(key.unsignedLongLongValue); + worker.assistantPasteRun = runID.UTF8String; + worker.compiledKeyLease = lease; + worker.compiledKeyExpected = expected; + worker.compiledKeyAssembly = assembly; + } + } completion:^(VCCMachineSnapshot *snapshot) { completion(text, snapshot); }]; +} +- (void)checkReviewedBASIC:(VCCMachineSnapshot *)expected source:(NSString *)source completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { CheckAssistantMachine(worker, expected, source); } completion:completion]; +} +- (void)assistantScreen:(VCCMachineSnapshot *)expected source:(NSString *)source completion:(void (^)(NSDictionary*, VCCMachineSnapshot*))completion { + __block NSDictionary *observation = nil; + [self perform:^(Worker& worker) { + worker.error.clear(); + CheckAssistantMachine(worker, expected, source); + auto text = worker.machine.copyScreenText(); + auto page = worker.machine.debuggerGraphicsPreview(true, true, 0, VCC::Mac::DebugGraphicsMode::SG4, false); + auto colors = [NSMutableArray array]; + if (page.text && page.bytesPerCell == 2 && page.width && page.linesPerRow) { + // Sample the middle of an actual space between words in each text row. + // Its glyph is blank, so the renderer's pixel gives the background for + // this cell under the active RGB/composite signal and the live palette. + unsigned row = 0, previous = ~0u; + for (unsigned y = 0; y < page.height; ++y) { + unsigned offset = page.rowByteOffsets[y]; + if (offset == previous) continue; + previous = offset; + unsigned columns = page.bytesPerRow / page.bytesPerCell; + bool word = false; + for (unsigned c = 0; c + 1 < columns; ++c) { + auto cell = offset + c * page.bytesPerCell; + if (page.bytes[cell] != ' ') { word = true; continue; } + if (!word || page.bytes[cell + page.bytesPerCell] == ' ') continue; + unsigned px = (2*c+1) * page.width / (2*columns); + unsigned py = std::min(y + page.linesPerRow/2, page.height-1); + unsigned rgb = page.pixels[py*page.width + px] & 0xffffff; + unsigned attribute = page.bytes[cell+1]; + [colors addObject:@{@"row":@(row), @"column":@(c), @"rgb":@(rgb), @"attribute":@(attribute), + @"palette_index":@(attribute & 7), @"palette_value":@(page.palette[attribute & 7])}]; + break; + } + ++row; + } + } + observation = @{@"text":[NSString stringWithUTF8String:text.c_str()], @"colors":colors, + @"columns":@(page.bytesPerRow / page.bytesPerCell), @"direct_prompt":@(worker.machine.basicAtDirectPrompt())}; + } completion:^(VCCMachineSnapshot *snapshot) { completion(observation, snapshot); }]; +} +- (void)cancelPasteWithCompletion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { worker.machine.cancelPaste(); } completion:completion]; +} +- (void)copyScreenTextWithCompletion:(void (^)(NSString*, VCCMachineSnapshot*))completion { + __block NSString* text = nil; + [self inspect:^(Worker& worker) { + worker.error.clear(); + text = [NSString stringWithUTF8String:worker.machine.copyScreenText().c_str()]; + } completion:^(VCCMachineSnapshot* snapshot) { completion(text, snapshot); }]; +} +- (void)inspectScreenTextWithCompletion:(void (^)(NSString*, VCCMachineSnapshot*))completion { + __block NSString* text = nil; + [self inspect:^(Worker& worker) { + // Unlike Copy, this is a probe: boot and games may legitimately have no + // readable hardware text. Preserve any existing machine error as well. + try { text = [NSString stringWithUTF8String:worker.machine.copyScreenText().c_str()]; } + catch (const std::logic_error&) { } + } completion:^(VCCMachineSnapshot* snapshot) { completion(text, snapshot); }]; +} +- (void)setPrinterEnabled:(BOOL)enabled completion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.error.clear(); worker.machine.printer().setEnabled(enabled); + } completion:completion]; +} +- (void)clearPrinterOutputWithCompletion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.error.clear(); worker.machine.printer().clear(); + } completion:completion]; +} +- (void)printerOutputWithCompletion:(void (^)(VCCPrinterOutput *, VCCMachineSnapshot *))completion { + auto output = [VCCPrinterOutput new]; + [self inspect:^(Worker& worker) { + const auto& printer = worker.machine.printer(); + output.bytes = [NSData dataWithBytes:printer.bytes().data() length:printer.bytes().size()]; + output.revision = printer.revision(); output.droppedBytes = printer.droppedBytes(); + output.enabled = printer.enabled(); output.capacity = VCC::Mac::PrinterCapture::capacity; + } completion:^(VCCMachineSnapshot* snapshot) { completion(output, snapshot); }]; +} +- (void)setKeyboardMask:(uint64_t)keys { + auto worker = _worker; + dispatch_async(_queue, ^{ if (!worker->closed && !worker->diskEdit) worker->machine.setKeyboard(keys); }); +} +- (void)launchAssembly:(NSData *)binary points:(NSArray *)points addresses:(NSArray *)addresses bytes:(NSArray *)bytes pauseAtEntry:(BOOL)pauseAtEntry requires6309:(BOOL)requires6309 generation:(uint64_t)generation revision:(uint64_t)revision mapping:(uint64_t)mapping completion:(VCCMachineCompletion)completion { + [self launchAssembly:binary points:points addresses:addresses bytes:bytes pauseAtEntry:pauseAtEntry requires6309:requires6309 + generation:generation revision:revision mapping:mapping shared:NO completion:completion]; +} +- (void)launchAssembly:(NSData *)binary points:(NSArray *)points addresses:(NSArray *)addresses bytes:(NSArray *)bytes pauseAtEntry:(BOOL)pauseAtEntry requires6309:(BOOL)requires6309 generation:(uint64_t)generation revision:(uint64_t)revision mapping:(uint64_t)mapping shared:(BOOL)shared completion:(VCCMachineCompletion)completion { + NSData *image = [binary copy]; + NSArray *stops = [points copy], *locations = [addresses copy]; + NSArray *instructions = [[NSArray alloc] initWithArray:bytes copyItems:YES]; + [self command:^(Worker& worker) { + if (shared) CheckAssistantGuestDevices(Capture(worker)); + worker.machine.launchAssembly(OwnedBytes(image, VCC::Mac::BinaryImage::maxBytes), DebugAddresses(stops, 1024), + CodeGuards(locations, instructions), pauseAtEntry, requires6309, generation, revision, mapping); + if (shared) { + const auto active = worker.machine.snapshot(); + worker.machine.armSharedCompiledCall(); + worker.assistantProgram = std::make_pair(active.generation, active.debuggerProgramRevision); + } + } completion:completion]; +} +- (void)pauseAssembly:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.machine.pauseAssembly(AssemblyIdentity(expected)); } completion:completion]; +} +- (void)controlAssembly:(BOOL)step expected:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.machine.controlAssembly(step, AssemblyIdentity(expected)); } completion:completion]; +} +- (void)updateAssembly:(NSArray *)points expected:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion { + NSArray *stops = [points copy]; + [self command:^(Worker& worker) { worker.machine.updateAssembly(DebugAddresses(stops, 1024), AssemblyIdentity(expected)); } completion:completion]; +} +- (void)clearAssembly:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.machine.clearAssembly(AssemblyIdentity(expected)); } completion:completion]; +} +- (void)startReviewedC:(NSData *)binary disk:(NSData *)disk name:(NSString *)name stop:(uint16_t)stop expected:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { + CheckAssistantMachine(worker, expected, @"", "occupied_basic_program"); + auto current = Capture(worker); + if (disk && (current.disks.count < 1 || current.disks[0].mounted)) + throw std::logic_error("Eject the disk in FD0 before running the Hello Disk example."); + if (current.basicDebugAttached || current.debuggerAssemblyAttached || + (current.debuggerDevelopmentAttached && !worker.machine.sharedCompiledCallReturned()) || current.pasteRemaining) + throw std::logic_error("Finish the active debugging or paste session before running this C build."); + if (!worker.machine.basicAtDirectPrompt()) + throw std::logic_error("Waiting for an empty Disk BASIC prompt."); + auto program = OwnedBytes(binary, VCC::Mac::BinaryImage::maxBytes); + if (disk) { + auto image = LoadFloppyImage(disk, name, true); + worker.requireFloppy().mount(0, std::move(image)); + worker.clearDrive(0); worker.diskNames[0] = name.UTF8String; worker.readOnly[0] = true; + } + try { + worker.machine.debuggerLoadBinary(program, stop); + const auto active = worker.machine.snapshot(); + worker.machine.armSharedCompiledCall(); + worker.assistantProgram = std::make_pair(active.generation, active.debuggerProgramRevision); + } catch (...) { + if (disk) { worker.requireFloppy().eject(0, false); worker.clearDrive(0); } + throw; + } + } completion:completion]; +} +- (void)continueReviewedC:(VCCMachineSnapshot *)expected name:(NSString *)name stop:(uint16_t)stop bytes:(NSData *)bytes completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { + auto current = Capture(worker); + const NSUInteger byteCount = bytes.length; + CheckAssistantGuestDevices(current); + if (current.generation != expected.generation || current.debuggerProgramRevision != expected.debuggerProgramRevision || + current.debuggerMappingFingerprint != expected.debuggerMappingFingerprint || + current.state != VCCMachineStatePaused || current.programCounter != stop || !current.debuggerDevelopmentAttached || + current.debuggerAssemblyAttached || !byteCount || + (name.length && (!current.disks.firstObject.writeProtected || ![current.disks.firstObject.name isEqualToString:name]))) + throw std::logic_error("The source stop, running program, or mounted project disk changed."); + if (byteCount > 65536u - stop) + throw std::invalid_argument("Memory range is outside the selected address space"); + auto actual = worker.machine.debuggerMemoryRange(stop, static_cast(byteCount), false); + if (actual.bytes.size() != byteCount || memcmp(actual.bytes.data(), bytes.bytes, byteCount) || + std::find(actual.available.begin(), actual.available.end(), 0) != actual.available.end()) + throw std::logic_error("The instruction in guest memory differs from the linked source map."); + if (name.length) { worker.machine.debuggerClearDevelopmentBreakpoints(); worker.machine.resume(); } + else worker.machine.debuggerContinueFromEntry(stop); + } completion:completion]; +} +- (void)ejectReviewedCDisk:(NSString *)name completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { + if (worker.readOnly[0] && worker.diskNames[0] == name.UTF8String) { + worker.requireFloppy().eject(0, false); worker.clearDrive(0); + } + } completion:completion]; +} +- (void)debuggerLoadBinary:(NSData *)binary breakpoint:(uint16_t)breakpoint completion:(VCCMachineCompletion)completion { + NSData *owned = [binary copy]; + [self command:^(Worker& worker) { + worker.machine.debuggerLoadBinary(OwnedBytes(owned, VCC::Mac::BinaryImage::maxBytes), breakpoint); + } completion:completion]; +} +- (void)debuggerLoadBinary:(NSData *)binary breakpoints:(NSArray *)breakpoints completion:(VCCMachineCompletion)completion { + NSData *owned = [binary copy]; NSArray *points = [breakpoints copy]; + [self command:^(Worker& worker) { + worker.machine.debuggerLoadBinary(OwnedBytes(owned, VCC::Mac::BinaryImage::maxBytes), DebugAddresses(points, 1024)); + } completion:completion]; +} +- (void)debuggerArmDevelopmentBreakpoints:(NSArray *)breakpoints guardAddresses:(NSArray *)guardAddresses guardBytes:(NSArray *)guardBytes completion:(VCCMachineCompletion)completion { + NSArray *points = [breakpoints copy], *addresses = [guardAddresses copy]; + NSArray *bytes = [[NSArray alloc] initWithArray:guardBytes copyItems:YES]; + [self command:^(Worker& worker) { + auto guards = CodeGuards(addresses, bytes); + worker.machine.debuggerArmDevelopmentBreakpoints(DebugAddresses(points, 1024), guards); + } completion:completion]; +} +- (void)debuggerArmBankedDevelopmentBreakpoints:(NSArray *)breakpoints modules:(NSArray *> *)modules completion:(VCCMachineCompletion)completion { + NSArray *points = [breakpoints copy]; + // Freeze the nested arrays and NSData before crossing onto the machine queue. + NSArray *owned = CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (__bridge CFPropertyListRef)modules, kCFPropertyListImmutable)); + [self command:^(Worker& worker) { + worker.machine.debuggerArmBankedDevelopmentBreakpoints(DebugAddresses(points, 1024), BankedModules(owned)); + } completion:completion]; +} +- (void)debuggerClearDevelopmentBreakpointsWithCompletion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.machine.debuggerClearDevelopmentBreakpoints(); } completion:completion]; +} +- (void)quickLoadBinary:(NSData *)binary completion:(VCCMachineCompletion)completion { + NSData *owned = [binary copy]; + [self command:^(Worker& worker) { + worker.machine.quickLoad(OwnedBytes(owned, VCC::Mac::BinaryImage::maxBytes)); + } completion:completion]; +} +- (void)requestNitros9BootWithCompletion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.machine.requestNitros9Boot(); + } completion:completion]; +} +- (void)resumeWithCompletion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.machine.resume(); } completion:completion]; +} +- (void)debuggerSnapshotAtAddress:(uint16_t)address followPC:(BOOL)followPC memoryAddress:(uint16_t)memoryAddress completion:(void (^)(VCCDebuggerSnapshot *))completion { + [self debuggerSnapshotAtAddress:address followPC:followPC memoryAddress:memoryAddress physicalAddress:0 physicalMemory:NO completion:completion]; +} +- (void)debuggerSnapshotAtAddress:(uint16_t)address followPC:(BOOL)followPC memoryAddress:(uint16_t)memoryAddress physicalAddress:(uint32_t)physicalAddress physicalMemory:(BOOL)physicalMemory completion:(void (^)(VCCDebuggerSnapshot *))completion { + auto result = [VCCDebuggerSnapshot new]; + result.registers = @{}; result.instructions = @[]; result.breakpoints = @[]; result.disabledBreakpoints = @[]; + result.memory = [NSData data]; result.memoryAvailable = [NSData data]; + result.logicalMemory = [NSData data]; result.logicalMemoryAvailable = [NSData data]; + result.memoryAddress = memoryAddress; result.stopReason = @"Load a machine to inspect it."; + result.physicalMemory = [NSData data]; + result.mmu = [VCCMMUSnapshot new]; + result.mmu.task0 = @[]; result.mmu.task1 = @[]; result.mmu.effective = @[]; + [self inspect:^(Worker& worker) { + if (worker.closed) return; + if (worker.machine.snapshot().state == VCC::Mac::RunState::Empty) return; + // An inspector can outlive a profile/RAM-size change. Recover its + // physical cursor on this queue using the current installed capacity. + constexpr uint32_t capacities[] = {0x20000, 0x80000, 0x200000, 0x800000}; + const auto capacity = capacities[worker.machine.snapshot().configuration.ram]; + const auto physicalStart = physicalAddress < capacity ? physicalAddress : capacity - 256; + const auto debug = worker.machine.debuggerSnapshot(0, 65536, physicalStart, physicalMemory ? 256 : 0); + result.logicalMemory = [NSData dataWithBytes:debug.memory.data() length:debug.memory.size()]; + result.logicalMemoryAvailable = [NSData dataWithBytes:debug.memoryAvailable.data() length:debug.memoryAvailable.size()]; + const auto& mapping = debug.mmu; + auto mmu = result.mmu; + mmu.enabled = mapping.Enabled; mmu.activeTask = mapping.ActiveTask; + mmu.ramVectors = mapping.RamVectors; mmu.romMap = mapping.RomMap; + mmu.allRAM = mapping.AllRAM; mmu.prefix = mapping.Prefix; + mmu.ramByteCount = mapping.RAMBytes; mmu.vectorRAMAddress = mapping.RAMVectorAddress; + auto task0 = [NSMutableArray array], task1 = [NSMutableArray array]; + auto effective = [NSMutableArray array]; + for (unsigned i = 0; i < 8; ++i) { + [task0 addObject:@(mapping.Task0[i])]; [task1 addObject:@(mapping.Task1[i])]; + const auto& bank = mapping.Effective[i]; + auto row = [VCCMemoryMapping new]; + row.page = bank.Page; row.ramAddress = bank.RAMStart; + row.source = static_cast(bank.Source); row.sourceAddress = bank.SourceStart; + [effective addObject:row]; + } + mmu.task0 = task0; mmu.task1 = task1; mmu.effective = effective; + result.physicalAddress = debug.physicalAddress; + result.physicalMemory = [NSData dataWithBytes:debug.physicalMemory.data() length:debug.physicalMemory.size()]; + const auto& cpu = debug.cpu; + auto registers = [NSMutableDictionary dictionaryWithDictionary:@{ + @"A": @(cpu.A), @"B": @(cpu.B), @"DP": @(cpu.DP), @"CC": @(cpu.CC), + @"X": @(cpu.X), @"Y": @(cpu.Y), @"U": @(cpu.U), @"S": @(cpu.S), @"PC": @(cpu.PC)}]; + const bool use6309 = worker.machine.snapshot().configuration.processor == VCC::Mac::Processor::HD6309; + if (use6309) [registers addEntriesFromDictionary:@{@"E": @(cpu.E), @"F": @(cpu.F), @"V": @(cpu.V), @"MD": @(cpu.MD)}]; + result.registers = registers; + auto breakpoints = [NSMutableArray array]; + for (auto pc : debug.breakpoints) [breakpoints addObject:@(pc)]; + result.breakpoints = breakpoints; + auto disabled = [NSMutableArray array]; + for (auto point : debug.disabledBreakpoints) [disabled addObject:@(point)]; + result.disabledBreakpoints = disabled; + result.stopReason = [NSString stringWithUTF8String:debug.stopReason.c_str()]; + auto instructions = [NSMutableArray array]; + uint16_t cursor = followPC ? cpu.PC : address; + for (unsigned row = 0; row < 48; ++row) { + const auto line = VCC::Mac::Disassemble(debug.memory, cpu, use6309, cursor, 1).front(); + auto item = [VCCDebugInstruction new]; item.address = line.address; + bool available = true; + for (std::size_t i = 0; i < line.bytes.size(); ++i) + available &= debug.memoryAvailable[uint16_t(line.address + i)] != 0; + item.bytes = available ? [NSData dataWithBytes:line.bytes.data() length:line.bytes.size()] : [NSData data]; + item.mnemonic = available ? [NSString stringWithUTF8String:line.mnemonic.c_str()] : @"—"; + item.operand = available ? [NSString stringWithUTF8String:line.operand.c_str()] : @"I/O unavailable"; + item.valid = available && line.valid; [instructions addObject:item]; + // Unknown I/O bytes cannot determine an instruction's length. + // Advance one address so safe bytes on the far side remain visible. + cursor = uint16_t(cursor + (available ? line.bytes.size() : 1)); + } + result.instructions = instructions; + uint8_t bytes[256], available[256]; + for (unsigned i = 0; i < 256; ++i) { + const auto offset = uint16_t(memoryAddress + i); + bytes[i] = debug.memory[offset]; available[i] = debug.memoryAvailable[offset]; + } + result.memory = [NSData dataWithBytes:bytes length:sizeof(bytes)]; + result.memoryAvailable = [NSData dataWithBytes:available length:sizeof(available)]; + } completion:^(VCCMachineSnapshot *snapshot) { + result.machine = snapshot; completion(result); + }]; +} +- (void)debuggerMemoryAtAddress:(uint32_t)address count:(uint32_t)count physical:(BOOL)physical logicalAddress:(uint16_t)logicalAddress os9:(BOOL)os9 decode:(BOOL)decode completion:(void (^)(VCCDebugMemoryCapture *))completion { + auto result = [VCCDebugMemoryCapture new]; + result.bytes = [NSData data]; result.available = [NSData data]; + result.instructions = @[]; result.instructionOffsets = @[]; + [self inspect:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.error.clear(); + if (decode && count > 65536) throw std::invalid_argument("Decode at most 64 KiB at once"); + const auto capture = worker.machine.debuggerMemoryRange(address, count, physical); + result.address = capture.address; result.capacity = capture.capacity; + result.bytes = [NSData dataWithBytes:capture.bytes.data() length:capture.bytes.size()]; + result.available = [NSData dataWithBytes:capture.available.data() length:capture.available.size()]; + if (decode) { + const bool use6309 = worker.machine.snapshot().configuration.processor == VCC::Mac::Processor::HD6309; + const auto decoded = VCC::Mac::DisassembleRange(capture.bytes, capture.available, use6309, physical ? logicalAddress : uint16_t(address), 128, os9); + auto rows = [NSMutableArray array]; + auto offsets = [NSMutableArray array]; + unsigned offset = 0; + for (const auto& line : decoded) { + auto item = [VCCDebugInstruction new]; item.address = line.address; + item.bytes = line.available ? [NSData dataWithBytes:line.bytes.data() length:line.bytes.size()] : [NSData data]; + item.mnemonic = [NSString stringWithUTF8String:line.mnemonic.c_str()]; + item.operand = [NSString stringWithUTF8String:line.operand.c_str()]; item.valid = line.valid; + [rows addObject:item]; [offsets addObject:@(offset)]; offset += line.bytes.size(); + } + result.instructions = rows; result.instructionOffsets = offsets; + } + } completion:^(VCCMachineSnapshot *snapshot) { result.machine = snapshot; completion(result); }]; +} +- (void)debuggerGraphicsCurrentPage:(BOOL)currentPage address:(uint32_t)address physical:(BOOL)physical mode:(NSInteger)mode alternatePalette:(BOOL)alternatePalette completion:(void (^)(VCCDebugGraphicsCapture *))completion { + auto result = [VCCDebugGraphicsCapture new]; + [self inspect:^(Worker& worker) { + // A preview failure belongs to this request. Preserve any existing machine error. + try { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + if (!currentPage && (mode < 0 || mode > 9)) throw std::invalid_argument("Unknown graphics mode"); + auto preview = worker.machine.debuggerGraphicsPreview(currentPage, physical, address, + static_cast(currentPage ? 0 : mode), alternatePalette); + [result takePreview:preview]; + } catch (const std::exception& error) { + result.errorMessage = [NSString stringWithUTF8String:error.what()]; + } + } completion:^(VCCMachineSnapshot *snapshot) { + result.machine = snapshot; completion(result); + }]; +} +- (void)debuggerStepWithCompletion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.machine.debuggerStep(); worker.machine.takeAudio(); } completion:completion]; +} +- (void)debuggerStepSource:(NSInteger)mode addresses:(NSArray *)addresses locations:(NSArray *)locations bytes:(NSArray *)bytes generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion { + NSArray *ownedAddresses = [addresses copy], *ownedLocations = [locations copy]; + NSArray *ownedBytes = [[NSArray alloc] initWithArray:bytes copyItems:YES]; + [self command:^(Worker& worker) { + if (mode < 0 || mode > 2 || ownedAddresses.count != ownedLocations.count || ownedAddresses.count != ownedBytes.count) + throw std::invalid_argument("Invalid C step mode or source locations"); + const auto parsed = DebugAddresses(ownedAddresses, 65536); + std::vector instructions; + for (NSUInteger i = 0; i < parsed.size(); ++i) { + const double location = ownedLocations[i].doubleValue; + if (!std::isfinite(location) || location < 0 || location > UINT32_MAX || location != std::floor(location)) + throw std::invalid_argument("Invalid C source location identity"); + instructions.push_back({parsed[i], uint32_t(location), OwnedBytes(ownedBytes[i], 8)}); + } + worker.machine.debuggerStepSource(static_cast(mode), instructions, + generation, programRevision, mappingFingerprint, programCounter); + } completion:completion]; +} +- (void)debuggerStepBankedSource:(NSInteger)mode addresses:(NSArray *)addresses locations:(NSArray *)locations bytes:(NSArray *)bytes moduleIdentifiers:(NSArray *)moduleIdentifiers generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion { + NSArray *ownedAddresses = [addresses copy], *ownedLocations = [locations copy]; + NSArray *ownedBytes = [[NSArray alloc] initWithArray:bytes copyItems:YES]; + NSArray *identifiers = [[NSArray alloc] initWithArray:moduleIdentifiers copyItems:YES]; + [self command:^(Worker& worker) { + if (mode < 0 || mode > 2 || ownedAddresses.count != ownedLocations.count || + ownedAddresses.count != ownedBytes.count || ownedAddresses.count != identifiers.count) + throw std::invalid_argument("Invalid banked C step mode or source locations"); + if (!worker.machine.snapshot().debuggerBankedDevelopment) + throw std::invalid_argument("Arm verified banked modules before banked C stepping"); + const auto parsed = DebugAddresses(ownedAddresses, 65536); + std::vector instructions; + for (NSUInteger i = 0; i < parsed.size(); ++i) { + const double location = ownedLocations[i].doubleValue; + if (!std::isfinite(location) || location < 0 || location > UINT32_MAX || location != std::floor(location)) + throw std::invalid_argument("Invalid C source location identity"); + instructions.push_back({parsed[i], uint32_t(location), OwnedBytes(ownedBytes[i], 8), identifiers[i].UTF8String}); + } + worker.machine.debuggerStepSource(static_cast(mode), instructions, + generation, programRevision, mappingFingerprint, programCounter); + } completion:completion]; +} +- (void)debuggerSetPC:(uint16_t)address completion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.error.clear(); worker.machine.debuggerSetPC(address); + } completion:completion]; +} +- (void)debuggerSetBreakpoints:(NSArray *)addresses completion:(VCCMachineCompletion)completion { + NSArray *owned = [addresses copy]; + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.error.clear(); + if (owned.count > 1024) throw std::invalid_argument("Use at most 1,024 breakpoints"); + std::vector points; + for (NSNumber *value in owned) { + const double n = value.doubleValue; + if (!std::isfinite(n) || n < 0 || n > 65535 || n != std::floor(n)) + throw std::invalid_argument("Breakpoint addresses must be hexadecimal 0000 through FFFF"); + points.push_back(uint16_t(n)); + } + worker.machine.debuggerSetBreakpoints(std::move(points)); + } completion:completion]; +} +- (void)debuggerConfigureBreakpoints:(NSArray *)enabled disabled:(NSArray *)disabled completion:(VCCMachineCompletion)completion { + NSArray *on = [enabled copy], *off = [disabled copy]; + [self perform:^(Worker& worker) { + worker.error.clear(); worker.machine.debuggerConfigureBreakpoints(DebugAddresses(on, 1024), DebugAddresses(off, 1024)); + } completion:completion]; +} +- (void)debuggerStartTrace:(NSUInteger)maximum starts:(NSArray *)starts stops:(NSArray *)stops screen:(BOOL)screen scheduler:(BOOL)scheduler completion:(VCCMachineCompletion)completion { + NSArray *begin = [starts copy], *end = [stops copy]; + [self perform:^(Worker& worker) { + worker.error.clear(); + if (maximum > 100000) throw std::invalid_argument("Use at most 100,000 trace samples"); + worker.machine.debuggerStartTrace(unsigned(maximum), DebugAddresses(begin, 32), DebugAddresses(end, 32), screen, scheduler); + } completion:completion]; +} +- (void)debuggerStopTraceWithCompletion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { worker.error.clear(); worker.machine.debuggerStopTrace(); } completion:completion]; +} +- (void)debuggerClearTraceWithCompletion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { worker.error.clear(); worker.machine.debuggerClearTrace(); } completion:completion]; +} +- (void)debuggerTraceAtOffset:(NSUInteger)offset completion:(void (^)(VCCTraceSnapshot *, VCCMachineSnapshot *))completion { + auto result = [VCCTraceSnapshot new]; result.records = @[]; result.status = @"No trace"; + [self inspect:^(Worker& worker) { + const auto trace = worker.machine.debuggerTrace(offset); + result.identifier = trace.identifier; result.armed = trace.armed; result.capturing = trace.capturing; + result.total = trace.total; result.offset = trace.offset; result.limit = trace.limit; + result.status = [NSString stringWithUTF8String:trace.status.c_str()]; + auto rows = [NSMutableArray array]; + std::vector memory(65536); + for (std::size_t i = 0; i < trace.records.size(); ++i) { + const auto& row = trace.records[i]; auto item = [VCCTraceRecord new]; + item.index = trace.offset + i; item.clock = row.clock; item.frame = row.frame; + item.address = row.before.PC; item.cycles = row.cycles; item.kind = TraceKind(row.event); + item.before = TraceRegisters(row.before, trace.use6309); item.after = TraceRegisters(row.after, trace.use6309); + item.instruction = @""; + item.detail = [NSString stringWithFormat:@"Line %u%@%s", row.line, row.detail.empty() ? @"" : @" · ", row.detail.c_str()]; + if (row.event == VCC::TraceEvent::Instruction) { + for (unsigned byte = 0; byte < row.availableBytes; ++byte) memory[uint16_t(row.before.PC + byte)] = row.bytes[byte]; + const auto instruction = VCC::Mac::Disassemble(memory, row.before, trace.use6309, row.before.PC, 1).front(); + item.instruction = instruction.bytes.size() <= row.availableBytes ? [NSString stringWithFormat:@"%s %s", instruction.mnemonic.c_str(), instruction.operand.c_str()] : @"I/O bytes unavailable"; + } + [rows addObject:item]; + } + result.records = rows; + } completion:^(VCCMachineSnapshot* machine) { completion(result, machine); }]; +} +- (void)debuggerExportTraceFrom:(NSUInteger)first count:(NSUInteger)count completion:(void (^)(NSString * _Nullable, VCCMachineSnapshot *))completion { + auto captured = std::make_shared(); + __block BOOL valid = NO; + [self inspect:^(Worker& worker) { + worker.error.clear(); *captured = worker.machine.debuggerTraceForExport(first, count); valid = YES; + } completion:^(VCCMachineSnapshot* initial) { + if (!valid) { completion(nil, initial); return; } + dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + NSString* text = nil; NSString* failure = nil; + try { const auto csv = VCC::Mac::FormatDebugTraceCSV(*captured); text = [NSString stringWithUTF8String:csv.c_str()]; } + catch (const std::exception& error) { failure = [NSString stringWithUTF8String:error.what()]; } + // Formatting never blocks the emulator queue. Deliver a current + // machine snapshot, not the stale state from export's beginning. + [self inspect:^(Worker& worker) { if (failure) worker.error = failure.UTF8String; } + completion:^(VCCMachineSnapshot* current) { completion(text, current); }]; + }); + }]; +} +- (void)basicLoadSource:(NSString *)source run:(BOOL)run completion:(VCCMachineCompletion)completion { + [self basicLoadSource:source run:run breakpoints:@[] completion:completion]; +} +- (void)basicLoadSource:(NSString *)source run:(BOOL)run breakpoints:(NSArray *)lines completion:(VCCMachineCompletion)completion { + [self loadBASICSource:source run:run points:lines expected:nil existing:nil completion:completion]; +} +- (void)assistantLoadSource:(NSString *)source breakpoints:(NSArray *)lines expected:(VCCMachineSnapshot *)expected existing:(NSString *)existing completion:(VCCMachineCompletion)completion { + [self loadBASICSource:source run:YES points:lines expected:expected existing:existing completion:completion]; +} +- (void)loadBASICSource:(NSString *)source run:(BOOL)run points:(NSArray *)lines expected:(VCCMachineSnapshot *)expected existing:(NSString *)existing completion:(VCCMachineCompletion)completion { + __block NSString *installed = nil; + NSString *owned = [source copy]; NSArray *points = [lines copy]; + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.error.clear(); + if (expected) CheckAssistantMachine(worker, expected, existing); + NSData *utf8 = [owned dataUsingEncoding:NSUTF8StringEncoding]; + if (!utf8 || utf8.length > 1024 * 1024) throw std::invalid_argument("BASIC source must be at most 1 MB of text"); + const std::string text(static_cast(utf8.bytes), utf8.length); + std::vector requested; + if (points.count > 1024) throw std::invalid_argument("At most 1024 BASIC breakpoints are supported"); + for (NSNumber *point in points) { + if (point.integerValue < 0 || point.integerValue > 63999) throw std::invalid_argument("Invalid BASIC breakpoint number"); + requested.push_back(point.unsignedShortValue); + } + worker.machine.basicLoadSource(text, run, requested); + if (expected) { + const auto active = worker.machine.snapshot(); + worker.assistantProgram = std::make_pair(active.generation, active.debuggerProgramRevision); + installed = [NSString stringWithUTF8String:worker.machine.basicReadSource().c_str()]; + } + // Reset host buffering only after a successful transfer. Rejected loads + // preserve the running program and its audio state. + worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); + } completion:^(VCCMachineSnapshot *snapshot) { + snapshot.assistantLoadedSource = installed; + completion(snapshot); + }]; +} +- (void)basicSetBreakpoints:(NSArray *)lines source:(NSString *)source completion:(VCCMachineCompletion)completion { + NSArray *points = [lines copy]; NSString *owned = [source copy]; + [self perform:^(Worker& worker) { + worker.error.clear(); + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + NSData *data = [owned dataUsingEncoding:NSUTF8StringEncoding]; + if (!data || data.length > 1024 * 1024 || points.count > 1024) throw std::invalid_argument("BASIC source or breakpoint limit exceeded"); + std::vector requested; + for (NSNumber *point in points) { + if (point.integerValue < 0 || point.integerValue > 63999) throw std::invalid_argument("Invalid BASIC breakpoint number"); + requested.push_back(point.unsignedShortValue); + } + worker.machine.basicSetBreakpoints(std::string(static_cast(data.bytes), data.length), requested); + } completion:completion]; +} +- (void)basicContinueSource:(NSString *)source completion:(VCCMachineCompletion)completion { + NSString *owned = [source copy]; + [self command:^(Worker& worker) { + NSData *data = [owned dataUsingEncoding:NSUTF8StringEncoding]; + if (!data || data.length > 1024 * 1024) throw std::invalid_argument("BASIC source limit exceeded"); + worker.machine.basicContinue(std::string(static_cast(data.bytes), data.length)); + } completion:completion]; +} +- (void)basicStepSource:(NSString *)source over:(BOOL)over completion:(VCCMachineCompletion)completion { + NSString *owned = [source copy]; + [self command:^(Worker& worker) { + NSData *data = [owned dataUsingEncoding:NSUTF8StringEncoding]; + if (!data || data.length > 1024 * 1024) throw std::invalid_argument("BASIC source limit exceeded"); + worker.machine.basicStep(std::string(static_cast(data.bytes), data.length), over); + } completion:completion]; +} +- (void)basicStepOutSource:(NSString *)source completion:(VCCMachineCompletion)completion { + NSString *owned = [source copy]; + [self command:^(Worker& worker) { + NSData *data = [owned dataUsingEncoding:NSUTF8StringEncoding]; + if (!data || data.length > 1024 * 1024) throw std::invalid_argument("BASIC source limit exceeded"); + worker.machine.basicStepOut(std::string(static_cast(data.bytes), data.length)); + } completion:completion]; +} +- (void)basicClearDebugWithCompletion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { worker.error.clear(); worker.machine.basicClearDebug(); } completion:completion]; +} +- (void)basicExportSource:(NSString *)source name:(NSString *)name cassette:(BOOL)cassette completion:(void (^)(NSData *, VCCMachineSnapshot *))completion { + NSString *owned = [source copy], *filename = [name copy]; + __block NSData *result = nil; + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.error.clear(); + NSData *utf8 = [owned dataUsingEncoding:NSUTF8StringEncoding]; + NSData *nameBytes = [filename dataUsingEncoding:NSUTF8StringEncoding]; + if (!utf8 || utf8.length > 1024 * 1024 || !nameBytes || nameBytes.length > 8) + throw std::invalid_argument("Use BASIC source up to 1 MB and a name of 1–8 letters or digits"); + const std::string text(utf8.length ? static_cast(utf8.bytes) : "", utf8.length); + const std::string stem(nameBytes.length ? static_cast(nameBytes.bytes) : "", nameBytes.length); + const auto bytes = worker.machine.basicExportSource(text, stem, cassette ? VCC::Mac::BasicExportFormat::Cassette : VCC::Mac::BasicExportFormat::Disk); + result = [NSData dataWithBytes:bytes.data() length:bytes.size()]; + } completion:^(VCCMachineSnapshot *snapshot) { completion(result, snapshot); }]; +} +- (void)basicInspectSource:(NSString *)source completion:(void (^)(NSArray *> *, VCCMachineSnapshot *))completion { + NSString *owned = [source copy]; + __block NSArray *result = nil; + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.error.clear(); + NSData *data = [owned dataUsingEncoding:NSUTF8StringEncoding]; + if (!data || data.length > 1024 * 1024) throw std::invalid_argument("BASIC source limit exceeded"); + const auto variables = worker.machine.basicInspect(std::string(static_cast(data.bytes), data.length)); + NSMutableArray *rows = [NSMutableArray array]; + for (const auto& v : variables) { + NSMutableArray *dimensions = [NSMutableArray array], *elements = [NSMutableArray array]; + for (auto length : v.dimensions) [dimensions addObject:@(length)]; + for (const auto& text : v.elements) [elements addObject:[NSString stringWithUTF8String:text.c_str()]]; + [rows addObject:@{@"name": [NSString stringWithUTF8String:v.name.c_str()], + @"kind": [NSString stringWithUTF8String:v.kind.c_str()], + @"value": [NSString stringWithUTF8String:v.value.c_str()], + @"address": @(v.address), @"dimensions": dimensions, @"elements": elements}]; + } + result = rows; + } completion:^(VCCMachineSnapshot *snapshot) { completion(result, snapshot); }]; +} +- (void)basicReadSourceWithCompletion:(void (^)(NSString *, VCCMachineSnapshot *))completion { + __block NSString *source = nil; + [self inspect:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.error.clear(); + const auto text = worker.machine.basicReadSource(); + source = [[NSString alloc] initWithBytes:text.data() length:text.size() encoding:NSUTF8StringEncoding]; + if (!source) throw std::runtime_error("The BASIC program cannot be represented as editable text"); + } completion:^(VCCMachineSnapshot *snapshot) { completion(source, snapshot); }]; +} +- (void)debuggerWriteMemoryAtAddress:(uint16_t)address data:(NSData *)data completion:(VCCMachineCompletion)completion { + NSData *owned = [data copy]; + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.error.clear(); worker.machine.debuggerWriteMemory(address, OwnedBytes(owned, 256)); + } completion:completion]; +} +- (void)pauseWithCompletion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.machine.pause(); } completion:completion]; +} +- (void)softResetWithCompletion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.machine.softReset(); } completion:completion]; +} +- (void)resetWithCompletion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.machine.reset(); } completion:completion]; +} +- (void)startMacShellWithCompletion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { + if (worker.closed || !worker.machine.driveWireEnabled()) + throw std::logic_error("Enable DriveWire networking before starting a Mac shell session."); + worker.shell.arm(); worker.error.clear(); + } completion:completion]; +} +- (void)stopMacShellWithCompletion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { worker.shell.stop(); worker.error.clear(); } completion:completion]; +} +- (void)decideMacShellRequest:(uint64_t)requestID allow:(BOOL)allow completion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { + if (worker.closed || !worker.machine.driveWireEnabled() || !worker.shell.decide(requestID, allow)) + throw std::logic_error("This guest shell request has ended."); + worker.error.clear(); + } completion:completion]; +} +- (void)setDriveWireEnabled:(BOOL)enabled completion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + if (enabled && worker.assistantProgram) { + const auto active = worker.machine.snapshot(); + if (std::make_pair(active.generation, active.debuggerProgramRevision) == *worker.assistantProgram && + !worker.machine.basicAtDirectPrompt()) + throw std::logic_error("Return the shared program to the BASIC prompt before enabling DriveWire."); + } + if (worker.machine.driveWireEnabled() != bool(enabled)) { + worker.shell.stop(); + VCC::Devices::DriveWireFactory factory; + if (enabled) { + factory = [owner = &worker](const std::string& host, uint16_t port) { + return VCC::Mac::openDriveWireEndpoint(owner->shell, host, port); + }; + } + worker.machine.setDriveWireFactory(std::move(factory)); + } + worker.error.clear(); + } completion:completion]; +} +- (void)setAudioEnabled:(BOOL)enabled volume:(float)volume completion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + // Gain/mute changes must not flush buffered sound or advance the guest + // to refill it. Only an actual output enable/disable changes the clock. + if (worker.audioEnabled != bool(enabled)) { + worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); + worker.audioEnabled = enabled; worker.error.clear(); + } + worker.audio.buffer().gain.store(std::isfinite(volume) ? std::clamp(volume,0.0f,1.0f) : 0.0f); + } completion:completion]; +} +- (void)mountTape:(NSData*)data wav:(BOOL)wav completion:(VCCMachineCompletion)completion { + NSData *owned=[data copy]; + [self command:^(Worker& worker) { + if(worker.machine.cassette().snapshot().dirty) throw std::logic_error("Export or discard the recording first"); + if(owned.length>VCC::Mac::CassetteDeck::maxBytes) throw std::invalid_argument("Tape exceeds 64 MiB"); + const auto *begin=static_cast(owned.bytes); + std::vector bytes; + if(owned.length) bytes.assign(begin,begin+owned.length); + worker.machine.cassette().mount(bytes,wav?VCC::Mac::TapeFormat::WAV:VCC::Mac::TapeFormat::CAS); + ++worker.mediaRevision; + } completion:completion]; +} +- (void)tapeAction:(NSInteger)action completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { + auto& tape=worker.machine.cassette(); + if(action>=3 && tape.snapshot().dirty) throw std::logic_error("Export or discard the recording first"); + switch(action) { + case 0: tape.stop(); break; + case 1: tape.play(); break; + case 2: tape.rewind(); break; + case 3: tape.eject(); ++worker.mediaRevision; break; + case 4: tape.record(VCC::Mac::TapeFormat::CAS); ++worker.mediaRevision; break; + case 5: tape.record(VCC::Mac::TapeFormat::WAV); ++worker.mediaRevision; break; + default: throw std::invalid_argument("Unknown tape action"); + } + } completion:completion]; +} +- (void)seekTape:(uint64_t)position completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.machine.cassette().seek(position); } completion:completion]; +} +- (void)setTapeFast:(BOOL)enabled completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.machine.cassette().setFast(enabled); } completion:completion]; +} +- (void)exportTapeWithCompletion:(void (^)(NSData*,VCCMachineSnapshot*))completion { + __block NSData *data=nil; + [self command:^(Worker& worker) { + auto bytes=worker.machine.cassette().exportImage(); + data=[NSData dataWithBytes:bytes.data() length:bytes.size()]; + } completion:^(VCCMachineSnapshot *snapshot) { completion(data,snapshot); }]; +} +- (void)discardTapeWithCompletion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { + // One queue operation: a recording tick cannot make it dirty again + // between confirming discard and ejecting the in-memory image. + auto& tape=worker.machine.cassette(); tape.stop(); tape.markSaved(); tape.eject(); ++worker.mediaRevision; + } completion:completion]; +} +- (void)markTapeSavedWithCompletion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.machine.cassette().markSaved(); } completion:completion]; +} +- (void)configureCartridges:(NSArray*)kinds roms:(NSArray*)roms names:(NSArray*)names multiPak:(BOOL)enabled physicalSlot:(NSInteger)slot completion:(VCCMachineCompletion)completion { + [self configureCartridges:kinds roms:roms names:names multiPak:enabled physicalSlot:slot + sdcFolders:@[@"",@"",@"",@"",@""] sdcReadOnly:@[@YES,@YES,@YES,@YES,@YES] completion:completion]; +} +- (void)configureCartridges:(NSArray*)kinds roms:(NSArray*)roms names:(NSArray*)names multiPak:(BOOL)enabled physicalSlot:(NSInteger)slot sdcFolders:(NSArray*)folders sdcReadOnly:(NSArray*)readOnly completion:(VCCMachineCompletion)completion { + NSArray *roots = [[NSArray alloc] initWithArray:folders copyItems:YES]; + NSArray *protectedCards = [[NSArray alloc] initWithArray:readOnly copyItems:YES]; + // Copy each payload, not only the container, before crossing the queue. + NSMutableArray *bytes = [NSMutableArray new]; + for (NSData* data in roms) [bytes addObject:[data copy]]; + NSArray *types = [kinds copy]; NSArray *labels = [[NSArray alloc] initWithArray:names copyItems:YES]; + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.error.clear(); + if (types.count != 5 || bytes.count != 5 || labels.count != 5 || roots.count != 5 || protectedCards.count != 5 || slot < 1 || slot > 4) + throw std::invalid_argument("Invalid cartridge layout"); + VCC::Devices::CartridgeBus::Slots next; + std::array nextKinds; std::array nextNames; + unsigned floppyCount = 0, hardCount = 0, ramCount = 0, orchestraCount = 0, speechCount = 0, sdcCount = 0; + std::shared_ptr ram; + for (unsigned i = 0; i < 5; ++i) { + int kind = [types[i] intValue]; + if (kind < 0 || kind > 7) throw std::invalid_argument("Unknown cartridge device"); + nextKinds[i] = kind; nextNames[i] = [labels[i] UTF8String]; + if (kind == 1 && [bytes[i] length]) next[i] = std::make_shared(OwnedBytes(bytes[i], 262144)); + if (kind == 7) { + if ([bytes[i] length]) next[i] = std::make_shared( + OwnedBytes(bytes[i], 16384), [roots[i] UTF8String], [protectedCards[i] boolValue]); + if (i) ++sdcCount; + } + if (kind == 6) { + next[i] = std::make_shared(OwnedBytes(bytes[i], 6144)); + if (i) ++speechCount; + } + if (kind == 5) { + auto rom = OwnedBytes(bytes[i], 8192); + // Retain DAC latches on reset, slot moves and unrelated changes. + // Retained single/MPI modes may have different optional ROMs. + // Prefer this assignment, then an MPI slot move, before the + // retained single mode (which may have its own playback state). + for (unsigned previous : {i, 1u, 2u, 3u, 4u, 0u}) { + auto device = std::dynamic_pointer_cast(worker.cartridgeDevices[previous]); + if (device && device->hasROM(rom)) { next[i] = device; break; } + } + if (!next[i]) next[i] = std::make_shared(std::move(rom)); + if (i > 0) ++orchestraCount; + } + if (kind == 4) { + if (!ram) ram = worker.ramDevice ? worker.ramDevice : std::make_shared(); + next[i] = ram; if (i > 0) ++ramCount; + } + if (kind == 3) { next[i] = worker.hardDevice; if (i > 0) ++hardCount; } + if (kind == 2) { next[i] = worker.diskDevice; if (i > 0) ++floppyCount; } + } + if (sdcCount > 1) throw std::invalid_argument("Only one CoCo SDC is supported in the Multi-Pak"); + if (speechCount > 1) throw std::invalid_argument("Only one Speech/Sound Cartridge is supported in the Multi-Pak"); + if (orchestraCount > 1) throw std::invalid_argument("Only one Orchestra-90 is supported in the Multi-Pak"); + if (ramCount > 1) throw std::invalid_argument("Only one RAM disk is supported in the Multi-Pak"); + if (hardCount > 1) throw std::invalid_argument("Only one virtual hard-disk controller is supported in the Multi-Pak"); + if (floppyCount > 1) throw std::invalid_argument("Only one floppy controller is supported in the Multi-Pak"); + worker.pauseForDisks(); + worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); + worker.machine.cartridges().configure(next, enabled, static_cast(slot)); + worker.ramDevice = std::move(ram); + worker.cartridgeDevices = std::move(next); worker.cartridgeKinds = nextKinds; worker.cartridgeNames = std::move(nextNames); + if (worker.machine.snapshot().state != VCC::Mac::RunState::Empty) worker.machine.reset(); + } completion:completion]; +} +- (void)pauseForDiskChangeWithCompletion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.pauseForDisks(); } completion:completion]; +} +- (void)loadDiskROM:(NSData*)rom name:(NSString*)name completion:(VCCMachineCompletion)completion { + NSData *owned = [rom copy]; NSString *label = [name copy]; + [self command:^(Worker& worker) { + auto bytes = OwnedBytes(owned, 16384); + // Construct/validate first, preserving the previous device on failure. + auto next = VCC::Devices::makeDevice(VCC::Devices::DeviceKind::FD502, bytes); + worker.pauseForDisks(); + if (auto* existing = worker.floppy()) existing->setROM(bytes); + else worker.diskDevice = std::shared_ptr(static_cast(next.release())); + worker.applyLayout(worker.machine.cartridges().multiPak(), worker.machine.cartridges().physicalSlot()); + worker.diskROMName = label.UTF8String; + if (worker.machine.snapshot().state != VCC::Mac::RunState::Empty) worker.machine.reset(); + } completion:completion]; +} +- (void)disableDisksWithCompletion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { + auto& floppy = worker.requireFloppy(); + for (unsigned i = 0; i < 4; ++i) + if (floppy.image(i) && floppy.image(i)->dirty()) + throw std::logic_error("Save or discard all modified disks before disabling the controller"); + worker.pauseForDisks(); worker.diskDevice.reset(); + worker.applyLayout(worker.machine.cartridges().multiPak(), worker.machine.cartridges().physicalSlot()); + worker.diskROMName.clear(); for (unsigned i = 0; i < 4; ++i) worker.clearDrive(i); + if (worker.machine.snapshot().state != VCC::Mac::RunState::Empty) worker.machine.reset(); + } completion:completion]; +} +- (void)mountDisk:(NSData*)data drive:(NSInteger)drive name:(NSString*)name readOnly:(BOOL)readOnly completion:(VCCMachineCompletion)completion { + [self mountDisk:data drive:drive name:name readOnly:readOnly reset:VCCDiskInsertionResetNone completion:completion]; +} +- (void)mountDisk:(NSData*)data drive:(NSInteger)drive name:(NSString*)name readOnly:(BOOL)readOnly reset:(VCCDiskInsertionReset)reset completion:(VCCMachineCompletion)completion { + NSData *owned = [data copy]; NSString *label = [name copy]; + [self command:^(Worker& worker) { + if (reset < VCCDiskInsertionResetNone || reset > VCCDiskInsertionResetColdRestart) + throw std::invalid_argument("Unknown disk insertion reset option"); + const auto index = DriveIndex(drive); + auto image = LoadFloppyImage(owned, label, readOnly); + auto& floppy = worker.requireFloppy(); + if (const auto* current = floppy.image(index); current && current->dirty()) + throw std::logic_error("Save or discard the modified disk before replacing it"); + worker.pauseForDisks(); + if (reset == VCCDiskInsertionResetSoftReset) worker.machine.softReset(); + else if (reset == VCCDiskInsertionResetColdRestart) worker.machine.reset(); + floppy.mount(index, std::move(image)); + worker.clearDrive(index); worker.diskNames[index] = label.UTF8String; worker.readOnly[index] = readOnly; + } completion:completion]; +} +- (void)createDiskInDrive:(NSInteger)drive completion:(VCCMachineCompletion)completion { + [self createDiskInDrive:drive format:VCCFloppyFormatStandard completion:completion]; +} +- (void)createDiskInDrive:(NSInteger)drive format:(VCCFloppyFormat)format completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { + using VCC::Devices::DiskFormat; + DiskFormat kind; + std::string name; + switch (format) { + case VCCFloppyFormatStandard: kind = DiskFormat::JVC; name = "Untitled.dsk"; break; + case VCCFloppyFormatTrackDMK: kind = DiskFormat::DMK; name = "Untitled.dmk"; break; + case VCCFloppyFormatSectorVDK: kind = DiskFormat::VDK; name = "Untitled.vdk"; break; + default: throw std::invalid_argument("Unknown floppy image format"); + } + const auto index = DriveIndex(drive); + auto disk = VCC::Devices::DiskImage::blank({}, kind); + worker.pauseForDisks(); worker.requireFloppy().mount(index, std::move(disk)); + worker.clearDrive(index); worker.diskNames[index] = name; + } completion:completion]; +} +- (void)ejectDiskInDrive:(NSInteger)drive discard:(BOOL)discard completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { + const auto index = DriveIndex(drive); worker.pauseForDisks(); + worker.requireFloppy().eject(index, discard); worker.clearDrive(index); + } completion:completion]; +} +- (void)setDiskWriteProtected:(BOOL)enabled drive:(NSInteger)drive completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { + const auto index = DriveIndex(drive); + if (!enabled && worker.readOnly[index]) throw std::logic_error("This image was opened from a read-only file"); + auto& floppy = worker.requireFloppy(); + auto* image = floppy.image(index); + if (!enabled && image && image->formatWriteProtected()) + throw std::logic_error("The disk image header specifies write protection"); + worker.pauseForDisks(); + const bool changed = image && image->writeProtected() != bool(enabled); + floppy.setWriteProtected(index, enabled); + if (changed) ++worker.mediaRevision; + } completion:completion]; +} +- (void)exportDiskInDrive:(NSInteger)drive completion:(void (^)(NSData*,uint64_t,VCCMachineSnapshot*))completion { + __block NSData *data = nil; __block uint64_t token = 0; + [self command:^(Worker& worker) { + const auto index = DriveIndex(drive); worker.pauseForDisks(); + auto* image = worker.requireFloppy().image(index); + if (!image) throw std::logic_error("Insert a disk first"); + token = ++worker.nextExport; + worker.exports[index] = Worker::Export{token, image->bytes()}; + data = [NSData dataWithBytes:image->bytes().data() length:image->bytes().size()]; + } completion:^(VCCMachineSnapshot *snapshot) { completion(data,token,snapshot); }]; +} +- (void)snapshotDiskCopyInDrive:(NSInteger)drive completion:(void (^)(NSData*,VCCMachineSnapshot*))completion { + __block NSData *data = nil; + [self perform:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + const auto index = DriveIndex(drive); + auto* floppy = worker.floppy(); + if (!floppy || !floppy->image(index)) throw std::logic_error("Insert a disk first"); + if (floppy->snapshot().busy) throw std::logic_error("Wait for the current disk transfer to finish before copying this disk"); + worker.error.clear(); + const auto& bytes = floppy->image(index)->bytes(); + data = [NSData dataWithBytes:bytes.data() length:bytes.size()]; + } completion:^(VCCMachineSnapshot *snapshot) { completion(data, snapshot); }]; +} +- (void)markDiskSavedInDrive:(NSInteger)drive token:(uint64_t)token name:(NSString*)name completion:(VCCMachineCompletion)completion { + NSString *label = [name copy]; + [self command:^(Worker& worker) { + const auto index = DriveIndex(drive); + auto& floppy = worker.requireFloppy(); auto* image = floppy.image(index); + const auto& exported = worker.exports[index]; + if (!exported || exported->token != token || !image || floppy.snapshot().busy || image->bytes() != exported->bytes) + throw std::logic_error("Disk changed while saving; the current disk still needs to be saved"); + floppy.markSaved(index); worker.exports[index].reset(); worker.diskNames[index] = label.UTF8String; + } completion:completion]; +} +- (void)beginDiskEditorInDrive:(NSInteger)drive completion:(void (^)(VCCDiskEditCapture *, VCCMachineSnapshot *))completion { + __block VCCDiskEditCapture *capture = nil; + [self inspect:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.requireNoDiskEditor(); + const auto index = DriveIndex(drive); + auto& floppy = worker.requireFloppy(); + const auto* image = floppy.image(index); + if (!image) throw std::logic_error("Insert a disk before opening its editor."); + if (floppy.snapshot().busy) throw std::logic_error("Wait for the floppy operation to finish before editing. A paused transfer must finish before opening the editor."); + if (worker.machine.pasteRemaining()) throw std::logic_error("Finish or cancel the current paste before editing a disk."); + worker.error.clear(); worker.machine.pause(); worker.machine.setKeyboard(0); + worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); + const auto token = ++worker.nextDiskEdit; + worker.diskEdit = Worker::DiskEdit{token, worker.machine.snapshot().generation, worker.mediaRevision, index, image->bytes(), {}}; + capture = [VCCDiskEditCapture new]; capture.token = token; capture.drive = drive; + capture.data = [NSData dataWithBytes:image->bytes().data() length:image->bytes().size()]; + capture.name = [NSString stringWithUTF8String:worker.diskNames[index].c_str()]; + capture.canApply = !image->writeProtected() && !worker.readOnly[index]; + } completion:^(VCCMachineSnapshot *snapshot) { completion(capture, snapshot); }]; +} +- (void)beginHardDiskEditorInDrive:(NSInteger)drive completion:(void (^)(VCCDiskEditCapture *, VCCMachineSnapshot *))completion { + __block VCCDiskEditCapture *capture = nil; + [self inspect:^(Worker& worker) { + if (worker.closed) throw std::logic_error("The machine controller has shut down"); + worker.requireNoDiskEditor(); + const auto index = HardDriveIndex(drive); + const auto* image = worker.hardDevice->image(index); + if (!image) throw std::logic_error("Insert a hard disk before opening its editor."); + if (worker.floppy() && worker.floppy()->snapshot().busy) + throw std::logic_error("Wait for the floppy operation to finish before editing. A paused transfer must finish before opening the editor."); + if (worker.machine.pasteRemaining()) throw std::logic_error("Finish or cancel the current paste before editing a disk."); + worker.error.clear(); worker.machine.pause(); worker.machine.setKeyboard(0); + worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); + const auto token = ++worker.nextDiskEdit; + worker.diskEdit = Worker::DiskEdit{token, worker.machine.snapshot().generation, worker.mediaRevision, index, image->bytes(), {}, true, {}}; + capture = [VCCDiskEditCapture new]; capture.token = token; capture.drive = drive; + capture.data = [NSData dataWithBytes:image->bytes().data() length:image->bytes().size()]; + capture.name = [NSString stringWithUTF8String:worker.hardNames[index].c_str()]; + capture.canApply = !image->writeProtected() && !worker.hardReadOnly[index]; + } completion:^(VCCMachineSnapshot *snapshot) { completion(capture, snapshot); }]; +} +- (void)prepareDiskEditorToken:(uint64_t)token data:(NSData *)data completion:(void (^)(BOOL, VCCMachineSnapshot *))completion { + NSData *owned = [data copy]; __block BOOL prepared = NO; + [self inspect:^(Worker& worker) { + auto& edit = worker.requireDiskEditor(token); + edit.prepared.reset(); edit.preparedHard.reset(); + if (edit.hardDisk) { + const auto* current = worker.hardDevice->image(edit.drive); + if (current->writeProtected() || worker.hardReadOnly[edit.drive]) throw std::logic_error("This hard disk is write protected. Save an edited copy instead."); + auto next = VCC::Devices::HardDiskImage(OwnedBytes(owned, VCC::Devices::HardDiskImage::maxBytes)); + if (next.bytes().size() != current->bytes().size()) throw std::logic_error("Editing must preserve this hard disk's image size. Save a separate image for conversion."); + const auto tape = worker.machine.cassette().snapshot(); + if (tape.dirty || tape.mode == VCC::Mac::TapeMode::Recording) throw std::logic_error("Export the cassette recording before applying disk edits and restarting the CoCo."); + for (unsigned i = 0; i < 4; ++i) if (worker.floppy() && worker.floppy()->image(i) && worker.floppy()->image(i)->dirty()) + throw std::logic_error("Save changes on the floppy drives before applying edits and restarting the CoCo."); + for (unsigned i = 0; i < 2; ++i) if (i != edit.drive && worker.hardDevice->image(i) && worker.hardDevice->image(i)->dirty()) + throw std::logic_error("Save changes on the other hard disk before applying edits and restarting the CoCo."); + // Preserve existing unsaved-sector revisions and temporary-mode + // bytes, then track every editor change through the normal image + // write path so a later automatic save has a complete patch plan. + auto replacement = *current; + for (std::size_t offset = 0; offset < next.bytes().size(); offset += 256) { + if (std::equal(next.bytes().begin() + offset, next.bytes().begin() + offset + 256, + current->bytes().begin() + offset)) continue; + std::array sector; + std::copy_n(next.bytes().begin() + offset, 256, sector.begin()); + if (!replacement.write(static_cast(offset / 256), sector)) + throw std::logic_error("The edited hard disk could not be prepared."); + } + edit.preparedHard = std::move(replacement); worker.error.clear(); prepared = YES; + return; + } + const auto* current = worker.requireFloppy().image(edit.drive); + if (current->writeProtected() || worker.readOnly[edit.drive]) throw std::logic_error("This disk is write protected. Save an edited copy instead."); + auto next = LoadFloppyImage(owned, [NSString stringWithUTF8String:worker.diskNames[edit.drive].c_str()], false); + const auto& before = current->geometry(); const auto& after = next.geometry(); + if (next.format() != current->format() || next.bytes().size() != current->bytes().size() || + next.formatWriteProtected() != current->formatWriteProtected() || + next.containerHeaderBytes() != current->containerHeaderBytes() || + !std::equal(current->bytes().begin(), current->bytes().begin() + current->containerHeaderBytes(), next.bytes().begin()) || + before.tracks != after.tracks || + before.sides != after.sides || before.sectors != after.sectors || before.sizeCode != after.sizeCode || before.firstSector != after.firstSector) + throw std::logic_error("Editing must preserve this disk's image format, geometry and protection header. Save a separate image for conversion."); + const auto tape = worker.machine.cassette().snapshot(); + if (tape.dirty || tape.mode == VCC::Mac::TapeMode::Recording) throw std::logic_error("Export the cassette recording before applying disk edits and restarting the CoCo."); + for (unsigned i = 0; i < 4; ++i) if (i != edit.drive && worker.requireFloppy().image(i) && worker.requireFloppy().image(i)->dirty()) + throw std::logic_error("Save changes on the other floppy drives before applying edits and restarting the CoCo."); + for (unsigned i = 0; i < 2; ++i) if (worker.hardDevice->image(i) && worker.hardDevice->image(i)->dirty()) + throw std::logic_error("Save changes on the hard disks before applying edits and restarting the CoCo."); + edit.prepared = std::move(next); worker.error.clear(); prepared = YES; + } completion:^(VCCMachineSnapshot *snapshot) { completion(prepared, snapshot); }]; +} +- (void)commitDiskEditorToken:(uint64_t)token restartConfirmed:(BOOL)restartConfirmed sourceSaved:(BOOL)sourceSaved completion:(void (^)(BOOL, VCCMachineSnapshot *))completion { + __block BOOL applied = NO; + [self inspect:^(Worker& worker) { + auto& edit = worker.requireDiskEditor(token); + if (!restartConfirmed) throw std::logic_error("Confirm the cold restart before applying filesystem changes."); + const auto index = edit.drive; + if (edit.hardDisk) { + if (!edit.preparedHard) throw std::logic_error("Validate the edited hard disk before applying it."); + if (worker.hardDevice->image(index)->writeProtected() || worker.hardReadOnly[index]) throw std::logic_error("This hard disk is write protected. Save an edited copy instead."); + } else { + if (!edit.prepared) throw std::logic_error("Validate the edited disk before applying it."); + if (worker.requireFloppy().image(index)->writeProtected() || worker.readOnly[index]) throw std::logic_error("This disk is write protected. Save an edited copy instead."); + } + // Reset while old media remain mounted; no guest instruction can run + // between reset and replacement. All replacement bytes were validated. + if (worker.machine.snapshot().state != VCC::Mac::RunState::Empty) worker.machine.reset(); + worker.machine.pause(); worker.machine.setKeyboard(0); + if (edit.hardDisk) { + auto replacement = std::move(*edit.preparedHard); + if (sourceSaved) replacement.acknowledge(replacement.capture()); + worker.hardDevice->eject(index, true); + worker.hardDevice->mount(index, std::move(replacement)); + worker.hardExports[index].reset(); + } else { + auto replacement = std::move(*edit.prepared); + if (sourceSaved) replacement.markSaved(); else replacement.markDirty(); + worker.requireFloppy().mount(index, std::move(replacement), true); + worker.exports[index].reset(); + } + ++worker.mediaRevision; worker.assistantProgram.reset(); + worker.compiledKeyLease = nil; worker.compiledKeyExpected = nil; worker.assistantPasteRun.clear(); + worker.diskEdit.reset(); worker.error.clear(); applied = YES; + } completion:^(VCCMachineSnapshot *snapshot) { completion(applied, snapshot); }]; +} +- (void)cancelDiskEditorToken:(uint64_t)token completion:(VCCMachineCompletion)completion { + [self inspect:^(Worker& worker) { + worker.requireDiskEditor(token); + worker.machine.pause(); worker.machine.setKeyboard(0); worker.diskEdit.reset(); worker.error.clear(); + } completion:completion]; +} +- (void)assistantReadinessWithCompletion:(VCCMachineCompletion)completion { + __block NSNumber *prompt = nil, *empty = nil; + [self inspect:^(Worker& worker) { + if (worker.closed) return; + try { + // Unsupported ROMs and transient memory maps leave these fields unknown. + empty = @(worker.machine.basicReadSource().empty()); + prompt = @(worker.machine.basicAtDirectPrompt()); + } catch (const std::exception&) { } + } completion:^(VCCMachineSnapshot *snapshot) { + snapshot.assistantDirectPrompt = prompt; + snapshot.assistantEmptyBASIC = empty; + completion(snapshot); + }]; +} +- (void)snapshotWithCompletion:(VCCMachineCompletion)completion { + [self inspect:^(Worker&) {} completion:completion]; +} +- (void)captureDiskForSavingInDrive:(NSInteger)drive completion:(void (^)(NSData*,uint64_t,VCCMachineSnapshot*))completion { + __block NSData *data = nil; __block uint64_t token = 0; + [self perform:^(Worker& worker) { + const auto index = DriveIndex(drive); + auto* floppy = worker.floppy(); + if (worker.closed || !floppy || floppy->snapshot().busy) return; + auto* image = floppy->image(index); + if (!image || !image->dirty() || image->writeProtected() || worker.readOnly[index]) return; + token = ++worker.nextExport; + worker.exports[index] = Worker::Export{token, image->bytes()}; + data = [NSData dataWithBytes:image->bytes().data() length:image->bytes().size()]; + } completion:^(VCCMachineSnapshot *snapshot) { completion(data,token,snapshot); }]; +} +- (void)acknowledgeDiskSaveInDrive:(NSInteger)drive token:(uint64_t)token completion:(VCCMachineCompletion)completion { + [self perform:^(Worker& worker) { + const auto index = DriveIndex(drive); + auto* floppy = worker.floppy(); + if (worker.closed || !floppy) return; + auto* image = floppy->image(index); + const auto& exported = worker.exports[index]; + if (!exported || exported->token != token) return; + // Partial transfers have not changed image bytes yet; their eventual + // commit will mark dirty again even if this acknowledgement clears it. + if (image && image->bytes() == exported->bytes) floppy->markSaved(index); + worker.exports[index].reset(); + } completion:completion]; +} +- (void)mountHardDisk:(NSData*)data drive:(NSInteger)drive name:(NSString*)name readOnly:(BOOL)readOnly completion:(VCCMachineCompletion)completion { + NSData* owned = [data copy]; NSString* label = [name copy]; + [self command:^(Worker& worker) { + auto index = HardDriveIndex(drive); + auto image = VCC::Devices::HardDiskImage(OwnedBytes(owned, VCC::Devices::HardDiskImage::maxBytes), readOnly); + worker.pauseForDisks(); worker.hardDevice->mount(index, std::move(image)); worker.clearHardDrive(index); + worker.hardNames[index] = label.UTF8String; worker.hardReadOnly[index] = readOnly; + } completion:completion]; +} +- (void)createHardDiskInDrive:(NSInteger)drive size:(NSUInteger)size completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { + auto index = HardDriveIndex(drive); auto image = VCC::Devices::HardDiskImage::blank(size); + worker.pauseForDisks(); worker.hardDevice->mount(index, std::move(image)); worker.clearHardDrive(index); worker.hardNames[index] = "Untitled.vhd"; + } completion:completion]; +} +- (void)hardDiskAction:(NSInteger)action drive:(NSInteger)drive completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { + auto index = HardDriveIndex(drive); worker.pauseForDisks(); + if (action == 0 || action == 1) { worker.hardDevice->eject(index, action == 1); worker.clearHardDrive(index); } + else if (action == 2 || action == 3) { + auto* image = worker.hardDevice->image(index); + if (!image) throw std::logic_error("No hard disk is mounted"); + if (action == 3 && worker.hardReadOnly[index]) throw std::logic_error("This file is read-only. Save a writable copy first"); + if (image->writeProtected() != (action == 2)) ++worker.mediaRevision; + image->protect(action == 2); + } else throw std::invalid_argument("Unknown hard disk action"); + } completion:completion]; +} +- (void)configureHardClock:(BOOL)enabled readOnly:(BOOL)readOnly completion:(VCCMachineCompletion)completion { + [self command:^(Worker& worker) { worker.pauseForDisks(); worker.hardDevice->configureClock(enabled, readOnly); } completion:completion]; +} +- (void)captureHardDiskInDrive:(NSInteger)drive full:(BOOL)full completion:(void (^)(VCCHardDiskSave*,VCCMachineSnapshot*))completion { + __block VCCHardDiskSave* result = nil; + void (^capture)(Worker&) = ^(Worker& worker) { + if (worker.closed) return; + auto index = HardDriveIndex(drive); auto* image = worker.hardDevice->image(index); + if (!image) return; + if (full) worker.pauseForDisks(); + else if (!image->dirty() || image->writeProtected() || worker.hardReadOnly[index]) return; + auto saved = image->capture(); result = [VCCHardDiskSave new]; + result.token = ++worker.nextExport; result.byteCount = saved.length; + if (full) result.data = [NSData dataWithBytes:image->bytes().data() length:image->bytes().size()]; + else { + NSMutableData* patches = [NSMutableData dataWithCapacity:saved.records.size() * 260]; + for (const auto& record : saved.records) { + std::uint8_t indexBytes[4]{std::uint8_t(record.sector), std::uint8_t(record.sector >> 8), std::uint8_t(record.sector >> 16), std::uint8_t(record.sector >> 24)}; + [patches appendBytes:indexBytes length:4]; [patches appendBytes:record.bytes.data() length:256]; + } + result.data = patches; + } + worker.hardExports[index] = Worker::HardExport{result.token, std::move(saved)}; + }; + VCCMachineCompletion finish = ^(VCCMachineSnapshot* snapshot) { completion(result, snapshot); }; + if (full) [self command:capture completion:finish]; else [self perform:capture completion:finish]; +} +- (void)acknowledgeHardDiskInDrive:(NSInteger)drive token:(uint64_t)token name:(NSString*)name completion:(VCCMachineCompletion)completion { + NSString* label = [name copy]; + [self perform:^(Worker& worker) { + auto index = HardDriveIndex(drive); auto* image = worker.hardDevice->image(index); auto& saved = worker.hardExports[index]; + if (worker.closed || !image || !saved || saved->token != token) return; + image->acknowledge(saved->saved); saved.reset(); + if (label) { worker.hardNames[index] = label.UTF8String; worker.hardReadOnly[index] = false; } + } completion:completion]; +} +- (void)shutdownWithCompletion:(VCCMachineCompletion)completion { + dispatch_source_cancel(_timer); + [self inspect:^(Worker& worker) { + worker.diskEdit.reset(); + worker.closed = true; worker.shell.stop(); worker.audio.stop(); worker.machine.shutdown(); worker.error.clear(); + } completion:completion]; +} +- (void)dealloc { + dispatch_source_cancel(_timer); + auto worker = _worker; + // Worker blocks never retain self; deallocation cannot originate on _queue. + dispatch_sync(_queue, ^{ worker->closed = true; worker->audio.stop(); worker->machine.shutdown(); }); +} +@end diff --git a/platforms/macos/Companion/CompanionDiskTransfer.swift b/platforms/macos/Companion/CompanionDiskTransfer.swift new file mode 100644 index 0000000..c07da94 --- /dev/null +++ b/platforms/macos/Companion/CompanionDiskTransfer.swift @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// Immutable disk copies only. No writable file URL is passed between hosts. +enum CompanionDiskTransfer { + static let version = 1 + struct Slot: Codable, Identifiable, Sendable { + let number: Int + let name: String? + let editing: Bool + var mediaID: UUID? = nil + var id: Int { number } + } + struct Destination: Codable, Identifiable, Sendable { + let id: UUID + let name: String + let permissionGranted: Bool + let slots: [Slot] + } + struct Request: Codable, Sendable { + let destination: UUID + let drive: Int + let name: String + let bytes: Data + let expectedDiskName: String? + var expectedMediaID: UUID? = nil + } + struct Receipt: Codable, Sendable { + enum Status: String, Codable { case waitingForPermission, received, denied } + let id: UUID + let status: Status + let message: String + } +} + +struct CompanionCapabilities: Codable, Sendable { + let protocolVersion: Int + let productVersion: String + let diskEditor: Bool + let diskLibrary: Bool +} diff --git a/platforms/macos/Companion/CompanionTransport.swift b/platforms/macos/Companion/CompanionTransport.swift new file mode 100644 index 0000000..20f784a --- /dev/null +++ b/platforms/macos/Companion/CompanionTransport.swift @@ -0,0 +1,446 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import Darwin +import Security + +/// Private, authenticated, one-request-per-connection companion IPC. Both apps +/// compile this exact source; no database, disk, or emulator commands live here. +enum CompanionTransport { + static var publisherTeamID: String { + (Bundle.main.object(forInfoDictionaryKey: "VCCCompanionTeamIdentifier") as? String ?? "") + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + static let protocolVersion = 1 + static let maximumPayloadBytes = 24 * 1024 * 1024 + private static let maximumFrameBytes = 32 * 1024 * 1024 + 4096 + + struct Configuration: Sendable { + var directory: URL + var timeout: TimeInterval = 120 + var socketName = "service.sock" + var teamID = CompanionTransport.publisherTeamID + var serverBundleIDs: Set = ["com.brianholman.vccplus.oss.mac"] + var clientBundleIDs: Set = ["com.brianholman.vccplus.oss.drivewire"] + #if VCC_COMPANION_TESTING + var allowUnsignedTestPeers = false + #endif + static var production: Configuration { + Configuration(directory: URL(fileURLWithPath: "/private/tmp/vccplus-oss-companion-\(geteuid())", isDirectory: true)) + } + static var vccPlus: Configuration { .production } + static var driveWire: Configuration { + var configuration = production + configuration.socketName = "drivewire.sock" + configuration.serverBundleIDs = ["com.brianholman.vccplus.oss.drivewire"] + configuration.clientBundleIDs = ["com.brianholman.vccplus.oss.mac"] + return configuration + } + var expectedServerBundleIDs: Set { + get { serverBundleIDs } + set { serverBundleIDs = newValue } + } + var expectedClientBundleIDs: Set { + get { clientBundleIDs } + set { clientBundleIDs = newValue } + } + var socketPath: String { directory.appendingPathComponent(socketName).path } + } + + enum Failure: LocalizedError { + case unavailable, busy, untrustedPeer, unsafeEndpoint, unsupportedVersion, malformedFrame, tooLarge, timedOut + case remote(String) + var errorDescription: String? { + switch self { + case .unavailable: "VCC Plus's companion service is not available." + case .busy: "Another VCC Plus companion service is already running." + case .untrustedPeer: "The companion application's identity could not be verified." + case .unsafeEndpoint: "The companion service location is not private or has changed." + case .unsupportedVersion: "These application versions do not support the same companion protocol." + case .malformedFrame: "The companion service returned an invalid response." + case .tooLarge: "The companion request or response exceeds the supported size." + case .timedOut: "The companion operation timed out." + case .remote(let message): message + } + } + } + + private struct Request: Codable { + let version: Int + let id: UUID + let method: String + let payload: Data + } + private struct Response: Codable { + let version: Int + let id: UUID + let payload: Data? + let error: String? + } + + struct Client: Sendable { + let configuration: Configuration + init(configuration: Configuration = .production) { self.configuration = configuration } + + func request(method: String, payload: Data = Data()) async throws -> Data { + guard !method.isEmpty, method.utf8.count <= 128 else { throw Failure.malformedFrame } + guard payload.count <= maximumPayloadBytes else { throw Failure.tooLarge } + let state = Connection() + return try await withTaskCancellationHandler { + try Task.checkCancellation() + return try await withCheckedThrowingContinuation { continuation in + DispatchQueue.global(qos: .userInitiated).async { + defer { state.finish() } + do { + let fd = try makeSocket() + try state.attach(fd) + try checkDirectory(configuration.directory, create: false) + try checkSocket(configuration.socketPath) + let deadline = Date().addingTimeInterval(configuration.timeout) + try connect(fd, path: configuration.socketPath, deadline: deadline, state: state) + try authenticate(fd, configuration: configuration, permittedIDs: configuration.serverBundleIDs) + let id = UUID() + try writeFrame(JSONEncoder().encode(Request(version: protocolVersion, id: id, method: method, payload: payload)), fd: fd, deadline: deadline, state: state) + let result = try JSONDecoder().decode(Response.self, from: readFrame(fd, deadline: deadline, state: state)) + guard result.version == protocolVersion else { throw Failure.unsupportedVersion } + guard result.id == id else { throw Failure.malformedFrame } + if let error = result.error { throw Failure.remote(error) } + guard let data = result.payload, data.count <= maximumPayloadBytes else { throw Failure.malformedFrame } + continuation.resume(returning: data) + } catch { continuation.resume(throwing: state.isCancelled ? CancellationError() : error) } + } + } + } onCancel: { state.cancel() } + } + } + + final class Server: @unchecked Sendable { + typealias Handler = @Sendable (String, Data) async throws -> Data + let configuration: Configuration + private let handler: Handler + private let stateLock = NSLock() + private let queue = DispatchQueue(label: "com.brianholman.vccplus.companion.accept") + private let slots = DispatchSemaphore(value: 4) + private var listener: DispatchSourceRead? + private var lockFD: Int32 = -1 + private var endpoint: (dev_t, ino_t)? + private var connections: [UUID: Connection] = [:] + private var stopped = false + + init(configuration: Configuration = .production, handler: @escaping Handler) throws { + self.configuration = configuration; self.handler = handler + try checkDirectory(configuration.directory, create: true) + let lockPath = configuration.directory.appendingPathComponent(configuration.socketName + ".lock").path + lockFD = open(lockPath, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard lockFD >= 0 else { throw Failure.unsafeEndpoint } + var lockInfo = stat() + guard fstat(lockFD, &lockInfo) == 0, lockInfo.st_uid == geteuid(), + lockInfo.st_mode & S_IFMT == S_IFREG, lockInfo.st_mode & 0o777 == 0o600 else { + close(lockFD); lockFD = -1; throw Failure.unsafeEndpoint + } + guard flock(lockFD, LOCK_EX | LOCK_NB) == 0 else { + close(lockFD); lockFD = -1; throw Failure.busy + } + var fd: Int32 = -1 + do { + try removeStaleSocket(configuration.socketPath) + fd = try makeSocket() + var address = try unixAddress(configuration.socketPath) + try checked(withUnsafePointer(to: &address) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.bind(fd, $0, socklen_t(MemoryLayout.size)) } + }) + guard chmod(configuration.socketPath, 0o600) == 0 else { throw Failure.unsafeEndpoint } + var info = stat(); guard lstat(configuration.socketPath, &info) == 0 else { throw Failure.unsafeEndpoint } + endpoint = (info.st_dev, info.st_ino) + try checked(Darwin.listen(fd, 8)) + let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: queue) + let socketFD = fd + source.setEventHandler { [weak self] in self?.acceptConnection(socketFD) } + source.setCancelHandler { close(socketFD) } + listener = source; source.resume() + } catch { + if fd >= 0 { close(fd) } + removeOwnedEndpoint() + flock(lockFD, LOCK_UN); close(lockFD); lockFD = -1 + throw error + } + } + + private func acceptConnection(_ fd: Int32) { + while true { + let peer = Darwin.accept(fd, nil, nil) + guard peer >= 0 else { return } + guard slots.wait(timeout: .now()) == .success else { close(peer); continue } + let connection = Connection(), id = UUID() + do { try configureSocket(peer); try connection.attach(peer) } + catch { close(peer); slots.signal(); continue } + stateLock.lock() + let accepting = !stopped + if accepting { connections[id] = connection } + stateLock.unlock() + guard accepting else { connection.finish(); slots.signal(); return } + DispatchQueue.global(qos: .utility).async { [self] in + do { + try authenticate(peer, configuration: configuration, permittedIDs: configuration.clientBundleIDs) + let deadline = Date().addingTimeInterval(configuration.timeout) + let request = try JSONDecoder().decode(Request.self, from: readFrame(peer, deadline: deadline, state: connection)) + guard request.version == protocolVersion else { throw Failure.unsupportedVersion } + guard !request.method.isEmpty, request.method.utf8.count <= 128, + request.payload.count <= maximumPayloadBytes else { throw Failure.malformedFrame } + let task = Task { [self] in + let response: Response + do { + let payload = try await withThrowingTaskGroup(of: Data.self) { group in + group.addTask { try await self.handler(request.method, request.payload) } + group.addTask { + while true { + try Task.checkCancellation() + if Date() >= deadline { throw Failure.timedOut } + if connection.isCancelled { throw CancellationError() } + var byte: UInt8 = 0 + let count = recv(peer, &byte, 1, MSG_PEEK | MSG_DONTWAIT) + if count == 0 { throw CancellationError() } + if count > 0 { throw Failure.malformedFrame } // exactly one request per connection + if errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR { throw Failure.unavailable } + try await Task.sleep(nanoseconds: 100_000_000) + } + } + defer { group.cancelAll() } + return try await group.next()! + } + guard payload.count <= maximumPayloadBytes else { throw Failure.tooLarge } + response = Response(version: protocolVersion, id: request.id, payload: payload, error: nil) + } catch { + response = Response(version: protocolVersion, id: request.id, payload: nil, error: String(error.localizedDescription.prefix(2048))) + } + await withCheckedContinuation { (done: CheckedContinuation) in + DispatchQueue.global(qos: .utility).async { [self] in + defer { finish(id, connection: connection); done.resume() } + if let bytes = try? JSONEncoder().encode(response) { + try? writeFrame(bytes, fd: peer, deadline: deadline, state: connection) + } + } + } + } + connection.setTask(task) + } catch { finish(id, connection: connection) } + } + } + } + + private func finish(_ id: UUID, connection: Connection) { + connection.finish() + stateLock.lock(); let removed = connections.removeValue(forKey: id); stateLock.unlock() + if removed != nil { slots.signal() } + } + + func stop() { + stateLock.lock() + guard !stopped else { stateLock.unlock(); return } + stopped = true + let source = listener; listener = nil + let active = Array(connections.values) + stateLock.unlock() + source?.cancel() + for connection in active { connection.cancel() } + removeOwnedEndpoint() + if lockFD >= 0 { flock(lockFD, LOCK_UN); close(lockFD); lockFD = -1 } + } + private func removeOwnedEndpoint() { + guard let endpoint else { return } + var info = stat() + if lstat(configuration.socketPath, &info) == 0, info.st_uid == geteuid(), + info.st_mode & S_IFMT == S_IFSOCK, info.st_dev == endpoint.0, info.st_ino == endpoint.1 { + _ = unlink(configuration.socketPath) + } + self.endpoint = nil + } + deinit { stop() } + } + + /// A descriptor is closed once, by its IO worker. Cancellation only shuts it + /// down under a lock so a recycled descriptor can never be closed by a task. + private final class Connection: @unchecked Sendable { + private let lock = NSLock() + private var fd: Int32 = -1 + private var cancelled = false + private var finished = false + private var task: Task? + var isCancelled: Bool { lock.lock(); defer { lock.unlock() }; return cancelled } + func attach(_ value: Int32) throws { + lock.lock(); defer { lock.unlock() } + if cancelled { close(value); throw CancellationError() } + fd = value + } + func setTask(_ value: Task) { + lock.lock(); let cancel = cancelled || finished + if !cancel { task = value } + lock.unlock() + if cancel { value.cancel() } + } + func cancel() { + lock.lock(); cancelled = true + if fd >= 0 { _ = shutdown(fd, SHUT_RDWR) } + let running = task; lock.unlock(); running?.cancel() + } + func finish() { + lock.lock(); let value = fd; fd = -1; task = nil; finished = true; lock.unlock() + if value >= 0 { close(value) } + } + } + + private static func checked(_ value: Int32) throws { + guard value >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + } + private static func makeSocket() throws -> Int32 { + let fd = socket(AF_UNIX, SOCK_STREAM, 0) + guard fd >= 0 else { throw Failure.unavailable } + do { try configureSocket(fd); return fd } catch { close(fd); throw error } + } + private static func configureSocket(_ fd: Int32) throws { + try checked(fcntl(fd, F_SETFL, O_NONBLOCK)); try checked(fcntl(fd, F_SETFD, FD_CLOEXEC)) + var yes: Int32 = 1 + try checked(setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &yes, socklen_t(MemoryLayout.size(ofValue: yes)))) + } + private static func unixAddress(_ path: String) throws -> sockaddr_un { + var address = sockaddr_un() + address.sun_family = sa_family_t(AF_UNIX); address.sun_len = UInt8(MemoryLayout.size) + let bytes = Array(path.utf8CString) + guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else { throw Failure.unsafeEndpoint } + withUnsafeMutableBytes(of: &address.sun_path) { target in bytes.withUnsafeBytes { target.copyBytes(from: $0) } } + return address + } + private static func checkDirectory(_ url: URL, create: Bool) throws { + if create, mkdir(url.path, 0o700) != 0, errno != EEXIST { throw Failure.unsafeEndpoint } + var info = stat() + guard lstat(url.path, &info) == 0, info.st_uid == geteuid(), info.st_mode & S_IFMT == S_IFDIR, + info.st_mode & 0o777 == 0o700 else { throw Failure.unsafeEndpoint } + } + private static func checkSocket(_ path: String) throws { + var info = stat() + guard lstat(path, &info) == 0 else { throw Failure.unavailable } + guard info.st_uid == geteuid(), info.st_mode & S_IFMT == S_IFSOCK, + info.st_mode & 0o777 == 0o600 else { throw Failure.unsafeEndpoint } + } + private static func removeStaleSocket(_ path: String) throws { + var before = stat() + guard lstat(path, &before) == 0 else { + if errno == ENOENT { return }; throw Failure.unsafeEndpoint + } + try checkSocket(path) + let fd = try makeSocket(); defer { close(fd) } + var address = try unixAddress(path) + let rc = withUnsafePointer(to: &address) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, socklen_t(MemoryLayout.size)) } + } + guard rc < 0, errno == ECONNREFUSED || errno == ENOENT else { throw Failure.busy } + var after = stat() + guard lstat(path, &after) == 0, after.st_uid == geteuid(), after.st_mode & S_IFMT == S_IFSOCK, + before.st_dev == after.st_dev, before.st_ino == after.st_ino else { throw Failure.unsafeEndpoint } + try checked(unlink(path)) + } + private static func connect(_ fd: Int32, path: String, deadline: Date, state: Connection) throws { + var address = try unixAddress(path) + let rc = withUnsafePointer(to: &address) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, socklen_t(MemoryLayout.size)) } + } + if rc < 0 { + guard errno == EINPROGRESS || errno == EAGAIN else { throw Failure.unavailable } + try wait(fd, events: Int16(POLLOUT), deadline: deadline, state: state) + var error: Int32 = 0, length = socklen_t(MemoryLayout.size) + guard getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &length) == 0, error == 0 else { throw Failure.unavailable } + } + } + private static func wait(_ fd: Int32, events: Int16, deadline: Date, state: Connection) throws { + while true { + if state.isCancelled { throw CancellationError() } + guard Date() < deadline else { throw Failure.timedOut } + var descriptor = pollfd(fd: fd, events: events, revents: 0) + let rc = poll(&descriptor, 1, 100) + if rc > 0 { + if descriptor.revents & events != 0 { return } + throw Failure.unavailable + } + if rc < 0 && errno != EINTR { throw Failure.unavailable } + } + } + private static func readBytes(_ count: Int, fd: Int32, deadline: Date, state: Connection) throws -> Data { + var result = Data(count: count) + try result.withUnsafeMutableBytes { buffer in + var offset = 0 + while offset < count { + try wait(fd, events: Int16(POLLIN), deadline: deadline, state: state) + let size = recv(fd, buffer.baseAddress! + offset, count - offset, 0) + if size > 0 { offset += size } + else if size == 0 { throw Failure.unavailable } + else if errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK { throw Failure.unavailable } + } + } + return result + } + private static func readFrame(_ fd: Int32, deadline: Date, state: Connection) throws -> Data { + let prefix = try readBytes(4, fd: fd, deadline: deadline, state: state) + let size = prefix.reduce(UInt32(0)) { ($0 << 8) | UInt32($1) } + guard size > 0, size <= maximumFrameBytes else { throw Failure.tooLarge } + return try readBytes(Int(size), fd: fd, deadline: deadline, state: state) + } + private static func writeFrame(_ data: Data, fd: Int32, deadline: Date, state: Connection) throws { + guard data.count <= maximumFrameBytes else { throw Failure.tooLarge } + var size = UInt32(data.count).bigEndian + let frame = withUnsafeBytes(of: &size) { Data($0) } + data + try frame.withUnsafeBytes { buffer in + var offset = 0 + while offset < frame.count { + try wait(fd, events: Int16(POLLOUT), deadline: deadline, state: state) + let sent = send(fd, buffer.baseAddress! + offset, frame.count - offset, 0) + if sent > 0 { offset += sent } + else if sent == 0 { throw Failure.unavailable } + else if errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK { throw Failure.unavailable } + } + } + } + /// Validate a discovered/selected companion before asking Launch Services to + /// run it. Bundle metadata alone is not authorization to execute an app. + /// This reads and verifies code on disk; callers should run it off the main actor. + static func validateApplication(at url: URL, permittedBundleIDs: Set, + teamID: String = CompanionTransport.publisherTeamID) throws { + guard !teamID.isEmpty, url.isFileURL, !permittedBundleIDs.isEmpty else { throw Failure.untrustedPeer } + var code: SecStaticCode? + guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess, let code else { throw Failure.untrustedPeer } + var info: CFDictionary? + guard SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess, + let values = info as? [String: Any], let identifier = values[kSecCodeInfoIdentifier as String] as? String, + permittedBundleIDs.contains(identifier), values[kSecCodeInfoTeamIdentifier as String] as? String == teamID else { + throw Failure.untrustedPeer + } + var requirement: SecRequirement? + guard SecRequirementCreateWithString("anchor apple generic" as CFString, [], &requirement) == errSecSuccess, + SecStaticCodeCheckValidity(code, SecCSFlags(rawValue: kSecCSStrictValidate | kSecCSCheckAllArchitectures), requirement) == errSecSuccess else { + throw Failure.untrustedPeer + } + } + + private static func authenticate(_ fd: Int32, configuration: Configuration, permittedIDs: Set) throws { + var uid: uid_t = 0, gid: gid_t = 0 + guard getpeereid(fd, &uid, &gid) == 0, uid == geteuid() else { throw Failure.untrustedPeer } + #if VCC_COMPANION_TESTING + if configuration.allowUnsignedTestPeers { return } + #endif + guard !configuration.teamID.isEmpty else { throw Failure.untrustedPeer } + var pid: pid_t = 0, length = socklen_t(MemoryLayout.size) + guard getsockopt(fd, SOL_LOCAL, LOCAL_PEERPID, &pid, &length) == 0, pid > 0 else { throw Failure.untrustedPeer } + var guest: SecCode? + let attributes = [kSecGuestAttributePid: NSNumber(value: pid)] as CFDictionary + guard SecCodeCopyGuestWithAttributes(nil, attributes, [], &guest) == errSecSuccess, let guest else { throw Failure.untrustedPeer } + var staticCode: SecStaticCode? + guard SecCodeCopyStaticCode(guest, [], &staticCode) == errSecSuccess, let staticCode else { throw Failure.untrustedPeer } + var info: CFDictionary? + guard SecCodeCopySigningInformation(staticCode, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess, + let values = info as? [String: Any], let identifier = values[kSecCodeInfoIdentifier as String] as? String, + permittedIDs.contains(identifier), values[kSecCodeInfoTeamIdentifier as String] as? String == configuration.teamID else { throw Failure.untrustedPeer } + // A matching string in an unsigned plist or an ad-hoc signature is not trust. + var requirement: SecRequirement? + guard SecRequirementCreateWithString("anchor apple generic" as CFString, [], &requirement) == errSecSuccess, + SecCodeCheckValidity(guest, SecCSFlags(rawValue: kSecCSStrictValidate), requirement) == errSecSuccess else { throw Failure.untrustedPeer } + } +} diff --git a/platforms/macos/Companion/CompanionValidation.swift b/platforms/macos/Companion/CompanionValidation.swift new file mode 100644 index 0000000..4c32d92 --- /dev/null +++ b/platforms/macos/Companion/CompanionValidation.swift @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import Darwin + +/// Explicit, isolated native companion fixtures. Shipping identities cannot opt +/// into this mode, and its peers still need normal same-team Apple signatures. +enum CompanionValidation { + static let vccPlusBundleID = "com.brianholman.vccplus.oss.mac.uitesting" + static let driveWireBundleID = "com.brianholman.vccplus.oss.drivewire.companionpreview" + private static let rootArgument = "--companion-validation-root" + private static let peerArgument = "--companion-validation-peer" + + static var requested: Bool { + CommandLine.arguments.contains(rootArgument) || CommandLine.arguments.contains(peerArgument) + } + static var enabled: Bool { (try? context()) != nil } + static var root: URL? { (try? context())?.directory } + static var vccApplicationURL: URL? { (try? context())?.peer } + + /// Invalid explicit fixture arguments never fall through to a real listener. + /// Both apps use this helper for every server and client endpoint selection. + static func configuration(forVCCPlus: Bool) throws -> CompanionTransport.Configuration { + let production: CompanionTransport.Configuration = forVCCPlus ? .vccPlus : .driveWire + guard requested else { + // An isolated preview accidentally launched without its arguments + // must never occupy the real application's service endpoint. + guard ![vccPlusBundleID, driveWireBundleID].contains(Bundle.main.bundleIdentifier ?? "") else { + throw CompanionTransport.Failure.unsafeEndpoint + } + return production + } + guard let fixture = try context() else { throw CompanionTransport.Failure.unsafeEndpoint } + var config = production + config.directory = fixture.directory + config.expectedServerBundleIDs = [forVCCPlus ? vccPlusBundleID : driveWireBundleID] + config.expectedClientBundleIDs = [forVCCPlus ? driveWireBundleID : vccPlusBundleID] + return config + } + + private struct Context { let directory: URL; let peer: URL? } + private static func context() throws -> Context? { + guard requested else { return nil } + #if DEBUG + guard let identifier = Bundle.main.bundleIdentifier, + [vccPlusBundleID, driveWireBundleID].contains(identifier) else { + throw CompanionTransport.Failure.untrustedPeer + } + let arguments = CommandLine.arguments + func value(_ flag: String) throws -> String? { + let positions = arguments.indices.filter { arguments[$0] == flag } + guard positions.count <= 1 else { throw CompanionTransport.Failure.unsafeEndpoint } + guard let position = positions.first else { return nil } + guard arguments.indices.contains(position + 1), !arguments[position + 1].hasPrefix("--") else { + throw CompanionTransport.Failure.unsafeEndpoint + } + return arguments[position + 1] + } + guard let supplied = try value(rootArgument), supplied.hasPrefix("/") else { + throw CompanionTransport.Failure.unsafeEndpoint + } + let url = URL(fileURLWithPath: supplied, isDirectory: true).standardizedFileURL + let canonical = url.resolvingSymlinksInPath() + var info = stat() + // Foundation canonicalizes /private/tmp to /tmp on some macOS builds. + // Both aliases name the system temporary directory; the final component + // is checked without following a supplied root symlink. + var rawRoot = supplied + while rawRoot.count > 1 && rawRoot.hasSuffix("/") { rawRoot.removeLast() } + guard (canonical.path.hasPrefix("/private/tmp/") || canonical.path.hasPrefix("/tmp/")), + lstat(rawRoot, &info) == 0, info.st_uid == geteuid(), + info.st_mode & S_IFMT == S_IFDIR, info.st_mode & 0o777 == 0o700, + canonical.appendingPathComponent("drivewire.sock").path.utf8.count < MemoryLayout.size(ofValue: sockaddr_un().sun_path) else { + throw CompanionTransport.Failure.unsafeEndpoint + } + var peer: URL? + if let path = try value(peerArgument) { + guard path.hasPrefix("/") else { throw CompanionTransport.Failure.untrustedPeer } + let url = URL(fileURLWithPath: path).standardizedFileURL + guard Bundle(url: url)?.bundleIdentifier == vccPlusBundleID else { throw CompanionTransport.Failure.untrustedPeer } + // The launch path is additionally checked with validateApplication + // off the main actor before it is ever executed. + peer = url + } + return Context(directory: canonical, peer: peer) + #else + throw CompanionTransport.Failure.untrustedPeer + #endif + } +} diff --git a/platforms/macos/Companion/SharedSecondaryCards.swift b/platforms/macos/Companion/SharedSecondaryCards.swift new file mode 100644 index 0000000..8d7c2f5 --- /dev/null +++ b/platforms/macos/Companion/SharedSecondaryCards.swift @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI + +struct SecondaryCard: View { + private let content: Content + init(@ViewBuilder content: () -> Content) { self.content = content() } + var body: some View { + VStack(alignment: .leading, spacing: 12) { content } + .frame(maxWidth: .infinity, alignment: .leading).padding(14) + .background(Color.primary.opacity(0.035), in: RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.primary.opacity(0.07))) + } +} + +struct SecondaryHelp: View { + let title: String + private let content: Content + @State private var expanded = false + init(title: String, @ViewBuilder content: () -> Content) { + self.title = title; self.content = content() + } + var body: some View { + DisclosureGroup(isExpanded: $expanded) { + VStack(alignment: .leading, spacing: 8) { content } + .font(.callout).foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true).padding(.top, 6) + } label: { + Label(title, systemImage: "questionmark.circle").font(.callout) + } + } +} + +struct SecondaryAction: View { + let title: String + let systemImage: String + let action: () -> Void + var body: some View { + Button(action: action) { Label(title, systemImage: systemImage).foregroundStyle(.primary) } + .buttonStyle(.bordered) + } +} diff --git a/platforms/macos/Companion/VCCCompanionService.swift b/platforms/macos/Companion/VCCCompanionService.swift new file mode 100644 index 0000000..5082226 --- /dev/null +++ b/platforms/macos/Companion/VCCCompanionService.swift @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation + +/// VCC Plus owns one catalog and installation authority. Only the authenticated, +/// disk-only request vocabulary crosses this boundary; no machine is exposed. +final class VCCCompanionService: @unchecked Sendable { + private let server: CompanionTransport.Server + + @MainActor + init(library: SoftwareLibraryModel, configuration: CompanionTransport.Configuration = .vccPlus) throws { + let authority = CompanionLibraryAuthority(model: library) + let capabilities = CompanionCapabilities(protocolVersion: CompanionTransport.protocolVersion, + productVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "", + diskEditor: true, diskLibrary: true) + server = try CompanionTransport.Server(configuration: configuration) { method, payload in + try await Self.handle(method: method, payload: payload, authority: authority, capabilities: capabilities) + } + } + nonisolated private static func handle(method: String, payload: Data, + authority: CompanionLibraryAuthority, capabilities: CompanionCapabilities) async throws -> Data { + try Task.checkCancellation() + switch method { + case "capabilities": + guard payload.isEmpty else { throw CompanionLibraryFailure(message: "Invalid companion capabilities request.") } + return try JSONEncoder().encode(capabilities) + case "library": + guard payload.count <= 32 * 1024 else { throw CompanionLibraryFailure(message: "The library request is too large.") } + let request = try JSONDecoder().decode(CompanionLibraryRequest.self, from: payload) + let response = try await authority.handle(request) + try Task.checkCancellation() + // A complete catalog snapshot can be several MiB. Its encoding must + // not occupy the native window's main actor. + return try await Task.detached(priority: .utility) { try JSONEncoder().encode(response) }.value + default: + throw CompanionLibraryFailure(message: "This VCC Plus version does not support that companion operation.") + } + } + func stop() { server.stop() } + deinit { server.stop() } +} + + +import AppKit +import SwiftUI + +/// A background catalog request creates no Metal display, polling timer, input +/// owner or saved machine-window placement. The same window hosts MachineView +/// only after an explicit activation of VCC Plus. +struct VCCCompanionDeferredMachineView: NSViewRepresentable { + let onWindow: @MainActor (NSWindow) -> Void + func makeNSView(context: Context) -> Anchor { + let view = Anchor(); view.onWindow = onWindow; return view + } + func updateNSView(_ view: Anchor, context: Context) { view.onWindow = onWindow } + final class Anchor: NSView { + var onWindow: (@MainActor (NSWindow) -> Void)? + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + guard let window else { return } + DispatchQueue.main.async { [weak self, weak window] in + guard let window else { return } + self?.onWindow?(window) + } + } + } +} diff --git a/platforms/macos/Companion/VCCDriveWireTransfer.swift b/platforms/macos/Companion/VCCDriveWireTransfer.swift new file mode 100644 index 0000000..548bd03 --- /dev/null +++ b/platforms/macos/Companion/VCCDriveWireTransfer.swift @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import SwiftUI + +/// Explicit immutable copies from an emulated floppy to an already running host. +/// This view never opens the source file, pauses/restarts the machine or launches DriveWire. +struct VCCDriveWireTransferView: View { + @ObservedObject var machine: MachineModel + let drive: Int + let sourceName: String + let sourceEpoch: UInt64 + @Environment(\.dismiss) private var dismiss + @State private var destinations: [CompanionDiskTransfer.Destination] = [] + @State private var destinationID: UUID? + @State private var selectedDrive = 0 + @State private var loading = false + @State private var busy = false + @State private var canceling = false + @State private var receipt: CompanionDiskTransfer.Receipt? + @State private var error: String? + @State private var sending: Task? + private var client: CompanionTransport.Client { + get throws { CompanionTransport.Client(configuration: try CompanionValidation.configuration(forVCCPlus: false)) } + } + + private var destination: CompanionDiskTransfer.Destination? { destinations.first { $0.id == destinationID } } + private var slot: CompanionDiskTransfer.Slot? { destination?.slots.first { $0.number == selectedDrive } } + private var sourceFormatSupported: Bool { + guard (0.. 0 && disk.byteCount % 256 == 0 + } + private var completed: Bool { receipt?.status == .received } + private var waiting: Bool { receipt?.status == .waitingForPermission } + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + SecondaryHeader(title: "Send a Copy to DriveWire", symbol: "paperplane", + subtitle: "Copy FD\(drive)'s current disk to your real CoCo's DriveWire host.") + .padding(20) + Divider() + ScrollView { + VStack(alignment: .leading, spacing: 16) { + SecondaryCard { + Label("Source disk", systemImage: "externaldrive").font(.headline) + Text(sourceName).font(.callout.weight(.medium)).textSelection(.enabled) + if !sourceFormatSupported { + Label("This image uses an encoded disk format. Convert a compatible raw DSK copy before sending it to DriveWire.", systemImage: "info.circle") + .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + Label("Includes current changes in memory. The emulator, source disk and save mode stay as they are.", systemImage: "doc.on.doc") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + if loading { + ProgressView("Looking for DriveWire sessions…").frame(maxWidth: .infinity) + } else if destinations.isEmpty { + ContentUnavailableView { + Label("No DriveWire sessions available", systemImage: "cable.connector") + } description: { + Text("Open DriveWire for VCC Plus and start the serial session you want to use, then choose Refresh. This window does not start or reconnect it.") + } actions: { + Button("Refresh", systemImage: "arrow.clockwise") { Task { await refresh() } } + } + } else { + SecondaryCard { + Label("Destination", systemImage: "paperplane").font(.headline) + Picker("DriveWire session", selection: $destinationID) { + Text("Choose a session").tag(UUID?.none) + ForEach(destinations) { destination in Text(destination.name).tag(Optional(destination.id)) } + }.accessibilityIdentifier("drivewire-copy-session") + if let destination { + Picker("Drive", selection: $selectedDrive) { + ForEach(destination.slots) { slot in + Text("DW\(slot.number) — " + (slot.editing ? "Editing" : slot.name ?? "Empty")) + .tag(slot.number).disabled(slot.editing) + } + }.accessibilityIdentifier("drivewire-copy-slot") + if let slot, slot.editing { + Label("Finish editing this DriveWire disk before sending a copy.", systemImage: "pencil") + .font(.callout).foregroundStyle(.secondary) + } else if let name = slot?.name { + Label("DW\(selectedDrive) currently holds \(name). DriveWire will retain its current bytes as a recoverable copy before replacing it.", systemImage: "doc.on.doc") + .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + Label(destination.permissionGranted + ? "This DriveWire connection has already allowed copies from VCC Plus." + : "DriveWire will ask for permission before accepting the first copy on this connection.", + systemImage: destination.permissionGranted ? "checkmark.shield" : "hand.raised") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + Button("Refresh Sessions", systemImage: "arrow.clockwise") { Task { await refresh() } } + .disabled(busy) + }.disabled(busy || completed) + } + if let receipt { + Label(receipt.message, systemImage: completed ? "checkmark.circle" : waiting ? "hand.raised" : "xmark.circle") + .font(.callout).foregroundStyle(completed ? Color.green : Color.secondary) + .fixedSize(horizontal: false, vertical: true).textSelection(.enabled) + .accessibilityIdentifier("drivewire-copy-status") + } + if let error { + Label(error, systemImage: "exclamationmark.circle").font(.callout).foregroundStyle(.red) + .fixedSize(horizontal: false, vertical: true).textSelection(.enabled) + .accessibilityIdentifier("drivewire-copy-error") + } + }.padding(20) + } + Divider() + HStack { + if busy { ProgressView().controlSize(.small) } + Button(completed ? "Done" : "Cancel", role: completed ? nil : .cancel) { cancelOrClose() } + .disabled(canceling || (busy && receipt == nil)) + .keyboardShortcut(.cancelAction) + Spacer() + if !completed { + Button("Send Copy", systemImage: "paperplane") { beginSend() } + .keyboardShortcut(.defaultAction) + .disabled(!sourceFormatSupported || loading || busy || canceling || destination == nil || slot == nil || slot?.editing == true) + .accessibilityIdentifier("drivewire-send-copy") + } + }.padding(16) + } + .frame(width: 600, height: 580) + .interactiveDismissDisabled(busy || canceling) + .task { await refresh() } + .onDisappear { sending?.cancel() } + } + + private func refresh() async { + guard !busy else { return } + loading = true; error = nil + defer { loading = false } + do { + let bytes = try await client.request(method: "destinations") + try Task.checkCancellation() + let available = try JSONDecoder().decode([CompanionDiskTransfer.Destination].self, from: bytes) + destinations = available + if destinationID == nil || !available.contains(where: { $0.id == destinationID }) { destinationID = available.first?.id } + if let destination, !destination.slots.contains(where: { $0.number == selectedDrive && !$0.editing }) { + selectedDrive = destination.slots.first(where: { !$0.editing })?.number ?? 0 + } + } catch { + guard !Task.isCancelled else { return } + destinations = []; destinationID = nil + self.error = "DriveWire could not be reached. Open a compatible signed DriveWire for VCC Plus build and try Refresh. " + error.localizedDescription + } + } + private func beginSend() { + guard let destination, let slot, !slot.editing, !busy else { return } + error = nil; receipt = nil; busy = true + sending = Task { + defer { busy = false; sending = nil } + do { + try checkSource() + let bytes = try await machine.snapshotDiskCopy(inDrive: drive) + try Task.checkCancellation(); try checkSource() + guard !bytes.isEmpty, bytes.count <= 16 * 1024 * 1024 else { + throw TransferFailure(message: "Choose a floppy image within the 16 MiB transfer limit.") + } + guard bytes.count % 256 == 0 else { + throw TransferFailure(message: "This image contains a file-format header. DriveWire needs a raw image of 256-byte sectors; export or convert a compatible disk copy first.") + } + let request = CompanionDiskTransfer.Request(destination: destination.id, drive: slot.number, + name: transferName, bytes: bytes, expectedDiskName: slot.name, expectedMediaID: slot.mediaID) + let response = try await client.request(method: "sendDisk", payload: JSONEncoder().encode(request)) + var result = try JSONDecoder().decode(CompanionDiskTransfer.Receipt.self, from: response) + receipt = result + while result.status == .waitingForPermission { + try await Task.sleep(nanoseconds: 350_000_000) + let data = try await client.request(method: "transferStatus", payload: JSONEncoder().encode(result.id)) + try Task.checkCancellation() + result = try JSONDecoder().decode(CompanionDiskTransfer.Receipt.self, from: data) + receipt = result + } + if result.status == .denied { error = result.message } + } catch { + if !Task.isCancelled { self.error = error.localizedDescription } + } + } + } + private var transferName: String { + let file = URL(fileURLWithPath: sourceName).lastPathComponent + let stem = (file as NSString).deletingPathExtension + return (stem.isEmpty ? "Disk" : stem) + ".dsk" + } + private func checkSource() throws { + guard machine.inputEpoch == sourceEpoch, machine.state != .closed, (0..&2; exit 1 ;; +esac +kit="$resources/StarterKit" +case "${VCC_BUILD_CONTENT_PROFILE:-normal}" in + normal) ;; + source) + # Source builds select only their explicit source-built bundle or its + # dedicated default. The helper omits bundles entirely for the isolated + # UI app; neither path inspects normal maintainer ROMs/media. + python3 "$SRCROOT/../../tools/roms/stage.py" --srcroot "$SRCROOT" --resources "$resources" + exit 0 ;; + *) echo 'error: Unsupported VCC_BUILD_CONTENT_PROFILE' >&2; exit 1 ;; +esac +# Always remove a previous build's payload, including when local ROMs are removed +# or the configuration changes. Never leave private inputs in a source Release. +rm -rf "$kit" +mkdir -p "$resources" +cp "$SRCROOT/Resources/StarterMedia/Blank OS9 Header.bin" "$resources/" +[ "${CONFIGURATION:?}" = Debug ] || exit 0 +source="${SRCROOT:?}/LocalResources/ROMs" +boot_source="$source" +assembled="$SRCROOT/LocalResources/SourceROMBundle" +if [ -e "$assembled" ] || [ -L "$assembled" ]; then + python3 "$SRCROOT/../../tools/roms/core_inputs.py" validate "$assembled" + boot_source="$assembled" +elif [ ! -d "$source" ]; then + exit 0 +fi +for specification in coco3.rom:32768 disk11.rom:8192; do + name=${specification%:*}; size=${specification#*:} + if [ ! -f "$boot_source/$name" ] || [ "$(wc -c < "$boot_source/$name" | tr -d ' ')" != "$size" ]; then + echo "error: Selected development $name must be $size bytes." >&2 + exit 1 + fi +done +for name in rgbdos.rom orch90.rom; do + if [ -f "$source/$name" ] && [ "$(wc -c < "$source/$name" | tr -d ' ')" != 8192 ]; then + echo "error: LocalResources/ROMs/$name must be 8192 bytes." >&2 + exit 1 + fi +done +if [ -f "$source/sdcdos.rom" ]; then + size=$(wc -c < "$source/sdcdos.rom" | tr -d ' ') + if [ "$size" != 8192 ] && [ "$size" != 16384 ]; then + echo 'error: LocalResources/ROMs/sdcdos.rom must be 8192 or 16384 bytes.' >&2; exit 1 + fi +fi +if [ -f "$source/pic-7040-510.bin" ] || [ -f "$source/sp0256-al2.bin" ]; then + for specification in pic-7040-510.bin:4096 sp0256-al2.bin:2048; do + name=${specification%:*}; size=${specification#*:} + if [ ! -f "$source/$name" ] || [ "$(wc -c < "$source/$name" | tr -d ' ')" != "$size" ]; then + echo "error: Speech/Sound needs both internal ROMs; $name must be $size bytes." >&2 + exit 1 + fi + done +fi +mkdir -p "$resources" +staging=$(mktemp -d "$resources/.starter-build.XXXXXX") +trap 'rm -rf "$staging"' EXIT HUP INT TERM +cp "$boot_source/coco3.rom" "$boot_source/disk11.rom" "$staging/" +if [ "$boot_source" = "$assembled" ]; then + cp "$assembled/ROMBuild.json" "$assembled/ROM_SOURCE_NOTICE.txt" "$staging/" +fi +cp "$SRCROOT/Resources/StarterMedia/Hello World.dsk" "$SRCROOT/Resources/StarterMedia/Hello World.cas" "$staging/" +cp "$SRCROOT/Resources/StarterMedia/Blank Disk.dsk" "$SRCROOT/Resources/StarterMedia/Hello Hard Disk.dsk" "$staging/" +cp "$SRCROOT/Resources/StarterMedia/Blank OS9 Header.bin" "$staging/" +media="$SRCROOT/LocalResources/Media/NitrOS-9 L2 V3.3.0.vhd" +if [ -f "$media" ]; then + if [ "$(wc -c < "$media" | tr -d ' ')" != 135659520 ]; then + echo 'error: NitrOS-9 starter image must be the 135659520-byte archive image.' >&2; exit 1 + fi + python3 "$SRCROOT/Tools/prepare-nitros9.py" "$media" "$staging/NitrOS-9 L2 V3.3.0.vhd" +fi +for name in rgbdos.rom orch90.rom sdcdos.rom pic-7040-510.bin sp0256-al2.bin; do + if [ -f "$source/$name" ]; then cp "$source/$name" "$staging/"; fi +done +mv "$staging" "$kit" +echo 'Included selected boot ROMs, existing cartridge inputs and authored starter media.' diff --git a/platforms/macos/Resources/About/ArtworkNotice.txt b/platforms/macos/Resources/About/ArtworkNotice.txt new file mode 100644 index 0000000..f443197 --- /dev/null +++ b/platforms/macos/Resources/About/ArtworkNotice.txt @@ -0,0 +1,5 @@ +Except where otherwise identified, original artwork owned by Brian K. Holman is © 2026 Brian K. Holman. All rights reserved. + +Permission is granted to use and redistribute this artwork unchanged with VCC Plus, including modified versions of its GPL-licensed software. Other reproduction, modification or redistribution requires prior written permission, except as permitted by applicable law. Third-party materials remain subject to their respective licenses and rights. + +The CoCo 3 and CM-8 monitor presentation in VCC Plus’s skeuomorphic System view was inspired by SockMaster’s “pic of CoCo 3 and CM-8 monitor,â€� published on CoCopedia. VCC Plus’s artwork was designed and rendered independently. The remaining hardware illustrations were independently designed using historical photographs and renderings as references. diff --git a/platforms/macos/Resources/About/CopyrightNotice.txt b/platforms/macos/Resources/About/CopyrightNotice.txt new file mode 100644 index 0000000..089563b --- /dev/null +++ b/platforms/macos/Resources/About/CopyrightNotice.txt @@ -0,0 +1,5 @@ +VCC Plus contributions © 2026 Brian K. Holman. Original VCC code and other third-party components remain copyrighted by their respective authors. VCC Plus is distributed under the GNU General Public License, version 3 or later, without warranty. See the included license and third-party notices. + +Designed by Brian Holman. Sponsored by Dezota LLC. + +Dezota and its logo are trademarks of Dezota LLC. Tandy, Motorola, Hitachi and other referenced names, logos and trademarks belong to their respective owners. Third-party marks identify the hardware and processor models represented by the emulator; their inclusion does not imply affiliation, sponsorship or endorsement. Neither Brian Holman nor Dezota LLC claims ownership of those third-party marks. diff --git a/platforms/macos/Resources/About/DriveWireCredit.txt b/platforms/macos/Resources/About/DriveWireCredit.txt new file mode 100644 index 0000000..5c371b3 --- /dev/null +++ b/platforms/macos/Resources/About/DriveWireCredit.txt @@ -0,0 +1,3 @@ +DriveWire was created by Boisy G. Pitre. The DriveWire networking extensions +were developed by Aaron Wolfe, Boisy Pitre, and Jim Hathaway. VCC Plus implements +outbound networking independently from the published DriveWire specification. diff --git a/platforms/macos/Resources/About/GPL.txt b/platforms/macos/Resources/About/GPL.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/platforms/macos/Resources/About/GPL.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/platforms/macos/Resources/About/ROMNotice.txt b/platforms/macos/Resources/About/ROMNotice.txt new file mode 100644 index 0000000..0a319f7 --- /dev/null +++ b/platforms/macos/Resources/About/ROMNotice.txt @@ -0,0 +1,3 @@ +ROM images and other third-party software included in compiled distributions of VCC Plus remain the property of their respective copyright holders. The GPL license for VCC Plus does not grant rights to these materials; their use and redistribution remain subject to their applicable licenses and law. Neither Brian Holman nor Dezota LLC claims ownership of third-party ROMs. + +If you own the copyright to a ROM included in a compiled distribution of VCC Plus, or are authorized to act on the owner’s behalf, and wish to request its removal, please contact me@brianholman.com. Please identify the ROM and provide information supporting your ownership or authority so the request can be reviewed promptly. diff --git a/platforms/macos/Resources/About/ThirdPartyNotices.txt b/platforms/macos/Resources/About/ThirdPartyNotices.txt new file mode 100644 index 0000000..d4339e3 --- /dev/null +++ b/platforms/macos/Resources/About/ThirdPartyNotices.txt @@ -0,0 +1,70 @@ +Original VCC + +Original VCC source and Windows About artwork retain their upstream copyright and licensing notices. The complete original Windows credits are included in About and in the Original Windows VCC notice. The GNU GPL version 3 is included in full; the project permits version 3 or later. + +CoCo screen character shapes + +Copyright 2015 Joseph Forgione. Derived from VCC’s cc2font.h and licensed under GPL-3.0-or-later, including character shapes reproduced in interface illustrations. These materials are not covered by the restriction on Brian Holman’s original artwork. + +Third-party names, symbols and typography + +The TANDY wordmark was adapted from “Tandy computer logo.svgâ€� on Wikimedia Commons, identified there as public-domain text/logo artwork and trademarked. Motorola and Hitachi symbols retain their respective owners’ rights. The original-artwork notice does not claim exclusive rights in third-party marks or public-domain material. + +Native interface symbols and typography use Apple SF Symbols and SF Pro. Hardware lettering includes outlines from Arial and Eurostile. These third-party materials retain their applicable rights and terms; no font binaries are distributed. Per-file provenance is retained in docs/media/ATTRIBUTION.md in the source repository. Processor badges use original frame artwork inspired by Intel Inside styling; Intel retains its marks, and the badge does not represent Intel hardware or certification. + +Optional NitrOS-9 media + +The optional NitrOS-9 L2 V3.3.0 image contains software by the NitrOS-9 project and other authors. Its EmuDsk driver credits Alan DeKok and its source carries a personal-use notice. The archive displays a development-build/not-for-distribution banner. Local HD1 preparation is not an official NitrOS-9 release. Neither the ROM notice nor the artwork notice grants permission to redistribute this third-party software; retained media notices continue to apply. + +ToolShed filesystem libraries + +The native Disk Image Editor uses an unchanged subset of ToolShed 2.6.1 by the ToolShed contributors, pinned to revision 3667a41c9605b7fcb150eace29cc7f42d460be1a. The official ToolShed SourceForge project listing identifies its license as Public Domain. Original source comments and notices are retained in the corresponding source snapshot; this statement does not replace file-specific notices. + +The subset contains DECB and OS-9 RBF filesystem code, required disk-container/common routines and public headers. It contains no wxWidgets interface, ROMs or disk images. VCC Plus's separate native wrapper validates bounded, supported raw image layouts and operates on private working copies. The wrapper is part of VCC Plus under GPL-3.0-or-later; this does not relabel the public-domain ToolShed sources. + +Upstream source: https://github.com/nitros9project/toolshed +Published license evidence: https://sourceforge.net/projects/toolshed/ +Exact file provenance: third_party/manifests/toolshed.json in the VCC Plus source repository. + +Speech/Sound emulation components + +BSD 3-Clause License + +SSC wiring and SP0256/TMS7000 portions are derived from MAME: +Copyright holders: Tim Lindner, Joseph Zbiciak, hap. +See the individual source headers for component provenance. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. + +Capital Quest manual screenshots + +Book 12 includes published guest captures from Brian Holman's CoCoCapitalQuiz project: +https://vccplus-git.brianholman.com/VCCPlusApps/CoCoCapitalQuiz + +The map shown in the question capture is adapted from © Fla-shop.com, licensed under Creative Commons Attribution 4.0 International: +https://www.fla-shop.com/svg/usa/ +https://creativecommons.org/licenses/by/4.0/ + +The game adapts the SVG through scan conversion, state-region assignment, resolution reduction, simplified pixel boundaries, recoloring, run-length encoding and Northeast/Hawaii detail crops. Insets use different scales. These credits do not imply endorsement. The map retains its CC BY 4.0 terms; it is not covered by the separate notice for original VCC Plus artwork. The project preserves its source and adaptation credits in assets/CREDITS.md. diff --git a/platforms/macos/Resources/About/WindowsAbout.txt b/platforms/macos/Resources/About/WindowsAbout.txt new file mode 100644 index 0000000..61430a1 --- /dev/null +++ b/platforms/macos/Resources/About/WindowsAbout.txt @@ -0,0 +1,13 @@ +Copyright 2015 By Joseph Forgione + +VCC (Virtual Color Computer) is free software: you can redistribute and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + +VCC (Virtual Color Computer) is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VCC (Virtual Color Computer). If not, see http://www.gnu.org/licenses/. + +VCC Repository and Release Packages maintained by Bill Pierce and Ed Jaquay. + +Adapted to Visual Studio by Gary Coulbourne and Wes Gale. Hitachi 6309 port by Walter Zambotti. + +Bug fixes and Enhancements by Bill Pierce, James Ross, Peter Westberg, James Rye, EJ Jaquay, Mike Rojas, Trey Tomes and Craig Allsop. diff --git a/platforms/macos/Resources/About/dezota-dark.pdf b/platforms/macos/Resources/About/dezota-dark.pdf new file mode 100644 index 0000000..3a2b981 Binary files /dev/null and b/platforms/macos/Resources/About/dezota-dark.pdf differ diff --git a/platforms/macos/Resources/About/dezota.pdf b/platforms/macos/Resources/About/dezota.pdf new file mode 100644 index 0000000..13b1b96 Binary files /dev/null and b/platforms/macos/Resources/About/dezota.pdf differ diff --git a/platforms/macos/Resources/About/founder.pdf b/platforms/macos/Resources/About/founder.pdf new file mode 100644 index 0000000..62a7567 Binary files /dev/null and b/platforms/macos/Resources/About/founder.pdf differ diff --git a/platforms/macos/Resources/About/windows-founders.bmp b/platforms/macos/Resources/About/windows-founders.bmp new file mode 100644 index 0000000..f69e19e Binary files /dev/null and b/platforms/macos/Resources/About/windows-founders.bmp differ diff --git a/platforms/macos/Resources/About/windows-vcc.bmp b/platforms/macos/Resources/About/windows-vcc.bmp new file mode 100644 index 0000000..b041cdc Binary files /dev/null and b/platforms/macos/Resources/About/windows-vcc.bmp differ diff --git a/platforms/macos/Resources/AppIcon.icns b/platforms/macos/Resources/AppIcon.icns new file mode 100644 index 0000000..381a636 Binary files /dev/null and b/platforms/macos/Resources/AppIcon.icns differ diff --git a/platforms/macos/Resources/AppIconArtwork.pdf b/platforms/macos/Resources/AppIconArtwork.pdf new file mode 100644 index 0000000..24f73ef Binary files /dev/null and b/platforms/macos/Resources/AppIconArtwork.pdf differ diff --git a/platforms/macos/Resources/AssemblyReference.json b/platforms/macos/Resources/AssemblyReference.json new file mode 100644 index 0000000..aff6f77 --- /dev/null +++ b/platforms/macos/Resources/AssemblyReference.json @@ -0,0 +1,315 @@ +{ +"sourceSHA256": "a555c419b539d5ba783ab5f66f0662926caee58c1635a080dddb45ebebd82174", +"entries": [ +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "*PRAGMAPOP", "operation": "Restore saved pragma settings.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "*PRAGMAPOP"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "*PRAGMAPUSH", "operation": "Save pragma settings on the assembler’s pragma stack.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "*PRAGMAPUSH"}, +{"category": "Registers & Flags", "name": "A", "operation": "Eight-bit accumulator. A forms the high byte of D.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Instructions", "flags": "CC is preserved.", "form": "inherent", "name": "ABX", "operation": "Add the unsigned byte in B to X.", "sources": ["Atkinson (2009), pp. 4", "Motorola (1981), Appendix A, ABX", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks unsigned carry. H records carry from bit 3.", "form": "value", "name": "ADCA", "operation": "Add the operand and incoming carry to A. Keep the low 8 bits in A.", "sources": ["Atkinson (2009), pp. 5", "Motorola (1981), Appendix A, ADCA", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks unsigned carry. H records carry from bit 3.", "form": "value", "name": "ADCB", "operation": "Add the operand and incoming carry to B. Keep the low 8 bits in B.", "sources": ["Atkinson (2009), pp. 5", "Motorola (1981), Appendix A, ADCB", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks unsigned carry. H is preserved.", "form": "value", "hd6309": true, "name": "ADCD", "operation": "Add the operand and incoming carry to D. Keep the low 16 bits in D.", "sources": ["Atkinson (2009), pp. 6", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "detail": "The destination selects the width. A word source supplies its low byte to a byte destination. For a word destination A/B supply D, E/F supply W, CC is zero-extended and DP supplies the high byte. PC is undefined in this family. See Atkinson, p. 143.", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks unsigned carry.", "form": "pair", "hd6309": true, "name": "ADCR", "operation": "Add source and carry to destination.", "sources": ["Atkinson (2009), pp. 7", "Astle, LWTools 4.25, ch. 3"], "syntax": "source register,destination register"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks unsigned carry. H records carry from bit 3.", "form": "value", "name": "ADDA", "operation": "Add the operand to A. Keep the low 8 bits in A.", "sources": ["Atkinson (2009), pp. 8", "Motorola (1981), Appendix A, ADDA", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks unsigned carry. H records carry from bit 3.", "form": "value", "name": "ADDB", "operation": "Add the operand to B. Keep the low 8 bits in B.", "sources": ["Atkinson (2009), pp. 8", "Motorola (1981), Appendix A, ADDB", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks unsigned carry. H is preserved.", "form": "value", "name": "ADDD", "operation": "Add the operand to D. Keep the low 16 bits in D.", "sources": ["Atkinson (2009), pp. 9", "Motorola (1981), Appendix A, ADDD", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks unsigned carry. H records carry from bit 3.", "form": "value", "hd6309": true, "name": "ADDE", "operation": "Add the operand to E. Keep the low 8 bits in E.", "sources": ["Atkinson (2009), pp. 8", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks unsigned carry. H records carry from bit 3.", "form": "value", "hd6309": true, "name": "ADDF", "operation": "Add the operand to F. Keep the low 8 bits in F.", "sources": ["Atkinson (2009), pp. 8", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "detail": "The destination selects the width. A word source supplies its low byte to a byte destination. For a word destination A/B supply D, E/F supply W, CC is zero-extended and DP supplies the high byte. PC is undefined in this family. See Atkinson, p. 143.", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks unsigned carry.", "form": "pair", "hd6309": true, "name": "ADDR", "operation": "Add source to destination.", "sources": ["Atkinson (2009), pp. 10", "Astle, LWTools 4.25, ch. 3"], "syntax": "source register,destination register"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks unsigned carry. H is preserved.", "form": "value", "hd6309": true, "name": "ADDW", "operation": "Add the operand to W. Keep the low 16 bits in W.", "sources": ["Atkinson (2009), pp. 9", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "maskMemory", "hd6309": true, "name": "AIM", "operation": "Combine the literal mask and the addressed byte with AND. Write the result to that address.", "sources": ["Atkinson (2009), pp. 11", "Astle, LWTools 4.25, ch. 3"], "syntax": "#mask,address · #mask,offset,X"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "ALIGN", "operation": "Advance to a boundary divisible by the supplied value.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "ALIGN boundary"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "ANDA", "operation": "Keep bits set in both inputs. Combine A with the operand and save the result in A.", "sources": ["Atkinson (2009), pp. 12", "Motorola (1981), Appendix A, ANDA", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "ANDB", "operation": "Keep bits set in both inputs. Combine B with the operand and save the result in B.", "sources": ["Atkinson (2009), pp. 12", "Motorola (1981), Appendix A, ANDB", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "Any CC bit can clear.", "form": "immediate", "name": "ANDCC", "operation": "Keep only CC bits selected by the mask.", "sources": ["Atkinson (2009), pp. 13", "Motorola (1981), Appendix A, ANDCC", "Astle, LWTools 4.25, ch. 3"], "syntax": "#mask"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "hd6309": true, "name": "ANDD", "operation": "Keep bits set in both inputs. Combine D with the operand and save the result in D.", "sources": ["Atkinson (2009), pp. 14", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "detail": "The destination selects the width. A word source supplies its low byte to a byte destination. For a word destination A/B supply D, E/F supply W, CC is zero-extended and DP supplies the high byte. PC is undefined in this family. See Atkinson, p. 143.", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "pair", "hd6309": true, "name": "ANDR", "operation": "Apply bitwise AND to the destination using the source.", "sources": ["Atkinson (2009), pp. 15", "Astle, LWTools 4.25, ch. 3"], "syntax": "source register,destination register"}, +{"aliases": ["LSL"], "category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old top bit. V is N XOR C. H is undefined.", "form": "memory", "name": "ASL", "operation": "Operate on a memory byte. Shift one place left and fill bit 0 with zero.", "sources": ["Atkinson (2009), pp. 16–17", "Motorola (1981), Appendix A, ASL", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"aliases": ["LSLA"], "category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old top bit. V is N XOR C. H is undefined.", "form": "inherent", "name": "ASLA", "operation": "Operate on register A. Shift one place left and fill bit 0 with zero.", "sources": ["Atkinson (2009), pp. 16–17", "Motorola (1981), Appendix A, ASLA", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"aliases": ["LSLB"], "category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old top bit. V is N XOR C. H is undefined.", "form": "inherent", "name": "ASLB", "operation": "Operate on register B. Shift one place left and fill bit 0 with zero.", "sources": ["Atkinson (2009), pp. 16–17", "Motorola (1981), Appendix A, ASLB", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"aliases": ["LSLD"], "category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old top bit. V is N XOR C.", "form": "inherent", "hd6309": true, "name": "ASLD", "operation": "Operate on register D. Shift one place left and fill bit 0 with zero.", "sources": ["Atkinson (2009), pp. 16–17", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"aliases": ["IFC", "IFNC", "EXITM", "EXIT"], "category": "Dialect & Compatibility", "name": "ASM-09 dialect", "operation": "The ASM-09 compatibility dialect adds string equality and inequality conditionals and an early macro exit.", "sources": ["Astle, LWTools 4.25, ch. 3"]}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old bit 0. V is preserved. H is undefined.", "form": "memory", "name": "ASR", "operation": "Operate on a memory byte. Shift right, preserving the sign bit.", "sources": ["Atkinson (2009), pp. 18–19", "Motorola (1981), Appendix A, ASR", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old bit 0. V is preserved. H is undefined.", "form": "inherent", "name": "ASRA", "operation": "Operate on register A. Shift right, preserving the sign bit.", "sources": ["Atkinson (2009), pp. 18–19", "Motorola (1981), Appendix A, ASRA", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old bit 0. V is preserved. H is undefined.", "form": "inherent", "name": "ASRB", "operation": "Operate on register B. Shift right, preserving the sign bit.", "sources": ["Atkinson (2009), pp. 18–19", "Motorola (1981), Appendix A, ASRB", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old bit 0. V is preserved.", "form": "inherent", "hd6309": true, "name": "ASRD", "operation": "Operate on register D. Shift right, preserving the sign bit.", "sources": ["Atkinson (2009), pp. 18–19", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"aliases": ["ASRQ", "CLRQ", "COMQ", "LSLE", "LSLF", "LSLQ", "LSRQ", "NEGE", "NEGF", "NEGW", "NEGQ", "TSTQ"], "category": "Dialect & Compatibility", "detail": "6809 expansions include ASLD, ASRD, CLRD, COMD, LSLD, LSRD, NEGD and TSTD. These names also identify real HD6309 operations. Additional 6309 convenience spellings include ASRQ, CLRQ, COMQ, LSLE, LSLF, LSLQ, LSRQ, NEGE, NEGF, NEGW, NEGQ and TSTQ. MC6800 compatibility is a separate optional dialect.", "name": "Assembler conveniences", "operation": "LWASM can expand convenience operations into several instructions when the corresponding pragma is active. The listing gives the actual expansion. A 6809 emulation of CLRD, for example, executes CLRA and CLRB separately.", "sources": ["Astle, LWTools 4.25, ch. 3"]}, +{"category": "Registers & Flags", "name": "B", "operation": "Eight-bit accumulator. B forms the low byte of D.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Instructions", "flags": "CC can change when a destination bit in CC is selected.", "form": "bit", "hd6309": true, "name": "BAND", "operation": "Combine the selected memory bit with the destination register bit using AND. Only the destination bit changes.", "sources": ["Atkinson (2009), pp. 20", "Astle, LWTools 4.25, ch. 3"], "syntax": "A|B|CC,source bit,destination bit,direct address"}, +{"aliases": ["BHS"], "category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BCC", "operation": "Continue at the target when C is clear (unsigned higher or equal after a compare). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 21", "Motorola (1981), Appendix A, BCC", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"aliases": ["BLO"], "category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BCS", "operation": "Continue at the target when C is set (unsigned lower). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 22", "Motorola (1981), Appendix A, BCS", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "flags": "CC can change when a destination bit in CC is selected.", "form": "bit", "hd6309": true, "name": "BEOR", "operation": "Combine the selected memory bit with the destination register bit using exclusive OR. Only the destination bit changes.", "sources": ["Atkinson (2009), pp. 23", "Astle, LWTools 4.25, ch. 3"], "syntax": "A|B|CC,source bit,destination bit,direct address"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BEQ", "operation": "Continue at the target when Z is set (equal). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 24", "Motorola (1981), Appendix A, BEQ", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BGE", "operation": "Continue at the target when N equals V (signed greater or equal). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 25", "Motorola (1981), Appendix A, BGE", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BGT", "operation": "Continue at the target when Z is clear and N equals V (signed greater). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 26", "Motorola (1981), Appendix A, BGT", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BHI", "operation": "Continue at the target when C and Z are both clear (unsigned higher). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 27", "Motorola (1981), Appendix A, BHI", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "flags": "CC can change when a destination bit in CC is selected.", "form": "bit", "hd6309": true, "name": "BIAND", "operation": "Combine the selected memory bit with the destination register bit using AND with the inverted source. Only the destination bit changes.", "sources": ["Atkinson (2009), pp. 29", "Astle, LWTools 4.25, ch. 3"], "syntax": "A|B|CC,source bit,destination bit,direct address"}, +{"category": "Instructions", "flags": "CC can change when a destination bit in CC is selected.", "form": "bit", "hd6309": true, "name": "BIEOR", "operation": "Combine the selected memory bit with the destination register bit using exclusive OR with the inverted source. Only the destination bit changes.", "sources": ["Atkinson (2009), pp. 30", "Astle, LWTools 4.25, ch. 3"], "syntax": "A|B|CC,source bit,destination bit,direct address"}, +{"category": "Instructions", "flags": "CC can change when a destination bit in CC is selected.", "form": "bit", "hd6309": true, "name": "BIOR", "operation": "Combine the selected memory bit with the destination register bit using OR with the inverted source. Only the destination bit changes.", "sources": ["Atkinson (2009), pp. 31", "Astle, LWTools 4.25, ch. 3"], "syntax": "A|B|CC,source bit,destination bit,direct address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "BITA", "operation": "Test the bits of A selected by the operand. Preserve both inputs.", "sources": ["Atkinson (2009), pp. 32", "Motorola (1981), Appendix A, BITA", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "BITB", "operation": "Test the bits of B selected by the operand. Preserve both inputs.", "sources": ["Atkinson (2009), pp. 32", "Motorola (1981), Appendix A, BITB", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "hd6309": true, "name": "BITD", "operation": "Test the bits of D selected by the operand. Preserve both inputs.", "sources": ["Atkinson (2009), pp. 33", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "Z sets if no selected error was pending.", "form": "immediate", "hd6309": true, "name": "BITMD", "operation": "Test the masked trap status bits of MD. Reading a selected sticky error clears it.", "sources": ["Atkinson (2009), pp. 34", "Astle, LWTools 4.25, ch. 3"], "syntax": "#mask"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BLE", "operation": "Continue at the target when Z is set or N differs from V (signed less or equal). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 35", "Motorola (1981), Appendix A, BLE", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BLS", "operation": "Continue at the target when C or Z is set (unsigned lower or equal). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 37", "Motorola (1981), Appendix A, BLS", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BLT", "operation": "Continue at the target when N differs from V (signed less). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 38", "Motorola (1981), Appendix A, BLT", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BMI", "operation": "Continue at the target when N is set (negative). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 39", "Motorola (1981), Appendix A, BMI", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BNE", "operation": "Continue at the target when Z is clear (unequal). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 40", "Motorola (1981), Appendix A, BNE", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "flags": "CC can change when a destination bit in CC is selected.", "form": "bit", "hd6309": true, "name": "BOR", "operation": "Combine the selected memory bit with the destination register bit using OR. Only the destination bit changes.", "sources": ["Atkinson (2009), pp. 41", "Astle, LWTools 4.25, ch. 3"], "syntax": "A|B|CC,source bit,destination bit,direct address"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BPL", "operation": "Continue at the target when N is clear (nonnegative). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 42", "Motorola (1981), Appendix A, BPL", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BRA", "operation": "Continue at the target. A branch to its own label forms a hold loop.", "sources": ["Atkinson (2009), pp. 43", "Motorola (1981), Appendix A, BRA", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BRN", "operation": "Read the displacement and continue at the next instruction.", "sources": ["Atkinson (2009), pp. 44", "Motorola (1981), Appendix A, BRN", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BSR", "operation": "Push the following instruction’s address on S, then continue at the target. RTS returns to the caller.", "sources": ["Atkinson (2009), pp. 45", "Motorola (1981), Appendix A, BSR", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BVC", "operation": "Continue at the target when V is clear (no signed overflow). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 46", "Motorola (1981), Appendix A, BVC", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 8-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "BVS", "operation": "Continue at the target when V is set (signed overflow). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 47", "Motorola (1981), Appendix A, BVS", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Registers & Flags", "name": "CC.C", "operation": "Carry or borrow. An unsigned addition sets C when the sum exceeds the register. A comparison sets C when the unsigned left operand is lower.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Registers & Flags", "name": "CC.E", "operation": "Entire state stacked. RTI checks E in the saved condition byte to choose between the short and full interrupt frames.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Registers & Flags", "name": "CC.F", "operation": "Fast interrupt request mask. Set F to mask FIRQ. A saved CC value can restore the previous mask.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Registers & Flags", "name": "CC.H", "operation": "Half carry. An eight-bit addition places the carry from bit 3 here. DAA uses H to adjust a packed decimal result.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Registers & Flags", "name": "CC.I", "operation": "Interrupt request mask. Set I to mask IRQ. Clear I to permit IRQ when the external request is active.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Registers & Flags", "name": "CC.N", "operation": "Negative. For operations that set N from the result, it copies the most significant bit. A signed comparison also needs V.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Registers & Flags", "name": "CC.V", "operation": "Signed overflow. For example, adding one to $7F produces $80 in a byte and sets V.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Registers & Flags", "name": "CC.Z", "operation": "Zero. Many arithmetic and load instructions set Z when the result is zero. After a compare, BEQ uses Z to test equality.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Instructions", "flags": "Z sets. N, V and C clear.", "form": "memory", "name": "CLR", "operation": "Operate on a memory byte. Write zero.", "sources": ["Atkinson (2009), pp. 48–49", "Motorola (1981), Appendix A, CLR", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "Z sets. N, V and C clear.", "form": "inherent", "name": "CLRA", "operation": "Operate on register A. Write zero.", "sources": ["Atkinson (2009), pp. 48–49", "Motorola (1981), Appendix A, CLRA", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "Z sets. N, V and C clear.", "form": "inherent", "name": "CLRB", "operation": "Operate on register B. Write zero.", "sources": ["Atkinson (2009), pp. 48–49", "Motorola (1981), Appendix A, CLRB", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "Z sets. N, V and C clear.", "form": "inherent", "hd6309": true, "name": "CLRD", "operation": "Operate on register D. Write zero.", "sources": ["Atkinson (2009), pp. 48–49", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "Z sets. N, V and C clear.", "form": "inherent", "hd6309": true, "name": "CLRE", "operation": "Operate on register E. Write zero.", "sources": ["Atkinson (2009), pp. 48–49", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "Z sets. N, V and C clear.", "form": "inherent", "hd6309": true, "name": "CLRF", "operation": "Operate on register F. Write zero.", "sources": ["Atkinson (2009), pp. 48–49", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "Z sets. N, V and C clear.", "form": "inherent", "hd6309": true, "name": "CLRW", "operation": "Operate on register W. Write zero.", "sources": ["Atkinson (2009), pp. 48–49", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow. H is undefined.", "form": "value", "name": "CMPA", "operation": "Subtract the operand from A. Keep A intact for a later branch.", "sources": ["Atkinson (2009), pp. 50", "Motorola (1981), Appendix A, CMPA", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow. H is undefined.", "form": "value", "name": "CMPB", "operation": "Subtract the operand from B. Keep B intact for a later branch.", "sources": ["Atkinson (2009), pp. 50", "Motorola (1981), Appendix A, CMPB", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow.", "form": "value", "name": "CMPD", "operation": "Subtract the operand from D. Keep D intact for a later branch.", "sources": ["Atkinson (2009), pp. 51", "Motorola (1981), Appendix A, CMPD", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow. H is undefined.", "form": "value", "hd6309": true, "name": "CMPE", "operation": "Subtract the operand from E. Keep E intact for a later branch.", "sources": ["Atkinson (2009), pp. 50", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow. H is undefined.", "form": "value", "hd6309": true, "name": "CMPF", "operation": "Subtract the operand from F. Keep F intact for a later branch.", "sources": ["Atkinson (2009), pp. 50", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "detail": "The destination selects the width. A word source supplies its low byte to a byte destination. For a word destination A/B supply D, E/F supply W, CC is zero-extended and DP supplies the high byte. PC is undefined in this family. See Atkinson, p. 143.", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow.", "form": "pair", "hd6309": true, "name": "CMPR", "operation": "Compare destination minus source, preserving both.", "sources": ["Atkinson (2009), pp. 52", "Astle, LWTools 4.25, ch. 3"], "syntax": "source register,destination register"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow.", "form": "value", "name": "CMPS", "operation": "Subtract the operand from S. Keep S intact for a later branch.", "sources": ["Atkinson (2009), pp. 51", "Motorola (1981), Appendix A, CMPS", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow.", "form": "value", "name": "CMPU", "operation": "Subtract the operand from U. Keep U intact for a later branch.", "sources": ["Atkinson (2009), pp. 51", "Motorola (1981), Appendix A, CMPU", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow.", "form": "value", "hd6309": true, "name": "CMPW", "operation": "Subtract the operand from W. Keep W intact for a later branch.", "sources": ["Atkinson (2009), pp. 51", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow.", "form": "value", "name": "CMPX", "operation": "Subtract the operand from X. Keep X intact for a later branch.", "sources": ["Atkinson (2009), pp. 51", "Motorola (1981), Appendix A, CMPX", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow.", "form": "value", "name": "CMPY", "operation": "Subtract the operand from Y. Keep Y intact for a later branch.", "sources": ["Atkinson (2009), pp. 51", "Motorola (1981), Appendix A, CMPY", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C sets and V clears.", "form": "memory", "name": "COM", "operation": "Operate on a memory byte. Invert every bit.", "sources": ["Atkinson (2009), pp. 53–54", "Motorola (1981), Appendix A, COM", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C sets and V clears.", "form": "inherent", "name": "COMA", "operation": "Operate on register A. Invert every bit.", "sources": ["Atkinson (2009), pp. 53–54", "Motorola (1981), Appendix A, COMA", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C sets and V clears.", "form": "inherent", "name": "COMB", "operation": "Operate on register B. Invert every bit.", "sources": ["Atkinson (2009), pp. 53–54", "Motorola (1981), Appendix A, COMB", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C sets and V clears.", "form": "inherent", "hd6309": true, "name": "COMD", "operation": "Operate on register D. Invert every bit.", "sources": ["Atkinson (2009), pp. 53–54", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C sets and V clears.", "form": "inherent", "hd6309": true, "name": "COME", "operation": "Operate on register E. Invert every bit.", "sources": ["Atkinson (2009), pp. 53–54", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C sets and V clears.", "form": "inherent", "hd6309": true, "name": "COMF", "operation": "Operate on register F. Invert every bit.", "sources": ["Atkinson (2009), pp. 53–54", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C sets and V clears.", "form": "inherent", "hd6309": true, "name": "COMW", "operation": "Operate on register W. Invert every bit.", "sources": ["Atkinson (2009), pp. 53–54", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "The mask updates CC. E sets for the stacked full context.", "form": "immediate", "name": "CWAI", "operation": "AND CC with the mask, stack the full interrupt context on S, then wait for an eligible interrupt.", "sources": ["Atkinson (2009), pp. 55", "Motorola (1981), Appendix A, CWAI", "Astle, LWTools 4.25, ch. 3"], "syntax": "#mask"}, +{"aliases": ["NAM", "PAG", "PAGE", "SPC", "TTL", ".BANK", ".MODULE"], "category": "Dialect & Compatibility", "name": "Compatibility directives", "operation": "LWASM accepts these listing and tool-compatibility directives without generating code.", "sources": ["Astle, LWTools 4.25, ch. 3"]}, +{"aliases": ["CC"], "category": "Registers & Flags", "detail": "Branch choices depend on how the previous instruction defined these bits. For example, Z=1 after CMP means equal; C=1 after CMP means unsigned lower. An undefined bit cannot support a portable decision.", "name": "Condition codes", "operation": "CC holds eight one-bit values. E marks an entire interrupt frame. F masks FIRQ, H is half carry, I masks IRQ. N is negative, Z zero, V signed overflow and C carry or borrow.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Registers & Flags", "name": "D", "operation": "Sixteen-bit accumulator built from A (high) and B (low). Writing D immediately changes both halves.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C reports decimal carry. V is undefined.", "form": "inherent", "name": "DAA", "operation": "Adjust A after adding packed BCD bytes, using H and C from the addition.", "sources": ["Atkinson (2009), pp. 56", "Motorola (1981), Appendix A, DAA", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from minimum negative to maximum positive. C is preserved.", "form": "memory", "name": "DEC", "operation": "Operate on a memory byte. Subtract one.", "sources": ["Atkinson (2009), pp. 57–58", "Motorola (1981), Appendix A, DEC", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from minimum negative to maximum positive. C is preserved.", "form": "inherent", "name": "DECA", "operation": "Operate on register A. Subtract one.", "sources": ["Atkinson (2009), pp. 57–58", "Motorola (1981), Appendix A, DECA", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from minimum negative to maximum positive. C is preserved.", "form": "inherent", "name": "DECB", "operation": "Operate on register B. Subtract one.", "sources": ["Atkinson (2009), pp. 57–58", "Motorola (1981), Appendix A, DECB", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from minimum negative to maximum positive. C is preserved.", "form": "inherent", "hd6309": true, "name": "DECD", "operation": "Operate on register D. Subtract one.", "sources": ["Atkinson (2009), pp. 57–58", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from minimum negative to maximum positive. C is preserved.", "form": "inherent", "hd6309": true, "name": "DECE", "operation": "Operate on register E. Subtract one.", "sources": ["Atkinson (2009), pp. 57–58", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from minimum negative to maximum positive. C is preserved.", "form": "inherent", "hd6309": true, "name": "DECF", "operation": "Operate on register F. Subtract one.", "sources": ["Atkinson (2009), pp. 57–58", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from minimum negative to maximum positive. C is preserved.", "form": "inherent", "hd6309": true, "name": "DECW", "operation": "Operate on register W. Subtract one.", "sources": ["Atkinson (2009), pp. 57–58", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "DEPHASE", "operation": "Resume the original address calculation after PHASE.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "DEPHASE"}, +{"category": "Instructions", "flags": "For an in-range quotient, N and Z describe it, V clears, and C receives its low bit. Signed overflow sets V. Range overflow preserves the dividend and clears N, Z and C.", "form": "value", "hd6309": true, "name": "DIVD", "operation": "Divide signed D by a signed byte. The quotient goes in B and the remainder in A. A zero divisor traps.", "sources": ["Atkinson (2009), pp. 59", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "detail": "VCC Plus’s retained core has differences in DIVQ overflow and carry handling. Treat these flags as processor documentation.", "flags": "For an in-range quotient, N and Z describe it, V clears, and C receives its low bit. Signed overflow sets V. Range overflow preserves the dividend and clears N, Z and C.", "form": "value", "hd6309": true, "name": "DIVQ", "operation": "Divide signed Q by a signed word. The quotient goes in W and the remainder in D. A zero divisor traps.", "sources": ["Atkinson (2009), pp. 60", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Registers & Flags", "name": "DP", "operation": "Direct-page register. Its byte supplies the upper address bits of a direct operand. LWASM SETDP describes your assumption during assembly.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "DTB", "operation": "Emit six host-local date and time bytes.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "DTB"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "DTS", "operation": "Emit a textual build timestamp. Its value changes with the host clock.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "DTS"}, +{"category": "Addressing Modes", "name": "Direct", "operation": "Join DP with the 8-bit operand to make the memory address. With DP=$12, LDA <$34 reads $1234.", "sources": ["Motorola (1981), ch. 2", "Astle, LWTools 4.25, ch. 3"], "syntax": "LDA <$34"}, +{"category": "Registers & Flags", "hd6309": true, "name": "E", "operation": "Eight-bit accumulator and high byte of the HD6309 W register. CC.E is a separate flag.", "sources": ["Burke (1993), register file"]}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "maskMemory", "hd6309": true, "name": "EIM", "operation": "Combine the literal mask and the addressed byte with exclusive OR. Write the result to that address.", "sources": ["Atkinson (2009), pp. 61", "Astle, LWTools 4.25, ch. 3"], "syntax": "#mask,address · #mask,offset,X"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "ELSE", "operation": "Select the alternate branch of a conditional assembly block.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "ELSE"}, +{"aliases": [".END"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "END", "operation": "Finish the assembly and specify the DECB execution address. END itself emits no machine instruction.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "END entry"}, +{"aliases": ["ENDIF"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "ENDC", "operation": "Close the current conditional assembly block.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "ENDC"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "ENDM", "operation": "Finish a macro definition.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "ENDM"}, +{"aliases": ["ENDSTRUCT"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "ENDS", "operation": "Close a structure definition.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "ENDS"}, +{"aliases": ["ENDSECTION"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "ENDSECT", "operation": "Finish the current object section.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "ENDSECT"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "EORA", "operation": "Set bits where the inputs differ. Combine A with the operand and save the result in A.", "sources": ["Atkinson (2009), pp. 62", "Motorola (1981), Appendix A, EORA", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "EORB", "operation": "Set bits where the inputs differ. Combine B with the operand and save the result in B.", "sources": ["Atkinson (2009), pp. 62", "Motorola (1981), Appendix A, EORB", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "hd6309": true, "name": "EORD", "operation": "Set bits where the inputs differ. Combine D with the operand and save the result in D.", "sources": ["Atkinson (2009), pp. 63", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "detail": "The destination selects the width. A word source supplies its low byte to a byte destination. For a word destination A/B supply D, E/F supply W, CC is zero-extended and DP supplies the high byte. PC is undefined in this family. See Atkinson, p. 143.", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "pair", "hd6309": true, "name": "EORR", "operation": "Toggle destination bits selected by the source.", "sources": ["Atkinson (2009), pp. 64", "Astle, LWTools 4.25, ch. 3"], "syntax": "source register,destination register"}, +{"aliases": ["="], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "EQU", "operation": "Assign a fixed value to a symbol.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "name EQU expression"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "ERROR", "operation": "Report an assembly error with the supplied text.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "ERROR message"}, +{"category": "Instructions", "detail": "Use equal-width registers on the MC6809. The HD6309 has additional registers and defined mixed-width behavior. Writing PC transfers control.", "flags": "Writing CC replaces its flags.", "form": "pair", "name": "EXG", "operation": "Exchange the contents of the two registers.", "sources": ["Atkinson (2009), pp. 65–66", "Motorola (1981), Appendix A, EXG", "Astle, LWTools 4.25, ch. 3"], "syntax": "source register,destination register"}, +{"aliases": [".GLOBL"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "EXPORT", "operation": "Expose a symbol to other object modules.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "EXPORT name"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "EXTDEP", "operation": "Mark an external symbol as a link dependency without emitting storage for it.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "name EXTDEP"}, +{"aliases": ["EXTERNAL", "IMPORT"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "EXTERN", "operation": "Declare a name defined in another object module.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "name EXTERN"}, +{"category": "Addressing Modes", "detail": "On the CoCo 3, the address in STA >$1A00 selects a byte through the CPU memory map. The MMU chooses the physical 8 KiB block and preserves the low 13 address bits. Use Mapped CPU in the debugger to inspect that store.", "name": "Extended", "operation": "Use the full 16-bit address in the instruction. LDA >$0400 reads a byte there.", "sources": ["Tepolt (1987), p. 20, fig. 3-4", "Motorola (1981), ch. 2", "Astle, LWTools 4.25, ch. 3"], "syntax": "LDA >$0400"}, +{"category": "Registers & Flags", "hd6309": true, "name": "F", "operation": "Eight-bit accumulator and low byte of W. CC.F is the fast-interrupt mask.", "sources": ["Burke (1993), register file"]}, +{"aliases": [".BYTE", ".DB"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "FCB", "operation": "Emit each expression as one byte. The listing shows data at the current location.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "FCB byte[,byte…]"}, +{"aliases": [".ASCII", ".STR"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "FCC", "operation": "Emit character bytes between matching delimiters.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "FCC /text/"}, +{"aliases": ["FCZ", ".ASCIZ", ".STRZ"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "FCN", "operation": "Emit a string followed by a zero byte.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "FCN /text/"}, +{"aliases": [".ASCIS", ".STRS"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "FCS", "operation": "Emit a string with the high bit set in its last character.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "FCS /text/"}, +{"aliases": [".WORD", ".DW"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "FDB", "operation": "Emit 16-bit words, high byte first.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "FDB word[,word…]"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "FDBS", "operation": "Emit 16-bit values low byte first, opposite to the processor’s normal word order.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "FDBS word[,word…]"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "FILL", "operation": "Emit the given byte repeatedly.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "FILL byte,count"}, +{"aliases": [".4BYTE", ".QUAD"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "FQB", "operation": "Emit 32-bit quantities, high byte first.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "FQB value"}, +{"category": "Addressing Modes", "hd6309": true, "name": "HD6309 indexed", "operation": "E, F and W can supply offsets for X, Y, U or S. W also supports ,W, offset,W, ,W++ and ,--W, including their indirect forms.", "sources": ["Atkinson (2009), p. 148", "Astle, LWTools 4.25, ch. 3"], "syntax": "LDA E,X · LDA ,W++"}, +{"category": "Registers & Flags", "detail": "MD bit 0 selects native mode. Bit 1 selects full FIRQ stacking. A native full-state interrupt frame includes E and F; the mode on return must agree with the frame. Cycle counts also depend on indexed postbytes, branch outcomes and transfer lengths. In VCC Plus, Step completes a TFM instruction across its byte transfers.", "hd6309": true, "name": "HD6309 modes", "operation": "The HD6309 starts in emulation mode. Many instructions take fewer cycles in native mode. LDMD #1 selects native mode with the ordinary short FIRQ frame. Mode selection is independent of the LWASM target.", "sources": ["Atkinson (2009), pp. 2, 120, 136, 144", "Burke (1993), mode register", "VCC Plus, Native Debugger, HD6309 Step"]}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "IFDEF", "operation": "Test whether a symbol has already been defined.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "IFDEF symbol"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "IFEQ", "operation": "Include the following block when the expression equals zero.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "IFEQ expression"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "IFGE", "operation": "Include the block when the expression is zero or positive.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "IFGE expression"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "IFGT", "operation": "Include the block when the expression is positive.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "IFGT expression"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "IFLE", "operation": "Include the block when the expression is zero or negative.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "IFLE expression"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "IFLT", "operation": "Include the block when the expression is negative.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "IFLT expression"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "IFNDEF", "operation": "Test whether a symbol is still undefined.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "IFNDEF symbol"}, +{"aliases": ["IF"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "IFNE", "operation": "Include the block when the expression is nonzero.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "IFNE expression"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "IFP1", "operation": "Legacy pass-number conditional. LWASM warns that it cannot reproduce pass-one assembly semantics.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "IFP1"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "IFP2", "operation": "Legacy pass-number conditional. LWASM warns that it cannot reproduce pass-two assembly semantics.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "IFP2"}, +{"aliases": ["IFOPT"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "IFPRAGMA", "operation": "Include a block according to the current pragma setting.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "IFPRAGMA option"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "IFSTR", "operation": "Include a block according to the specified string comparison.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "IFSTR comparison,arguments"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from maximum positive to minimum negative. C is preserved.", "form": "memory", "name": "INC", "operation": "Operate on a memory byte. Add one.", "sources": ["Atkinson (2009), pp. 67–68", "Motorola (1981), Appendix A, INC", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from maximum positive to minimum negative. C is preserved.", "form": "inherent", "name": "INCA", "operation": "Operate on register A. Add one.", "sources": ["Atkinson (2009), pp. 67–68", "Motorola (1981), Appendix A, INCA", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from maximum positive to minimum negative. C is preserved.", "form": "inherent", "name": "INCB", "operation": "Operate on register B. Add one.", "sources": ["Atkinson (2009), pp. 67–68", "Motorola (1981), Appendix A, INCB", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from maximum positive to minimum negative. C is preserved.", "form": "inherent", "hd6309": true, "name": "INCD", "operation": "Operate on register D. Add one.", "sources": ["Atkinson (2009), pp. 67–68", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from maximum positive to minimum negative. C is preserved.", "form": "inherent", "hd6309": true, "name": "INCE", "operation": "Operate on register E. Add one.", "sources": ["Atkinson (2009), pp. 67–68", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from maximum positive to minimum negative. C is preserved.", "form": "inherent", "hd6309": true, "name": "INCF", "operation": "Operate on register F. Add one.", "sources": ["Atkinson (2009), pp. 67–68", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"aliases": ["INCL", "LIB", "USE"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "INCLUDE", "operation": "Read another source file at this location.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "INCLUDE filename"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "INCLUDEBIN", "operation": "Copy bytes from a binary file into the assembly output.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "INCLUDEBIN filename"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "INCLUDESTR", "operation": "Treat the contents of the given string as additional assembler source.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "INCLUDESTR string"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V sets on crossing from maximum positive to minimum negative. C is preserved.", "form": "inherent", "hd6309": true, "name": "INCW", "operation": "Operate on register W. Add one.", "sources": ["Atkinson (2009), pp. 67–68", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Addressing Modes", "name": "Immediate", "operation": "Use the following operand bytes as the value.", "sources": ["Motorola (1981), ch. 2", "Astle, LWTools 4.25, ch. 3"], "syntax": "LDA #$20"}, +{"category": "Addressing Modes", "name": "Indexed", "operation": "Calculate an address from a register and an offset. LDA ,X+ reads at the original X then increments X by one. Use ,X++ for a two-byte advance. Indexed operands can also use A, B or D as signed offsets.", "sources": ["Motorola (1981), ch. 2", "Astle, LWTools 4.25, ch. 3"], "syntax": "LDA ,X+ · LDD 2,S · LDA B,Y"}, +{"category": "Addressing Modes", "name": "Indirect", "operation": "Use square brackets to fetch a two-byte pointer at the intermediate address, then access the final address. Use a two-byte increment when walking a pointer table.", "sources": ["Motorola (1981), ch. 2", "Astle, LWTools 4.25, ch. 3"], "syntax": "LDA [,X++] · JMP [$4000]"}, +{"category": "Addressing Modes", "name": "Inherent", "operation": "The opcode specifies the operation and its operands. INCA, for example, acts on A.", "sources": ["Motorola (1981), ch. 2", "Astle, LWTools 4.25, ch. 3"], "syntax": "INCA"}, +{"category": "Instructions", "flags": "CC is preserved.", "form": "memory", "name": "JMP", "operation": "Set PC to the effective address.", "sources": ["Atkinson (2009), pp. 69", "Motorola (1981), Appendix A, JMP", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "CC is preserved.", "form": "memory", "name": "JSR", "operation": "Push the return address on S, then set PC to the effective address.", "sources": ["Atkinson (2009), pp. 70", "Motorola (1981), Appendix A, JSR", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"aliases": ["LBHS"], "category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBCC", "operation": "Continue at the target when C is clear (unsigned higher or equal after a compare). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 71", "Motorola (1981), Appendix A, LBCC", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"aliases": ["LBLO"], "category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBCS", "operation": "Continue at the target when C is set (unsigned lower). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 72", "Motorola (1981), Appendix A, LBCS", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBEQ", "operation": "Continue at the target when Z is set (equal). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 73", "Motorola (1981), Appendix A, LBEQ", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBGE", "operation": "Continue at the target when N equals V (signed greater or equal). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 74", "Motorola (1981), Appendix A, LBGE", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBGT", "operation": "Continue at the target when Z is clear and N equals V (signed greater). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 75", "Motorola (1981), Appendix A, LBGT", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBHI", "operation": "Continue at the target when C and Z are both clear (unsigned higher). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 76", "Motorola (1981), Appendix A, LBHI", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBLE", "operation": "Continue at the target when Z is set or N differs from V (signed less or equal). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 78", "Motorola (1981), Appendix A, LBLE", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBLS", "operation": "Continue at the target when C or Z is set (unsigned lower or equal). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 80", "Motorola (1981), Appendix A, LBLS", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBLT", "operation": "Continue at the target when N differs from V (signed less). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 81", "Motorola (1981), Appendix A, LBLT", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBMI", "operation": "Continue at the target when N is set (negative). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 82", "Motorola (1981), Appendix A, LBMI", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBNE", "operation": "Continue at the target when Z is clear (unequal). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 83", "Motorola (1981), Appendix A, LBNE", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBPL", "operation": "Continue at the target when N is clear (nonnegative). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 84", "Motorola (1981), Appendix A, LBPL", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBRA", "operation": "Continue at the target. A branch to its own label forms a hold loop.", "sources": ["Atkinson (2009), pp. 85", "Motorola (1981), Appendix A, LBRA", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBRN", "operation": "Read the displacement and continue at the next instruction.", "sources": ["Atkinson (2009), pp. 86", "Motorola (1981), Appendix A, LBRN", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBSR", "operation": "Push the following instruction’s address on S, then continue at the target. RTS returns to the caller.", "sources": ["Atkinson (2009), pp. 87", "Motorola (1981), Appendix A, LBSR", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBVC", "operation": "Continue at the target when V is clear (no signed overflow). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 88", "Motorola (1981), Appendix A, LBVC", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "The signed 16-bit displacement is relative to the following instruction.", "flags": "CC is preserved.", "form": "relative", "name": "LBVS", "operation": "Continue at the target when V is set (signed overflow). Otherwise execute the next instruction.", "sources": ["Atkinson (2009), pp. 89", "Motorola (1981), Appendix A, LBVS", "Astle, LWTools 4.25, ch. 3"], "syntax": "target label"}, +{"category": "Instructions", "detail": "LDA #$20 places $20 in A. LDA $0400 reads the byte at $0400. LDA ,X+ reads at X, then advances X by one. The remaining CC bits keep their values. Immediate LDA takes 2 cycles. Extended LDA takes 5 on MC6809 or HD6309 emulation mode and 4 in HD6309 native mode. Indexed timing depends on the postbyte.", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "LDA", "operation": "Copy the operand into A. Use # for a literal or read one byte from the addressed memory.", "sources": ["Atkinson (2009), pp. 90", "Motorola (1981), Appendix A, LDA", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "LDB", "operation": "Copy the operand into B. Use # for a literal or read one byte from the addressed memory.", "sources": ["Atkinson (2009), pp. 90", "Motorola (1981), Appendix A, LDB", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "CC can change when a destination bit in CC is selected.", "form": "bit", "hd6309": true, "name": "LDBT", "operation": "Combine the selected memory bit with the destination register bit using copy. Only the destination bit changes.", "sources": ["Atkinson (2009), pp. 92", "Astle, LWTools 4.25, ch. 3"], "syntax": "A|B|CC,source bit,destination bit,direct address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "LDD", "operation": "Copy the operand into D. Use # for a literal or read two bytes from the addressed memory.", "sources": ["Atkinson (2009), pp. 91", "Motorola (1981), Appendix A, LDD", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "hd6309": true, "name": "LDE", "operation": "Copy the operand into E. Use # for a literal or read one byte from the addressed memory.", "sources": ["Atkinson (2009), pp. 90", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "hd6309": true, "name": "LDF", "operation": "Copy the operand into F. Use # for a literal or read one byte from the addressed memory.", "sources": ["Atkinson (2009), pp. 90", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "CC is preserved.", "form": "immediate", "hd6309": true, "name": "LDMD", "operation": "Write the low two mode-control bits of MD.", "sources": ["Atkinson (2009), pp. 93", "Astle, LWTools 4.25, ch. 3"], "syntax": "#mask"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "hd6309": true, "name": "LDQ", "operation": "Copy the operand into Q. Use # for a literal or read four bytes from the addressed memory.", "sources": ["Atkinson (2009), pp. 94", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "LDS", "operation": "Copy the operand into S. Use # for a literal or read two bytes from the addressed memory.", "sources": ["Atkinson (2009), pp. 91", "Motorola (1981), Appendix A, LDS", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "LDU", "operation": "Copy the operand into U. Use # for a literal or read two bytes from the addressed memory.", "sources": ["Atkinson (2009), pp. 91", "Motorola (1981), Appendix A, LDU", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "detail": "LDW #$1234 encodes as 10 86 12 34. E becomes $12 and F becomes $34 in either HD6309 execution mode.", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "hd6309": true, "name": "LDW", "operation": "Copy the operand into W. Use # for a literal or read two bytes from the addressed memory.", "sources": ["Atkinson (2009), pp. 91", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "LDX", "operation": "Copy the operand into X. Use # for a literal or read two bytes from the addressed memory.", "sources": ["Atkinson (2009), pp. 91", "Motorola (1981), Appendix A, LDX", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "LDY", "operation": "Copy the operand into Y. Use # for a literal or read two bytes from the addressed memory.", "sources": ["Atkinson (2009), pp. 91", "Motorola (1981), Appendix A, LDY", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "CC is preserved.", "form": "indexed", "name": "LEAS", "operation": "Calculate an indexed address and place it in S. Indirect addressing reads a pointer before producing the address.", "sources": ["Atkinson (2009), pp. 95", "Motorola (1981), Appendix A, LEAS", "Astle, LWTools 4.25, ch. 3"], "syntax": "offset,index"}, +{"category": "Instructions", "flags": "CC is preserved.", "form": "indexed", "name": "LEAU", "operation": "Calculate an indexed address and place it in U. Indirect addressing reads a pointer before producing the address.", "sources": ["Atkinson (2009), pp. 95", "Motorola (1981), Appendix A, LEAU", "Astle, LWTools 4.25, ch. 3"], "syntax": "offset,index"}, +{"category": "Instructions", "flags": "Only Z changes, to indicate a zero address.", "form": "indexed", "name": "LEAX", "operation": "Calculate an indexed address and place it in X. Indirect addressing reads a pointer before producing the address.", "sources": ["Atkinson (2009), pp. 95", "Motorola (1981), Appendix A, LEAX", "Astle, LWTools 4.25, ch. 3"], "syntax": "offset,index"}, +{"category": "Instructions", "flags": "Only Z changes, to indicate a zero address.", "form": "indexed", "name": "LEAY", "operation": "Calculate an indexed address and place it in Y. Indirect addressing reads a pointer before producing the address.", "sources": ["Atkinson (2009), pp. 95", "Motorola (1981), Appendix A, LEAY", "Astle, LWTools 4.25, ch. 3"], "syntax": "offset,index"}, +{"category": "Instructions", "flags": "N clears. Z marks zero. C receives the old bit 0. V is preserved.", "form": "memory", "name": "LSR", "operation": "Operate on a memory byte. Shift right, bringing zero into the top bit.", "sources": ["Atkinson (2009), pp. 98–99", "Motorola (1981), Appendix A, LSR", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N clears. Z marks zero. C receives the old bit 0. V is preserved.", "form": "inherent", "name": "LSRA", "operation": "Operate on register A. Shift right, bringing zero into the top bit.", "sources": ["Atkinson (2009), pp. 98–99", "Motorola (1981), Appendix A, LSRA", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N clears. Z marks zero. C receives the old bit 0. V is preserved.", "form": "inherent", "name": "LSRB", "operation": "Operate on register B. Shift right, bringing zero into the top bit.", "sources": ["Atkinson (2009), pp. 98–99", "Motorola (1981), Appendix A, LSRB", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N clears. Z marks zero. C receives the old bit 0. V is preserved.", "form": "inherent", "hd6309": true, "name": "LSRD", "operation": "Operate on register D. Shift right, bringing zero into the top bit.", "sources": ["Atkinson (2009), pp. 98–99", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N clears. Z marks zero. C receives the old bit 0. V is preserved.", "form": "inherent", "hd6309": true, "name": "LSRW", "operation": "Operate on register W. Shift right, bringing zero into the top bit.", "sources": ["Atkinson (2009), pp. 98–99", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"aliases": ["MACR"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "MACRO", "operation": "Begin defining a sequence of source lines for later expansion.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "name MACRO"}, +{"aliases": ["ABA", "CBA", "CLC", "CLF", "CLI", "CLIF", "CLV", "CPX", "DES", "DEX", "DEY", "INS", "INX", "INY", "SBA", "SEC", "SEF", "SEI", "SEIF", "SEV", "TAB", "TAP", "TBA", "TPA", "TSX", "TXS", "WAI"], "category": "Dialect & Compatibility", "name": "MC6800 compatibility", "operation": "These optional LWASM spellings expand to 6809 encodings with the 6800compat pragma. Expansion can require several instructions. Inspect the listing when stepping.", "sources": ["Astle, LWTools 4.25, ch. 3"]}, +{"category": "Registers & Flags", "hd6309": true, "name": "MD", "operation": "Mode register. LDMD controls execution mode and FIRQ stacking. BITMD tests the latched illegal-instruction and division-by-zero status.", "sources": ["Burke (1993), register file"]}, +{"category": "Instructions", "flags": "Z marks a zero product. C receives product bit 7.", "form": "inherent", "name": "MUL", "operation": "Multiply unsigned A by B and place the 16-bit product in D.", "sources": ["Atkinson (2009), pp. 100", "Motorola (1981), Appendix A, MUL", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V and C clear.", "form": "value", "hd6309": true, "name": "MULD", "operation": "Multiply signed D by a signed 16-bit operand and store the 32-bit product in Q.", "sources": ["Atkinson (2009), pp. 101", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C sets for a nonzero input. V marks negation of the most negative value.", "form": "memory", "name": "NEG", "operation": "Operate on a memory byte. Subtract the value from zero.", "sources": ["Atkinson (2009), pp. 102–103", "Motorola (1981), Appendix A, NEG", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C sets for a nonzero input. V marks negation of the most negative value.", "form": "inherent", "name": "NEGA", "operation": "Operate on register A. Subtract the value from zero.", "sources": ["Atkinson (2009), pp. 102–103", "Motorola (1981), Appendix A, NEGA", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C sets for a nonzero input. V marks negation of the most negative value.", "form": "inherent", "name": "NEGB", "operation": "Operate on register B. Subtract the value from zero.", "sources": ["Atkinson (2009), pp. 102–103", "Motorola (1981), Appendix A, NEGB", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C sets for a nonzero input. V marks negation of the most negative value.", "form": "inherent", "hd6309": true, "name": "NEGD", "operation": "Operate on register D. Subtract the value from zero.", "sources": ["Atkinson (2009), pp. 102–103", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "CC is preserved.", "form": "inherent", "name": "NOP", "operation": "Advance to the following instruction.", "sources": ["Atkinson (2009), pp. 104", "Motorola (1981), Appendix A, NOP", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "maskMemory", "hd6309": true, "name": "OIM", "operation": "Combine the literal mask and the addressed byte with OR. Write the result to that address.", "sources": ["Atkinson (2009), pp. 105", "Astle, LWTools 4.25, ch. 3"], "syntax": "#mask,address · #mask,offset,X"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "ORA", "operation": "Set bits present in either input. Combine A with the operand and save the result in A.", "sources": ["Atkinson (2009), pp. 106", "Motorola (1981), Appendix A, ORA", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "name": "ORB", "operation": "Set bits present in either input. Combine B with the operand and save the result in B.", "sources": ["Atkinson (2009), pp. 106", "Motorola (1981), Appendix A, ORB", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "Any CC bit can set.", "form": "immediate", "name": "ORCC", "operation": "Set each CC bit selected by the mask.", "sources": ["Atkinson (2009), pp. 107", "Motorola (1981), Appendix A, ORCC", "Astle, LWTools 4.25, ch. 3"], "syntax": "#mask"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "value", "hd6309": true, "name": "ORD", "operation": "Set bits present in either input. Combine D with the operand and save the result in D.", "sources": ["Atkinson (2009), pp. 108", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "ORG", "operation": "Set the address of the following output. In DECB an origin determines where a data block loads.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "ORG address"}, +{"category": "Instructions", "detail": "The destination selects the width. A word source supplies its low byte to a byte destination. For a word destination A/B supply D, E/F supply W, CC is zero-extended and DP supplies the high byte. PC is undefined in this family. See Atkinson, p. 143.", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "pair", "hd6309": true, "name": "ORR", "operation": "Apply bitwise OR to the destination using the source.", "sources": ["Atkinson (2009), pp. 109", "Astle, LWTools 4.25, ch. 3"], "syntax": "source register,destination register"}, +{"aliases": ["OS9", "MOD", "EMOD"], "category": "Dialect & Compatibility", "name": "OS-9 output directives", "operation": "OS9 encodes SWI2 followed by a service byte for OS-9 or object output. MOD and EMOD frame an OS-9 module. Assembly Development runs standalone Disk BASIC block images.", "sources": ["Astle, LWTools 4.25, ch. 3"]}, +{"category": "Registers & Flags", "name": "PC", "operation": "Program counter. Branches, jumps, calls and returns change the address of the next instruction.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "PHASE", "operation": "Give following code a different logical address for labels and expressions while retaining its output placement.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "PHASE expression"}, +{"aliases": ["*PRAGMA", "**PRAGMA", "OPT"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "PRAGMA", "operation": "Change a LWASM dialect option. A target-changing pragma affects subsequent assembly.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "PRAGMA option"}, +{"category": "Instructions", "detail": "Select CC, A, B, DP, X, Y, U or PC. LWASM also accepts D for A and B. Hardware determines the register order.", "flags": "CC is preserved.", "form": "stack", "name": "PSHS", "operation": "Save selected registers on S. The stack grows toward lower addresses.", "sources": ["Atkinson (2009), pp. 110", "Motorola (1981), Appendix A, PSHS", "Astle, LWTools 4.25, ch. 3"], "syntax": "register[,register…] · #mask"}, +{"category": "Instructions", "flags": "CC is preserved.", "form": "inherent", "hd6309": true, "name": "PSHSW", "operation": "Push both bytes of W onto S, subtracting two from the pointer.", "sources": ["Atkinson (2009), pp. 111", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "detail": "Select CC, A, B, DP, X, Y, S or PC. LWASM also accepts D for A and B. Hardware determines the register order.", "flags": "CC is preserved.", "form": "stack", "name": "PSHU", "operation": "Save selected registers on U. The stack grows toward lower addresses.", "sources": ["Atkinson (2009), pp. 110", "Motorola (1981), Appendix A, PSHU", "Astle, LWTools 4.25, ch. 3"], "syntax": "register[,register…] · #mask"}, +{"category": "Instructions", "flags": "CC is preserved.", "form": "inherent", "hd6309": true, "name": "PSHUW", "operation": "Push both bytes of W onto U, subtracting two from the pointer.", "sources": ["Atkinson (2009), pp. 112", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "detail": "Select CC, A, B, DP, X, Y, U or PC. LWASM also accepts D for A and B. Hardware determines the register order.", "flags": "Pulling CC replaces all its flags.", "form": "stack", "name": "PULS", "operation": "Restore selected registers from S, advancing the stack pointer. Pulling PC transfers control.", "sources": ["Atkinson (2009), pp. 113", "Motorola (1981), Appendix A, PULS", "Astle, LWTools 4.25, ch. 3"], "syntax": "register[,register…] · #mask"}, +{"category": "Instructions", "flags": "CC is preserved.", "form": "inherent", "hd6309": true, "name": "PULSW", "operation": "Pull two bytes into W from S, advancing the pointer by two.", "sources": ["Atkinson (2009), pp. 114", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "detail": "Select CC, A, B, DP, X, Y, S or PC. LWASM also accepts D for A and B. Hardware determines the register order.", "flags": "Pulling CC replaces all its flags.", "form": "stack", "name": "PULU", "operation": "Restore selected registers from U, advancing the stack pointer. Pulling PC transfers control.", "sources": ["Atkinson (2009), pp. 113", "Motorola (1981), Appendix A, PULU", "Astle, LWTools 4.25, ch. 3"], "syntax": "register[,register…] · #mask"}, +{"category": "Instructions", "flags": "CC is preserved.", "form": "inherent", "hd6309": true, "name": "PULUW", "operation": "Pull two bytes into W from U, advancing the pointer by two.", "sources": ["Atkinson (2009), pp. 115", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Registers & Flags", "hd6309": true, "name": "Q", "operation": "Thirty-two-bit accumulator. From most to least significant its bytes are A, B, E, F. D is the high word and W the low word.", "sources": ["Burke (1993), register file"]}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "REORG", "operation": "Restore the location associated with the previous ORG.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "REORG"}, +{"aliases": [".BLKB", ".DS", ".RS"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "RMB", "operation": "Advance the location counter by a number of bytes. Use ZMB when the load image must contain zeros.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "RMB count"}, +{"aliases": ["RMW"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "RMD", "operation": "Reserve 16-bit words.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "RMD count"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "RMQ", "operation": "Reserve 32-bit values.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "RMQ count"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old top bit. V is N XOR C.", "form": "memory", "name": "ROL", "operation": "Operate on a memory byte. Shift left, moving the old carry into bit 0.", "sources": ["Atkinson (2009), pp. 116–117", "Motorola (1981), Appendix A, ROL", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old top bit. V is N XOR C.", "form": "inherent", "name": "ROLA", "operation": "Operate on register A. Shift left, moving the old carry into bit 0.", "sources": ["Atkinson (2009), pp. 116–117", "Motorola (1981), Appendix A, ROLA", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old top bit. V is N XOR C.", "form": "inherent", "name": "ROLB", "operation": "Operate on register B. Shift left, moving the old carry into bit 0.", "sources": ["Atkinson (2009), pp. 116–117", "Motorola (1981), Appendix A, ROLB", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old top bit. V is N XOR C.", "form": "inherent", "hd6309": true, "name": "ROLD", "operation": "Operate on register D. Shift left, moving the old carry into bit 0.", "sources": ["Atkinson (2009), pp. 116–117", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old top bit. V is N XOR C.", "form": "inherent", "hd6309": true, "name": "ROLW", "operation": "Operate on register W. Shift left, moving the old carry into bit 0.", "sources": ["Atkinson (2009), pp. 116–117", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old bit 0. V is preserved.", "form": "memory", "name": "ROR", "operation": "Operate on a memory byte. Shift right, moving the old carry into the top bit.", "sources": ["Atkinson (2009), pp. 118–119", "Motorola (1981), Appendix A, ROR", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old bit 0. V is preserved.", "form": "inherent", "name": "RORA", "operation": "Operate on register A. Shift right, moving the old carry into the top bit.", "sources": ["Atkinson (2009), pp. 118–119", "Motorola (1981), Appendix A, RORA", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old bit 0. V is preserved.", "form": "inherent", "name": "RORB", "operation": "Operate on register B. Shift right, moving the old carry into the top bit.", "sources": ["Atkinson (2009), pp. 118–119", "Motorola (1981), Appendix A, RORB", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old bit 0. V is preserved.", "form": "inherent", "hd6309": true, "name": "RORD", "operation": "Operate on register D. Shift right, moving the old carry into the top bit.", "sources": ["Atkinson (2009), pp. 118–119", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. C receives the old bit 0. V is preserved.", "form": "inherent", "hd6309": true, "name": "RORW", "operation": "Operate on register W. Shift right, moving the old carry into the top bit.", "sources": ["Atkinson (2009), pp. 118–119", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "Restores saved CC.", "form": "inherent", "name": "RTI", "operation": "Pull CC and the return state from S. Stacked E determines whether to restore a full frame.", "sources": ["Atkinson (2009), pp. 120", "Motorola (1981), Appendix A, RTI", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "CC is preserved.", "form": "inherent", "name": "RTS", "operation": "Pull the return address from S into PC and advance S by two.", "sources": ["Atkinson (2009), pp. 121", "Motorola (1981), Appendix A, RTS", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Addressing Modes", "name": "Relative", "operation": "Add a signed displacement to PC after the operand. Branch targets are labels. Indexed PC-relative data references use PCR in LWASM.", "sources": ["Motorola (1981), ch. 2", "Astle, LWTools 4.25, ch. 3"], "syntax": "BNE again · LDA table,PCR"}, +{"category": "Registers & Flags", "name": "S", "operation": "Sixteen-bit hardware stack pointer. JSR, interrupts and PSHS use memory below S. Initialize a writable stack before making a standalone call.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow. H is undefined.", "form": "value", "name": "SBCA", "operation": "Subtract the operand and incoming borrow from A. Write the difference to A.", "sources": ["Atkinson (2009), pp. 122", "Motorola (1981), Appendix A, SBCA", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow. H is undefined.", "form": "value", "name": "SBCB", "operation": "Subtract the operand and incoming borrow from B. Write the difference to B.", "sources": ["Atkinson (2009), pp. 122", "Motorola (1981), Appendix A, SBCB", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow.", "form": "value", "hd6309": true, "name": "SBCD", "operation": "Subtract the operand and incoming borrow from D. Write the difference to D.", "sources": ["Atkinson (2009), pp. 123", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "detail": "The destination selects the width. A word source supplies its low byte to a byte destination. For a word destination A/B supply D, E/F supply W, CC is zero-extended and DP supplies the high byte. PC is undefined in this family. See Atkinson, p. 143.", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow.", "form": "pair", "hd6309": true, "name": "SBCR", "operation": "Subtract source and borrow from destination.", "sources": ["Atkinson (2009), pp. 124", "Astle, LWTools 4.25, ch. 3"], "syntax": "source register,destination register"}, +{"aliases": ["SECT", ".AREA"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "SECTION", "operation": "Begin a section in an object module. The linker determines final placement.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "SECTION name"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "SET", "operation": "Assign a symbol a value that later SET statements may change.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "name SET expression"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "SETDP", "operation": "Tell the assembler the assumed direct page. Guest software must establish the matching DP value.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "SETDP page"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "SETSTR", "operation": "Set an assembler string variable.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "SETSTR name=string"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V and C are preserved.", "form": "inherent", "name": "SEX", "operation": "Copy B’s sign bit across A to extend B into D.", "sources": ["Atkinson (2009), pp. 125", "Motorola (1981), Appendix A, SEX", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V and C are preserved.", "form": "inherent", "hd6309": true, "name": "SEXW", "operation": "Copy W’s sign bit across D to extend W into Q.", "sources": ["Atkinson (2009), pp. 126", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "memory", "name": "STA", "operation": "Copy A to the destination address. Multi-byte stores write the high byte first.", "sources": ["Atkinson (2009), pp. 127", "Motorola (1981), Appendix A, STA", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "memory", "name": "STB", "operation": "Copy B to the destination address. Multi-byte stores write the high byte first.", "sources": ["Atkinson (2009), pp. 127", "Motorola (1981), Appendix A, STB", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "CC can change when a destination bit in CC is selected.", "form": "bit", "hd6309": true, "name": "STBT", "operation": "Copy the selected register bit to the destination bit in direct-page memory.", "sources": ["Atkinson (2009), pp. 129", "Astle, LWTools 4.25, ch. 3"], "syntax": "A|B|CC,source bit,destination bit,direct address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "memory", "name": "STD", "operation": "Copy D to the destination address. Multi-byte stores write the high byte first.", "sources": ["Atkinson (2009), pp. 128", "Motorola (1981), Appendix A, STD", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "memory", "hd6309": true, "name": "STE", "operation": "Copy E to the destination address. Multi-byte stores write the high byte first.", "sources": ["Atkinson (2009), pp. 127", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "memory", "hd6309": true, "name": "STF", "operation": "Copy F to the destination address. Multi-byte stores write the high byte first.", "sources": ["Atkinson (2009), pp. 127", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "memory", "hd6309": true, "name": "STQ", "operation": "Copy Q to the destination address. Multi-byte stores write the high byte first.", "sources": ["Atkinson (2009), pp. 130", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "STRUCT", "operation": "Begin a structure layout. Field labels describe offsets in its instances.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "name STRUCT"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "memory", "name": "STS", "operation": "Copy S to the destination address. Multi-byte stores write the high byte first.", "sources": ["Atkinson (2009), pp. 128", "Motorola (1981), Appendix A, STS", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "memory", "name": "STU", "operation": "Copy U to the destination address. Multi-byte stores write the high byte first.", "sources": ["Atkinson (2009), pp. 128", "Motorola (1981), Appendix A, STU", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "memory", "hd6309": true, "name": "STW", "operation": "Copy W to the destination address. Multi-byte stores write the high byte first.", "sources": ["Atkinson (2009), pp. 128", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "memory", "name": "STX", "operation": "Copy X to the destination address. Multi-byte stores write the high byte first.", "sources": ["Atkinson (2009), pp. 128", "Motorola (1981), Appendix A, STX", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "memory", "name": "STY", "operation": "Copy Y to the destination address. Multi-byte stores write the high byte first.", "sources": ["Atkinson (2009), pp. 128", "Motorola (1981), Appendix A, STY", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow. H is undefined.", "form": "value", "name": "SUBA", "operation": "Subtract the operand from A. Write the difference to A.", "sources": ["Atkinson (2009), pp. 131", "Motorola (1981), Appendix A, SUBA", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow. H is undefined.", "form": "value", "name": "SUBB", "operation": "Subtract the operand from B. Write the difference to B.", "sources": ["Atkinson (2009), pp. 131", "Motorola (1981), Appendix A, SUBB", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow.", "form": "value", "name": "SUBD", "operation": "Subtract the operand from D. Write the difference to D.", "sources": ["Atkinson (2009), pp. 132", "Motorola (1981), Appendix A, SUBD", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow. H is undefined.", "form": "value", "hd6309": true, "name": "SUBE", "operation": "Subtract the operand from E. Write the difference to E.", "sources": ["Atkinson (2009), pp. 131", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow. H is undefined.", "form": "value", "hd6309": true, "name": "SUBF", "operation": "Subtract the operand from F. Write the difference to F.", "sources": ["Atkinson (2009), pp. 131", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "detail": "The destination selects the width. A word source supplies its low byte to a byte destination. For a word destination A/B supply D, E/F supply W, CC is zero-extended and DP supplies the high byte. PC is undefined in this family. See Atkinson, p. 143.", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow.", "form": "pair", "hd6309": true, "name": "SUBR", "operation": "Subtract source from destination.", "sources": ["Atkinson (2009), pp. 133", "Astle, LWTools 4.25, ch. 3"], "syntax": "source register,destination register"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V marks signed overflow. C marks a borrow.", "form": "value", "hd6309": true, "name": "SUBW", "operation": "Subtract the operand from W. Write the difference to W.", "sources": ["Atkinson (2009), pp. 132", "Astle, LWTools 4.25, ch. 3"], "syntax": "#literal · address"}, +{"category": "Instructions", "flags": "E sets. I and F set after stacking.", "form": "inherent", "name": "SWI", "operation": "Save a full interrupt frame on S and fetch the new PC from $FFFA.", "sources": ["Atkinson (2009), pp. 134", "Motorola (1981), Appendix A, SWI", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "E sets. I and F keep their values.", "form": "inherent", "name": "SWI2", "operation": "Save a full interrupt frame on S and fetch the new PC from $FFF4.", "sources": ["Atkinson (2009), pp. 134", "Motorola (1981), Appendix A, SWI", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "E sets. I and F keep their values.", "form": "inherent", "name": "SWI3", "operation": "Save a full interrupt frame on S and fetch the new PC from $FFF2.", "sources": ["Atkinson (2009), pp. 134", "Motorola (1981), Appendix A, SWI", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "CC is preserved.", "form": "inherent", "name": "SYNC", "operation": "Wait for an interrupt request. Even a masked request can release the wait.", "sources": ["Atkinson (2009), pp. 135", "Motorola (1981), Appendix A, SYNC", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"aliases": ["COPY", "COPY+", "COPY-", "TFRP", "TFRM", "IMP", "IMPLODE", "TFRS", "EXP", "EXPAND", "TFRR"], "category": "Instructions", "detail": "LWASM’s alternative spellings take two bare registers. COPY/COPY+/TFRP advance both, COPY-/TFRM retreat both, IMP/IMPLODE/TFRS advance the source and EXP/EXPAND/TFRR advance the destination. In VCC Plus, debugger Step finishes the block. Continue can hit a breakpoint again between bytes.", "flags": "CC is preserved.", "form": "transfer", "hd6309": true, "name": "TFM", "operation": "Copy W bytes between addresses held in D, X, Y, U or S. Each suffix advances, retreats or holds its pointer after a byte. W counts down to zero. Without interruption the transfer costs 6 cycles plus 3 per byte.", "sources": ["Atkinson (2009), pp. 136", "VCC Plus, Native Debugger, HD6309 Step", "Astle, LWTools 4.25, ch. 3"], "syntax": "r+,r+ · r-,r- · r+,r · r,r+"}, +{"category": "Instructions", "detail": "Use equal-width registers on the MC6809. The HD6309 has additional registers and defined mixed-width behavior. Writing PC transfers control.", "flags": "Writing CC replaces its flags.", "form": "pair", "name": "TFR", "operation": "Copy the source register to the destination.", "sources": ["Atkinson (2009), pp. 137–138", "Motorola (1981), Appendix A, TFR", "Astle, LWTools 4.25, ch. 3"], "syntax": "source register,destination register"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "maskMemory", "hd6309": true, "name": "TIM", "operation": "Combine the literal mask and the addressed byte with AND. Use the result only to test flags.", "sources": ["Atkinson (2009), pp. 139", "Astle, LWTools 4.25, ch. 3"], "syntax": "#mask,address · #mask,offset,X"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "memory", "name": "TST", "operation": "Operate on a memory byte. Test the value while preserving it.", "sources": ["Atkinson (2009), pp. 140–141", "Motorola (1981), Appendix A, TST", "Astle, LWTools 4.25, ch. 3"], "syntax": "address"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "inherent", "name": "TSTA", "operation": "Operate on register A. Test the value while preserving it.", "sources": ["Atkinson (2009), pp. 140–141", "Motorola (1981), Appendix A, TSTA", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "inherent", "name": "TSTB", "operation": "Operate on register B. Test the value while preserving it.", "sources": ["Atkinson (2009), pp. 140–141", "Motorola (1981), Appendix A, TSTB", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "inherent", "hd6309": true, "name": "TSTD", "operation": "Operate on register D. Test the value while preserving it.", "sources": ["Atkinson (2009), pp. 140–141", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "inherent", "hd6309": true, "name": "TSTE", "operation": "Operate on register E. Test the value while preserving it.", "sources": ["Atkinson (2009), pp. 140–141", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "inherent", "hd6309": true, "name": "TSTF", "operation": "Operate on register F. Test the value while preserving it.", "sources": ["Atkinson (2009), pp. 140–141", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Instructions", "flags": "N reflects the sign bit. Z marks a zero result. V clears. C is preserved.", "form": "inherent", "hd6309": true, "name": "TSTW", "operation": "Operate on register W. Test the value while preserving it.", "sources": ["Atkinson (2009), pp. 140–141", "Astle, LWTools 4.25, ch. 3"], "syntax": "No operand"}, +{"category": "Registers & Flags", "name": "U", "operation": "Sixteen-bit user stack pointer, also available as an index register. PSHU and PULU use this stack.", "sources": ["Motorola (1981), ch. 1"]}, +{"aliases": ["HCF", "RHF", "RESET", "HALT", "BREAK", "LOG"], "category": "Dialect & Compatibility", "name": "Undocumented and emulator opcodes", "operation": "LWASM lists HCF, RHF and RESET for certain 6809 encodings. Behavior outside the documented instruction set can differ by chip. BREAK and LOG are emulator extensions. VCC Plus’s Mac decoder also excludes the optional HALT/BREAK encodings.", "sources": ["Atkinson (2009), p. 153", "Astle, LWTools 4.25, ch. 3", "VCC Plus, Native Debugger, disassembly"]}, +{"category": "Registers & Flags", "hd6309": true, "name": "V", "operation": "Additional 16-bit HD6309 register used in register operations. CC.V is a separate overflow flag.", "sources": ["Burke (1993), register file"]}, +{"category": "Registers & Flags", "hd6309": true, "name": "W", "operation": "Sixteen-bit accumulator combining E (high) and F (low). TFM uses W as a byte count.", "sources": ["Burke (1993), register file"]}, +{"aliases": ["MSG"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "WARNING", "operation": "Report a warning with the supplied text.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "WARNING message"}, +{"category": "Registers & Flags", "name": "X", "operation": "Sixteen-bit index register. Use X to address a table or traverse bytes.", "sources": ["Motorola (1981), ch. 1"]}, +{"category": "Registers & Flags", "name": "Y", "operation": "Sixteen-bit index register. X and Y can walk independent buffers.", "sources": ["Motorola (1981), ch. 1"]}, +{"aliases": ["BSZ", "FZB"], "category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "ZMB", "operation": "Emit the requested number of zero bytes.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "ZMB count"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "ZMD", "operation": "Emit zero-filled words.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "ZMD count"}, +{"category": "LWASM Directives", "detail": "LWASM directive. Its effects take place during assembly.", "name": "ZMQ", "operation": "Emit zero-filled four-byte quantities.", "sources": ["Astle, LWTools 4.25, ch. 3"], "syntax": "ZMQ count"} +]} diff --git a/platforms/macos/Resources/BASICReference.json b/platforms/macos/Resources/BASICReference.json new file mode 100644 index 0000000..a246abd --- /dev/null +++ b/platforms/macos/Resources/BASICReference.json @@ -0,0 +1,5237 @@ +{ + "entries": [ + { + "id": "ERROR./0", + "keyword": "/0", + "title": "/0 — Division by zero", + "category": "Errors", + "dialect": "common", + "summary": "A denominator evaluated to zero. Check the values at the reported line.", + "syntax": [ + "/0 ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "IF" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "ABS", + "keyword": "ABS", + "title": "ABS", + "category": "Math", + "dialect": "common", + "summary": "Return the magnitude of a number.", + "syntax": [ + "ABS(number)" + ], + "parameters": [], + "sample": "PRINT ABS(-7)", + "exampleID": "math", + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "18" + }, + { + "id": "ERROR.AE", + "keyword": "AE", + "title": "AE — File already exists", + "category": "Errors", + "dialect": "disk", + "summary": "The destination name is already in use. Choose another name or use the documented replacement behavior.", + "syntax": [ + "AE ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "COPY", + "RGB.COPY", + "RENAME" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "9" + }, + { + "id": "AND", + "keyword": "AND", + "title": "AND", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Combine integer bit patterns; often used to join conditions.", + "syntax": [ + "expression AND expression" + ], + "parameters": [], + "sample": "IF A>0 AND B>0 THEN PRINT \"BOTH\"", + "exampleID": null, + "related": [ + "OR", + "NOT", + "IF" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "ERROR.AO", + "keyword": "AO", + "title": "AO — Already open", + "category": "Errors", + "dialect": "common", + "summary": "The file is already open. Close it before reopening; on SDC, an image cannot be mounted twice.", + "syntax": [ + "AO ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "CLOSE", + "OPEN", + "SDC.DRIVE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "AS", + "keyword": "AS", + "title": "AS", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Give a string variable a field within a direct-access file buffer.", + "syntax": [ + "FIELD #file,length AS stringVariable" + ], + "parameters": [], + "sample": "FIELD #1,20 AS N$", + "exampleID": null, + "related": [ + "FIELD" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "ASC", + "keyword": "ASC", + "title": "ASC", + "category": "Strings", + "dialect": "common", + "summary": "Return the character code of the first character.", + "syntax": [ + "ASC(string)" + ], + "parameters": [ + "The string must not be empty." + ], + "sample": "PRINT ASC(\"A\")", + "exampleID": "strings", + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "18" + }, + { + "id": "ATN", + "keyword": "ATN", + "title": "ATN", + "category": "Math", + "dialect": "common", + "summary": "Return the arctangent in radians.", + "syntax": [ + "ATN(number)" + ], + "parameters": [ + "Multiply by 180/PI to convert the result to degrees." + ], + "sample": "PRINT ATN(1)", + "exampleID": null, + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "18" + }, + { + "id": "ATTR", + "keyword": "ATTR", + "title": "ATTR", + "category": "Text and output", + "dialect": "common", + "summary": "Choose text colors and optional character attributes.", + "syntax": [ + "ATTR foreground,background[,B][,U]" + ], + "parameters": [ + "B enables blinking; U enables underlining." + ], + "sample": "WIDTH 80:ATTR 3,0,U", + "exampleID": null, + "related": [ + "WIDTH", + "LOCATE", + "PALETTE" + ], + "notes": [ + "CoCo 3 high-resolution text modes." + ], + "source": "basicGuide", + "sourcePage": "2" + }, + { + "id": "AUDIO", + "keyword": "AUDIO", + "title": "AUDIO", + "category": "Cassette", + "dialect": "common", + "summary": "Connect or disconnect cassette playback sound from the CoCo audio output.", + "syntax": [ + "AUDIO ON", + "AUDIO OFF" + ], + "parameters": [], + "sample": "AUDIO ON", + "exampleID": null, + "related": [ + "MOTOR", + "CLOAD", + "SOUND" + ], + "notes": [ + "Use the cassette transport and audio settings in VCC Plus to supply and hear tape playback." + ], + "source": "basicGuide", + "sourcePage": "2" + }, + { + "id": "BACKUP", + "keyword": "BACKUP", + "title": "BACKUP", + "category": "Disk files", + "dialect": "disk", + "summary": "Duplicate a BASIC disk onto another disk.", + "syntax": [ + "BACKUP source TO destination", + "BACKUP drive" + ], + "parameters": [ + "Single-drive form requires disk exchanges." + ], + "sample": "BACKUP 0 TO 1", + "exampleID": null, + "related": [ + "COPY" + ], + "notes": [ + "Overwrites the destination disk. Use a new disposable image, never the only copy of your data." + ], + "source": "diskGuide", + "sourcePage": "3" + }, + { + "id": "ERROR.BR", + "keyword": "BR", + "title": "BR — Bad record", + "category": "Errors", + "dialect": "disk", + "summary": "The direct-access record number is invalid.", + "syntax": [ + "BR ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "DISK.GET", + "DISK.PUT", + "LOC", + "LOF" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "9" + }, + { + "id": "BRK", + "keyword": "BRK", + "title": "BRK", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Introduce a Break-key trap as part of ON BRK GOTO.", + "syntax": [ + "ON BRK GOTO line" + ], + "parameters": [], + "sample": "ON BRK GOTO 100", + "exampleID": null, + "related": [ + "ON.BRK" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "ERROR.BS", + "keyword": "BS", + "title": "BS — Bad subscript", + "category": "Errors", + "dialect": "common", + "summary": "An array index is outside its declared bounds or has the wrong number of dimensions.", + "syntax": [ + "BS ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "DIM" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "BUTTON", + "keyword": "BUTTON", + "title": "BUTTON", + "category": "Input", + "dialect": "common", + "summary": "Read a joystick button on the CoCo 3.", + "syntax": [ + "BUTTON(number)" + ], + "parameters": [ + "0/1: right first/second button; 2/3: left first/second button.", + "Returns 1 when pressed, otherwise 0." + ], + "sample": "PRINT BUTTON(2)", + "exampleID": null, + "related": [ + "JOYSTK" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "18" + }, + { + "id": "CHR$", + "keyword": "CHR$", + "title": "CHR$", + "category": "Strings", + "dialect": "common", + "summary": "Return the character with the specified code.", + "syntax": [ + "CHR$(code)" + ], + "parameters": [ + "code: 0-255.", + "Control codes may move the cursor or change display behavior." + ], + "sample": "PRINT CHR$(65)", + "exampleID": "strings", + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "18" + }, + { + "id": "CIRCLE", + "keyword": "CIRCLE", + "title": "CIRCLE", + "category": "Graphics", + "dialect": "common", + "summary": "Draw a circle, ellipse or arc on the PMODE screen.", + "syntax": [ + "CIRCLE(x,y),radius[,color[,ratio[,start,end]]]" + ], + "parameters": [ + "ratio changes height relative to width.", + "start and end select fractions of a full turn." + ], + "sample": "CIRCLE(128,96),30", + "exampleID": null, + "related": [ + "LINE", + "PAINT", + "HCIRCLE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "2" + }, + { + "id": "CLEAR", + "keyword": "CLEAR", + "title": "CLEAR", + "category": "Variables and arrays", + "dialect": "common", + "summary": "Clear variables and adjust string space or the BASIC memory ceiling.", + "syntax": [ + "CLEAR [stringBytes [, topAddress]]" + ], + "parameters": [ + "stringBytes reserves string workspace.", + "topAddress leaves higher memory for machine-language code." + ], + "sample": "CLEAR 300", + "exampleID": null, + "related": [ + "MEM", + "ERROR.OS" + ], + "notes": [ + "This discards current variable values; do not use it merely to clear the display." + ], + "source": "basicGuide", + "sourcePage": "2" + }, + { + "id": "CLOAD", + "keyword": "CLOAD", + "title": "CLOAD", + "category": "Cassette", + "dialect": "common", + "summary": "Load a BASIC program from cassette.", + "syntax": [ + "CLOAD [\"filename\"]" + ], + "parameters": [ + "Omitting the name selects the next BASIC program.", + "Cassette names have up to eight characters." + ], + "sample": "CLOAD \"HELLO\"", + "exampleID": null, + "related": [ + "CLOADM", + "CSAVE" + ], + "notes": [ + "Loading replaces the program in CoCo memory. It does not open a Mac source document." + ], + "source": "basicGuide", + "sourcePage": "2" + }, + { + "id": "CLOADM", + "keyword": "CLOADM", + "title": "CLOADM", + "category": "Cassette", + "dialect": "common", + "summary": "Load a machine-language program from cassette.", + "syntax": [ + "CLOADM [\"filename\"[,offset]]" + ], + "parameters": [ + "offset relocates loaded bytes; it does not rewrite addresses inside the program." + ], + "sample": "CLOADM \"DEMO\"", + "exampleID": null, + "related": [ + "EXEC", + "CSAVEM", + "CLOAD" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "3" + }, + { + "id": "CLOSE", + "keyword": "CLOSE", + "title": "CLOSE", + "category": "Disk files", + "dialect": "disk", + "summary": "Finish access to one or more open files.", + "syntax": [ + "CLOSE [#file[,#file ...]]" + ], + "parameters": [ + "With no file number, close all open files." + ], + "sample": "CLOSE #1", + "exampleID": null, + "related": [ + "OPEN", + "UNLOAD" + ], + "notes": [ + "Closing output files completes buffered writes." + ], + "source": "diskGuide", + "sourcePage": "3" + }, + { + "id": "CLS", + "keyword": "CLS", + "title": "CLS", + "category": "Text and output", + "dialect": "common", + "summary": "Clear the text screen.", + "syntax": [ + "CLS [color]" + ], + "parameters": [ + "color chooses a text-screen background when supplied." + ], + "sample": "CLS", + "exampleID": "hello", + "related": [ + "PRINT", + "WIDTH", + "HCLS", + "PCLS" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "3" + }, + { + "id": "CMP", + "keyword": "CMP", + "title": "CMP", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Restore the standard composite palette on a CoCo 3.", + "syntax": [ + "PALETTE CMP" + ], + "parameters": [], + "sample": "PALETTE CMP", + "exampleID": null, + "related": [ + "PALETTE", + "RGB" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "ERROR.CN", + "keyword": "CN", + "title": "CN — Cannot continue", + "category": "Errors", + "dialect": "common", + "summary": "BASIC no longer has a valid continuation after a stop. Restart with RUN if appropriate.", + "syntax": [ + "CN ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "CONT", + "RUN", + "STOP" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "COLOR", + "keyword": "COLOR", + "title": "COLOR", + "category": "Graphics", + "dialect": "common", + "summary": "Choose foreground and background colors for PMODE graphics.", + "syntax": [ + "COLOR foreground,background" + ], + "parameters": [ + "Available colors depend on the current graphics mode." + ], + "sample": "COLOR 1,0", + "exampleID": null, + "related": [ + "PMODE", + "PCLS", + "PSET" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "3" + }, + { + "id": "CONT", + "keyword": "CONT", + "title": "CONT", + "category": "Debugging and errors", + "dialect": "common", + "summary": "Continue after an ordinary BASIC stop when the interpreter still has a valid continuation.", + "syntax": [ + "CONT" + ], + "parameters": [], + "sample": "CONT", + "exampleID": null, + "related": [ + "STOP", + "ERROR.CN" + ], + "notes": [ + "The editor Continue button resumes its debugger stop. It does not type this command.", + "Changing the program can invalidate BASIC's saved continuation." + ], + "source": "basicGuide", + "sourcePage": "3" + }, + { + "id": "COPY", + "keyword": "COPY", + "title": "COPY", + "category": "Disk files", + "dialect": "disk", + "summary": "Copy one BASIC disk file to another filename or drive.", + "syntax": [ + "COPY \"source/ext:drive\" TO \"destination/ext:drive\"" + ], + "parameters": [ + "Include the filename extensions." + ], + "sample": "COPY \"HELLO/BAS:0\" TO \"HELLO/BAS:1\"", + "exampleID": null, + "related": [ + "RGB.COPY", + "BACKUP" + ], + "notes": [ + "Writes to the destination disk. RGB-DOS changes overwrite behavior; see its variant entry." + ], + "source": "diskGuide", + "sourcePage": "3" + }, + { + "id": "RGB.COPY", + "keyword": "COPY", + "title": "COPY — RGB-DOS", + "category": "DOS differences", + "dialect": "rgbdos", + "summary": "Copy a file, retaining its name when the destination is only a drive number.", + "syntax": [ + "COPY \"source/ext:drive\" TO drive", + "COPY \"source/ext:drive\" TO \"destination/ext:drive\"" + ], + "parameters": [], + "sample": "COPY \"HELLO/BAS:0\" TO 1", + "exampleID": null, + "related": [ + "COPY", + "RGB.DRIVE" + ], + "notes": [ + "Writes the destination. Direct mode asks before replacing an existing file; inside a BASIC program, replacement occurs without that prompt." + ], + "source": "rgbdos", + "sourcePage": "PDF page 8" + }, + { + "id": "COS", + "keyword": "COS", + "title": "COS", + "category": "Math", + "dialect": "common", + "summary": "Return the cosine of an angle in radians.", + "syntax": [ + "COS(angle)" + ], + "parameters": [ + "Angles are radians, not degrees." + ], + "sample": "PRINT COS(0)", + "exampleID": null, + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "18" + }, + { + "id": "CSAVE", + "keyword": "CSAVE", + "title": "CSAVE", + "category": "Cassette", + "dialect": "common", + "summary": "Record the current BASIC program on cassette.", + "syntax": [ + "CSAVE \"filename\"[,A]" + ], + "parameters": [ + "A selects ASCII rather than tokenized program storage." + ], + "sample": "CSAVE \"HELLO\"", + "exampleID": null, + "related": [ + "CLOAD", + "CSAVEM" + ], + "notes": [ + "Prepare the cassette recording transport first. Export the recording in VCC Plus to retain it as a Mac file." + ], + "source": "basicGuide", + "sourcePage": "3" + }, + { + "id": "CSAVEM", + "keyword": "CSAVEM", + "title": "CSAVEM", + "category": "Cassette", + "dialect": "common", + "summary": "Record a memory range as a machine-language cassette file.", + "syntax": [ + "CSAVEM \"filename\",first,last,entry" + ], + "parameters": [ + "first and last are inclusive byte addresses; entry is the EXEC address." + ], + "sample": "CSAVEM \"DEMO\",&H5000,&H50FF,&H5000", + "exampleID": null, + "related": [ + "CLOADM", + "EXEC" + ], + "notes": [ + "Prepare cassette recording before issuing the command." + ], + "source": "basicGuide", + "sourcePage": "4" + }, + { + "id": "CVN", + "keyword": "CVN", + "title": "CVN", + "category": "Disk files", + "dialect": "disk", + "summary": "Decode a five-byte BASIC number stored in a string.", + "syntax": [ + "CVN(string)" + ], + "parameters": [ + "The string must contain the expected numeric encoding." + ], + "sample": "A=CVN(MKN$(42))", + "exampleID": null, + "related": [ + "MKN$" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "3" + }, + { + "id": "DATA", + "keyword": "DATA", + "title": "DATA", + "category": "Variables and arrays", + "dialect": "common", + "summary": "Place constant values in a program for READ.", + "syntax": [ + "DATA constant [, constant ...]" + ], + "parameters": [ + "Use quotes around strings containing commas." + ], + "sample": "DATA 12,\"COCO\"", + "exampleID": "data", + "related": [ + "READ", + "RESTORE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "4" + }, + { + "id": "ERROR.DD", + "keyword": "DD", + "title": "DD — Duplicate dimension", + "category": "Errors", + "dialect": "common", + "summary": "An array has already been dimensioned or implicitly created. Dimension it before its first use.", + "syntax": [ + "DD ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "DIM" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "DEF", + "keyword": "DEF", + "title": "DEF", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Introduce a user-defined BASIC or machine-language function.", + "syntax": [ + "DEF FNname(argument)=expression", + "DEF USRn=address" + ], + "parameters": [], + "sample": "DEF FNA(X)=X*X", + "exampleID": null, + "related": [ + "DEF.FN", + "DEF.USR" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "DEF.FN", + "keyword": "DEF FN", + "title": "DEF FN", + "category": "Math", + "dialect": "common", + "summary": "Define a numeric function to evaluate later.", + "syntax": [ + "DEF FNname(parameter) = expression" + ], + "parameters": [ + "FNname is invoked with a numeric argument." + ], + "sample": "DEF FNA(X)=X*X", + "exampleID": "math", + "related": [ + "FN" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "4" + }, + { + "id": "DEF.USR", + "keyword": "DEF USR", + "title": "DEF USR", + "category": "Machine language", + "dialect": "common", + "summary": "Set the entry address of a machine-language function.", + "syntax": [ + "DEF USRn = address" + ], + "parameters": [ + "n: 0-9; the function must follow BASIC's machine-language calling convention." + ], + "sample": "DEF USR0=&H5000", + "exampleID": null, + "related": [ + "USR", + "EXEC" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "4" + }, + { + "id": "DEL", + "keyword": "DEL", + "title": "DEL", + "category": "Source editing", + "dialect": "common", + "summary": "Delete one or more lines from the CoCo's in-memory program.", + "syntax": [ + "DEL first[-last]", + "DEL -last", + "DEL first-" + ], + "parameters": [], + "sample": "DEL 100-200", + "exampleID": null, + "related": [ + "LIST", + "NEW" + ], + "notes": [ + "Use care: the interpreter does not provide Mac-style Undo for this command." + ], + "source": "basicGuide", + "sourcePage": "4" + }, + { + "id": "ERROR.DF", + "keyword": "DF", + "title": "DF — Disk full", + "category": "Errors", + "dialect": "disk", + "summary": "There is insufficient space for the write. Use another working image or remove unneeded files carefully.", + "syntax": [ + "DF ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "FREE", + "DIR" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "9" + }, + { + "id": "DIM", + "keyword": "DIM", + "title": "DIM", + "category": "Variables and arrays", + "dialect": "common", + "summary": "Reserve numeric or string arrays with inclusive upper bounds.", + "syntax": [ + "DIM name(upperBound [, upperBound ...]) [, ...]" + ], + "parameters": [ + "Indices start at zero: DIM A(5) provides six elements.", + "Dimension an array before using it; do not dimension it twice." + ], + "sample": "DIM A(5),N$(2,3)", + "exampleID": "arrays", + "related": [ + "ERROR.BS", + "ERROR.DD" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "5" + }, + { + "id": "DIR", + "keyword": "DIR", + "title": "DIR", + "category": "Disk files", + "dialect": "disk", + "summary": "List files stored on a BASIC disk.", + "syntax": [ + "DIR [drive]" + ], + "parameters": [ + "Omit drive to list the default drive.", + "The listing shows name, extension, type, storage form and granule count." + ], + "sample": "DIR 0", + "exampleID": "disk-directory", + "related": [ + "DRIVE", + "RGB.DRIVE", + "SDC.DIR" + ], + "notes": [ + "In SDC-DOS, plain DIR still lists the mounted disk; DIR - browses the SD folder." + ], + "source": "diskGuide", + "sourcePage": "3" + }, + { + "id": "SDC.DIR", + "keyword": "DIR", + "title": "DIR — SDC-DOS", + "category": "DOS differences", + "dialect": "sdcdos", + "summary": "Browse the card folder instead of the files inside a mounted disk.", + "syntax": [ + "DIR -", + "DIR \"path\"", + "DIR = \"path\"" + ], + "parameters": [ + "DIR = \"/\" selects the card root; DIR = \"..\" selects its parent folder." + ], + "sample": "DIR = \"/\":DIR -", + "exampleID": "sdc-mount", + "related": [ + "DIR", + "SDC.DRIVE" + ], + "notes": [ + "Paths are relative to the SDC card folder selected in VCC Plus, not arbitrary Mac paths.", + "Plain DIR 0 still lists files inside the image mounted in drive 0." + ], + "source": "sdcGuide", + "sourcePage": "11-12" + }, + { + "id": "DLOAD", + "keyword": "DLOAD", + "title": "DLOAD", + "category": "Machine language", + "dialect": "common", + "summary": "Historical serial program-loading command.", + "syntax": [ + "DLOAD [\"filename\"]" + ], + "parameters": [ + "Requires a compatible serial host and protocol." + ], + "sample": "DLOAD \"PROGRAM\"", + "exampleID": null, + "related": [ + "CLOAD", + "LOAD" + ], + "notes": [ + "The bundled CoCo 3 environment does not provide the historical DLOAD host service. Use native source opening or media loading instead." + ], + "source": "basicGuide", + "sourcePage": null + }, + { + "id": "ERROR.DN", + "keyword": "DN", + "title": "DN — Device number", + "category": "Errors", + "dialect": "common", + "summary": "The selected device or drive number is not valid for this operation.", + "syntax": [ + "DN ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "OPEN", + "DRIVE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "DOS", + "keyword": "DOS", + "title": "DOS", + "category": "Disk files", + "dialect": "disk", + "summary": "Invoke a boot loader from drive 0.", + "syntax": [ + "DOS" + ], + "parameters": [ + "Drive 0 must contain a compatible boot loader." + ], + "sample": "DOS", + "exampleID": null, + "related": [ + "RGB.DOS" + ], + "notes": [ + "A boot loader can start another operating system or a program; DOS does not always mean OS-9." + ], + "source": "diskGuide", + "sourcePage": "3" + }, + { + "id": "RGB.DOS", + "keyword": "DOS", + "title": "DOS — RGB-DOS", + "category": "DOS differences", + "dialect": "rgbdos", + "summary": "Boot a selected BASIC volume, or try its AUTOEXEC program.", + "syntax": [ + "DOS [drive]" + ], + "parameters": [], + "sample": "DOS 255", + "exampleID": null, + "related": [ + "DOS", + "RGB.DRIVE" + ], + "notes": [ + "The NitrOS-9 preset boots automatically. Its running OS-9 shell is not a BASIC editor target." + ], + "source": "rgbdos", + "sourcePage": "PDF page 7" + }, + { + "id": "DRAW", + "keyword": "DRAW", + "title": "DRAW", + "category": "Graphics", + "dialect": "common", + "summary": "Draw PMODE graphics using a compact movement string.", + "syntax": [ + "DRAW string" + ], + "parameters": [ + "U,D,L,R move in the four main directions; E,F,G,H move diagonally.", + "BM moves without drawing. C selects color, S scale and A angle.", + "X executes a string variable embedded in the drawing sequence." + ], + "sample": "DRAW \"BM40,40;R30;D30;L30;U30\"", + "exampleID": null, + "related": [ + "HDRAW", + "LINE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "5" + }, + { + "id": "DRIVE", + "keyword": "DRIVE", + "title": "DRIVE", + "category": "Disk files", + "dialect": "disk", + "summary": "Choose the default drive for later disk commands.", + "syntax": [ + "DRIVE number" + ], + "parameters": [ + "Disk BASIC uses drive numbers 0-3." + ], + "sample": "DRIVE 0", + "exampleID": null, + "related": [ + "DIR", + "RGB.DRIVE", + "SDC.DRIVE" + ], + "notes": [ + "RGB-DOS and SDC-DOS extend this command in different ways." + ], + "source": "diskGuide", + "sourcePage": "4" + }, + { + "id": "RGB.DRIVE", + "keyword": "DRIVE", + "title": "DRIVE — RGB-DOS", + "category": "DOS differences", + "dialect": "rgbdos", + "summary": "Switch between virtual hard-disk volumes and floppy drives.", + "syntax": [ + "DRIVE volume", + "DRIVE ON", + "DRIVE OFF [lastFloppy]", + "DRIVE #unit" + ], + "parameters": [ + "volume: 0-255 selects a default virtual BASIC disk. With DRIVE OFF, drives 0-3 refer to floppy drives instead.", + "DRIVE OFF exposes floppy drives; DRIVE ON restores hard-disk routing.", + "#unit selects the hard-disk unit. VCC Plus has HD0 and HD1." + ], + "sample": "DRIVE OFF:DIR 0:DRIVE ON", + "exampleID": "rgb-routing", + "related": [ + "DRIVE", + "DIR", + "RGB.DOS" + ], + "notes": [ + "The Hard Drive BASIC preset uses RGB-DOS. Do not confuse a virtual BASIC volume number with an HD device number.", + "Historical DRIVE STOP and DRIVE RESTORE hardware operations are not needed for VCC Plus image files." + ], + "source": "rgbdos", + "sourcePage": "PDF page 7" + }, + { + "id": "SDC.DRIVE", + "keyword": "DRIVE", + "title": "DRIVE — SDC-DOS", + "category": "DOS differences", + "dialect": "sdcdos", + "summary": "Inspect, mount or unload images on the SDC card.", + "syntax": [ + "DRIVE", + "DRIVE drive,\"path\"[,volume]", + "DRIVE drive,UNLOAD" + ], + "parameters": [ + "drive is 0 or 1; volume selects a BASIC volume inside a compatible hard-disk image." + ], + "sample": "DRIVE 0,\"HELLO.DSK\"", + "exampleID": "sdc-mount", + "related": [ + "DRIVE", + "SDC.DIR", + "SDC.NEW" + ], + "notes": [ + "Use short card filenames. A mounted image is a disk containing BASIC files, not itself a BASIC program.", + "The same image cannot be mounted in both drives." + ], + "source": "sdcGuide", + "sourcePage": "9-12" + }, + { + "id": "SDC.NEW", + "keyword": "DRIVE NEW", + "title": "DRIVE NEW", + "category": "DOS differences", + "dialect": "sdcdos", + "summary": "Create and mount a new disk image in the selected card folder.", + "syntax": [ + "DRIVE drive,\"filename.DSK\",NEW" + ], + "parameters": [], + "sample": "DRIVE 0,\"WORK.DSK\",NEW", + "exampleID": null, + "related": [ + "SDC.DRIVE", + "SDC.DIR", + "DSKINI" + ], + "notes": [ + "Writes a new file; it does not replace an existing one.", + "Hardware documentation also covers SDF, flash, RTC and DriveWire features. These are not supported SDC features in VCC Plus." + ], + "source": "sdcGuide", + "sourcePage": "12" + }, + { + "id": "ERROR.DS", + "keyword": "DS", + "title": "DS — Direct statement in file", + "category": "Errors", + "dialect": "common", + "summary": "A program being loaded contains a statement without a BASIC line number.", + "syntax": [ + "DS ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "LOAD", + "MERGE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "DSKI$", + "keyword": "DSKI$", + "title": "DSKI$", + "category": "Disk files", + "dialect": "disk", + "summary": "Read a disk sector into two string variables.", + "syntax": [ + "DSKI$ drive,track,sector,string1,string2" + ], + "parameters": [ + "The strings receive the two halves of a 256-byte sector." + ], + "sample": "DSKI$ 0,17,1,A$,B$", + "exampleID": null, + "related": [ + "DSKO$" + ], + "notes": [ + "Raw-sector access bypasses normal file interpretation." + ], + "source": "diskGuide", + "sourcePage": "4" + }, + { + "id": "DSKINI", + "keyword": "DSKINI", + "title": "DSKINI", + "category": "Disk files", + "dialect": "disk", + "summary": "Initialize a disk for BASIC file storage.", + "syntax": [ + "DSKINI [drive]" + ], + "parameters": [ + "Select the intended drive explicitly." + ], + "sample": "DSKINI 1", + "exampleID": null, + "related": [ + "FREE", + "DIR" + ], + "notes": [ + "Erases the selected disk and disturbs BASIC workspace. Use only a blank disposable image." + ], + "source": "diskGuide", + "sourcePage": "4" + }, + { + "id": "DSKO$", + "keyword": "DSKO$", + "title": "DSKO$", + "category": "Disk files", + "dialect": "disk", + "summary": "Write two strings directly to a disk sector.", + "syntax": [ + "DSKO$ drive,track,sector,string1,string2" + ], + "parameters": [ + "Use properly sized data for the selected sector." + ], + "sample": "DSKO$ 1,17,1,A$,B$", + "exampleID": null, + "related": [ + "DSKI$" + ], + "notes": [ + "Raw writes can corrupt the filesystem. This is not a safe way to save a BASIC program." + ], + "source": "diskGuide", + "sourcePage": "4" + }, + { + "id": "EDIT", + "keyword": "EDIT", + "title": "EDIT", + "category": "Source editing", + "dialect": "common", + "summary": "Use the original BASIC line editor for one program line.", + "syntax": [ + "EDIT line" + ], + "parameters": [ + "The native BASIC editor is a separate way to edit source." + ], + "sample": "EDIT 100", + "exampleID": null, + "related": [ + "LIST", + "DEL", + "RENUM" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "5" + }, + { + "id": "ELSE", + "keyword": "ELSE", + "title": "ELSE", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Introduce the false branch of an IF statement.", + "syntax": [ + "IF condition THEN statements ELSE statements" + ], + "parameters": [], + "sample": "IF A=1 THEN PRINT \"ONE\" ELSE PRINT \"OTHER\"", + "exampleID": null, + "related": [ + "IF", + "THEN" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "END", + "keyword": "END", + "title": "END", + "category": "Program flow", + "dialect": "common", + "summary": "Finish the program.", + "syntax": [ + "END" + ], + "parameters": [], + "sample": "END", + "exampleID": "hello", + "related": [ + "STOP", + "RUN" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "5" + }, + { + "id": "EOF", + "keyword": "EOF", + "title": "EOF", + "category": "Disk files", + "dialect": "disk", + "summary": "Check whether an open input stream is at end of file.", + "syntax": [ + "EOF(file)" + ], + "parameters": [ + "0 means more input remains; -1 indicates end of file.", + "Also applies to cassette input with device -1." + ], + "sample": "IF EOF(1) THEN CLOSE #1", + "exampleID": null, + "related": [ + "OPEN", + "DISK.INPUT" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "4" + }, + { + "id": "ERROR.ER", + "keyword": "ER", + "title": "ER — End of record", + "category": "Errors", + "dialect": "disk", + "summary": "A direct-access operation went beyond the current record boundary. Check record size and fields.", + "syntax": [ + "ER ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "OPEN", + "FIELD" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "9" + }, + { + "id": "ERLIN", + "keyword": "ERLIN", + "title": "ERLIN", + "category": "Debugging and errors", + "dialect": "common", + "summary": "Read the BASIC line number that caused the trapped error.", + "syntax": [ + "ERLIN" + ], + "parameters": [ + "Use inside an ON ERR handler." + ], + "sample": "PRINT ERLIN", + "exampleID": "error-trap", + "related": [ + "ERNO", + "ON.ERR" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "18" + }, + { + "id": "ERNO", + "keyword": "ERNO", + "title": "ERNO", + "category": "Debugging and errors", + "dialect": "common", + "summary": "Read the numeric code for the last trapped BASIC error.", + "syntax": [ + "ERNO" + ], + "parameters": [ + "Use inside an ON ERR handler." + ], + "sample": "PRINT ERNO", + "exampleID": "error-trap", + "related": [ + "ERLIN", + "ON.ERR" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "18" + }, + { + "id": "ERR", + "keyword": "ERR", + "title": "ERR", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Introduce an error trap as part of ON ERR GOTO.", + "syntax": [ + "ON ERR GOTO line" + ], + "parameters": [], + "sample": "ON ERR GOTO 100", + "exampleID": null, + "related": [ + "ON.ERR", + "ERNO", + "ERLIN" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "EXEC", + "keyword": "EXEC", + "title": "EXEC", + "category": "Machine language", + "dialect": "common", + "summary": "Transfer execution to a machine-language entry point.", + "syntax": [ + "EXEC [address]" + ], + "parameters": [ + "Without an address, use the entry point from the last applicable machine-language load." + ], + "sample": "EXEC &H5000", + "exampleID": null, + "related": [ + "LOADM", + "CLOADM", + "DEF.USR" + ], + "notes": [ + "Running arbitrary memory as code can crash or alter the emulated machine." + ], + "source": "basicGuide", + "sourcePage": "6" + }, + { + "id": "EXP", + "keyword": "EXP", + "title": "EXP", + "category": "Math", + "dialect": "common", + "summary": "Raise e to a numeric power.", + "syntax": [ + "EXP(number)" + ], + "parameters": [ + "Large arguments can overflow." + ], + "sample": "PRINT EXP(0)", + "exampleID": null, + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "19" + }, + { + "id": "ERROR.FC", + "keyword": "FC", + "title": "FC — Illegal function call", + "category": "Errors", + "dialect": "common", + "summary": "An argument is outside the range accepted by this command or function. Check its parameter descriptions.", + "syntax": [ + "FC ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "SQR", + "ASC" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "ERROR.FD", + "keyword": "FD", + "title": "FD — Bad file data", + "category": "Errors", + "dialect": "common", + "summary": "The next input value cannot be read into the requested variable type.", + "syntax": [ + "FD ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "INPUT", + "DISK.INPUT", + "WRITE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "FIELD", + "keyword": "FIELD", + "title": "FIELD", + "category": "Disk files", + "dialect": "disk", + "summary": "Divide a direct-access buffer into string fields.", + "syntax": [ + "FIELD #file,length AS stringVariable[, ...]" + ], + "parameters": [ + "Field lengths must fit in the opened record." + ], + "sample": "FIELD #1,20 AS N$,5 AS V$", + "exampleID": null, + "related": [ + "OPEN", + "LSET", + "RSET", + "DISK.GET", + "DISK.PUT" + ], + "notes": [ + "Use LSET/RSET rather than ordinary string assignment when filling fields." + ], + "source": "diskGuide", + "sourcePage": "4" + }, + { + "id": "FILES", + "keyword": "FILES", + "title": "FILES", + "category": "Disk files", + "dialect": "disk", + "summary": "Allocate file buffers for disk access.", + "syntax": [ + "FILES count[,size]" + ], + "parameters": [ + "count reserves file buffers; size supplies the total buffer size." + ], + "sample": "FILES 2", + "exampleID": null, + "related": [ + "OPEN", + "FIELD" + ], + "notes": [ + "Changes BASIC workspace allocation. Arrange file buffers before storing working data." + ], + "source": "diskGuide", + "sourcePage": "4" + }, + { + "id": "FIX", + "keyword": "FIX", + "title": "FIX", + "category": "Math", + "dialect": "common", + "summary": "Remove the fractional part toward zero.", + "syntax": [ + "FIX(number)" + ], + "parameters": [ + "FIX(-2.7) is -2." + ], + "sample": "PRINT FIX(-2.7)", + "exampleID": "math", + "related": [ + "INT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "19" + }, + { + "id": "ERROR.FM", + "keyword": "FM", + "title": "FM — File mode", + "category": "Errors", + "dialect": "common", + "summary": "The operation does not match the mode used to open the file.", + "syntax": [ + "FM ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "OPEN" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "FN", + "keyword": "FN", + "title": "FN", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Invoke a function defined with DEF FN.", + "syntax": [ + "FNname(argument)" + ], + "parameters": [], + "sample": "PRINT FNA(3)", + "exampleID": null, + "related": [ + "DEF.FN" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "ERROR.FN", + "keyword": "FN", + "title": "FN — Bad filename", + "category": "Errors", + "dialect": "disk", + "summary": "The filename is not valid for the selected filesystem. Check its length, extension and drive syntax.", + "syntax": [ + "FN ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "LOAD", + "SAVE" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "9" + }, + { + "id": "ERROR.FO", + "keyword": "FO", + "title": "FO — Field overflow", + "category": "Errors", + "dialect": "disk", + "summary": "FIELD definitions exceed the file buffer's record size.", + "syntax": [ + "FO ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "FIELD", + "OPEN" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "9" + }, + { + "id": "FOR", + "keyword": "FOR", + "title": "FOR", + "category": "Program flow", + "dialect": "common", + "summary": "Start a counted loop.", + "syntax": [ + "FOR variable = start TO finish [STEP increment]" + ], + "parameters": [ + "increment defaults to 1; a negative value counts downward.", + "NEXT closes the loop." + ], + "sample": "FOR I=1 TO 5", + "exampleID": "count", + "related": [ + "NEXT", + "TO", + "STEP" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "6" + }, + { + "id": "FREE", + "keyword": "FREE", + "title": "FREE", + "category": "Disk files", + "dialect": "disk", + "summary": "Count free granules on a BASIC disk.", + "syntax": [ + "FREE(drive)" + ], + "parameters": [ + "Granules are the BASIC filesystem's allocation units." + ], + "sample": "PRINT FREE(0)", + "exampleID": null, + "related": [ + "DIR" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "4" + }, + { + "id": "ERROR.FS", + "keyword": "FS", + "title": "FS — Bad file structure", + "category": "Errors", + "dialect": "disk", + "summary": "The disk file or filesystem structure is inconsistent with the requested operation.", + "syntax": [ + "FS ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "DIR" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "9" + }, + { + "id": "GET", + "keyword": "GET", + "title": "GET", + "category": "Graphics", + "dialect": "common", + "summary": "Copy a PMODE rectangle into a numeric array.", + "syntax": [ + "GET(x1,y1)-(x2,y2),array[,G]" + ], + "parameters": [ + "Dimension a two-dimensional array large enough for the rectangle.", + "G stores full graphics detail for PUT operations." + ], + "sample": "GET(0,0)-(7,7),A,G", + "exampleID": null, + "related": [ + "PUT", + "DISK.GET" + ], + "notes": [ + "GET #file,record is a different form for disk files." + ], + "source": "basicGuide", + "sourcePage": "6" + }, + { + "id": "DISK.GET", + "keyword": "GET", + "title": "GET — disk record", + "category": "Disk files", + "dialect": "disk", + "summary": "Read a direct-access record into its file buffer.", + "syntax": [ + "GET #file[,record]" + ], + "parameters": [ + "Use OPEN \"D\" and FIELD to interpret the record.", + "An omitted record advances through the file." + ], + "sample": "GET #1,3", + "exampleID": null, + "related": [ + "FIELD", + "DISK.PUT", + "GET" + ], + "notes": [ + "This form is separate from graphics GET." + ], + "source": "diskGuide", + "sourcePage": "4" + }, + { + "id": "GO", + "keyword": "GO", + "title": "GO", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Prefix of GO TO and GO SUB; the joined forms are also accepted.", + "syntax": [ + "GO TO line", + "GO SUB line" + ], + "parameters": [], + "sample": "GO TO 100", + "exampleID": null, + "related": [ + "GOTO", + "GOSUB" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "GOSUB", + "keyword": "GOSUB", + "title": "GOSUB", + "category": "Program flow", + "dialect": "common", + "summary": "Call a numbered subroutine and remember where to return.", + "syntax": [ + "GOSUB line" + ], + "parameters": [ + "End the subroutine with RETURN.", + "Use the editor's Step Into, Step Over or Step Out to follow calls." + ], + "sample": "GOSUB 100", + "exampleID": "subroutine", + "related": [ + "RETURN", + "ON" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "6" + }, + { + "id": "GOTO", + "keyword": "GOTO", + "title": "GOTO", + "category": "Program flow", + "dialect": "common", + "summary": "Continue execution at another numbered line.", + "syntax": [ + "GOTO line" + ], + "parameters": [ + "line must exist in the loaded program." + ], + "sample": "GOTO 100", + "exampleID": "branch", + "related": [ + "GOSUB", + "ON", + "ERROR.UL" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "6" + }, + { + "id": "HBUFF", + "keyword": "HBUFF", + "title": "HBUFF", + "category": "Graphics", + "dialect": "common", + "summary": "Reserve a buffer for high-resolution GET/PUT graphics.", + "syntax": [ + "HBUFF buffer,size" + ], + "parameters": [ + "size is the number of bytes to reserve; maximum 7931." + ], + "sample": "HBUFF 1,200", + "exampleID": null, + "related": [ + "HGET", + "HPUT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "6" + }, + { + "id": "HCIRCLE", + "keyword": "HCIRCLE", + "title": "HCIRCLE", + "category": "Graphics", + "dialect": "common", + "summary": "Draw a high-resolution circle, ellipse or arc.", + "syntax": [ + "HCIRCLE(x,y),radius[,color[,ratio[,start,end]]]" + ], + "parameters": [ + "Optional ratio changes the shape; start/end restrict the arc." + ], + "sample": "HCIRCLE(160,96),30,3", + "exampleID": null, + "related": [ + "HLINE", + "HPAINT", + "CIRCLE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "7" + }, + { + "id": "HCLS", + "keyword": "HCLS", + "title": "HCLS", + "category": "Graphics", + "dialect": "common", + "summary": "Fill the CoCo 3 high-resolution graphics screen.", + "syntax": [ + "HCLS [color]" + ], + "parameters": [ + "Omitting color uses the current background." + ], + "sample": "HCLS 0", + "exampleID": "high-graphics", + "related": [ + "HSCREEN", + "HCOLOR" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "7" + }, + { + "id": "HCOLOR", + "keyword": "HCOLOR", + "title": "HCOLOR", + "category": "Graphics", + "dialect": "common", + "summary": "Choose foreground and background palette entries for high-resolution graphics.", + "syntax": [ + "HCOLOR foreground,background" + ], + "parameters": [ + "Use palette entries available in the selected HSCREEN mode." + ], + "sample": "HCOLOR 3,0", + "exampleID": null, + "related": [ + "HSCREEN", + "PALETTE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "7" + }, + { + "id": "HDRAW", + "keyword": "HDRAW", + "title": "HDRAW", + "category": "Graphics", + "dialect": "common", + "summary": "Use a movement string to draw high-resolution graphics.", + "syntax": [ + "HDRAW string" + ], + "parameters": [ + "Uses the movement commands described under DRAW." + ], + "sample": "HDRAW \"BM40,40;R30;D30;L30;U30\"", + "exampleID": null, + "related": [ + "DRAW", + "HLINE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "7" + }, + { + "id": "HEX$", + "keyword": "HEX$", + "title": "HEX$", + "category": "Strings", + "dialect": "common", + "summary": "Convert a number to hexadecimal text.", + "syntax": [ + "HEX$(number)" + ], + "parameters": [ + "The returned string has no &H prefix." + ], + "sample": "PRINT HEX$(255)", + "exampleID": null, + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "19" + }, + { + "id": "HGET", + "keyword": "HGET", + "title": "HGET", + "category": "Graphics", + "dialect": "common", + "summary": "Save a high-resolution rectangle in an HBUFF buffer.", + "syntax": [ + "HGET(x1,y1)-(x2,y2),buffer" + ], + "parameters": [ + "Reserve sufficient space with HBUFF before copying." + ], + "sample": "HGET(0,0)-(7,7),1", + "exampleID": null, + "related": [ + "HBUFF", + "HPUT", + "GET" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "8" + }, + { + "id": "HLINE", + "keyword": "HLINE", + "title": "HLINE", + "category": "Graphics", + "dialect": "common", + "summary": "Draw a high-resolution line or rectangle.", + "syntax": [ + "HLINE [(x1,y1)]-(x2,y2),color[,B or BF]" + ], + "parameters": [ + "B draws a box; BF fills it.", + "color may be a palette entry, PSET or PRESET." + ], + "sample": "HLINE(10,10)-(100,70),3,BF", + "exampleID": null, + "related": [ + "HSET", + "HCIRCLE", + "LINE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "8" + }, + { + "id": "ERROR.HP", + "keyword": "HP", + "title": "HP — High-resolution print error", + "category": "Errors", + "dialect": "common", + "summary": "The requested high-resolution text operation is invalid. Check the display mode and coordinates.", + "syntax": [ + "HP ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "HPRINT", + "HSCREEN" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "HPAINT", + "keyword": "HPAINT", + "title": "HPAINT", + "category": "Graphics", + "dialect": "common", + "summary": "Fill a bounded high-resolution region.", + "syntax": [ + "HPAINT(x,y)[,color[,border]]" + ], + "parameters": [ + "Select a point inside a closed border." + ], + "sample": "HPAINT(160,96),3,3", + "exampleID": null, + "related": [ + "HCIRCLE", + "HLINE", + "PAINT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "8" + }, + { + "id": "HPOINT", + "keyword": "HPOINT", + "title": "HPOINT", + "category": "Graphics", + "dialect": "common", + "summary": "Read the color of a high-resolution graphics point.", + "syntax": [ + "HPOINT(x,y)" + ], + "parameters": [ + "Coordinates follow the selected HSCREEN mode." + ], + "sample": "A=HPOINT(20,20)", + "exampleID": "high-graphics", + "related": [ + "HSET" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "19" + }, + { + "id": "HPRINT", + "keyword": "HPRINT", + "title": "HPRINT", + "category": "Graphics", + "dialect": "common", + "summary": "Draw text in a CoCo 3 high-resolution graphics display.", + "syntax": [ + "HPRINT(column,row),string" + ], + "parameters": [ + "Coordinates select character cells, not individual pixels." + ], + "sample": "HPRINT(2,2),\"COCO\"", + "exampleID": null, + "related": [ + "HSCREEN", + "HCOLOR", + "PRINT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "8" + }, + { + "id": "HPUT", + "keyword": "HPUT", + "title": "HPUT", + "category": "Graphics", + "dialect": "common", + "summary": "Restore a high-resolution rectangle from a buffer.", + "syntax": [ + "HPUT(x1,y1)-(x2,y2),buffer,action" + ], + "parameters": [ + "action: PSET, PRESET, AND, OR or NOT." + ], + "sample": "HPUT(10,10)-(17,17),1,PSET", + "exampleID": null, + "related": [ + "HBUFF", + "HGET", + "PUT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "9" + }, + { + "id": "ERROR.HR", + "keyword": "HR", + "title": "HR — High-resolution graphics error", + "category": "Errors", + "dialect": "common", + "summary": "A CoCo 3 graphics argument or buffer is invalid. Check coordinates, mode and allocated buffer size.", + "syntax": [ + "HR ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "HSCREEN", + "HBUFF", + "HGET", + "HPUT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "HRESET", + "keyword": "HRESET", + "title": "HRESET", + "category": "Graphics", + "dialect": "common", + "summary": "Reset a high-resolution point to the background.", + "syntax": [ + "HRESET(x,y)" + ], + "parameters": [], + "sample": "HRESET(20,20)", + "exampleID": null, + "related": [ + "HSET", + "HPOINT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "9" + }, + { + "id": "HSCREEN", + "keyword": "HSCREEN", + "title": "HSCREEN", + "category": "Graphics", + "dialect": "common", + "summary": "Select a CoCo 3 high-resolution graphics display.", + "syntax": [ + "HSCREEN mode" + ], + "parameters": [ + "0: return to low-resolution display.", + "1: 320x192, 4 colors; 2: 320x192, 16 colors.", + "3: 640x192, 2 colors; 4: 640x192, 4 colors.", + "Selecting modes 1-4 also clears that graphics display." + ], + "sample": "HSCREEN 2", + "exampleID": "high-graphics", + "related": [ + "HCLS", + "HCOLOR", + "PALETTE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "9" + }, + { + "id": "HSET", + "keyword": "HSET", + "title": "HSET", + "category": "Graphics", + "dialect": "common", + "summary": "Set a point in CoCo 3 high-resolution graphics.", + "syntax": [ + "HSET(x,y[,color])" + ], + "parameters": [ + "Omitting color uses the foreground.", + "Coordinates depend on the HSCREEN resolution." + ], + "sample": "HSET(20,20,3)", + "exampleID": "high-graphics", + "related": [ + "HRESET", + "HPOINT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "9" + }, + { + "id": "HSTAT", + "keyword": "HSTAT", + "title": "HSTAT", + "category": "Text and output", + "dialect": "common", + "summary": "Read the high-resolution text character, attributes and cursor coordinates.", + "syntax": [ + "HSTAT character,attribute,column,row" + ], + "parameters": [ + "Supply numeric variables to receive the four results." + ], + "sample": "HSTAT C,A,X,Y", + "exampleID": null, + "related": [ + "LOCATE", + "ATTR", + "WIDTH" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "9" + }, + { + "id": "ERROR.ID", + "keyword": "ID", + "title": "ID — Illegal direct statement", + "category": "Errors", + "dialect": "common", + "summary": "This statement requires execution from a numbered program rather than the immediate prompt.", + "syntax": [ + "ID ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "RUN" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "ERROR.IE", + "keyword": "IE", + "title": "IE — Input past end", + "category": "Errors", + "dialect": "common", + "summary": "The program tried to read beyond the end of a file. Test EOF before requesting another item.", + "syntax": [ + "IE ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "EOF" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "IF", + "keyword": "IF", + "title": "IF", + "category": "Program flow", + "dialect": "common", + "summary": "Choose statements or a destination line according to a test.", + "syntax": [ + "IF condition THEN statements [ELSE statements]", + "IF condition THEN line [ELSE line]" + ], + "parameters": [ + "Zero is false; a nonzero value is true.", + "A false condition skips the remainder of its branch on that BASIC line." + ], + "sample": "IF A=42 THEN PRINT \"YES\" ELSE PRINT \"NO\"", + "exampleID": "branch", + "related": [ + "THEN", + "ELSE", + "AND", + "OR" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "9" + }, + { + "id": "INKEY$", + "keyword": "INKEY$", + "title": "INKEY$", + "category": "Input", + "dialect": "common", + "summary": "Read a waiting key without stopping for input.", + "syntax": [ + "INKEY$" + ], + "parameters": [ + "The result is an empty string when no key is waiting." + ], + "sample": "A$=INKEY$", + "exampleID": null, + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "19" + }, + { + "id": "INPUT", + "keyword": "INPUT", + "title": "INPUT", + "category": "Input", + "dialect": "common", + "summary": "Read keyboard values into numeric or string variables.", + "syntax": [ + "INPUT [\"prompt\";] variable [, variable ...]" + ], + "parameters": [ + "Separate multiple responses with commas.", + "Use LINE INPUT when a whole line, including commas, belongs in one string." + ], + "sample": "INPUT \"YOUR NAME\";N$", + "exampleID": null, + "related": [ + "LINE.INPUT", + "INKEY$" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "10" + }, + { + "id": "DISK.INPUT", + "keyword": "INPUT", + "title": "INPUT — disk file", + "category": "Disk files", + "dialect": "disk", + "summary": "Read delimited values from an open input file.", + "syntax": [ + "INPUT #file,variable[,variable ...]" + ], + "parameters": [ + "Variable types must match the stored fields." + ], + "sample": "INPUT #1,A,N$", + "exampleID": null, + "related": [ + "OPEN", + "WRITE", + "EOF" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "5" + }, + { + "id": "INSTR", + "keyword": "INSTR", + "title": "INSTR", + "category": "Strings", + "dialect": "common", + "summary": "Find the first occurrence of a substring.", + "syntax": [ + "INSTR([start,]string,target)" + ], + "parameters": [ + "Positions start at 1; a zero result means no match." + ], + "sample": "PRINT INSTR(\"COMPUTER\",\"PUT\")", + "exampleID": "strings", + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "19" + }, + { + "id": "INT", + "keyword": "INT", + "title": "INT", + "category": "Math", + "dialect": "common", + "summary": "Round down to an integer, including for negative values.", + "syntax": [ + "INT(number)" + ], + "parameters": [ + "INT(-2.7) is -3." + ], + "sample": "PRINT INT(-2.7)", + "exampleID": "math", + "related": [ + "FIX" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "19" + }, + { + "id": "ERROR.IO", + "keyword": "IO", + "title": "IO — Input/output error", + "category": "Errors", + "dialect": "common", + "summary": "The requested media operation failed. Check mounting, format, filename and the selected drive.", + "syntax": [ + "IO ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "DIR", + "DRIVE", + "CLOAD" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "JOYSTK", + "keyword": "JOYSTK", + "title": "JOYSTK", + "category": "Input", + "dialect": "common", + "summary": "Read an emulated joystick axis.", + "syntax": [ + "JOYSTK(axis)" + ], + "parameters": [ + "0: right X; 1: right Y; 2: left X; 3: left Y.", + "Values range from 0 to 63; center is about 31." + ], + "sample": "PRINT JOYSTK(2)", + "exampleID": null, + "related": [ + "BUTTON" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "19" + }, + { + "id": "KILL", + "keyword": "KILL", + "title": "KILL", + "category": "Disk files", + "dialect": "disk", + "summary": "Remove a file from a BASIC disk directory.", + "syntax": [ + "KILL \"filename/ext[:drive]\"" + ], + "parameters": [ + "Include the extension." + ], + "sample": "KILL \"OLD/BAS:0\"", + "exampleID": null, + "related": [ + "DIR", + "RENAME" + ], + "notes": [ + "Deletes the file from the selected disk; the command has no Undo." + ], + "source": "diskGuide", + "sourcePage": "5" + }, + { + "id": "LEFT$", + "keyword": "LEFT$", + "title": "LEFT$", + "category": "Strings", + "dialect": "common", + "summary": "Take characters from the beginning of a string.", + "syntax": [ + "LEFT$(string,count)" + ], + "parameters": [ + "count is the maximum number of characters returned." + ], + "sample": "PRINT LEFT$(\"COMPUTER\",3)", + "exampleID": "strings", + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "20" + }, + { + "id": "LEN", + "keyword": "LEN", + "title": "LEN", + "category": "Strings", + "dialect": "common", + "summary": "Count the characters in a string.", + "syntax": [ + "LEN(string)" + ], + "parameters": [], + "sample": "PRINT LEN(\"COCO\")", + "exampleID": "strings", + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "20" + }, + { + "id": "LET", + "keyword": "LET", + "title": "LET", + "category": "Variables and arrays", + "dialect": "common", + "summary": "Assign a value to a variable; LET is optional.", + "syntax": [ + "[LET] variable = expression" + ], + "parameters": [ + "Use a name ending in $ for a string.", + "Only the first two characters of a variable name distinguish it in this BASIC." + ], + "sample": "A=6*7", + "exampleID": "math", + "related": [ + "DIM" + ], + "notes": [ + "Changing source in the editor does not change variables in a running CoCo program." + ], + "source": "basicGuide", + "sourcePage": "10" + }, + { + "id": "LINE", + "keyword": "LINE", + "title": "LINE", + "category": "Graphics", + "dialect": "common", + "summary": "Draw a PMODE line, rectangle or filled rectangle.", + "syntax": [ + "LINE [(x1,y1)]-(x2,y2),action[,B or BF]" + ], + "parameters": [ + "action is PSET or PRESET; B draws a rectangle and BF fills it.", + "If the first point is omitted, drawing starts at the previous endpoint.", + "B or BF can be used with either PSET or PRESET." + ], + "sample": "LINE (10,10)-(80,60),PSET,BF", + "exampleID": null, + "related": [ + "PSET", + "CIRCLE", + "HLINE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "10" + }, + { + "id": "LINE.INPUT", + "keyword": "LINE INPUT", + "title": "LINE INPUT", + "category": "Input", + "dialect": "common", + "summary": "Read an entire line into a string variable.", + "syntax": [ + "LINE INPUT [\"prompt\";] stringVariable" + ], + "parameters": [ + "Commas in the entered line remain part of the string." + ], + "sample": "LINE INPUT \"MESSAGE\";M$", + "exampleID": null, + "related": [ + "INPUT", + "DISK.LINE.INPUT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "10" + }, + { + "id": "DISK.LINE.INPUT", + "keyword": "LINE INPUT", + "title": "LINE INPUT — disk file", + "category": "Disk files", + "dialect": "disk", + "summary": "Read an entire file line into one string.", + "syntax": [ + "LINE INPUT #file,stringVariable" + ], + "parameters": [ + "Commas remain part of the string." + ], + "sample": "LINE INPUT #1,A$", + "exampleID": null, + "related": [ + "OPEN", + "EOF", + "LINE.INPUT" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "5" + }, + { + "id": "LIST", + "keyword": "LIST", + "title": "LIST", + "category": "Source editing", + "dialect": "common", + "summary": "Display a program or a range of BASIC lines.", + "syntax": [ + "LIST [first[-last]]", + "LIST -last", + "LIST first-" + ], + "parameters": [ + "A single line number lists only that line." + ], + "sample": "LIST 100-200", + "exampleID": null, + "related": [ + "LLIST", + "EDIT" + ], + "notes": [ + "Read from CoCo brings program text into the native editor without typing LIST." + ], + "source": "basicGuide", + "sourcePage": "11" + }, + { + "id": "LLIST", + "keyword": "LLIST", + "title": "LLIST", + "category": "Text and output", + "dialect": "common", + "summary": "Send a program listing to the printer device.", + "syntax": [ + "LLIST [first[-last]]" + ], + "parameters": [], + "sample": "LLIST 100-200", + "exampleID": null, + "related": [ + "LIST", + "PRINT" + ], + "notes": [ + "Enable VCC Plus Printer Output capture to collect printer text." + ], + "source": "basicGuide", + "sourcePage": "11" + }, + { + "id": "LOAD", + "keyword": "LOAD", + "title": "LOAD", + "category": "Disk files", + "dialect": "disk", + "summary": "Load a BASIC program from disk.", + "syntax": [ + "LOAD \"filename\"[,R]" + ], + "parameters": [ + "R runs the program after loading.", + "A :drive suffix selects a drive instead of the default." + ], + "sample": "LOAD \"HELLO:0\"", + "exampleID": null, + "related": [ + "SAVE", + "DISK.RUN" + ], + "notes": [ + "Loading replaces the BASIC program in CoCo memory." + ], + "source": "diskGuide", + "sourcePage": "5" + }, + { + "id": "LOADM", + "keyword": "LOADM", + "title": "LOADM", + "category": "Disk files", + "dialect": "disk", + "summary": "Load a machine-language file from disk.", + "syntax": [ + "LOADM \"filename\"[,offset]" + ], + "parameters": [ + "offset changes where bytes are loaded; internal machine-code addresses are not relocated." + ], + "sample": "LOADM \"DEMO:0\"", + "exampleID": null, + "related": [ + "EXEC", + "SAVEM" + ], + "notes": [ + "Use EXEC after loading unless the file implements its own autostart." + ], + "source": "diskGuide", + "sourcePage": "5" + }, + { + "id": "LOC", + "keyword": "LOC", + "title": "LOC", + "category": "Disk files", + "dialect": "disk", + "summary": "Read the current record number for an open disk file.", + "syntax": [ + "LOC(file)" + ], + "parameters": [ + "file refers to an open disk buffer." + ], + "sample": "PRINT LOC(1)", + "exampleID": null, + "related": [ + "OPEN", + "LOF" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "5" + }, + { + "id": "LOCATE", + "keyword": "LOCATE", + "title": "LOCATE", + "category": "Text and output", + "dialect": "common", + "summary": "Position the cursor in the CoCo 3 high-resolution text screen.", + "syntax": [ + "LOCATE column,row" + ], + "parameters": [ + "Coordinates start at zero." + ], + "sample": "WIDTH 80:LOCATE 10,5:PRINT \"COCO\"", + "exampleID": null, + "related": [ + "WIDTH", + "ATTR", + "HSTAT" + ], + "notes": [ + "Use WIDTH 40 or WIDTH 80 first." + ], + "source": "basicGuide", + "sourcePage": "11" + }, + { + "id": "LOF", + "keyword": "LOF", + "title": "LOF", + "category": "Disk files", + "dialect": "disk", + "summary": "Read the highest record number in an open disk file.", + "syntax": [ + "LOF(file)" + ], + "parameters": [ + "This is a record count, not a Mac file-size query." + ], + "sample": "PRINT LOF(1)", + "exampleID": null, + "related": [ + "OPEN", + "LOC" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "5" + }, + { + "id": "LOG", + "keyword": "LOG", + "title": "LOG", + "category": "Math", + "dialect": "common", + "summary": "Return the natural logarithm.", + "syntax": [ + "LOG(number)" + ], + "parameters": [ + "number must be positive." + ], + "sample": "PRINT LOG(1)", + "exampleID": null, + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "20" + }, + { + "id": "LPEEK", + "keyword": "LPEEK", + "title": "LPEEK", + "category": "Memory", + "dialect": "common", + "summary": "Read a byte using the CoCo 3 long-memory interface.", + "syntax": [ + "LPEEK(address)" + ], + "parameters": [ + "address: 0-524287. This BASIC interface is limited to 512 KB." + ], + "sample": "PRINT LPEEK(&H70000)", + "exampleID": null, + "related": [ + "LPOKE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "20" + }, + { + "id": "LPOKE", + "keyword": "LPOKE", + "title": "LPOKE", + "category": "Memory", + "dialect": "common", + "summary": "Write a byte using the CoCo 3 BASIC long-memory interface.", + "syntax": [ + "LPOKE address,value" + ], + "parameters": [ + "address: 0-524287; value: 0-255.", + "This command's address range does not expand simply because the emulator has more RAM." + ], + "sample": "LPOKE &H70000,65", + "exampleID": null, + "related": [ + "LPEEK", + "POKE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "11" + }, + { + "id": "ERROR.LS", + "keyword": "LS", + "title": "LS — String too long", + "category": "Errors", + "dialect": "common", + "summary": "The result exceeds BASIC's maximum string length of 255 characters.", + "syntax": [ + "LS ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "LEN", + "LEFT$", + "MID$" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "LSET", + "keyword": "LSET", + "title": "LSET", + "category": "Disk files", + "dialect": "disk", + "summary": "Left-align text in a direct-access field.", + "syntax": [ + "LSET stringField = string" + ], + "parameters": [ + "Short strings are padded; long strings are limited to the field length." + ], + "sample": "LSET N$=\"COCO\"", + "exampleID": null, + "related": [ + "FIELD", + "RSET" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "5" + }, + { + "id": "MEM", + "keyword": "MEM", + "title": "MEM", + "category": "Memory", + "dialect": "common", + "summary": "Report currently free BASIC memory.", + "syntax": [ + "MEM" + ], + "parameters": [ + "Available BASIC workspace is not the same as the selected total machine RAM." + ], + "sample": "PRINT MEM", + "exampleID": null, + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "20" + }, + { + "id": "MERGE", + "keyword": "MERGE", + "title": "MERGE", + "category": "Disk files", + "dialect": "disk", + "summary": "Combine a disk ASCII listing with the program in memory.", + "syntax": [ + "MERGE \"filename\"[,R]" + ], + "parameters": [ + "Save the source file with SAVE ...,A first.", + "R starts the merged program." + ], + "sample": "MERGE \"SUBS:0\"", + "exampleID": null, + "related": [ + "LOAD", + "SAVE" + ], + "notes": [ + "Duplicate line numbers are replaced by the incoming lines." + ], + "source": "diskGuide", + "sourcePage": "5" + }, + { + "id": "MID$", + "keyword": "MID$", + "title": "MID$", + "category": "Strings", + "dialect": "common", + "summary": "Read a substring, or replace characters in a string variable.", + "syntax": [ + "MID$(string,start[,count])", + "MID$(stringVariable,start[,count]) = replacement" + ], + "parameters": [ + "Positions start at 1.", + "Without count, the function reads to the end.", + "Assignment changes existing characters; it does not insert new space." + ], + "sample": "PRINT MID$(\"COMPUTER\",4,3)", + "exampleID": "strings", + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "11, 20" + }, + { + "id": "MKN$", + "keyword": "MKN$", + "title": "MKN$", + "category": "Disk files", + "dialect": "disk", + "summary": "Encode a BASIC number into its five-byte representation.", + "syntax": [ + "MKN$(number)" + ], + "parameters": [ + "Use with fixed-length binary fields; this is not decimal text." + ], + "sample": "A$=MKN$(42)", + "exampleID": null, + "related": [ + "CVN", + "FIELD" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "6" + }, + { + "id": "MOTOR", + "keyword": "MOTOR", + "title": "MOTOR", + "category": "Cassette", + "dialect": "common", + "summary": "Control the cassette motor signal.", + "syntax": [ + "MOTOR ON", + "MOTOR OFF" + ], + "parameters": [], + "sample": "MOTOR OFF", + "exampleID": null, + "related": [ + "AUDIO", + "CLOAD", + "CSAVE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "12" + }, + { + "id": "ERROR.NE", + "keyword": "NE", + "title": "NE — File not found", + "category": "Errors", + "dialect": "disk", + "summary": "The named disk file was not found on the selected drive. Check DIR, extension and drive suffix.", + "syntax": [ + "NE ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "DIR", + "LOAD", + "DRIVE" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "9" + }, + { + "id": "NEW", + "keyword": "NEW", + "title": "NEW", + "category": "Source editing", + "dialect": "common", + "summary": "Erase the program currently held by BASIC.", + "syntax": [ + "NEW" + ], + "parameters": [], + "sample": "NEW", + "exampleID": null, + "related": [ + "CLEAR", + "RUN" + ], + "notes": [ + "This changes CoCo memory, not a saved Mac source file." + ], + "source": "basicGuide", + "sourcePage": "12" + }, + { + "id": "NEXT", + "keyword": "NEXT", + "title": "NEXT", + "category": "Program flow", + "dialect": "common", + "summary": "Advance a FOR loop and test whether it should repeat.", + "syntax": [ + "NEXT [variable [, variable ...]]" + ], + "parameters": [ + "For nested loops, close the innermost loop first." + ], + "sample": "NEXT I", + "exampleID": "count", + "related": [ + "FOR", + "ERROR.NF" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "12" + }, + { + "id": "ERROR.NF", + "keyword": "NF", + "title": "NF — NEXT without FOR", + "category": "Errors", + "dialect": "common", + "summary": "Execution reached NEXT without a matching active loop. Check loop entry paths.", + "syntax": [ + "NF ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "FOR", + "NEXT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "ERROR.NO", + "keyword": "NO", + "title": "NO — File not open", + "category": "Errors", + "dialect": "common", + "summary": "Open the file before reading, writing or requesting its records.", + "syntax": [ + "NO ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "OPEN", + "CLOSE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "NOT", + "keyword": "NOT", + "title": "NOT", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Invert an integer bit pattern or a BASIC truth value.", + "syntax": [ + "NOT expression" + ], + "parameters": [], + "sample": "IF NOT A=0 THEN PRINT \"NONZERO\"", + "exampleID": null, + "related": [ + "AND", + "OR", + "IF" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "ERROR.OB", + "keyword": "OB", + "title": "OB — Out of buffers", + "category": "Errors", + "dialect": "disk", + "summary": "No suitable disk buffer is available. Allocate the required file buffers before opening files.", + "syntax": [ + "OB ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "FILES", + "OPEN" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "9" + }, + { + "id": "ERROR.OD", + "keyword": "OD", + "title": "OD — Out of DATA", + "category": "Errors", + "dialect": "common", + "summary": "READ requested more values than the DATA statements provide.", + "syntax": [ + "OD ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "DATA", + "READ", + "RESTORE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "OFF", + "keyword": "OFF", + "title": "OFF", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Disable a feature in commands that accept an ON/OFF switch.", + "syntax": [ + "AUDIO OFF", + "MOTOR OFF", + "VERIFY OFF" + ], + "parameters": [], + "sample": "MOTOR OFF", + "exampleID": null, + "related": [ + "AUDIO", + "MOTOR", + "VERIFY" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "ERROR.OM", + "keyword": "OM", + "title": "OM — Out of memory", + "category": "Errors", + "dialect": "common", + "summary": "BASIC has insufficient workspace for the operation. Check arrays, strings, graphics pages and program size.", + "syntax": [ + "OM ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "MEM", + "CLEAR", + "DIM", + "PCLEAR" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "ON", + "keyword": "ON", + "title": "ON", + "category": "Program flow", + "dialect": "common", + "summary": "Select a GOTO or GOSUB destination by its position in a list.", + "syntax": [ + "ON expression GOTO line [, line ...]", + "ON expression GOSUB line [, line ...]" + ], + "parameters": [ + "A value of 1 selects the first destination.", + "Zero or a value beyond the list falls through." + ], + "sample": "ON N GOSUB 100,200,300", + "exampleID": "branch", + "related": [ + "GOTO", + "GOSUB", + "ON.ERR", + "ON.BRK" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "12" + }, + { + "id": "ON.BRK", + "keyword": "ON BRK", + "title": "ON BRK", + "category": "Debugging and errors", + "dialect": "common", + "summary": "Branch to a handler when the CoCo Break key is pressed.", + "syntax": [ + "ON BRK GOTO line" + ], + "parameters": [ + "CoCo 3 extension.", + "ON BRK GOTO 0 restores ordinary Break handling." + ], + "sample": "ON BRK GOTO 200", + "exampleID": null, + "related": [ + "STOP", + "ON.ERR" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "12" + }, + { + "id": "ON.ERR", + "keyword": "ON ERR", + "title": "ON ERR", + "category": "Debugging and errors", + "dialect": "common", + "summary": "Send runtime errors to a BASIC handler on the CoCo 3.", + "syntax": [ + "ON ERR GOTO line" + ], + "parameters": [ + "Use ERNO and ERLIN in the handler to identify the error.", + "ON ERR GOTO 0 disables the handler." + ], + "sample": "ON ERR GOTO 100", + "exampleID": "error-trap", + "related": [ + "ERNO", + "ERLIN", + "ERROR.SN" + ], + "notes": [ + "Handled errors remain under BASIC control; VCC Plus does not replace them with its unhandled-error pause." + ], + "source": "basicGuide", + "sourcePage": "12" + }, + { + "id": "OPEN", + "keyword": "OPEN", + "title": "OPEN", + "category": "Disk files", + "dialect": "disk", + "summary": "Open a data stream to a file or device.", + "syntax": [ + "OPEN \"mode\",#file,\"filename\"[,recordLength]" + ], + "parameters": [ + "I reads sequential data; O writes sequential data; D selects direct-access disk records.", + "Disk file numbers: 1-15, subject to FILES allocation.", + "Device -1 is cassette; -2 is printer; 0 is console." + ], + "sample": "OPEN \"I\",#1,\"DATA/TXT:0\"", + "exampleID": null, + "related": [ + "CLOSE", + "FILES", + "FIELD" + ], + "notes": [ + "O can replace an existing file; use a disposable output filename while learning." + ], + "source": "diskGuide", + "sourcePage": "6" + }, + { + "id": "OR", + "keyword": "OR", + "title": "OR", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Combine conditions or integer bit patterns when either side is set.", + "syntax": [ + "expression OR expression" + ], + "parameters": [], + "sample": "IF A=0 OR B=0 THEN PRINT \"ZERO\"", + "exampleID": null, + "related": [ + "AND", + "NOT", + "IF" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "ERROR.OS", + "keyword": "OS", + "title": "OS — Out of string space", + "category": "Errors", + "dialect": "common", + "summary": "The reserved string workspace is exhausted. Consider reserving more with CLEAR before creating data.", + "syntax": [ + "OS ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "CLEAR", + "LEN" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "ERROR.OV", + "keyword": "OV", + "title": "OV — Overflow", + "category": "Errors", + "dialect": "common", + "summary": "A numeric result is too large for BASIC to represent.", + "syntax": [ + "OV ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "EXP" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "PAINT", + "keyword": "PAINT", + "title": "PAINT", + "category": "Graphics", + "dialect": "common", + "summary": "Fill a bounded PMODE area from a starting point.", + "syntax": [ + "PAINT(x,y)[,color[,border]]" + ], + "parameters": [ + "The starting point must be inside a closed border for a bounded fill." + ], + "sample": "PAINT(128,96),1,1", + "exampleID": null, + "related": [ + "CIRCLE", + "LINE", + "HPAINT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "13" + }, + { + "id": "PALETTE", + "keyword": "PALETTE", + "title": "PALETTE", + "category": "Graphics", + "dialect": "common", + "summary": "Assign a CoCo 3 palette entry or restore a standard palette.", + "syntax": [ + "PALETTE register,color", + "PALETTE CMP", + "PALETTE RGB" + ], + "parameters": [ + "register: 0-15; color: 0-63.", + "CMP and RGB choose standard tables for the corresponding monitor signal." + ], + "sample": "PALETTE 1,13", + "exampleID": null, + "related": [ + "HSCREEN", + "HCOLOR", + "CMP", + "RGB" + ], + "notes": [ + "The BASIC palette and VCC Plus Video Signal setting are related but separate controls." + ], + "source": "basicGuide", + "sourcePage": "13" + }, + { + "id": "PCLEAR", + "keyword": "PCLEAR", + "title": "PCLEAR", + "category": "Graphics", + "dialect": "common", + "summary": "Reserve 1.5 KB pages for PMODE graphics.", + "syntax": [ + "PCLEAR pages" + ], + "parameters": [ + "Reserve enough pages for the chosen PMODE and starting page." + ], + "sample": "PCLEAR 4", + "exampleID": "low-graphics", + "related": [ + "PMODE", + "PCOPY", + "MEM" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "13" + }, + { + "id": "PCLS", + "keyword": "PCLS", + "title": "PCLS", + "category": "Graphics", + "dialect": "common", + "summary": "Fill the current PMODE graphics screen.", + "syntax": [ + "PCLS [color]" + ], + "parameters": [ + "Omitting color uses the current background." + ], + "sample": "PCLS 0", + "exampleID": "low-graphics", + "related": [ + "PMODE", + "COLOR", + "CLS" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "13" + }, + { + "id": "PCOPY", + "keyword": "PCOPY", + "title": "PCOPY", + "category": "Graphics", + "dialect": "common", + "summary": "Copy one reserved PMODE graphics page to another.", + "syntax": [ + "PCOPY source TO destination" + ], + "parameters": [ + "Pages must have been reserved with PCLEAR." + ], + "sample": "PCOPY 1 TO 2", + "exampleID": null, + "related": [ + "PCLEAR", + "PMODE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "13" + }, + { + "id": "PEEK", + "keyword": "PEEK", + "title": "PEEK", + "category": "Memory", + "dialect": "common", + "summary": "Read a byte through the current CPU memory map.", + "syntax": [ + "PEEK(address)" + ], + "parameters": [ + "address: 0-65535.", + "Reading device registers can affect the device." + ], + "sample": "PRINT PEEK(&H400)", + "exampleID": null, + "related": [ + "POKE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "20" + }, + { + "id": "PLAY", + "keyword": "PLAY", + "title": "PLAY", + "category": "Sound", + "dialect": "common", + "summary": "Play notes described by a music string.", + "syntax": [ + "PLAY string" + ], + "parameters": [ + "A-G name notes; O selects octave, L note length and T tempo.", + "# or + sharpens a note; - flattens it; P inserts a pause." + ], + "sample": "PLAY \"T120O3L8CEG\"", + "exampleID": null, + "related": [ + "SOUND" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "13" + }, + { + "id": "PMODE", + "keyword": "PMODE", + "title": "PMODE", + "category": "Graphics", + "dialect": "common", + "summary": "Choose the resolution and starting page for traditional CoCo graphics.", + "syntax": [ + "PMODE mode,page" + ], + "parameters": [ + "0: 128x96, 2 colors; 1: 128x96, 4 colors.", + "2: 128x192, 2 colors; 3: 128x192, 4 colors.", + "4: 256x192, 2 colors." + ], + "sample": "PMODE 4,1", + "exampleID": "low-graphics", + "related": [ + "PCLEAR", + "SCREEN", + "PCLS" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "14" + }, + { + "id": "POINT", + "keyword": "POINT", + "title": "POINT", + "category": "Graphics", + "dialect": "common", + "summary": "Read a semigraphics block on the text screen.", + "syntax": [ + "POINT(x,y)" + ], + "parameters": [ + "-1 indicates part of an ordinary text character; otherwise the result describes the block color." + ], + "sample": "PRINT POINT(10,10)", + "exampleID": null, + "related": [ + "SET" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "20" + }, + { + "id": "POKE", + "keyword": "POKE", + "title": "POKE", + "category": "Memory", + "dialect": "common", + "summary": "Write one byte through the current CPU memory map.", + "syntax": [ + "POKE address,value" + ], + "parameters": [ + "address: 0-65535; value: 0-255." + ], + "sample": "POKE &H400,65", + "exampleID": null, + "related": [ + "PEEK", + "LPOKE" + ], + "notes": [ + "Writes can change programs, device registers or system state. Use only addresses you understand." + ], + "source": "basicGuide", + "sourcePage": "14" + }, + { + "id": "POS", + "keyword": "POS", + "title": "POS", + "category": "Text and output", + "dialect": "common", + "summary": "Read the current print-column position for a device.", + "syntax": [ + "POS(device)" + ], + "parameters": [ + "device 0 is the screen; -2 is the printer." + ], + "sample": "PRINT POS(0)", + "exampleID": null, + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "20" + }, + { + "id": "PPOINT", + "keyword": "PPOINT", + "title": "PPOINT", + "category": "Graphics", + "dialect": "common", + "summary": "Read the color of a PMODE graphics point.", + "syntax": [ + "PPOINT(x,y)" + ], + "parameters": [], + "sample": "PRINT PPOINT(20,20)", + "exampleID": "low-graphics", + "related": [ + "PSET" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "21" + }, + { + "id": "PRESET", + "keyword": "PRESET", + "title": "PRESET", + "category": "Graphics", + "dialect": "common", + "summary": "Reset a PMODE point to the background color.", + "syntax": [ + "PRESET(x,y)" + ], + "parameters": [], + "sample": "PRESET(20,20)", + "exampleID": null, + "related": [ + "PSET", + "PPOINT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "14" + }, + { + "id": "PRINT", + "keyword": "PRINT", + "title": "PRINT", + "category": "Text and output", + "dialect": "common", + "summary": "Display values on the text screen.", + "syntax": [ + "PRINT [expression [; or , expression] ...]" + ], + "parameters": [ + "Semicolon joins output without a print-zone advance.", + "Comma advances to the next print zone.", + "A trailing separator suppresses the usual newline." + ], + "sample": "PRINT \"ANSWER=\";42", + "exampleID": "hello", + "related": [ + "PRINT@", + "USING", + "TAB" + ], + "notes": [ + "? is a shorthand for PRINT." + ], + "source": "basicGuide", + "sourcePage": "14-15" + }, + { + "id": "DISK.PRINT", + "keyword": "PRINT", + "title": "PRINT — file or printer", + "category": "Disk files", + "dialect": "disk", + "summary": "Write formatted values to an open file or output device.", + "syntax": [ + "PRINT #file,expression[; or , expression ...]" + ], + "parameters": [ + "-2 selects the printer; -1 selects cassette.", + "Positive file numbers refer to previously opened disk files." + ], + "sample": "PRINT #-2,\"HELLO PRINTER\"", + "exampleID": null, + "related": [ + "OPEN", + "CLOSE", + "WRITE", + "USING" + ], + "notes": [ + "Disk/cassette output writes media. Printer text is captured only when the VCC Plus printer is enabled." + ], + "source": "diskGuide", + "sourcePage": "6-7" + }, + { + "id": "PRINT.USING", + "keyword": "PRINT USING", + "title": "PRINT USING", + "category": "Text and output", + "dialect": "common", + "summary": "Print values with a reusable layout.", + "syntax": [ + "PRINT USING \"format\";expression[;expression ...]" + ], + "parameters": [ + "Each # reserves a digit position; a decimal point places the fractional part.", + "For strings, ! prints one character and % followed by spaces and % defines a fixed-width field." + ], + "sample": "PRINT USING \"###.##\";12.5", + "exampleID": "formatting", + "related": [ + "PRINT", + "USING", + "TAB" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "15" + }, + { + "id": "PRINT@", + "keyword": "PRINT@", + "title": "PRINT@", + "category": "Text and output", + "dialect": "common", + "summary": "Place text at a numbered position on the 32-column screen.", + "syntax": [ + "PRINT @position, expression" + ], + "parameters": [ + "position: 0-511, counted across rows from the top left." + ], + "sample": "PRINT @64,\"ROW THREE\"", + "exampleID": null, + "related": [ + "PRINT", + "LOCATE", + "WIDTH" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "15" + }, + { + "id": "PSET", + "keyword": "PSET", + "title": "PSET", + "category": "Graphics", + "dialect": "common", + "summary": "Set a point in the PMODE drawing area.", + "syntax": [ + "PSET(x,y[,color])" + ], + "parameters": [ + "Drawing coordinates use x: 0-255 and y: 0-191.", + "Omit color to use the current foreground." + ], + "sample": "PSET(20,20,1)", + "exampleID": "low-graphics", + "related": [ + "PRESET", + "PPOINT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "15" + }, + { + "id": "PUT", + "keyword": "PUT", + "title": "PUT", + "category": "Graphics", + "dialect": "common", + "summary": "Draw a PMODE rectangle from a saved numeric array.", + "syntax": [ + "PUT(x1,y1)-(x2,y2),array[,action]" + ], + "parameters": [ + "action: PSET, PRESET, AND, OR or NOT.", + "Use a matching rectangle and storage prepared by GET." + ], + "sample": "PUT(10,10)-(17,17),A,PSET", + "exampleID": null, + "related": [ + "GET", + "DISK.PUT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "15" + }, + { + "id": "DISK.PUT", + "keyword": "PUT", + "title": "PUT — disk record", + "category": "Disk files", + "dialect": "disk", + "summary": "Write the file buffer as a direct-access record.", + "syntax": [ + "PUT #file[,record]" + ], + "parameters": [ + "Use LSET/RSET to fill the buffer before writing." + ], + "sample": "PUT #1,3", + "exampleID": null, + "related": [ + "FIELD", + "DISK.GET", + "PUT" + ], + "notes": [ + "This changes the opened disk file. It is separate from graphics PUT." + ], + "source": "diskGuide", + "sourcePage": "7" + }, + { + "id": "READ", + "keyword": "READ", + "title": "READ", + "category": "Variables and arrays", + "dialect": "common", + "summary": "Take the next values from the program's DATA statements.", + "syntax": [ + "READ variable [, variable ...]" + ], + "parameters": [ + "Variable type must match the corresponding value." + ], + "sample": "READ A,N$", + "exampleID": "data", + "related": [ + "DATA", + "RESTORE", + "ERROR.OD" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "15" + }, + { + "id": "REM", + "keyword": "REM", + "title": "REM", + "category": "Source editing", + "dialect": "common", + "summary": "Add a comment that BASIC does not execute.", + "syntax": [ + "REM comment" + ], + "parameters": [], + "sample": "REM CALCULATE THE TOTAL", + "exampleID": null, + "related": [ + "DATA" + ], + "notes": [ + "An apostrophe also starts a comment. Quoted strings and comments retain their entered case." + ], + "source": "basicGuide", + "sourcePage": "16" + }, + { + "id": "RENAME", + "keyword": "RENAME", + "title": "RENAME", + "category": "Disk files", + "dialect": "disk", + "summary": "Change a filename within the same BASIC disk.", + "syntax": [ + "RENAME \"old/ext[:drive]\" TO \"new/ext[:drive]\"" + ], + "parameters": [ + "Include both extensions." + ], + "sample": "RENAME \"OLD/BAS:0\" TO \"NEW/BAS:0\"", + "exampleID": null, + "related": [ + "DIR", + "COPY" + ], + "notes": [ + "Changes the disk directory." + ], + "source": "diskGuide", + "sourcePage": "7" + }, + { + "id": "RENUM", + "keyword": "RENUM", + "title": "RENUM", + "category": "Source editing", + "dialect": "common", + "summary": "Renumber program lines and update recognized line references.", + "syntax": [ + "RENUM [newStart [, oldStart [, increment]]]" + ], + "parameters": [ + "newStart is the first assigned number.", + "oldStart selects the first old line to change.", + "increment controls spacing." + ], + "sample": "RENUM 100,0,10", + "exampleID": null, + "related": [ + "LIST" + ], + "notes": [ + "The editor Renumber action supports Undo and updates editor source rather than the current CoCo program." + ], + "source": "basicGuide", + "sourcePage": "16" + }, + { + "id": "RESET", + "keyword": "RESET", + "title": "RESET", + "category": "Graphics", + "dialect": "common", + "summary": "Clear a semigraphics block on the text screen.", + "syntax": [ + "RESET(x,y)" + ], + "parameters": [ + "x: 0-63; y: 0-31." + ], + "sample": "RESET(10,10)", + "exampleID": null, + "related": [ + "SET", + "POINT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "16" + }, + { + "id": "RESTORE", + "keyword": "RESTORE", + "title": "RESTORE", + "category": "Variables and arrays", + "dialect": "common", + "summary": "Move the DATA pointer back to the first item.", + "syntax": [ + "RESTORE" + ], + "parameters": [], + "sample": "RESTORE", + "exampleID": "data", + "related": [ + "READ", + "DATA" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "16" + }, + { + "id": "RETURN", + "keyword": "RETURN", + "title": "RETURN", + "category": "Program flow", + "dialect": "common", + "summary": "Resume immediately after the matching GOSUB call.", + "syntax": [ + "RETURN" + ], + "parameters": [ + "RETURN needs an active GOSUB call." + ], + "sample": "RETURN", + "exampleID": "subroutine", + "related": [ + "GOSUB", + "ERROR.RG" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "16" + }, + { + "id": "ERROR.RG", + "keyword": "RG", + "title": "RG — RETURN without GOSUB", + "category": "Errors", + "dialect": "common", + "summary": "There is no active subroutine call to return from. Avoid falling into a subroutine from the main program.", + "syntax": [ + "RG ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "GOSUB", + "RETURN", + "END" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "RGB", + "keyword": "RGB", + "title": "RGB", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Restore the standard RGB palette on a CoCo 3.", + "syntax": [ + "PALETTE RGB" + ], + "parameters": [], + "sample": "PALETTE RGB", + "exampleID": null, + "related": [ + "PALETTE", + "CMP" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "RIGHT$", + "keyword": "RIGHT$", + "title": "RIGHT$", + "category": "Strings", + "dialect": "common", + "summary": "Take characters from the end of a string.", + "syntax": [ + "RIGHT$(string,count)" + ], + "parameters": [ + "count is the maximum number of characters returned." + ], + "sample": "PRINT RIGHT$(\"COMPUTER\",3)", + "exampleID": "strings", + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "21" + }, + { + "id": "RND", + "keyword": "RND", + "title": "RND", + "category": "Math", + "dialect": "common", + "summary": "Generate a pseudo-random value.", + "syntax": [ + "RND(limit)" + ], + "parameters": [ + "RND(0) returns a fractional value.", + "A positive integer limit returns an integer from 1 through limit." + ], + "sample": "PRINT RND(6)", + "exampleID": null, + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "21" + }, + { + "id": "RSET", + "keyword": "RSET", + "title": "RSET", + "category": "Disk files", + "dialect": "disk", + "summary": "Right-align text in a direct-access field.", + "syntax": [ + "RSET stringField = string" + ], + "parameters": [ + "Short strings are padded on the left." + ], + "sample": "RSET N$=\"42\"", + "exampleID": null, + "related": [ + "FIELD", + "LSET" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "7" + }, + { + "id": "RUN", + "keyword": "RUN", + "title": "RUN", + "category": "Program flow", + "dialect": "common", + "summary": "Start the program in memory, normally clearing its variables.", + "syntax": [ + "RUN [line]" + ], + "parameters": [ + "Omit line to start at the beginning." + ], + "sample": "RUN", + "exampleID": "hello", + "related": [ + "END", + "DISK.RUN" + ], + "notes": [ + "Use the editor's Run button to transfer edited source and start it." + ], + "source": "basicGuide", + "sourcePage": "16" + }, + { + "id": "DISK.RUN", + "keyword": "RUN", + "title": "RUN — disk file", + "category": "Disk files", + "dialect": "disk", + "summary": "Load and run a BASIC program from disk.", + "syntax": [ + "RUN \"filename\"[,R]" + ], + "parameters": [ + "R preserves open files while chaining to the new program." + ], + "sample": "RUN \"HELLO:0\"", + "exampleID": null, + "related": [ + "LOAD", + "RUN" + ], + "notes": [ + "Replaces the in-memory BASIC program." + ], + "source": "diskGuide", + "sourcePage": "8" + }, + { + "id": "RGB.RUNM", + "keyword": "RUNM", + "title": "RUNM", + "category": "DOS differences", + "dialect": "rgbdos", + "summary": "Load and execute a machine-language program in one command.", + "syntax": [ + "RUNM \"filename[:drive]\"" + ], + "parameters": [], + "sample": "RUNM \"HELLO:0\"", + "exampleID": null, + "related": [ + "LOADM", + "EXEC" + ], + "notes": [ + "For binaries that start themselves during loading, use LOADM instead; RUNM can execute their entry point again." + ], + "source": "rgbdos", + "sourcePage": "PDF page 6" + }, + { + "id": "SAVE", + "keyword": "SAVE", + "title": "SAVE", + "category": "Disk files", + "dialect": "disk", + "summary": "Write the in-memory BASIC program to disk.", + "syntax": [ + "SAVE \"filename\"[,A]" + ], + "parameters": [ + "A selects an ASCII listing instead of tokenized storage." + ], + "sample": "SAVE \"HELLO:0\",A", + "exampleID": null, + "related": [ + "LOAD", + "CSAVE" + ], + "notes": [ + "Writes to the selected image and may replace an existing file. The native editor Save command instead saves a Mac source file." + ], + "source": "diskGuide", + "sourcePage": "8" + }, + { + "id": "SAVEM", + "keyword": "SAVEM", + "title": "SAVEM", + "category": "Disk files", + "dialect": "disk", + "summary": "Write a memory range as a machine-language disk file.", + "syntax": [ + "SAVEM \"filename\",first,last,entry" + ], + "parameters": [ + "first/last are inclusive addresses; entry is the default EXEC address." + ], + "sample": "SAVEM \"DEMO:0\",&H5000,&H50FF,&H5000", + "exampleID": null, + "related": [ + "LOADM", + "EXEC" + ], + "notes": [ + "Writes to the selected disk image." + ], + "source": "diskGuide", + "sourcePage": "8" + }, + { + "id": "SCREEN", + "keyword": "SCREEN", + "title": "SCREEN", + "category": "Graphics", + "dialect": "common", + "summary": "Switch between the traditional text and graphics displays.", + "syntax": [ + "SCREEN type,colorSet" + ], + "parameters": [ + "type: 0 for text, 1 for PMODE graphics.", + "colorSet: 0 or 1." + ], + "sample": "SCREEN 1,0", + "exampleID": "low-graphics", + "related": [ + "PMODE", + "HSCREEN" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "16" + }, + { + "id": "ERROR.SE", + "keyword": "SE", + "title": "SE — Not a field string", + "category": "Errors", + "dialect": "disk", + "summary": "LSET or RSET was given a string that is not currently mapped by FIELD.", + "syntax": [ + "SE ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "FIELD", + "LSET", + "RSET" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "9" + }, + { + "id": "SET", + "keyword": "SET", + "title": "SET", + "category": "Graphics", + "dialect": "common", + "summary": "Color one semigraphics block on the 32-column text screen.", + "syntax": [ + "SET(x,y,color)" + ], + "parameters": [ + "x: 0-63; y: 0-31; color: 0-8." + ], + "sample": "SET(10,10,3)", + "exampleID": null, + "related": [ + "RESET", + "POINT", + "PSET" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "16" + }, + { + "id": "SGN", + "keyword": "SGN", + "title": "SGN", + "category": "Math", + "dialect": "common", + "summary": "Return -1, 0 or 1 for a negative, zero or positive number.", + "syntax": [ + "SGN(number)" + ], + "parameters": [], + "sample": "PRINT SGN(-7)", + "exampleID": "math", + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "21" + }, + { + "id": "SIN", + "keyword": "SIN", + "title": "SIN", + "category": "Math", + "dialect": "common", + "summary": "Return the sine of an angle in radians.", + "syntax": [ + "SIN(angle)" + ], + "parameters": [ + "A full turn is 2*PI radians; use a numeric value for PI." + ], + "sample": "PRINT SIN(0)", + "exampleID": null, + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "21" + }, + { + "id": "SKIPF", + "keyword": "SKIPF", + "title": "SKIPF", + "category": "Cassette", + "dialect": "common", + "summary": "Advance through a cassette file without loading it.", + "syntax": [ + "SKIPF [\"filename\"]" + ], + "parameters": [], + "sample": "SKIPF \"DEMO\"", + "exampleID": null, + "related": [ + "CLOAD", + "CLOADM" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "17" + }, + { + "id": "ERROR.SN", + "keyword": "SN", + "title": "SN — Syntax error", + "category": "Errors", + "dialect": "common", + "summary": "BASIC could not interpret a statement. Check spelling, punctuation, quotes and the command form.", + "syntax": [ + "SN ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "PRINT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "SOUND", + "keyword": "SOUND", + "title": "SOUND", + "category": "Sound", + "dialect": "common", + "summary": "Play a tone for a specified duration.", + "syntax": [ + "SOUND pitch,duration" + ], + "parameters": [ + "pitch: 1-255; duration: 1-255." + ], + "sample": "SOUND 100,10", + "exampleID": null, + "related": [ + "PLAY", + "AUDIO" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "17" + }, + { + "id": "SQR", + "keyword": "SQR", + "title": "SQR", + "category": "Math", + "dialect": "common", + "summary": "Return the nonnegative square root.", + "syntax": [ + "SQR(number)" + ], + "parameters": [ + "number must be zero or positive." + ], + "sample": "PRINT SQR(16)", + "exampleID": "math", + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "21" + }, + { + "id": "ERROR.ST", + "keyword": "ST", + "title": "ST — String expression too complex", + "category": "Errors", + "dialect": "common", + "summary": "Simplify the expression by saving intermediate string results in variables.", + "syntax": [ + "ST ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "LET", + "MID$" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "STEP", + "keyword": "STEP", + "title": "STEP", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Set the increment of a FOR loop.", + "syntax": [ + "FOR variable=start TO finish STEP increment" + ], + "parameters": [], + "sample": "FOR I=10 TO 2 STEP -2", + "exampleID": null, + "related": [ + "FOR", + "NEXT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "STOP", + "keyword": "STOP", + "title": "STOP", + "category": "Debugging and errors", + "dialect": "common", + "summary": "Stop execution and report the BASIC line.", + "syntax": [ + "STOP" + ], + "parameters": [], + "sample": "STOP", + "exampleID": null, + "related": [ + "CONT", + "END" + ], + "notes": [ + "A BASIC STOP is distinct from an editor breakpoint." + ], + "source": "basicGuide", + "sourcePage": "17" + }, + { + "id": "STR$", + "keyword": "STR$", + "title": "STR$", + "category": "Strings", + "dialect": "common", + "summary": "Convert a number into a printable string.", + "syntax": [ + "STR$(number)" + ], + "parameters": [ + "Positive numbers normally include a leading space." + ], + "sample": "A$=STR$(42)", + "exampleID": "strings", + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "21" + }, + { + "id": "STRING$", + "keyword": "STRING$", + "title": "STRING$", + "category": "Strings", + "dialect": "common", + "summary": "Create a string containing a repeated character.", + "syntax": [ + "STRING$(count,codeOrString)" + ], + "parameters": [ + "A string argument supplies its first character." + ], + "sample": "PRINT STRING$(5,\"*\")", + "exampleID": "formatting", + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "21" + }, + { + "id": "SUB", + "keyword": "SUB", + "title": "SUB", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Complete the split spelling GO SUB.", + "syntax": [ + "GO SUB line" + ], + "parameters": [], + "sample": "GO SUB 100", + "exampleID": null, + "related": [ + "GOSUB", + "RETURN" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "TAB", + "keyword": "TAB", + "title": "TAB", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Advance within a PRINT line to a column.", + "syntax": [ + "PRINT TAB(column);expression" + ], + "parameters": [], + "sample": "PRINT TAB(8);\"COCO\"", + "exampleID": null, + "related": [ + "PRINT", + "POS" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "TAN", + "keyword": "TAN", + "title": "TAN", + "category": "Math", + "dialect": "common", + "summary": "Return the tangent of an angle in radians.", + "syntax": [ + "TAN(angle)" + ], + "parameters": [ + "Angles near odd multiples of PI/2 produce very large results." + ], + "sample": "PRINT TAN(0)", + "exampleID": null, + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "21" + }, + { + "id": "THEN", + "keyword": "THEN", + "title": "THEN", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Introduce the true branch of an IF statement.", + "syntax": [ + "IF condition THEN statements" + ], + "parameters": [], + "sample": "IF A=1 THEN PRINT \"ONE\"", + "exampleID": null, + "related": [ + "IF", + "ELSE" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "TIMER", + "keyword": "TIMER", + "title": "TIMER", + "category": "Timing", + "dialect": "common", + "summary": "Read or set the interpreter's ticking counter.", + "syntax": [ + "TIMER", + "TIMER = value" + ], + "parameters": [ + "The counter wraps at 65536.", + "It advances with the emulated machine, not a guaranteed wall-clock duration." + ], + "sample": "TIMER=0:PRINT TIMER", + "exampleID": null, + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "17, 22" + }, + { + "id": "ERROR.TM", + "keyword": "TM", + "title": "TM — Type mismatch", + "category": "Errors", + "dialect": "common", + "summary": "An expression uses a string where a number is required, or the reverse.", + "syntax": [ + "TM ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "VAL", + "STR$", + "INPUT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "TO", + "keyword": "TO", + "title": "TO", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Separate start/end values or source/destination operands.", + "syntax": [ + "FOR variable=start TO finish" + ], + "parameters": [], + "sample": "FOR I=1 TO 3", + "exampleID": null, + "related": [ + "FOR", + "COPY", + "BACKUP" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "TROFF", + "keyword": "TROFF", + "title": "TROFF", + "category": "Debugging and errors", + "dialect": "common", + "summary": "Turn off the BASIC line-number trace.", + "syntax": [ + "TROFF" + ], + "parameters": [], + "sample": "TROFF", + "exampleID": null, + "related": [ + "TRON" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "17" + }, + { + "id": "TRON", + "keyword": "TRON", + "title": "TRON", + "category": "Debugging and errors", + "dialect": "common", + "summary": "Show BASIC line numbers as the program executes.", + "syntax": [ + "TRON" + ], + "parameters": [], + "sample": "TRON", + "exampleID": null, + "related": [ + "TROFF" + ], + "notes": [ + "This is the interpreter's text trace; it is independent of editor breakpoints." + ], + "source": "basicGuide", + "sourcePage": "17" + }, + { + "id": "ERROR.UL", + "keyword": "UL", + "title": "UL — Undefined line", + "category": "Errors", + "dialect": "common", + "summary": "A branch or run command refers to a line that is not in the program.", + "syntax": [ + "UL ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "GOTO", + "GOSUB", + "RUN" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "27" + }, + { + "id": "UNLOAD", + "keyword": "UNLOAD", + "title": "UNLOAD", + "category": "Disk files", + "dialect": "disk", + "summary": "Close open files associated with a disk.", + "syntax": [ + "UNLOAD [drive]" + ], + "parameters": [ + "Omitting drive selects the default drive." + ], + "sample": "UNLOAD 0", + "exampleID": null, + "related": [ + "CLOSE", + "SDC.DRIVE" + ], + "notes": [ + "This BASIC command does not eject the Mac disk-image file from VCC Plus." + ], + "source": "diskGuide", + "sourcePage": "8" + }, + { + "id": "USING", + "keyword": "USING", + "title": "USING", + "category": "Keywords and operators", + "dialect": "common", + "summary": "Apply a numeric or string layout to printed values.", + "syntax": [ + "PRINT USING \"format\";expression" + ], + "parameters": [], + "sample": "PRINT USING \"###.##\";12.5", + "exampleID": "formatting", + "related": [ + "PRINT", + "DISK.PRINT" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "Commands and operators" + }, + { + "id": "USR", + "keyword": "USR", + "title": "USR", + "category": "Machine language", + "dialect": "common", + "summary": "Call a machine-language function defined with DEF USR.", + "syntax": [ + "USRn(argument)" + ], + "parameters": [ + "n: 0-9. Define a valid entry address and calling convention first." + ], + "sample": "A=USR0(42)", + "exampleID": null, + "related": [ + "DEF.USR" + ], + "notes": [], + "source": "basicGuide", + "sourcePage": "22" + }, + { + "id": "VAL", + "keyword": "VAL", + "title": "VAL", + "category": "Strings", + "dialect": "common", + "summary": "Convert a numeric prefix of a string into a number.", + "syntax": [ + "VAL(string)" + ], + "parameters": [ + "Parsing follows BASIC numeric notation." + ], + "sample": "PRINT VAL(\"12.5\")", + "exampleID": "strings", + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "22" + }, + { + "id": "VARPTR", + "keyword": "VARPTR", + "title": "VARPTR", + "category": "Memory", + "dialect": "common", + "summary": "Find the address of a variable's internal storage.", + "syntax": [ + "VARPTR(variable)" + ], + "parameters": [ + "BASIC may move storage later; do not assume the address remains valid." + ], + "sample": "A=42:PRINT VARPTR(A)", + "exampleID": null, + "related": [], + "notes": [], + "source": "basicGuide", + "sourcePage": "22" + }, + { + "id": "VERIFY", + "keyword": "VERIFY", + "title": "VERIFY", + "category": "Disk files", + "dialect": "disk", + "summary": "Choose whether disk writes are followed by a verification read.", + "syntax": [ + "VERIFY ON", + "VERIFY OFF" + ], + "parameters": [ + "Verification checks the data written to the emulated disk." + ], + "sample": "VERIFY ON", + "exampleID": null, + "related": [ + "SAVE" + ], + "notes": [ + "This is an interpreter setting, not the image's write-protection setting." + ], + "source": "diskGuide", + "sourcePage": "8" + }, + { + "id": "ERROR.VF", + "keyword": "VF", + "title": "VF — Verification error", + "category": "Errors", + "dialect": "disk", + "summary": "Data read back after a write did not verify. Preserve another copy before continuing to modify the image.", + "syntax": [ + "VF ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "VERIFY" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "9" + }, + { + "id": "WIDTH", + "keyword": "WIDTH", + "title": "WIDTH", + "category": "Text and output", + "dialect": "common", + "summary": "Select the CoCo 3 text-screen width.", + "syntax": [ + "WIDTH columns" + ], + "parameters": [ + "columns: 32, 40 or 80.", + "40- and 80-column modes have 24 rows." + ], + "sample": "WIDTH 80", + "exampleID": null, + "related": [ + "LOCATE", + "ATTR", + "PRINT" + ], + "notes": [ + "CoCo 3 extension." + ], + "source": "basicGuide", + "sourcePage": "17" + }, + { + "id": "ERROR.WP", + "keyword": "WP", + "title": "WP — Write protected", + "category": "Errors", + "dialect": "disk", + "summary": "The selected media is read-only. Change protection only if you intend to modify that working copy.", + "syntax": [ + "WP ERROR" + ], + "parameters": [], + "sample": "", + "exampleID": null, + "related": [ + "SAVE", + "SDC.DRIVE" + ], + "notes": [], + "source": "diskGuide", + "sourcePage": "9" + }, + { + "id": "WRITE", + "keyword": "WRITE", + "title": "WRITE", + "category": "Disk files", + "dialect": "disk", + "summary": "Write comma-delimited data suitable for INPUT.", + "syntax": [ + "WRITE #file,expression[,expression ...]" + ], + "parameters": [ + "String values are quoted automatically." + ], + "sample": "WRITE #1,42,\"COCO\"", + "exampleID": null, + "related": [ + "OPEN", + "INPUT", + "DISK.INPUT" + ], + "notes": [ + "Writes to the opened output file." + ], + "source": "diskGuide", + "sourcePage": "8" + } + ], + "examples": [ + { + "id": "hello", + "title": "Hello, CoCo", + "summary": "Print a message and see a string variable.", + "source": "10 CLS\n20 A$=\"HELLO, COCO\"\n30 PRINT A$\n40 END\n", + "expectedOutput": "HELLO, COCO", + "dialect": "common" + }, + { + "id": "count", + "title": "A counting loop", + "summary": "Add five values using FOR and NEXT.", + "source": "10 CLS\n20 S=0\n30 FOR I=1 TO 5\n40 S=S+I\n50 NEXT I\n60 IF S=15 THEN PRINT \"COUNT OK\" ELSE PRINT \"FAILED\"\n70 END\n", + "expectedOutput": "COUNT OK", + "dialect": "common" + }, + { + "id": "strings", + "title": "Working with strings", + "summary": "Extract and join text without changing its case.", + "source": "10 CLS\n20 A$=\"Color Computer\"\n30 B$=LEFT$(A$,5)+RIGHT$(A$,8)\n40 IF LEN(A$)=14 AND MID$(A$,7,8)=\"Computer\" AND B$=\"ColorComputer\" THEN PRINT \"STRINGS OK\" ELSE PRINT \"FAILED\"\n50 END\n", + "expectedOutput": "STRINGS OK", + "dialect": "common" + }, + { + "id": "data", + "title": "Read a small data table", + "summary": "Read mixed numeric and string DATA, then restore its position.", + "source": "10 CLS\n20 READ A,A$\n30 RESTORE\n40 READ B\n50 IF A=12 AND A$=\"COCO\" AND B=12 THEN PRINT \"DATA OK\" ELSE PRINT \"FAILED\"\n60 END\n70 DATA 12,\"COCO\"\n", + "expectedOutput": "DATA OK", + "dialect": "common" + }, + { + "id": "arrays", + "title": "Array bounds and elements", + "summary": "Store and retrieve a two-dimensional array element.", + "source": "10 CLS\n20 DIM A(2,3)\n30 A(2,3)=42\n40 IF A(2,3)=42 AND A(0,0)=0 THEN PRINT \"ARRAYS OK\" ELSE PRINT \"FAILED\"\n50 END\n", + "expectedOutput": "ARRAYS OK", + "dialect": "common" + }, + { + "id": "branch", + "title": "Choose a branch", + "summary": "Use a computed GOTO to select one of three destinations.", + "source": "10 CLS\n20 A=2\n30 ON A GOTO 100,200,300\n40 PRINT \"FAILED\":END\n100 PRINT \"FAILED\":END\n200 PRINT \"BRANCH OK\":END\n300 PRINT \"FAILED\":END\n", + "expectedOutput": "BRANCH OK", + "dialect": "common" + }, + { + "id": "subroutine", + "title": "A returning subroutine", + "summary": "Step into GOSUB, inspect a variable, then Step Out.", + "source": "10 CLS\n20 A=6\n30 GOSUB 100\n40 IF A=36 THEN PRINT \"SUBROUTINE OK\" ELSE PRINT \"FAILED\"\n50 END\n100 A=A*A\n110 RETURN\n", + "expectedOutput": "SUBROUTINE OK", + "dialect": "common" + }, + { + "id": "math", + "title": "Numbers and rounding", + "summary": "Compare INT and FIX and evaluate a user-defined function.", + "source": "10 CLS\n20 DEF FNA(X)=X*X\n30 A=INT(-2.7):B=FIX(-2.7)\n40 IF A=-3 AND B=-2 AND FNA(3)=9 AND ABS(-4)=4 AND SQR(16)=4 THEN PRINT \"MATH OK\" ELSE PRINT \"FAILED\"\n50 END\n", + "expectedOutput": "MATH OK", + "dialect": "common" + }, + { + "id": "formatting", + "title": "Formatted output", + "summary": "Print a decimal field and a repeated separator.", + "source": "10 CLS\n20 PRINT USING \"###.##\";12.5\n30 PRINT STRING$(8,\"-\")\n40 PRINT \"FORMATTING OK\"\n50 END\n", + "expectedOutput": "FORMATTING OK", + "dialect": "common" + }, + { + "id": "error-trap", + "title": "Handle an error", + "summary": "Catch division by zero with ON ERR and check its line number.", + "source": "10 CLS\n20 ON ERR GOTO 100\n30 A=1/0\n40 PRINT \"FAILED\":END\n100 IF ERLIN=30 AND ERNO=10 THEN PRINT \"ERROR TRAP OK\" ELSE PRINT \"FAILED\"\n110 END\n", + "expectedOutput": "ERROR TRAP OK", + "dialect": "common" + }, + { + "id": "low-graphics", + "title": "Draw and inspect a point", + "summary": "Draw in a PMODE screen, read the pixel, and return to text.", + "source": "10 CLS\n20 PCLEAR 4\n30 PMODE 4,1:PCLS 0\n40 PSET(20,20,1)\n50 A=PPOINT(20,20)\n60 SCREEN 0,0:CLS\n70 IF A=1 THEN PRINT \"LOW GRAPHICS OK\" ELSE PRINT \"FAILED\"\n80 END\n", + "expectedOutput": "LOW GRAPHICS OK", + "dialect": "common" + }, + { + "id": "high-graphics", + "title": "CoCo 3 graphics", + "summary": "Draw a high-resolution pixel and return to 32-column text.", + "source": "10 CLS\n20 HSCREEN 2:HCLS 0\n30 HSET(20,20,3)\n40 A=HPOINT(20,20)\n50 HSCREEN 0:WIDTH 32:CLS\n60 IF A=3 THEN PRINT \"HIGH GRAPHICS OK\" ELSE PRINT \"FAILED\"\n70 END\n", + "expectedOutput": "HIGH GRAPHICS OK", + "dialect": "common" + }, + { + "id": "disk-directory", + "title": "List the mounted disk", + "summary": "Read drive zero without modifying its files.", + "source": "10 CLS\n20 DIR 0\n30 PRINT \"DISK DIRECTORY OK\"\n40 END\n", + "expectedOutput": "DISK DIRECTORY OK", + "dialect": "disk" + }, + { + "id": "rgb-routing", + "title": "Floppy and hard-disk directories", + "summary": "For the Hard Drive BASIC preset: list FD0, then restore hard-disk routing and list volume zero.", + "source": "10 CLS\n20 DRIVE OFF\n30 DIR 0\n40 DRIVE ON\n50 DIR 0\n60 PRINT \"RGB ROUTING OK\"\n70 END\n", + "expectedOutput": "RGB ROUTING OK", + "dialect": "rgbdos" + }, + { + "id": "sdc-mount", + "title": "Browse and mount Hello Disk", + "summary": "For the CoCo SDC starter card: browse the root, mount HELLO.DSK, and list its contents. This changes the current mount but does not write the image.", + "source": "10 CLS\n20 DIR = \"/\"\n30 DIR -\n40 DRIVE 0,\"HELLO.DSK\"\n50 DIR 0\n60 PRINT \"SDC READY\"\n70 END\n", + "expectedOutput": "SDC READY", + "dialect": "sdcdos" + } + ] +} diff --git a/platforms/macos/Resources/Hardware/cassette.pdf b/platforms/macos/Resources/Hardware/cassette.pdf new file mode 100644 index 0000000..e430936 Binary files /dev/null and b/platforms/macos/Resources/Hardware/cassette.pdf differ diff --git a/platforms/macos/Resources/Hardware/coco-128kb.pdf b/platforms/macos/Resources/Hardware/coco-128kb.pdf new file mode 100644 index 0000000..bb48a54 Binary files /dev/null and b/platforms/macos/Resources/Hardware/coco-128kb.pdf differ diff --git a/platforms/macos/Resources/Hardware/coco-2mb.pdf b/platforms/macos/Resources/Hardware/coco-2mb.pdf new file mode 100644 index 0000000..65c5300 Binary files /dev/null and b/platforms/macos/Resources/Hardware/coco-2mb.pdf differ diff --git a/platforms/macos/Resources/Hardware/coco-512kb.pdf b/platforms/macos/Resources/Hardware/coco-512kb.pdf new file mode 100644 index 0000000..fe5298c Binary files /dev/null and b/platforms/macos/Resources/Hardware/coco-512kb.pdf differ diff --git a/platforms/macos/Resources/Hardware/coco-8mb.pdf b/platforms/macos/Resources/Hardware/coco-8mb.pdf new file mode 100644 index 0000000..861961b Binary files /dev/null and b/platforms/macos/Resources/Hardware/coco-8mb.pdf differ diff --git a/platforms/macos/Resources/Hardware/floppy.pdf b/platforms/macos/Resources/Hardware/floppy.pdf new file mode 100644 index 0000000..a60d8c3 Binary files /dev/null and b/platforms/macos/Resources/Hardware/floppy.pdf differ diff --git a/platforms/macos/Resources/Hardware/hard.pdf b/platforms/macos/Resources/Hardware/hard.pdf new file mode 100644 index 0000000..468ae3e Binary files /dev/null and b/platforms/macos/Resources/Hardware/hard.pdf differ diff --git a/platforms/macos/Resources/Hardware/hitachi.pdf b/platforms/macos/Resources/Hardware/hitachi.pdf new file mode 100644 index 0000000..1b27ab1 Binary files /dev/null and b/platforms/macos/Resources/Hardware/hitachi.pdf differ diff --git a/platforms/macos/Resources/Hardware/joystick.pdf b/platforms/macos/Resources/Hardware/joystick.pdf new file mode 100644 index 0000000..40f7e07 Binary files /dev/null and b/platforms/macos/Resources/Hardware/joystick.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-000.pdf b/platforms/macos/Resources/Hardware/layer-000.pdf new file mode 100644 index 0000000..e738598 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-000.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-001.pdf b/platforms/macos/Resources/Hardware/layer-001.pdf new file mode 100644 index 0000000..0aec029 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-001.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-002.pdf b/platforms/macos/Resources/Hardware/layer-002.pdf new file mode 100644 index 0000000..e0c82ec Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-002.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-003.pdf b/platforms/macos/Resources/Hardware/layer-003.pdf new file mode 100644 index 0000000..93d2885 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-003.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-004.pdf b/platforms/macos/Resources/Hardware/layer-004.pdf new file mode 100644 index 0000000..b3b94de Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-004.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-005.pdf b/platforms/macos/Resources/Hardware/layer-005.pdf new file mode 100644 index 0000000..f56a407 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-005.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-006.pdf b/platforms/macos/Resources/Hardware/layer-006.pdf new file mode 100644 index 0000000..7a0d862 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-006.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-007.pdf b/platforms/macos/Resources/Hardware/layer-007.pdf new file mode 100644 index 0000000..3b5a8ec Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-007.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-008.pdf b/platforms/macos/Resources/Hardware/layer-008.pdf new file mode 100644 index 0000000..f00cc3b Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-008.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-009.pdf b/platforms/macos/Resources/Hardware/layer-009.pdf new file mode 100644 index 0000000..bf2c23f Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-009.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-010.pdf b/platforms/macos/Resources/Hardware/layer-010.pdf new file mode 100644 index 0000000..4ea0156 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-010.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-011.pdf b/platforms/macos/Resources/Hardware/layer-011.pdf new file mode 100644 index 0000000..a8dcfda Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-011.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-012.pdf b/platforms/macos/Resources/Hardware/layer-012.pdf new file mode 100644 index 0000000..ccc8b64 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-012.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-013.pdf b/platforms/macos/Resources/Hardware/layer-013.pdf new file mode 100644 index 0000000..c62ee0c Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-013.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-014.pdf b/platforms/macos/Resources/Hardware/layer-014.pdf new file mode 100644 index 0000000..af9ecbb Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-014.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-015.pdf b/platforms/macos/Resources/Hardware/layer-015.pdf new file mode 100644 index 0000000..741cad4 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-015.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-016.pdf b/platforms/macos/Resources/Hardware/layer-016.pdf new file mode 100644 index 0000000..c60a708 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-016.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-017.pdf b/platforms/macos/Resources/Hardware/layer-017.pdf new file mode 100644 index 0000000..9b6060e Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-017.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-018.pdf b/platforms/macos/Resources/Hardware/layer-018.pdf new file mode 100644 index 0000000..73714e9 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-018.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-019.pdf b/platforms/macos/Resources/Hardware/layer-019.pdf new file mode 100644 index 0000000..b001545 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-019.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-020.pdf b/platforms/macos/Resources/Hardware/layer-020.pdf new file mode 100644 index 0000000..e3d4281 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-020.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-021.pdf b/platforms/macos/Resources/Hardware/layer-021.pdf new file mode 100644 index 0000000..98cc76e Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-021.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-022.pdf b/platforms/macos/Resources/Hardware/layer-022.pdf new file mode 100644 index 0000000..8b30938 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-022.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-023.pdf b/platforms/macos/Resources/Hardware/layer-023.pdf new file mode 100644 index 0000000..8d003cf Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-023.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-024.pdf b/platforms/macos/Resources/Hardware/layer-024.pdf new file mode 100644 index 0000000..78815fb Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-024.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-025.pdf b/platforms/macos/Resources/Hardware/layer-025.pdf new file mode 100644 index 0000000..a99a373 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-025.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-026.pdf b/platforms/macos/Resources/Hardware/layer-026.pdf new file mode 100644 index 0000000..30bc0f9 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-026.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-027.pdf b/platforms/macos/Resources/Hardware/layer-027.pdf new file mode 100644 index 0000000..c3a556c Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-027.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-028.pdf b/platforms/macos/Resources/Hardware/layer-028.pdf new file mode 100644 index 0000000..75b0134 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-028.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-029.pdf b/platforms/macos/Resources/Hardware/layer-029.pdf new file mode 100644 index 0000000..3bed8a5 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-029.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-030.pdf b/platforms/macos/Resources/Hardware/layer-030.pdf new file mode 100644 index 0000000..905afa1 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-030.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-031.pdf b/platforms/macos/Resources/Hardware/layer-031.pdf new file mode 100644 index 0000000..15bbce9 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-031.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-032.pdf b/platforms/macos/Resources/Hardware/layer-032.pdf new file mode 100644 index 0000000..f4c11ab Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-032.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-033.pdf b/platforms/macos/Resources/Hardware/layer-033.pdf new file mode 100644 index 0000000..d110e93 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-033.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-034.pdf b/platforms/macos/Resources/Hardware/layer-034.pdf new file mode 100644 index 0000000..cdc48ac Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-034.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-035.pdf b/platforms/macos/Resources/Hardware/layer-035.pdf new file mode 100644 index 0000000..6d3319a Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-035.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-036.pdf b/platforms/macos/Resources/Hardware/layer-036.pdf new file mode 100644 index 0000000..b11c979 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-036.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-037.pdf b/platforms/macos/Resources/Hardware/layer-037.pdf new file mode 100644 index 0000000..f0d7865 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-037.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-038.pdf b/platforms/macos/Resources/Hardware/layer-038.pdf new file mode 100644 index 0000000..af631b5 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-038.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-039.pdf b/platforms/macos/Resources/Hardware/layer-039.pdf new file mode 100644 index 0000000..b65caee Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-039.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-040.pdf b/platforms/macos/Resources/Hardware/layer-040.pdf new file mode 100644 index 0000000..48202d4 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-040.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-041.pdf b/platforms/macos/Resources/Hardware/layer-041.pdf new file mode 100644 index 0000000..1d3e493 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-041.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-042.pdf b/platforms/macos/Resources/Hardware/layer-042.pdf new file mode 100644 index 0000000..b175d7e Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-042.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-043.pdf b/platforms/macos/Resources/Hardware/layer-043.pdf new file mode 100644 index 0000000..a3cc57d Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-043.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-044.pdf b/platforms/macos/Resources/Hardware/layer-044.pdf new file mode 100644 index 0000000..d59f161 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-044.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-045.pdf b/platforms/macos/Resources/Hardware/layer-045.pdf new file mode 100644 index 0000000..253e23a Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-045.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-046.pdf b/platforms/macos/Resources/Hardware/layer-046.pdf new file mode 100644 index 0000000..b9ad4ea Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-046.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-047.pdf b/platforms/macos/Resources/Hardware/layer-047.pdf new file mode 100644 index 0000000..8088856 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-047.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-048.pdf b/platforms/macos/Resources/Hardware/layer-048.pdf new file mode 100644 index 0000000..5d68c66 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-048.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-049.pdf b/platforms/macos/Resources/Hardware/layer-049.pdf new file mode 100644 index 0000000..273a500 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-049.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-050.pdf b/platforms/macos/Resources/Hardware/layer-050.pdf new file mode 100644 index 0000000..6b4189e Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-050.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-051.pdf b/platforms/macos/Resources/Hardware/layer-051.pdf new file mode 100644 index 0000000..c6ed9fa Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-051.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-052.pdf b/platforms/macos/Resources/Hardware/layer-052.pdf new file mode 100644 index 0000000..2b8a4bc Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-052.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-053.pdf b/platforms/macos/Resources/Hardware/layer-053.pdf new file mode 100644 index 0000000..5547c76 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-053.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-054.pdf b/platforms/macos/Resources/Hardware/layer-054.pdf new file mode 100644 index 0000000..f85c2c6 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-054.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-055.pdf b/platforms/macos/Resources/Hardware/layer-055.pdf new file mode 100644 index 0000000..d1f81a9 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-055.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-056.pdf b/platforms/macos/Resources/Hardware/layer-056.pdf new file mode 100644 index 0000000..0fc4607 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-056.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-057.pdf b/platforms/macos/Resources/Hardware/layer-057.pdf new file mode 100644 index 0000000..f8209c6 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-057.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-058.pdf b/platforms/macos/Resources/Hardware/layer-058.pdf new file mode 100644 index 0000000..9f7fa31 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-058.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-059.pdf b/platforms/macos/Resources/Hardware/layer-059.pdf new file mode 100644 index 0000000..bd5c2d6 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-059.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-060.pdf b/platforms/macos/Resources/Hardware/layer-060.pdf new file mode 100644 index 0000000..a9c92b8 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-060.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-061.pdf b/platforms/macos/Resources/Hardware/layer-061.pdf new file mode 100644 index 0000000..c5fe273 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-061.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-062.pdf b/platforms/macos/Resources/Hardware/layer-062.pdf new file mode 100644 index 0000000..43b8d46 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-062.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-063.pdf b/platforms/macos/Resources/Hardware/layer-063.pdf new file mode 100644 index 0000000..9605d2e Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-063.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-064.pdf b/platforms/macos/Resources/Hardware/layer-064.pdf new file mode 100644 index 0000000..d39d4b9 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-064.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-065.pdf b/platforms/macos/Resources/Hardware/layer-065.pdf new file mode 100644 index 0000000..2486a93 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-065.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-066.pdf b/platforms/macos/Resources/Hardware/layer-066.pdf new file mode 100644 index 0000000..34410b2 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-066.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-067.pdf b/platforms/macos/Resources/Hardware/layer-067.pdf new file mode 100644 index 0000000..e9203c9 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-067.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-068.pdf b/platforms/macos/Resources/Hardware/layer-068.pdf new file mode 100644 index 0000000..eabcd95 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-068.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-069.pdf b/platforms/macos/Resources/Hardware/layer-069.pdf new file mode 100644 index 0000000..9a0e9d8 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-069.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-070.pdf b/platforms/macos/Resources/Hardware/layer-070.pdf new file mode 100644 index 0000000..a0c954f Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-070.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-071.pdf b/platforms/macos/Resources/Hardware/layer-071.pdf new file mode 100644 index 0000000..cd8b024 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-071.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-072.pdf b/platforms/macos/Resources/Hardware/layer-072.pdf new file mode 100644 index 0000000..e46acbb Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-072.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-073.pdf b/platforms/macos/Resources/Hardware/layer-073.pdf new file mode 100644 index 0000000..e5ef63e Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-073.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-074.pdf b/platforms/macos/Resources/Hardware/layer-074.pdf new file mode 100644 index 0000000..7d566e5 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-074.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-075.pdf b/platforms/macos/Resources/Hardware/layer-075.pdf new file mode 100644 index 0000000..dd11cd7 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-075.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-076.pdf b/platforms/macos/Resources/Hardware/layer-076.pdf new file mode 100644 index 0000000..0f2da31 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-076.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-077.pdf b/platforms/macos/Resources/Hardware/layer-077.pdf new file mode 100644 index 0000000..70c78cb Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-077.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-078.pdf b/platforms/macos/Resources/Hardware/layer-078.pdf new file mode 100644 index 0000000..0a5236d Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-078.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-079.pdf b/platforms/macos/Resources/Hardware/layer-079.pdf new file mode 100644 index 0000000..642086a Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-079.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-080.pdf b/platforms/macos/Resources/Hardware/layer-080.pdf new file mode 100644 index 0000000..be00b39 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-080.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-081.pdf b/platforms/macos/Resources/Hardware/layer-081.pdf new file mode 100644 index 0000000..18843ec Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-081.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-082.pdf b/platforms/macos/Resources/Hardware/layer-082.pdf new file mode 100644 index 0000000..e86c371 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-082.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-083.pdf b/platforms/macos/Resources/Hardware/layer-083.pdf new file mode 100644 index 0000000..153e168 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-083.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-084.pdf b/platforms/macos/Resources/Hardware/layer-084.pdf new file mode 100644 index 0000000..3ec080c Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-084.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-085.pdf b/platforms/macos/Resources/Hardware/layer-085.pdf new file mode 100644 index 0000000..674af8d Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-085.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-086.pdf b/platforms/macos/Resources/Hardware/layer-086.pdf new file mode 100644 index 0000000..b2a2e9a Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-086.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-087.pdf b/platforms/macos/Resources/Hardware/layer-087.pdf new file mode 100644 index 0000000..33897a5 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-087.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-088.pdf b/platforms/macos/Resources/Hardware/layer-088.pdf new file mode 100644 index 0000000..80921e8 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-088.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-089.pdf b/platforms/macos/Resources/Hardware/layer-089.pdf new file mode 100644 index 0000000..21daa6f Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-089.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-090.pdf b/platforms/macos/Resources/Hardware/layer-090.pdf new file mode 100644 index 0000000..40ae44f Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-090.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-091.pdf b/platforms/macos/Resources/Hardware/layer-091.pdf new file mode 100644 index 0000000..9924986 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-091.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-092.pdf b/platforms/macos/Resources/Hardware/layer-092.pdf new file mode 100644 index 0000000..70a2282 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-092.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-093.pdf b/platforms/macos/Resources/Hardware/layer-093.pdf new file mode 100644 index 0000000..dfd8d52 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-093.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-094.pdf b/platforms/macos/Resources/Hardware/layer-094.pdf new file mode 100644 index 0000000..b13d9fc Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-094.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-095.pdf b/platforms/macos/Resources/Hardware/layer-095.pdf new file mode 100644 index 0000000..39431d2 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-095.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-096.pdf b/platforms/macos/Resources/Hardware/layer-096.pdf new file mode 100644 index 0000000..2b88b73 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-096.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-097.pdf b/platforms/macos/Resources/Hardware/layer-097.pdf new file mode 100644 index 0000000..619cf45 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-097.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-098.pdf b/platforms/macos/Resources/Hardware/layer-098.pdf new file mode 100644 index 0000000..8a5537e Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-098.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-099.pdf b/platforms/macos/Resources/Hardware/layer-099.pdf new file mode 100644 index 0000000..e239ad8 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-099.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-100.pdf b/platforms/macos/Resources/Hardware/layer-100.pdf new file mode 100644 index 0000000..6335aa0 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-100.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-101.pdf b/platforms/macos/Resources/Hardware/layer-101.pdf new file mode 100644 index 0000000..04305de Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-101.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-102.pdf b/platforms/macos/Resources/Hardware/layer-102.pdf new file mode 100644 index 0000000..757a11a Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-102.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-103.pdf b/platforms/macos/Resources/Hardware/layer-103.pdf new file mode 100644 index 0000000..5e4df98 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-103.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-104.pdf b/platforms/macos/Resources/Hardware/layer-104.pdf new file mode 100644 index 0000000..5f7846c Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-104.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-105.pdf b/platforms/macos/Resources/Hardware/layer-105.pdf new file mode 100644 index 0000000..f503cc2 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-105.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-106.pdf b/platforms/macos/Resources/Hardware/layer-106.pdf new file mode 100644 index 0000000..7b8bcc5 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-106.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-107.pdf b/platforms/macos/Resources/Hardware/layer-107.pdf new file mode 100644 index 0000000..7e22940 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-107.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-108.pdf b/platforms/macos/Resources/Hardware/layer-108.pdf new file mode 100644 index 0000000..65720c0 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-108.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-109.pdf b/platforms/macos/Resources/Hardware/layer-109.pdf new file mode 100644 index 0000000..69c01c9 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-109.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-110.pdf b/platforms/macos/Resources/Hardware/layer-110.pdf new file mode 100644 index 0000000..a97b708 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-110.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-111.pdf b/platforms/macos/Resources/Hardware/layer-111.pdf new file mode 100644 index 0000000..ac86ff1 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-111.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-112.pdf b/platforms/macos/Resources/Hardware/layer-112.pdf new file mode 100644 index 0000000..c08b330 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-112.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-113.pdf b/platforms/macos/Resources/Hardware/layer-113.pdf new file mode 100644 index 0000000..e9e45be Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-113.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-114.pdf b/platforms/macos/Resources/Hardware/layer-114.pdf new file mode 100644 index 0000000..2114a70 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-114.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-115.pdf b/platforms/macos/Resources/Hardware/layer-115.pdf new file mode 100644 index 0000000..16542b6 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-115.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-116.pdf b/platforms/macos/Resources/Hardware/layer-116.pdf new file mode 100644 index 0000000..fe84a08 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-116.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-117.pdf b/platforms/macos/Resources/Hardware/layer-117.pdf new file mode 100644 index 0000000..f30e49d Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-117.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-118.pdf b/platforms/macos/Resources/Hardware/layer-118.pdf new file mode 100644 index 0000000..9bd7f28 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-118.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-119.pdf b/platforms/macos/Resources/Hardware/layer-119.pdf new file mode 100644 index 0000000..3e2dea1 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-119.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-120.pdf b/platforms/macos/Resources/Hardware/layer-120.pdf new file mode 100644 index 0000000..a4b967c Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-120.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-121.pdf b/platforms/macos/Resources/Hardware/layer-121.pdf new file mode 100644 index 0000000..188bfa2 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-121.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-122.pdf b/platforms/macos/Resources/Hardware/layer-122.pdf new file mode 100644 index 0000000..5f0474d Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-122.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-123.pdf b/platforms/macos/Resources/Hardware/layer-123.pdf new file mode 100644 index 0000000..2de8c34 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-123.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-124.pdf b/platforms/macos/Resources/Hardware/layer-124.pdf new file mode 100644 index 0000000..4b02cb2 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-124.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-125.pdf b/platforms/macos/Resources/Hardware/layer-125.pdf new file mode 100644 index 0000000..187fe8e Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-125.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-126.pdf b/platforms/macos/Resources/Hardware/layer-126.pdf new file mode 100644 index 0000000..0793c88 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-126.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-127.pdf b/platforms/macos/Resources/Hardware/layer-127.pdf new file mode 100644 index 0000000..83d65f8 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-127.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-128.pdf b/platforms/macos/Resources/Hardware/layer-128.pdf new file mode 100644 index 0000000..8cdd344 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-128.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-129.pdf b/platforms/macos/Resources/Hardware/layer-129.pdf new file mode 100644 index 0000000..38b59aa Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-129.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-130.pdf b/platforms/macos/Resources/Hardware/layer-130.pdf new file mode 100644 index 0000000..df246b4 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-130.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-131.pdf b/platforms/macos/Resources/Hardware/layer-131.pdf new file mode 100644 index 0000000..4176d79 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-131.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-132.pdf b/platforms/macos/Resources/Hardware/layer-132.pdf new file mode 100644 index 0000000..17453ab Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-132.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-133.pdf b/platforms/macos/Resources/Hardware/layer-133.pdf new file mode 100644 index 0000000..1d74142 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-133.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-134.pdf b/platforms/macos/Resources/Hardware/layer-134.pdf new file mode 100644 index 0000000..22bc7fe Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-134.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-135.pdf b/platforms/macos/Resources/Hardware/layer-135.pdf new file mode 100644 index 0000000..5189092 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-135.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-136.pdf b/platforms/macos/Resources/Hardware/layer-136.pdf new file mode 100644 index 0000000..6f707a3 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-136.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-137.pdf b/platforms/macos/Resources/Hardware/layer-137.pdf new file mode 100644 index 0000000..c8f4a4b Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-137.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-138.pdf b/platforms/macos/Resources/Hardware/layer-138.pdf new file mode 100644 index 0000000..c428c18 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-138.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-139.pdf b/platforms/macos/Resources/Hardware/layer-139.pdf new file mode 100644 index 0000000..bcceed8 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-139.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-140.pdf b/platforms/macos/Resources/Hardware/layer-140.pdf new file mode 100644 index 0000000..b0bef31 Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-140.pdf differ diff --git a/platforms/macos/Resources/Hardware/layer-141.pdf b/platforms/macos/Resources/Hardware/layer-141.pdf new file mode 100644 index 0000000..c16710a Binary files /dev/null and b/platforms/macos/Resources/Hardware/layer-141.pdf differ diff --git a/platforms/macos/Resources/Hardware/layers.json b/platforms/macos/Resources/Hardware/layers.json new file mode 100644 index 0000000..cac7761 --- /dev/null +++ b/platforms/macos/Resources/Hardware/layers.json @@ -0,0 +1,1939 @@ +[ + { + "file": "layer-000.pdf", + "bounds": [ + -108.0, + 210.5, + 142.5, + 131.5 + ], + "when": { + "scene": "on" + }, + "part": "scene" + }, + { + "file": "layer-001.pdf", + "bounds": [ + -92.5, + 273.5, + 102.0, + 21.5 + ], + "when": { + "scene": "on" + }, + "part": "scene" + }, + { + "file": "layer-002.pdf", + "bounds": [ + -19.5, + 286.5, + 6.0, + 4.0 + ], + "when": { + "scene": "on" + }, + "part": "scene" + }, + { + "file": "layer-003.pdf", + "bounds": [ + -18.5, + 287.0, + 4.0, + 3.0 + ], + "when": { + "scene": "on", + "tapeActivity": "empty" + }, + "part": "scene" + }, + { + "file": "layer-004.pdf", + "bounds": [ + -18.5, + 287.0, + 4.0, + 3.0 + ], + "when": { + "scene": "on", + "tapeActivity": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-005.pdf", + "bounds": [ + -18.5, + 287.0, + 4.0, + 3.0 + ], + "when": { + "scene": "on", + "tapeActivity": "read" + }, + "part": "scene" + }, + { + "file": "layer-006.pdf", + "bounds": [ + -18.5, + 287.0, + 4.0, + 3.0 + ], + "when": { + "scene": "on", + "tapeActivity": "write" + }, + "part": "scene" + }, + { + "file": "layer-007.pdf", + "bounds": [ + -83.5, + 277.5, + 81.5, + 16.0 + ], + "when": { + "scene": "on" + }, + "part": "scene" + }, + { + "file": "layer-008.pdf", + "bounds": [ + -94.5, + 292.5, + 90.0, + 20.0 + ], + "when": { + "scene": "on" + }, + "part": "scene" + }, + { + "file": "layer-009.pdf", + "bounds": [ + -84.0, + 243.0, + 103.5, + 35.5 + ], + "when": { + "scene": "on" + }, + "part": "scene" + }, + { + "file": "layer-010.pdf", + "bounds": [ + -53.5, + 255.0, + 64.5, + 13.5 + ], + "when": { + "scene": "on", + "tape": "empty" + }, + "part": "scene" + }, + { + "file": "layer-011.pdf", + "bounds": [ + -73.5, + 245.0, + 85.0, + 25.5 + ], + "when": { + "scene": "on", + "tape": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-012.pdf", + "bounds": [ + -81.5, + 244.0, + 98.0, + 32.5 + ], + "when": { + "scene": "on" + }, + "part": "scene" + }, + { + "file": "layer-013.pdf", + "bounds": [ + -94.5, + 359.0, + 104.0, + 85.5 + ], + "when": { + "scene": "on" + }, + "part": "scene" + }, + { + "file": "layer-014.pdf", + "bounds": [ + 414.5, + 216.5, + 291.5, + 65.0 + ], + "when": { + "slot1": "hard" + }, + "part": "scene" + }, + { + "file": "layer-015.pdf", + "bounds": [ + 408.5, + 204.5, + 297.5, + 77.0 + ], + "when": { + "slot2": "hard" + }, + "part": "scene" + }, + { + "file": "layer-016.pdf", + "bounds": [ + 401.5, + 192.5, + 304.5, + 89.0 + ], + "when": { + "slot3": "hard" + }, + "part": "scene" + }, + { + "file": "layer-017.pdf", + "bounds": [ + 394.5, + 180.5, + 311.5, + 101.0 + ], + "when": { + "slot4": "hard" + }, + "part": "scene" + }, + { + "file": "layer-018.pdf", + "bounds": [ + 414.0, + 204.5, + 292.0, + 49.0 + ], + "when": { + "slot1": "floppy" + }, + "part": "scene" + }, + { + "file": "layer-019.pdf", + "bounds": [ + 408.0, + 200.0, + 298.0, + 37.0 + ], + "when": { + "slot2": "floppy" + }, + "part": "scene" + }, + { + "file": "layer-020.pdf", + "bounds": [ + 401.0, + 189.0, + 305.0, + 48.0 + ], + "when": { + "slot3": "floppy" + }, + "part": "scene" + }, + { + "file": "layer-021.pdf", + "bounds": [ + 394.0, + 177.5, + 312.0, + 59.5 + ], + "when": { + "slot4": "floppy" + }, + "part": "scene" + }, + { + "file": "layer-022.pdf", + "bounds": [ + 558.5, + 255.0, + 268.5, + 189.0 + ], + "when": { + "hardCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-023.pdf", + "bounds": [ + 648.5, + 379.0, + 175.5, + 32.0 + ], + "when": { + "hardCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-024.pdf", + "bounds": [ + 657.0, + 384.0, + 6.5, + 4.0 + ], + "when": { + "hardCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-025.pdf", + "bounds": [ + 657.5, + 384.5, + 5.5, + 3.0 + ], + "when": { + "hardCase": "on", + "hd1Activity": "empty" + }, + "part": "scene" + }, + { + "file": "layer-026.pdf", + "bounds": [ + 657.5, + 384.5, + 5.5, + 3.0 + ], + "when": { + "hardCase": "on", + "hd1Activity": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-027.pdf", + "bounds": [ + 657.5, + 384.5, + 5.5, + 3.0 + ], + "when": { + "hardCase": "on", + "hd1Activity": "read" + }, + "part": "scene" + }, + { + "file": "layer-028.pdf", + "bounds": [ + 657.5, + 384.5, + 5.5, + 3.0 + ], + "when": { + "hardCase": "on", + "hd1Activity": "write" + }, + "part": "scene" + }, + { + "file": "layer-029.pdf", + "bounds": [ + 655.0, + 397.5, + 21.0, + 10.5 + ], + "when": { + "hardCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-030.pdf", + "bounds": [ + 648.5, + 410.5, + 175.5, + 32.0 + ], + "when": { + "hardCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-031.pdf", + "bounds": [ + 657.0, + 415.5, + 6.5, + 4.0 + ], + "when": { + "hardCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-032.pdf", + "bounds": [ + 657.5, + 416.0, + 5.5, + 3.0 + ], + "when": { + "hardCase": "on", + "hd0Activity": "empty" + }, + "part": "scene" + }, + { + "file": "layer-033.pdf", + "bounds": [ + 657.5, + 416.0, + 5.5, + 3.0 + ], + "when": { + "hardCase": "on", + "hd0Activity": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-034.pdf", + "bounds": [ + 657.5, + 416.0, + 5.5, + 3.0 + ], + "when": { + "hardCase": "on", + "hd0Activity": "read" + }, + "part": "scene" + }, + { + "file": "layer-035.pdf", + "bounds": [ + 657.5, + 416.0, + 5.5, + 3.0 + ], + "when": { + "hardCase": "on", + "hd0Activity": "write" + }, + "part": "scene" + }, + { + "file": "layer-036.pdf", + "bounds": [ + 655.0, + 429.0, + 21.0, + 10.5 + ], + "when": { + "hardCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-037.pdf", + "bounds": [ + 558.5, + 197.0, + 268.5, + 176.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-038.pdf", + "bounds": [ + 648.5, + 307.5, + 175.5, + 32.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-039.pdf", + "bounds": [ + 657.0, + 313.0, + 6.5, + 4.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-040.pdf", + "bounds": [ + 657.5, + 313.0, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd1Activity": "empty" + }, + "part": "scene" + }, + { + "file": "layer-041.pdf", + "bounds": [ + 657.5, + 313.0, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd1Activity": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-042.pdf", + "bounds": [ + 657.5, + 313.0, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd1Activity": "read" + }, + "part": "scene" + }, + { + "file": "layer-043.pdf", + "bounds": [ + 657.5, + 313.0, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd1Activity": "write" + }, + "part": "scene" + }, + { + "file": "layer-044.pdf", + "bounds": [ + 655.0, + 313.0, + 160.0, + 25.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-045.pdf", + "bounds": [ + 776.0, + 313.0, + 20.5, + 9.0 + ], + "when": { + "floppyCase": "on", + "fd1": "empty" + }, + "part": "scene" + }, + { + "file": "layer-046.pdf", + "bounds": [ + 658.0, + 315.5, + 154.5, + 20.5 + ], + "when": { + "floppyCase": "on", + "fd1": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-047.pdf", + "bounds": [ + 655.0, + 311.0, + 129.5, + 26.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-048.pdf", + "bounds": [ + 648.5, + 339.0, + 175.5, + 32.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-049.pdf", + "bounds": [ + 657.0, + 344.5, + 6.5, + 4.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-050.pdf", + "bounds": [ + 657.5, + 344.5, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd0Activity": "empty" + }, + "part": "scene" + }, + { + "file": "layer-051.pdf", + "bounds": [ + 657.5, + 344.5, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd0Activity": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-052.pdf", + "bounds": [ + 657.5, + 344.5, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd0Activity": "read" + }, + "part": "scene" + }, + { + "file": "layer-053.pdf", + "bounds": [ + 657.5, + 344.5, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd0Activity": "write" + }, + "part": "scene" + }, + { + "file": "layer-054.pdf", + "bounds": [ + 655.0, + 344.5, + 160.0, + 25.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-055.pdf", + "bounds": [ + 776.0, + 344.5, + 20.5, + 9.0 + ], + "when": { + "floppyCase": "on", + "fd0": "empty" + }, + "part": "scene" + }, + { + "file": "layer-056.pdf", + "bounds": [ + 658.0, + 347.0, + 154.5, + 20.5 + ], + "when": { + "floppyCase": "on", + "fd0": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-057.pdf", + "bounds": [ + 655.0, + 342.5, + 129.5, + 26.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-058.pdf", + "bounds": [ + 558.5, + 139.5, + 268.5, + 162.5 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-059.pdf", + "bounds": [ + 648.5, + 236.5, + 175.5, + 32.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-060.pdf", + "bounds": [ + 657.0, + 242.0, + 6.5, + 4.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-061.pdf", + "bounds": [ + 657.5, + 242.0, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd3Activity": "empty" + }, + "part": "scene" + }, + { + "file": "layer-062.pdf", + "bounds": [ + 657.5, + 242.0, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd3Activity": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-063.pdf", + "bounds": [ + 657.5, + 242.0, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd3Activity": "read" + }, + "part": "scene" + }, + { + "file": "layer-064.pdf", + "bounds": [ + 657.5, + 242.0, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd3Activity": "write" + }, + "part": "scene" + }, + { + "file": "layer-065.pdf", + "bounds": [ + 655.0, + 242.0, + 160.0, + 25.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-066.pdf", + "bounds": [ + 776.0, + 242.0, + 20.5, + 9.0 + ], + "when": { + "floppyCase": "on", + "fd3": "empty" + }, + "part": "scene" + }, + { + "file": "layer-067.pdf", + "bounds": [ + 658.0, + 244.5, + 154.5, + 20.5 + ], + "when": { + "floppyCase": "on", + "fd3": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-068.pdf", + "bounds": [ + 655.0, + 240.0, + 129.5, + 26.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-069.pdf", + "bounds": [ + 648.5, + 268.0, + 175.5, + 32.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-070.pdf", + "bounds": [ + 657.0, + 273.5, + 6.5, + 4.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-071.pdf", + "bounds": [ + 657.5, + 273.5, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd2Activity": "empty" + }, + "part": "scene" + }, + { + "file": "layer-072.pdf", + "bounds": [ + 657.5, + 273.5, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd2Activity": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-073.pdf", + "bounds": [ + 657.5, + 273.5, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd2Activity": "read" + }, + "part": "scene" + }, + { + "file": "layer-074.pdf", + "bounds": [ + 657.5, + 273.5, + 5.5, + 3.5 + ], + "when": { + "floppyCase": "on", + "fd2Activity": "write" + }, + "part": "scene" + }, + { + "file": "layer-075.pdf", + "bounds": [ + 655.0, + 273.5, + 160.0, + 25.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-076.pdf", + "bounds": [ + 776.0, + 273.5, + 20.5, + 9.0 + ], + "when": { + "floppyCase": "on", + "fd2": "empty" + }, + "part": "scene" + }, + { + "file": "layer-077.pdf", + "bounds": [ + 658.0, + 276.0, + 154.5, + 20.5 + ], + "when": { + "floppyCase": "on", + "fd2": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-078.pdf", + "bounds": [ + 655.0, + 271.5, + 129.5, + 26.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-079.pdf", + "bounds": [ + 587.5, + 153.0, + 221.5, + 76.0 + ], + "when": { + "floppyCase": "on" + }, + "part": "scene" + }, + { + "file": "layer-080.pdf", + "bounds": [ + 292.0, + 255.0, + 274.5, + 145.0 + ], + "when": { + "mpi": "on" + }, + "part": "scene" + }, + { + "file": "layer-081.pdf", + "bounds": [ + 471.5, + 371.0, + 46.0, + 13.5 + ], + "when": { + "mpi": "on" + }, + "part": "scene" + }, + { + "file": "layer-082.pdf", + "bounds": [ + 482.0, + 370.0, + 35.0, + 17.0 + ], + "when": { + "mpi": "on", + "startup": "1" + }, + "part": "scene" + }, + { + "file": "layer-083.pdf", + "bounds": [ + 478.0, + 370.0, + 35.0, + 17.0 + ], + "when": { + "mpi": "on", + "startup": "2" + }, + "part": "scene" + }, + { + "file": "layer-084.pdf", + "bounds": [ + 474.5, + 370.0, + 35.0, + 17.0 + ], + "when": { + "mpi": "on", + "startup": "3" + }, + "part": "scene" + }, + { + "file": "layer-085.pdf", + "bounds": [ + 470.5, + 370.0, + 35.0, + 17.0 + ], + "when": { + "mpi": "on", + "startup": "4" + }, + "part": "scene" + }, + { + "file": "layer-086.pdf", + "bounds": [ + 491.5, + 369.5, + 5.5, + 3.0 + ], + "when": { + "mpi": "on" + }, + "part": "scene" + }, + { + "file": "layer-087.pdf", + "bounds": [ + 359.5, + 212.0, + 81.0, + 62.5 + ], + "when": { + "mpi": "on", + "slot4": "rom" + }, + "part": "scene" + }, + { + "file": "layer-088.pdf", + "bounds": [ + 359.5, + 197.5, + 81.0, + 77.0 + ], + "when": { + "mpi": "on", + "slot4": "orchestra" + }, + "part": "scene" + }, + { + "file": "layer-089.pdf", + "bounds": [ + 359.5, + 197.5, + 81.0, + 77.0 + ], + "when": { + "mpi": "on", + "slot4": "speech" + }, + "part": "scene" + }, + { + "file": "layer-090.pdf", + "bounds": [ + 359.5, + 197.5, + 81.0, + 77.0 + ], + "when": { + "mpi": "on", + "slot4": "floppy" + }, + "part": "scene" + }, + { + "file": "layer-091.pdf", + "bounds": [ + 359.5, + 197.5, + 81.0, + 77.0 + ], + "when": { + "mpi": "on", + "slot4": "hard" + }, + "part": "scene" + }, + { + "file": "layer-092.pdf", + "bounds": [ + 359.5, + 205.5, + 81.0, + 69.5 + ], + "when": { + "mpi": "on", + "slot4": "sdc" + }, + "part": "scene" + }, + { + "file": "layer-093.pdf", + "bounds": [ + 429.5, + 265.0, + 4.5, + 4.0 + ], + "when": { + "mpi": "on", + "slot4": "sdc", + "sdcActivity": "empty" + }, + "part": "scene" + }, + { + "file": "layer-094.pdf", + "bounds": [ + 429.5, + 265.0, + 4.5, + 4.0 + ], + "when": { + "mpi": "on", + "slot4": "sdc", + "sdcActivity": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-095.pdf", + "bounds": [ + 429.5, + 265.0, + 4.5, + 4.0 + ], + "when": { + "mpi": "on", + "slot4": "sdc", + "sdcActivity": "read" + }, + "part": "scene" + }, + { + "file": "layer-096.pdf", + "bounds": [ + 429.5, + 265.0, + 4.5, + 4.0 + ], + "when": { + "mpi": "on", + "slot4": "sdc", + "sdcActivity": "write" + }, + "part": "scene" + }, + { + "file": "layer-097.pdf", + "bounds": [ + 364.5, + 226.0, + 83.0, + 64.5 + ], + "when": { + "mpi": "on", + "slot3": "rom" + }, + "part": "scene" + }, + { + "file": "layer-098.pdf", + "bounds": [ + 364.5, + 211.0, + 83.0, + 79.5 + ], + "when": { + "mpi": "on", + "slot3": "orchestra" + }, + "part": "scene" + }, + { + "file": "layer-099.pdf", + "bounds": [ + 364.5, + 211.0, + 83.0, + 79.5 + ], + "when": { + "mpi": "on", + "slot3": "speech" + }, + "part": "scene" + }, + { + "file": "layer-100.pdf", + "bounds": [ + 364.5, + 211.0, + 83.0, + 79.5 + ], + "when": { + "mpi": "on", + "slot3": "floppy" + }, + "part": "scene" + }, + { + "file": "layer-101.pdf", + "bounds": [ + 364.5, + 211.0, + 83.0, + 79.5 + ], + "when": { + "mpi": "on", + "slot3": "hard" + }, + "part": "scene" + }, + { + "file": "layer-102.pdf", + "bounds": [ + 364.5, + 219.5, + 83.5, + 71.5 + ], + "when": { + "mpi": "on", + "slot3": "sdc" + }, + "part": "scene" + }, + { + "file": "layer-103.pdf", + "bounds": [ + 437.0, + 280.5, + 4.0, + 4.5 + ], + "when": { + "mpi": "on", + "slot3": "sdc", + "sdcActivity": "empty" + }, + "part": "scene" + }, + { + "file": "layer-104.pdf", + "bounds": [ + 437.0, + 280.5, + 4.0, + 4.5 + ], + "when": { + "mpi": "on", + "slot3": "sdc", + "sdcActivity": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-105.pdf", + "bounds": [ + 437.0, + 280.5, + 4.0, + 4.5 + ], + "when": { + "mpi": "on", + "slot3": "sdc", + "sdcActivity": "read" + }, + "part": "scene" + }, + { + "file": "layer-106.pdf", + "bounds": [ + 437.0, + 280.5, + 4.0, + 4.5 + ], + "when": { + "mpi": "on", + "slot3": "sdc", + "sdcActivity": "write" + }, + "part": "scene" + }, + { + "file": "layer-107.pdf", + "bounds": [ + 369.5, + 241.0, + 86.0, + 66.5 + ], + "when": { + "mpi": "on", + "slot2": "rom" + }, + "part": "scene" + }, + { + "file": "layer-108.pdf", + "bounds": [ + 369.5, + 225.5, + 86.0, + 82.0 + ], + "when": { + "mpi": "on", + "slot2": "orchestra" + }, + "part": "scene" + }, + { + "file": "layer-109.pdf", + "bounds": [ + 369.5, + 225.5, + 86.0, + 82.0 + ], + "when": { + "mpi": "on", + "slot2": "speech" + }, + "part": "scene" + }, + { + "file": "layer-110.pdf", + "bounds": [ + 369.5, + 225.5, + 86.0, + 82.0 + ], + "when": { + "mpi": "on", + "slot2": "floppy" + }, + "part": "scene" + }, + { + "file": "layer-111.pdf", + "bounds": [ + 369.5, + 225.5, + 86.0, + 82.0 + ], + "when": { + "mpi": "on", + "slot2": "hard" + }, + "part": "scene" + }, + { + "file": "layer-112.pdf", + "bounds": [ + 369.5, + 234.0, + 86.5, + 74.0 + ], + "when": { + "mpi": "on", + "slot2": "sdc" + }, + "part": "scene" + }, + { + "file": "layer-113.pdf", + "bounds": [ + 444.5, + 297.5, + 4.5, + 4.5 + ], + "when": { + "mpi": "on", + "slot2": "sdc", + "sdcActivity": "empty" + }, + "part": "scene" + }, + { + "file": "layer-114.pdf", + "bounds": [ + 444.5, + 297.5, + 4.5, + 4.5 + ], + "when": { + "mpi": "on", + "slot2": "sdc", + "sdcActivity": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-115.pdf", + "bounds": [ + 444.5, + 297.5, + 4.5, + 4.5 + ], + "when": { + "mpi": "on", + "slot2": "sdc", + "sdcActivity": "read" + }, + "part": "scene" + }, + { + "file": "layer-116.pdf", + "bounds": [ + 444.5, + 297.5, + 4.5, + 4.5 + ], + "when": { + "mpi": "on", + "slot2": "sdc", + "sdcActivity": "write" + }, + "part": "scene" + }, + { + "file": "layer-117.pdf", + "bounds": [ + 375.5, + 256.5, + 88.5, + 69.0 + ], + "when": { + "mpi": "on", + "slot1": "rom" + }, + "part": "scene" + }, + { + "file": "layer-118.pdf", + "bounds": [ + 375.5, + 240.5, + 88.5, + 85.0 + ], + "when": { + "mpi": "on", + "slot1": "orchestra" + }, + "part": "scene" + }, + { + "file": "layer-119.pdf", + "bounds": [ + 375.5, + 240.5, + 88.5, + 85.0 + ], + "when": { + "mpi": "on", + "slot1": "speech" + }, + "part": "scene" + }, + { + "file": "layer-120.pdf", + "bounds": [ + 375.5, + 240.5, + 88.5, + 85.0 + ], + "when": { + "mpi": "on", + "slot1": "floppy" + }, + "part": "scene" + }, + { + "file": "layer-121.pdf", + "bounds": [ + 375.5, + 240.5, + 88.5, + 85.0 + ], + "when": { + "mpi": "on", + "slot1": "hard" + }, + "part": "scene" + }, + { + "file": "layer-122.pdf", + "bounds": [ + 375.5, + 249.5, + 88.5, + 76.0 + ], + "when": { + "mpi": "on", + "slot1": "sdc" + }, + "part": "scene" + }, + { + "file": "layer-123.pdf", + "bounds": [ + 453.0, + 315.5, + 4.5, + 4.5 + ], + "when": { + "mpi": "on", + "slot1": "sdc", + "sdcActivity": "empty" + }, + "part": "scene" + }, + { + "file": "layer-124.pdf", + "bounds": [ + 453.0, + 315.5, + 4.5, + 4.5 + ], + "when": { + "mpi": "on", + "slot1": "sdc", + "sdcActivity": "loaded" + }, + "part": "scene" + }, + { + "file": "layer-125.pdf", + "bounds": [ + 453.0, + 315.5, + 4.5, + 4.5 + ], + "when": { + "mpi": "on", + "slot1": "sdc", + "sdcActivity": "read" + }, + "part": "scene" + }, + { + "file": "layer-126.pdf", + "bounds": [ + 453.0, + 315.5, + 4.5, + 4.5 + ], + "when": { + "mpi": "on", + "slot1": "sdc", + "sdcActivity": "write" + }, + "part": "scene" + }, + { + "file": "layer-127.pdf", + "bounds": [ + 53.5, + 9.5, + 274.0, + 244.5 + ], + "when": {}, + "part": "monitor" + }, + { + "file": "layer-128.pdf", + "bounds": [ + 11.5, + 255.0, + 357.0, + 190.0 + ], + "when": {}, + "part": "scene" + }, + { + "file": "layer-129.pdf", + "bounds": [ + 134.0, + 287.0, + 112.5, + 9.0 + ], + "when": {}, + "part": "scene" + }, + { + "file": "layer-130.pdf", + "bounds": [ + 209.5, + 288.5, + 17.0, + 3.0 + ], + "when": { + "ram": "128kb" + }, + "part": "scene" + }, + { + "file": "layer-131.pdf", + "bounds": [ + 209.0, + 288.5, + 17.5, + 3.0 + ], + "when": { + "ram": "512kb" + }, + "part": "scene" + }, + { + "file": "layer-132.pdf", + "bounds": [ + 211.5, + 288.5, + 12.5, + 3.0 + ], + "when": { + "ram": "2mb" + }, + "part": "scene" + }, + { + "file": "layer-133.pdf", + "bounds": [ + 211.5, + 288.5, + 12.5, + 3.0 + ], + "when": { + "ram": "8mb" + }, + "part": "scene" + }, + { + "file": "layer-134.pdf", + "bounds": [ + 193.5, + 291.0, + 48.5, + 3.0 + ], + "when": {}, + "part": "scene" + }, + { + "file": "layer-135.pdf", + "bounds": [ + 54.5, + 330.0, + 271.5, + 74.0 + ], + "when": {}, + "part": "scene" + }, + { + "file": "layer-136.pdf", + "bounds": [ + 306.5, + 285.0, + 20.5, + 13.0 + ], + "when": { + "cpu": "6309" + }, + "part": "scene" + }, + { + "file": "layer-137.pdf", + "bounds": [ + 306.5, + 285.0, + 20.5, + 13.0 + ], + "when": { + "cpu": "6809" + }, + "part": "scene" + }, + { + "file": "layer-138.pdf", + "bounds": [ + -116.5, + 79.5, + 164.5, + 110.5 + ], + "when": { + "scene": "on" + }, + "part": "scene" + }, + { + "file": "layer-139.pdf", + "bounds": [ + -75.0, + 124.0, + 42.0, + 9.5 + ], + "when": { + "scene": "on", + "printerPaper": "printed" + }, + "part": "scene" + }, + { + "file": "layer-140.pdf", + "bounds": [ + 18.0, + 140.5, + 3.5, + 3.0 + ], + "when": { + "scene": "on", + "printerPower": "off" + }, + "part": "scene" + }, + { + "file": "layer-141.pdf", + "bounds": [ + 18.0, + 140.5, + 3.5, + 3.0 + ], + "when": { + "scene": "on", + "printerPower": "on" + }, + "part": "scene" + } +] diff --git a/platforms/macos/Resources/Hardware/manual-help.pdf b/platforms/macos/Resources/Hardware/manual-help.pdf new file mode 100644 index 0000000..453f25b Binary files /dev/null and b/platforms/macos/Resources/Hardware/manual-help.pdf differ diff --git a/platforms/macos/Resources/Hardware/motorola.pdf b/platforms/macos/Resources/Hardware/motorola.pdf new file mode 100644 index 0000000..da15b68 Binary files /dev/null and b/platforms/macos/Resources/Hardware/motorola.pdf differ diff --git a/platforms/macos/Resources/Hardware/mpi.pdf b/platforms/macos/Resources/Hardware/mpi.pdf new file mode 100644 index 0000000..a7cf196 Binary files /dev/null and b/platforms/macos/Resources/Hardware/mpi.pdf differ diff --git a/platforms/macos/Resources/Hardware/printer.pdf b/platforms/macos/Resources/Hardware/printer.pdf new file mode 100644 index 0000000..15538e4 Binary files /dev/null and b/platforms/macos/Resources/Hardware/printer.pdf differ diff --git a/platforms/macos/Resources/Hardware/software-library-shelf.png b/platforms/macos/Resources/Hardware/software-library-shelf.png new file mode 100644 index 0000000..0b9473b Binary files /dev/null and b/platforms/macos/Resources/Hardware/software-library-shelf.png differ diff --git a/platforms/macos/Resources/RuntimeTemplates.json b/platforms/macos/Resources/RuntimeTemplates.json new file mode 100644 index 0000000..fdbe9c3 --- /dev/null +++ b/platforms/macos/Resources/RuntimeTemplates.json @@ -0,0 +1,11 @@ +{ + "schemaVersion": 1, + "profiles": { + "normal": { + "PROJECT_SETUP_PREAMBLE.txt": "examples/vibe-coding-with-chatgpt/PROJECT_SETUP_PREAMBLE.txt" + }, + "source": { + "PROJECT_SETUP_PREAMBLE.txt": "platforms/macos/Resources/SourceProjectSetupPrompt.txt" + } + } +} diff --git a/platforms/macos/Resources/SourceProjectSetupPrompt.txt b/platforms/macos/Resources/SourceProjectSetupPrompt.txt new file mode 100644 index 0000000..d2845cb --- /dev/null +++ b/platforms/macos/Resources/SourceProjectSetupPrompt.txt @@ -0,0 +1,2 @@ +Work with the selected VCC Plus project and its installed development tools. +Read the project's source and build configuration before changing it. Preserve the user's documents and media. Use the connection's read-only inspection and BASIC/Assembly lookup tools to understand current state. Run a build or disposable playtest only within the connection's granted capabilities. Verify actual tool discovery and successful requests separately. Report what was checked and any unavailable evidence honestly. The source content profile includes reference lookup rather than the full manual collection. Do not bypass a missing capability through private files or guest-state injection. diff --git a/platforms/macos/Resources/StarterMedia/Blank Disk.dsk b/platforms/macos/Resources/StarterMedia/Blank Disk.dsk new file mode 100644 index 0000000..563ea1b --- /dev/null +++ b/platforms/macos/Resources/StarterMedia/Blank Disk.dsk @@ -0,0 +1 @@ +ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ \ No newline at end of file diff --git a/platforms/macos/Resources/StarterMedia/Blank OS9 Header.bin b/platforms/macos/Resources/StarterMedia/Blank OS9 Header.bin new file mode 100644 index 0000000..2698092 Binary files /dev/null and b/platforms/macos/Resources/StarterMedia/Blank OS9 Header.bin differ diff --git a/platforms/macos/Resources/StarterMedia/Hello Hard Disk.dsk b/platforms/macos/Resources/StarterMedia/Hello Hard Disk.dsk new file mode 100644 index 0000000..507ac1c --- /dev/null +++ b/platforms/macos/Resources/StarterMedia/Hello Hard Disk.dsk @@ -0,0 +1,2 @@ +ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ& +‚ EARTH OR MARS - COCO 3&)â 40:ž&M‡ "What planet do you live on?"&^(‡ "1) Earth"&n2‡ "2) Mars"&x ArchiveDocument { + let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() + return ArchiveDocument(id: digest, title: name, collection: "Books", + sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Documents/Books/" + name)!, + memberPath: member, pageCount: 1, deliveryURL: nil, deliveryBytes: nil, + format: format, sourceBytes: Int64(bytes.count), memberRange: range) + } + + private func waitFor(_ condition: () -> Bool) async throws { + let limit = ContinuousClock.now + .seconds(5) + while !condition() { + guard ContinuousClock.now < limit else { throw ReaderTimeout() } + try await Task.sleep(for: .milliseconds(10)) + } + } + + private struct ReaderTimeout: Error {} + + func testSelectingPDFPagesReusesTheVerifiedDocumentAndOpensTheCitedPage() async throws { + let pdf = PDFDocument() + for color in [NSColor.white, .gray] { + let image = NSImage(size: NSSize(width: 240, height: 320), flipped: false) { rect in + color.setFill() + rect.fill() + return true + } + pdf.insert(try XCTUnwrap(PDFPage(image: image)), at: pdf.pageCount) + } + let bytes = try XCTUnwrap(pdf.dataRepresentation()) + let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() + let source = URL(string: "https://colorcomputerarchive.com/repo/Documents/Books/Pages.pdf")! + let delivery = URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Books/Pages.pdf")! + let item = ArchiveDocument(id: digest, title: "Pages", collection: "Books", sourceURL: source, + memberPath: nil, pageCount: 2, deliveryURL: delivery, deliveryBytes: Int64(bytes.count)) + try bytes.write(to: directory.appendingPathComponent(digest + ".pdf")) + let model = ArchiveReaderModel(remembersPage: false, cache: cache) + defer { model.reset() } + model.view.frame = NSRect(x: 0, y: 0, width: 300, height: 300) + model.open(item, page: 1) + model.open(item, page: 2) + try await waitFor { model.progress == nil } + let rendered = try XCTUnwrap(model.document) + XCTAssertTrue(model.view.document === rendered) + XCTAssertEqual(rendered.pageCount, 2) + XCTAssertEqual(model.page, 2) + XCTAssertTrue(model.view.currentPage === rendered.page(at: 1)) + model.open(item, page: 1) + XCTAssertTrue(model.document === rendered) + XCTAssertNil(model.progress) + XCTAssertEqual(model.page, 1) + XCTAssertTrue(model.view.currentPage === rendered.page(at: 0)) + } + + func testSelectingTextThenCachedImageReplacesThePreview() async throws { + let model = ArchiveReaderModel(remembersPage: false, cache: cache) + defer { model.reset() } + let text = record("Notes.txt", format: "text", bytes: ArchiveFixtureTransport.listing) + model.open(text, page: 1) + try await waitFor { model.progress == nil } + XCTAssertNil(model.error) + guard case .text(let contents) = model.preview else { return XCTFail("Expected the selected text in the reader") } + XCTAssertEqual(contents, "A tide chart for the CoCo.\n") + + // The transport has no image response. A verified retained copy must open offline. + let png = Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAAAAAC4HznGAAAAEElEQVR4nGNQcEhgaFhzBAAH5AKxE0HCuwAAAABJRU5ErkJggg==")! + let image = record("Map.png", format: "image", bytes: png) + try png.write(to: directory.appendingPathComponent(image.id + ".png")) + model.open(image, page: 1) + XCTAssertNil(model.preview, "Selection changes must clear the previous document immediately") + try await waitFor { model.progress == nil } + XCTAssertNil(model.error) + guard case .image(let displayed) = model.preview else { return XCTFail("The cached image was not rendered") } + XCTAssertEqual(displayed.width, 3) + XCTAssertEqual(displayed.height, 2) + XCTAssertEqual(model.referenceID, image.id) + XCTAssertNil(model.document) + model.open(image, page: 2) + try await waitFor { model.progress == nil } + XCTAssertNil(model.preview, "A missing image frame must not be silently replaced by frame one") + XCTAssertNotNil(model.error) + + model.reset() + XCTAssertNil(model.preview) + XCTAssertNil(model.referenceID) + } + + func testTextReaderPreservesLegacyEncodingsAndRemovesFloppyPadding() throws { + let url = directory.appendingPathComponent("Letter.txt") + let accented = "Café\n£5" + let utf8 = Data([0xef, 0xbb, 0xbf]) + Data("Café\r£5".utf8) + let utf16 = Data([0xff, 0xfe]) + (try XCTUnwrap("Café\r£5".data(using: .utf16LittleEndian))) + let legacy = Data([0x43, 0x61, 0x66, 0xe9, 0x0d, 0x0a, 0xa3, 0x35, 0x1a, 0x00]) + for bytes in [utf8, utf16, legacy] { + try bytes.write(to: url) + guard case .text(let contents) = try ArchiveInlineContent.loadText(at: url) else { + return XCTFail("Expected a selectable text preview") + } + XCTAssertEqual(contents, accented) + } + try Data([0x93, 0x52, 0x55, 0x4e, 0x94]).write(to: url) + guard case .text(let instruction) = try ArchiveInlineContent.loadText(at: url) else { + return XCTFail("Expected Windows-1252 walkthrough text") + } + XCTAssertEqual(instruction, "“RUNâ€�") + } + + func testRapidSelectionCancelsAnUnfinishedTransfer() async throws { + let first = record("Hold.txt", format: "text", bytes: Data("Slow response".utf8)) + let next = record("Notes.txt", format: "text", bytes: ArchiveFixtureTransport.listing) + let model = ArchiveReaderModel(remembersPage: false, cache: cache) + defer { model.reset() } + model.open(first, page: 1) + try await waitFor { + if case .downloading = model.progress { return true } + return false + } + model.open(next, page: 1) + try await waitFor { model.progress == nil } + XCTAssertEqual(model.referenceID, next.id) + XCTAssertNil(model.error) + guard case .text(let contents) = model.preview else { return XCTFail("The next selection did not load") } + XCTAssertEqual(contents, "A tide chart for the CoCo.\n") + XCTAssertFalse(FileManager.default.fileExists(atPath: directory.appendingPathComponent(first.id + ".txt").path)) + } + + func testDownloadReportsBytesWhileTheRemainingContentIsStillPending() async throws { + let chunk = ArchiveFixtureTransport.listingChunk + let bytes = chunk + chunk + let item = record("Progress.txt", format: "text", bytes: bytes) + let receipt = try XCTUnwrap(ArchiveAssetReceipt(document: item)) + let total = Int64(bytes.count) + let advanced = XCTestExpectation(description: "Download reports a positive, incomplete byte count") + let complete = XCTestExpectation(description: "Download reports all expected bytes") + let download = Task { + try await cache.localCopy(receipt) { event in + guard case let .downloading(done, expected) = event, expected == total else { return } + if done > 0, done < total { advanced.fulfill() } + if done == total { complete.fulfill() } + } + } + defer { download.cancel() } + let first = await XCTWaiter.fulfillment(of: [advanced], timeout: 5) + XCTAssertEqual(first, .completed, "The download must advance while the second chunk is withheld") + NotificationCenter.default.post(name: ArchiveFixtureTransport.releaseSecondChunk, object: nil) + guard first == .completed else { return } + let local = try await download.value + XCTAssertEqual(try Data(contentsOf: local), bytes) + await fulfillment(of: [complete], timeout: 2) + } + + func testWorksheetCitationOpensTheSelectedSheetAndChangesSheetsInPlace() async throws { + let url = directory.appendingPathComponent("ArchiveLibrary.sqlite") + var db: OpaquePointer? + XCTAssertEqual(sqlite3_open(url.path, &db), SQLITE_OK) + defer { sqlite3_close(db) } + let digest = String(repeating: "a", count: 64) + let sql = """ + PRAGMA application_id=0x56434341; + PRAGMA user_version=2; + CREATE TABLE document(id INTEGER PRIMARY KEY,sha256 TEXT,title TEXT,collection TEXT,format TEXT,source_url TEXT,page_count INTEGER); + CREATE TABLE page(id INTEGER PRIMARY KEY,document_id INTEGER,page_number INTEGER,page_label TEXT,locator_kind TEXT,is_ocr INTEGER); + CREATE TABLE reader_section(page_id INTEGER PRIMARY KEY,text TEXT); + INSERT INTO document VALUES(1,'\(digest)','Ledger','Books','office-xls','https://colorcomputerarchive.com/repo/Documents/Books/Ledger.xls',2); + INSERT INTO page VALUES(1,1,1,'January','worksheet',0),(2,1,2,'February','worksheet',0); + INSERT INTO reader_section VALUES(1,'Parts' || char(9) || '3'),(2,'Disks' || char(9) || '8'); + """ + guard sqlite3_exec(db, sql, nil, nil, nil) == SQLITE_OK else { + return XCTFail(String(cString: sqlite3_errmsg(db))) + } + let catalog = ArchiveLibraryCatalog(url: url) + let citation = try await catalog.citation(id: "sha256:" + digest + ":worksheet:2") + let hit = try XCTUnwrap(citation) + XCTAssertNil(hit.page) + XCTAssertEqual(hit.locator, "February") + let model = ArchiveReaderModel(remembersPage: false, cache: cache, catalog: catalog) + defer { model.reset() } + model.open(hit.document, page: hit.locationNumber) + try await waitFor { model.progress == nil } + XCTAssertEqual(model.page, 2) + XCTAssertEqual(model.sectionLabel, "February") + guard case .worksheet(let february) = model.preview else { return XCTFail("Expected the cited worksheet") } + XCTAssertEqual(february, "Disks\t8") + model.open(hit.document, page: 1) + try await waitFor { model.progress == nil } + XCTAssertEqual(model.page, 1) + XCTAssertEqual(model.sectionLabel, "January") + guard case .worksheet(let january) = model.preview else { return XCTFail("Expected the first worksheet") } + XCTAssertEqual(january, "Parts\t3") + model.open(hit.document, page: 3) + try await waitFor { model.progress == nil } + XCTAssertNil(model.preview) + XCTAssertNotNil(model.error) + } + + func testZIPRangeAndWholeArchiveFallbackProduceTheVerifiedMember() async throws { + // The fixture archive has one raw-DEFLATE member, Tips/notes.txt, beginning at byte 44. + for name in ["Range.zip", "Whole.zip", "Shifted.zip", "Changed.zip"] { + let asset = record(name, format: "text", bytes: ArchiveFixtureTransport.listing, member: "Tips/notes.txt", + range: .init(offset: 44, compressedBytes: 30, method: 8, archiveBytes: 156)) + let receipt = try XCTUnwrap(ArchiveAssetReceipt(document: asset)) + if name == "Shifted.zip" || name == "Changed.zip" { + do { + _ = try await cache.localCopy(receipt) { _ in } + XCTFail("Accepted the incorrect response to " + name) + } catch { } + XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty) + } else { + let saved = try await cache.localCopy(receipt) { _ in } + XCTAssertEqual(try Data(contentsOf: saved), ArchiveFixtureTransport.listing) + try FileManager.default.removeItem(at: saved) + } + } + } +} + +private final class ArchiveFixtureTransport: URLProtocol { + static let listing = Data("A tide chart for the CoCo.\r\n".utf8) + static let listingChunk = Data(repeating: 65, count: 1024 * 1024) + static let releaseSecondChunk = Notification.Name("ArchiveReaderTests.releaseSecondChunk") + private var releaseObserver: NSObjectProtocol? + static let zip = Data(base64Encoded: "UEsDBBQAAAAIAAAAIVyuKpHqHgAAABwAAAAOAAAAVGlwcy9ub3Rlcy50eHRzVCjJTElVSM5ILCpRSMsvUijJSFVwznfO1+PlAgBQSwECFAMUAAAACAAAACFcriqR6h4AAAAcAAAADgAAAAAAAAAAAAAAgAEAAAAAVGlwcy9ub3Rlcy50eHRQSwUGAAAAAAEAAQA8AAAASgAAAAAA")! + + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + guard let url = request.url else { return } + var headers: [String: String] = [:] + var status = 200 + var payload = Data() + switch url.lastPathComponent { + case "Hold.txt": return // Intentionally pending until the user chooses another row. + case "Notes.txt": payload = Self.listing + case "Progress.txt": + let headers = ["Content-Length": String(2 * Self.listingChunk.count)] + let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: headers)! + releaseObserver = NotificationCenter.default.addObserver(forName: Self.releaseSecondChunk, object: nil, queue: nil) { [weak self] _ in + guard let self else { return } + self.client?.urlProtocol(self, didLoad: Self.listingChunk) + self.client?.urlProtocolDidFinishLoading(self) + } + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: Self.listingChunk) + return + case "Range.zip", "Whole.zip", "Shifted.zip", "Changed.zip": + guard request.value(forHTTPHeaderField: "Range") == "bytes=44-73" else { + client?.urlProtocol(self, didFailWithError: URLError(.badURL)) + return + } + if url.lastPathComponent == "Whole.zip" { + payload = Self.zip + } else { + status = 206 + payload = Self.zip.subdata(in: 44..<74) + headers["Content-Range"] = url.lastPathComponent == "Shifted.zip" ? "bytes 45-74/156" : "bytes 44-73/156" + // Valid DEFLATE with an altered first character and the original decoded length. + if url.lastPathComponent == "Changed.zip" { payload[0] ^= 0x10 } + } + default: + client?.urlProtocol(self, didFailWithError: URLError(.notConnectedToInternet)) + return + } + headers["Content-Length"] = String(payload.count) + let response = HTTPURLResponse(url: url, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: payload) + client?.urlProtocolDidFinishLoading(self) + } + override func stopLoading() { + if let releaseObserver { NotificationCenter.default.removeObserver(releaseObserver) } + } +} diff --git a/platforms/macos/Tests/AssemblyBuildServiceTests.swift b/platforms/macos/Tests/AssemblyBuildServiceTests.swift new file mode 100644 index 0000000..bd2a8c1 --- /dev/null +++ b/platforms/macos/Tests/AssemblyBuildServiceTests.swift @@ -0,0 +1,214 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class AssemblyBuildServiceTests: XCTestCase { + private var root: URL! + private var runtime: URL! + private var service: AssemblyBuildService { AssemblyBuildService(toolchain: runtime) } + private let first = """ + org $3f00 + start lda #$8f + sta $0400 + hold bra hold + end start + """ + + override func setUpWithError() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("Assembly tests " + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + runtime = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("LocalResources/ToolchainBundle") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: runtime.appendingPathComponent("bin/lwasm").path), + "Stage the bundled LWTools runtime for assembly workflow tests.") + } + + override func tearDownWithError() throws { + if let root { try? FileManager.default.removeItem(at: root) } + } + + private func write(_ text: String, _ path: String) throws { + let url = root.appendingPathComponent(path) + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: url) + } + + func testStarterImageSymbolLocationsDiagnosticsAndTargetOverride() async throws { + let result = try await service.build(.single(source: first)) + XCTAssertEqual(result.entry, 0x3f00) + XCTAssertEqual(result.ranges, [0x3f00...0x3f06]) + XCTAssertEqual(result.binaryData, Data([0,0,7,0x3f,0,0x86,0x8f,0xb7,4,0,0x20,0xfe,0xff,0,0,0x3f,0])) + XCTAssertEqual(result.instructions.map(\.line), [2,3,4]) + XCTAssertEqual(result.instructions.map(\.address), [0x3f00,0x3f02,0x3f05]) + XCTAssertTrue(result.symbols.contains("start EQU $3F00")) + let extended = first.replacingOccurrences(of: "lda #$8f", with: "ldw #$1234") + let hd = try await service.build(.single(source: extended, cpu: .hd6309)) + XCTAssertEqual(hd.instructions.first?.bytes, [0x10,0x86,0x12,0x34]) + for text in [extended, " pragma 6309\n" + extended] { + do { + _ = try await service.build(.single(source: text)) + XCTFail("MC6809 target accepted an HD6309 operation") + } catch let error as AssemblyBuildFailure { + XCTAssertEqual(error.diagnostics.first?.path, "main.asm") + XCTAssertEqual(error.diagnostics.first?.line, 2) + } + } + } + + func testPhysicalIncludesWithCollidingNamesOverlaysAndMacroExpansion() async throws { + let name = "same_long_include_name.inc" + try write(" org $3f00\n include 'a/" + name + "'\n include 'b/" + name + "'\n end $3f00", "main.asm") + try write(" include 'defs.inc'\n lda #one\n fcb $86,1\n", "a/" + name) + try write("one equ 1", "defs.inc") + try write(" ldb #2\n", "b/" + name) + try write("unrelated", "other.txt") + let main = root.appendingPathComponent("main.asm") + let saved = try AssemblyProjectSnapshot.readSource(at: main) + XCTAssertEqual(saved.files.count, 4) + let draft = try AssemblyProjectSnapshot.readSource(at: main, overlays: ["b/" + name: " ldb #3"]) + XCTAssertNotEqual(saved, draft) + let result = try await service.build(draft) + XCTAssertEqual(result.instructions.map(\.path), ["a/" + name, "b/" + name]) + XCTAssertEqual(result.instructions.map(\.bytes), [[0x86,1], [0xc6,3]]) + XCTAssertEqual(result.instructions.map(\.address), [0x3f00,0x3f04]) + let macros = " org $3f00\nload macro\n lda #1\n endm\n load\n fcb $86,1\nhold bra hold\n end $3f00" + let expanded = try await service.build(.single(source: macros)) + XCTAssertEqual(expanded.instructions.map(\.line), [7]) + + try write(" nop", "twice.inc") + let repeated = " org $3f00\n include 'twice.inc'\n include 'twice.inc'\n end $3f00" + let twice = try await service.build(AssemblyProjectSnapshot.readSource(at: main, overlays: ["main.asm": repeated])) + XCTAssertTrue(twice.instructions.isEmpty, "A single include line expanded at two addresses needs disambiguation.") + } + + func testLinkedSubroutineUsesFinalPlacementAndRelocatedOperands() async throws { + try write(#"{"main":"main.asm","modules":["lib/sub.asm"],"linkScript":"layout.link"}"#, AssemblyProjectSnapshot.configurationFilename) + try write(" section code\n export start\n import sub\nstart jsr sub\nhold bra hold\n endsection", "main.asm") + try write(" section code\n export sub\n include 'body.inc'\n endsection", "lib/sub.asm") + try write("sub incb\n rts", "lib/body.inc") + try write("section code load 3f00\nentry start\n", "layout.link") + let result = try await service.build(AssemblyProjectSnapshot.read(directory: root)) + XCTAssertEqual(result.entry, 0x3f00) + XCTAssertEqual(result.instructions.first?.bytes, [0xbd,0x3f,0x05]) + XCTAssertEqual(result.instructions.filter { $0.path == "lib/body.inc" }.map(\.address), [0x3f05,0x3f06]) + XCTAssertTrue(result.symbols.contains("sub (../out/module1.o) = 3F05")) + } + + func testAbsoluteAndBinaryIncludesCannotReadOutsideSnapshot() async throws { + try write(" nop", "outside.asm") + for directive in ["include", "includebin"] { + let line = " " + directive + " \"" + root.appendingPathComponent("outside.asm").path + "\"" + let source = " org $3f00\n" + line + "\n end $3f00" + do { + _ = try await service.build(.single(source: source)) + XCTFail("External include succeeded.") + } catch { XCTAssertTrue(error.localizedDescription.contains("leaves the project snapshot"), error.localizedDescription) } + } + } + + func testCustomMakeUsesOverlayAndDiscardsPriorProduct() async throws { + try write(first, "main.asm") + try write("stale", "program.bin") + let makefile = "all:\n\t$(LWASM) $(ASFLAGS) --decb -o program.bin main.asm\n" + try write(makefile, "Custom.mk") + try write(#"{"makefile":"Custom.mk","target":"all","binary":"program.bin"}"#, AssemblyProjectSnapshot.configurationFilename) + let snap = try AssemblyProjectSnapshot.read(directory: root, overlays: ["main.asm": first.replacingOccurrences(of: "#$8f", with: "#$8a")]) + let result = try await service.build(snap) + XCTAssertEqual(result.binaryData[6], 0x8a) + XCTAssertTrue(result.instructions.isEmpty) + XCTAssertEqual(try String(contentsOf: root.appendingPathComponent("program.bin")), "stale") + XCTAssertEqual(try String(contentsOf: root.appendingPathComponent("Custom.mk")), makefile) + } + + func testCancellingCustomRecipeLeavesNextBuildIndependent() async throws { + try write(first, "main.asm") + let marker = root.appendingPathComponent("started") + try write("all:\n\t@touch '" + marker.path + "'\n\t@sleep 60\n", "Makefile") + try write(#"{"makefile":"Makefile","binary":"program.bin"}"#, AssemblyProjectSnapshot.configurationFilename) + let project = try AssemblyProjectSnapshot.read(directory: root) + let buildService = service + let build = Task { try await buildService.build(project) } + defer { build.cancel() } + for _ in 0..<200 { + if FileManager.default.fileExists(atPath: marker.path) { break } + try await Task.sleep(nanoseconds: 20_000_000) + } + XCTAssertTrue(FileManager.default.fileExists(atPath: marker.path)) + build.cancel() + do { + _ = try await build.value + XCTFail("A cancelled recipe returned an artifact.") + } catch is CancellationError {} + let fresh = try await buildService.build(.single(source: first)) + XCTAssertEqual(fresh.instructions.count, 3) + XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("program.bin").path)) + } + + func testDiskExportContainsExactMachineLanguageEntry() async throws { + let artifact = try await service.build(.single(source: first)) + let disk = try await service.diskImage(for: artifact, name: "first") + XCTAssertEqual(disk.count, 35 * 18 * 256) + let directory = 17 * 18 * 256 + 2 * 256 + XCTAssertEqual(String(decoding: disk[directory..<(directory + 11)], as: UTF8.self), "FIRST BIN") + XCTAssertEqual(disk[directory + 11], 2) // Machine language + XCTAssertEqual(disk[directory + 12], 0) // Binary + let granule = Int(disk[directory + 13]), offset = (granule + (granule >= 34 ? 2 : 0)) * 9 * 256 + let size = Int(disk[directory + 14]) * 256 + Int(disk[directory + 15]) + XCTAssertEqual(size, artifact.binaryData.count) + XCTAssertEqual(disk.subdata(in: offset..<(offset + size)), artifact.binaryData) + } + + @MainActor func testDiskBASICLoadMAndExecOnBothProcessors() async throws { + let roms = runtime.deletingLastPathComponent().appendingPathComponent("ROMs") + let system = roms.appendingPathComponent("coco3.rom"), diskROM = roms.appendingPathComponent("disk11.rom") + try XCTSkipUnless(FileManager.default.fileExists(atPath: system.path) && FileManager.default.fileExists(atPath: diskROM.path), + "Stage the licensed CoCo 3 and Disk BASIC ROMs to execute the exported disk.") + let rom = try Data(contentsOf: system), dos = try Data(contentsOf: diskROM) + let build = try await service.build(.single(source: first)) + let disk = try await service.diskImage(for: build, name: "FIRST") + func command(_ body: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { c in body { c.resume(returning: $0) } } + } + for cpu in [false, true] { + let controller = VCCMachineController() + do { + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command { controller.loadDiskROM(dos, name: "Disk BASIC", completion: $0) } + _ = await command { controller.configureCartridges([2,0,0,0,2], roms: Array(repeating: Data(), count: 5), + names: Array(repeating: "", count: 5), multiPak: true, physicalSlot: 4, completion: $0) } + _ = await command { controller.mountDisk(disk, drive: 0, name: "FIRST.dsk", readOnly: true, completion: $0) } + _ = await command { controller.loadROM(rom, use6309: cpu, completion: $0) } + _ = await command(controller.resume) + var ready = false + for _ in 0..<250 { + let text: String? = await withCheckedContinuation { c in controller.copyScreenText { text, _ in c.resume(returning: text) } } + if text?.contains("OK") == true { ready = true; break } + try await Task.sleep(nanoseconds: 40_000_000) + } + XCTAssertTrue(ready) + let boot = await command(controller.snapshot) + for _ in 0..<100 { + if await command(controller.snapshot).frames >= boot.frames + 18 { break } + try await Task.sleep(nanoseconds: 20_000_000) + } + let paste = try CocoPaste("LOADM\"FIRST\":EXEC\n", mode: .text) + _ = await command { controller.pasteChords(paste.chords.map { NSNumber(value: $0) }, completion: $0) } + var finished = false + for _ in 0..<300 { + if await command(controller.snapshot).programCounter == 0x3f05 { finished = true; break } + try await Task.sleep(nanoseconds: 40_000_000) + } + XCTAssertTrue(finished, "The exported program should reach its hold loop after LOADM/EXEC.") + _ = await command(controller.pause) + let cell: VCCDebugMemoryCapture = await withCheckedContinuation { c in + controller.debuggerMemory(address: 0x400, count: 1, physical: false, logicalAddress: 0x400, + os9: false, decode: false) { c.resume(returning: $0) } + } + XCTAssertEqual(cell.bytes.first, 0x8f) + _ = await command(controller.shutdown) + } catch { + _ = await command(controller.shutdown) + throw error + } + } + } +} diff --git a/platforms/macos/Tests/AssemblyDevelopmentTests.swift b/platforms/macos/Tests/AssemblyDevelopmentTests.swift new file mode 100644 index 0000000..e07649b --- /dev/null +++ b/platforms/macos/Tests/AssemblyDevelopmentTests.swift @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest +import AppKit + +final class AssemblyDevelopmentTests: XCTestCase { + override func setUp() async throws { + try await super.setUp() + // InputHub reads the host application's activation state. Initialize + // AppKit explicitly so this class also runs without earlier suites. + await MainActor.run { _ = NSApplication.shared } + } + + private func temporaryFolder() throws -> URL { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) + return root + } + + #if DEBUG + @MainActor func testCompiledInputEndsAtBASICReturnAndPinsMediaIdentity() async throws { + let roms = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("LocalResources/ROMs") + try XCTSkipUnless(["coco3.rom", "disk11.rom"].allSatisfy { FileManager.default.fileExists(atPath: roms.appendingPathComponent($0).path) }, + "Requires the private CoCo BASIC ROMs.") + for enhanced in [false, true] { + let dir = try temporaryFolder(), suite = "CompiledRun." + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: dir) } + let controller = VCCMachineController() + let machine = MachineModel(diskStore: .init(url: dir.appendingPathComponent("disks.json")), + controller: controller, displayDefaults: defaults, + inputStore: .init(url: dir.appendingPathComponent("input.json"))) + let end = ContinuousClock.now.advanced(by: .seconds(5)) + while machine.busy && ContinuousClock.now < end { try await Task.sleep(for: .milliseconds(20)) } + try await MCPBASICRun.bootFixture(machine, romDirectory: roms, use6309: enhanced) + // Poll the real ROM keyboard, echo a key, then RTS into genuine BASIC direct mode. + let romCalls = Data([0,0,12,0x3f,0,0xad,0x9f,0xa0,0,0x4d,0x27,0xf9,0xad,0x9f,0xa0,2,0x39,0xff,0,0,0x3f,0]) + let disk = Data(repeating: 0xff, count: 35 * 18 * 256) + func mount(_ image: Data) async -> VCCMachineSnapshot { + await withCheckedContinuation { c in controller.mountDisk(image, drive: 1, name: "Same.dsk", readOnly: true) { c.resume(returning: $0) } } + } + func launch(_ image: Data) async throws -> MCPCompiledRunIO { + let before = await machine.mcpMachineSnapshot() + let launched: VCCMachineSnapshot? = await withCheckedContinuation { c in + machine.launchAssembly(image, breakpoints: [], guards: [:], pauseAtEntry: false, requires6309: enhanced, + expectedGeneration: before.generation, expectedRevision: before.debuggerProgramRevision, + expectedMapping: before.debuggerMappingFingerprint, shared: true) { c.resume(returning: $0) } + } + let state = try XCTUnwrap(launched) + XCTAssertNil(state.errorMessage) + return MCPCompiledRunIO(machine: machine, runID: "quiz", expected: state, assembly: true) + } + let media = await mount(disk) + XCTAssertNil(media.errorMessage) + let io = try await launch(romCalls) + let observed = try await io.reply("read_screen_text", arguments: ["run_id":"quiz"]) + XCTAssertNotNil(observed["text"] as? String) + let key = ["run_id":"quiz", "keys":"1", "request_id":"one"] + let accepted = try await io.reply("send_keys", arguments: key) + XCTAssertEqual(accepted["accepted"] as? Bool, true) + var now = await machine.mcpMachineSnapshot() + for _ in 0..<100 where !now.assistantCompiledReturned { + try await Task.sleep(for: .milliseconds(25)) + now = await machine.mcpMachineSnapshot() + } + XCTAssertTrue(now.assistantCompiledReturned) + XCTAssertEqual(now.pasteRemaining, 0) + for (tool, args) in [("read_screen_text", ["run_id":"quiz"]), ("send_keys", key)] { + do { _ = try await io.reply(tool, arguments: args); XCTFail("Live access survived RTS") } + catch { XCTAssertEqual(error.localizedDescription, "run_finished") } + } + io.invalidate() + // A program can print and return between any two client polls. Preserve the + // terminal screen at RTS, even if the operator later uses the BASIC prompt. + let printX = Data([0,0,7,0x3f,0,0x86,0x58,0xad,0x9f,0xa0,2,0x39,0xff,0,0,0x3f,0]) + try await machine.waitForMCPFixturePrompt() + let quick = try await launch(printX) + for _ in 0..<100 { + if await machine.mcpMachineSnapshot().assistantCompiledReturned { break } + try await Task.sleep(for: .milliseconds(25)) + } + let captured = try await quick.finalScreenText() + XCTAssertTrue(captured?.trimmingCharacters(in: .whitespacesAndNewlines).hasSuffix("X") == true, captured ?? "(unavailable)") + try await machine.waitForMCPFixturePrompt() + let type = try CocoPaste("CLS:PRINT 4242\n", mode: .text).chords.map { NSNumber(value: $0) } + let queued = await controller.pasteChords(type) + XCTAssertNil(queued.errorMessage) + for _ in 0..<200 { + if await machine.mcpMachineSnapshot().pasteRemaining == 0 { break } + try await Task.sleep(for: .milliseconds(15)) + } + let later = try await quick.finalScreenText() + XCTAssertEqual(later, captured) + let (actual, _) = await machine.reviewedCOutput() + XCTAssertTrue(actual?.contains("4242") == true) + quick.invalidate() + let next = try await launch(romCalls) + var otherDisk = disk; otherDisk[0] = 0 + let replaced = await mount(otherDisk) + XCTAssertNil(replaced.errorMessage) + do { _ = try await next.reply("read_screen_text", arguments: ["run_id":"quiz"]); XCTFail("Accepted a replacement with the original name") } + catch { XCTAssertEqual(error.localizedDescription, "media_changed") } + next.invalidate() + do { _ = try await next.reply("send_keys", arguments: key); XCTFail("Accepted a revoked lease") } + catch { XCTAssertEqual(error.localizedDescription, "stale_run") } + await withCheckedContinuation { c in machine.shutdown { c.resume() } } + } + } + #endif + + @MainActor func testReviewedAssemblyFilesApplyAndUndoAcrossUnopenedInclude() async throws { + let dir = try temporaryFolder(), project = dir.appendingPathComponent("Assembly") + let suite = "ReviewedAssembly." + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: dir) } + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: false) + let original = " include \"value.inc\"\nstart lda #VALUE\n rts\n" + try Data(original.utf8).write(to: project.appendingPathComponent("main.asm")) + try Data("VALUE equ 1\n".utf8).write(to: project.appendingPathComponent("value.inc")) + let machine = MachineModel(diskStore: .init(url: dir.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: dir.appendingPathComponent("input.json"))) + let model = AssemblyDevelopmentModel(machine: machine, recoveryURL: dir.appendingPathComponent("drafts.json")) + model.open(project, folder: true) + for _ in 0..<200 where !model.document.isProject { try await Task.sleep(for: .milliseconds(10)) } + let draft = original + "* unsaved native text\n" + model.edit(draft) + let input = try model.document.snapshot() + let files = Set(input.files.keys) + let rows = [["path": "value.inc", "source": "VALUE equ 21\n"], + ["path": "main.asm", "source": " include \"value.inc\"\nstart ldb #VALUE\n rts ; café\n"]] + let edits = try MCPAssembly.projectEdits(rows, snapshot: input, shared: files) + XCTAssertEqual(edits.map(\.path), ["main.asm", "value.inc"]) + let staleLast = AssemblyProjectEdit(path: "value.inc", before: "VALUE equ 2\n", after: "VALUE equ 42\n") + let epoch = model.sourceRevision + XCTAssertThrowsError(try model.replaceReviewedFiles([edits[0], staleLast], snapshot: input)) + XCTAssertEqual(model.sourceRevision, epoch) + XCTAssertEqual(model.document.buffers.count, 1) + XCTAssertEqual(model.buffer.text, draft) + let removed = try model.replaceReviewedFiles(edits, snapshot: input) + XCTAssertEqual(model.document.buffers.filter(\.dirty).count, 2) + XCTAssertEqual(model.buffer.text, rows[1]["source"]) + XCTAssertEqual(try String(contentsOf: project.appendingPathComponent("value.inc"), encoding: .utf8), "VALUE equ 1\n") + let applied = try model.document.snapshot() + _ = try model.replaceReviewedFiles(edits, snapshot: applied, undo: true, restoreStops: removed) + XCTAssertEqual(try model.document.snapshot(), input) + XCTAssertEqual(model.buffer.text, draft) + XCTAssertEqual(model.document.buffers.filter(\.dirty).map(\.path), ["main.asm"]) + XCTAssertEqual(try String(contentsOf: project.appendingPathComponent("main.asm"), encoding: .utf8), original) + + XCTAssertThrowsError(try MCPAssembly.projectEdits([rows[0], rows[0]], snapshot: input, shared: files)) + XCTAssertThrowsError(try MCPAssembly.projectEdits([["path": "main.asm", "source": draft]], snapshot: input, shared: files)) + XCTAssertThrowsError(try MCPAssembly.projectEdits([["path": "../outside.asm", "source": "rts"]], snapshot: input, shared: files)) + XCTAssertThrowsError(try MCPAssembly.projectEdits([["path": "main.asm", "source": "\0"]], snapshot: input, shared: files)) + XCTAssertThrowsError(try MCPAssembly.projectEdits([["path": "main.asm", "source": "a", "unrecognized": "b"]], snapshot: input, shared: files)) + let limit = String(repeating: "é", count: 8192) + XCTAssertNoThrow(try MCPAssembly.projectEdits([["path": "main.asm", "source": limit]], snapshot: input, shared: files)) + XCTAssertThrowsError(try MCPAssembly.projectEdits([["path": "main.asm", "source": limit], rows[0]], snapshot: input, shared: files)) + } + + @MainActor func testSwitchingDocumentsDuringBuildRetainsDraftAndRejectsLateResult() async throws { + let dir = try temporaryFolder() + let suite = "AssemblyWorkspaceTests." + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: dir) } + let tools = dir.appendingPathComponent("Toolchain") + let bin = tools.appendingPathComponent("bin"), assembler = bin.appendingPathComponent("lwasm") + try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true) + let script = "#!/bin/sh\n: > \"$VCC_TOOLCHAIN/started\"\nexec /bin/sleep 10\n" + try Data(script.utf8).write(to: assembler) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: assembler.path) + let machine = MachineModel(diskStore: .init(url: dir.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: dir.appendingPathComponent("input.json"))) + let recovery = dir.appendingPathComponent("Drafts.json") + let model = AssemblyDevelopmentModel(machine: machine, service: .init(toolchain: tools), recoveryURL: recovery) + let original = model.activeID + model.edit("; My unsaved revision\n" + model.buffer.text) + model.moveCursor(12) + model.perform(.assemble) + let marker = tools.appendingPathComponent("started") + for _ in 0..<300 where !FileManager.default.fileExists(atPath: marker.path) { + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertTrue(FileManager.default.fileExists(atPath: marker.path)) + model.openExample(title: "Second", source: "Second LDW #$1234", target6309: true) + try await Task.sleep(nanoseconds: 200_000_000) + XCTAssertFalse(model.working); XCTAssertNil(model.artifact) + XCTAssertEqual(model.cpu, .hd6309) + XCTAssertEqual(model.buffer.text, "Second LDW #$1234") + model.select(original) + XCTAssertEqual(model.cursor, 12, "Reference lookup and Set Stop must follow the restored document caret") + XCTAssertTrue(model.buffer.text.hasPrefix("; My unsaved revision")) + XCTAssertTrue(model.prepareToQuit()) + XCTAssertEqual(try AssemblyRecovery.read(from: recovery).documents.count, 2) + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + + @MainActor func testSaveCopyProtectsAnotherDocumentsIncludeAndCanSaveEmptySource() async throws { + let dir = try temporaryFolder(), suite = "AssemblySaveTests." + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: dir) } + let sub = dir.appendingPathComponent("Shared.inc"), entry = dir.appendingPathComponent("Main.asm") + let initial = Data("start lda #1\n".utf8) + try initial.write(to: sub) + try Data(" include \"Shared.inc\"\n".utf8).write(to: entry) + let machine = MachineModel(diskStore: .init(url: dir.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: dir.appendingPathComponent("input.json"))) + let model = AssemblyDevelopmentModel(machine: machine, recoveryURL: dir.appendingPathComponent("Drafts.json")) + model.open(entry, folder: false) + for _ in 0..<200 where model.document.title != "Main.asm" { try await Task.sleep(nanoseconds: 10_000_000) } + XCTAssertEqual(model.document.title, "Main.asm") + model.openExample(title: "Untitled", source: "", target6309: false) + let alias = dir.appendingPathComponent("alias.asm") + try FileManager.default.linkItem(at: sub, to: alias) + model.save(to: alias) + for _ in 0..<200 where !model.message.contains("separate") { try await Task.sleep(nanoseconds: 10_000_000) } + XCTAssertTrue(model.message.contains("separate"), model.message) + XCTAssertEqual(try Data(contentsOf: sub), initial) + XCTAssertEqual(try Data(contentsOf: alias), initial) + let empty = dir.appendingPathComponent("Empty.asm") + model.save(to: empty) + for _ in 0..<200 where model.document.title != "Empty.asm" { try await Task.sleep(nanoseconds: 10_000_000) } + XCTAssertEqual(try Data(contentsOf: empty), Data()) + XCTAssertEqual(model.document.title, "Empty.asm") + XCTAssertTrue(model.prepareToQuit()) + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + + func testLooseSourceIncludesPreserveCaseAndOverlayWithoutWriting() throws { + let dir = try temporaryFolder(); defer { try? FileManager.default.removeItem(at: dir) } + let entry = dir.appendingPathComponent("Game.asm"), include = dir.appendingPathComponent("Data.inc") + let main = " ORG $3f00\n INCLUDE \"Data.inc\"\n END Start\n" + let saved = "Start LDA #1\n" + try Data(main.utf8).write(to: entry); try Data(saved.utf8).write(to: include) + try Data("private".utf8).write(to: dir.appendingPathComponent("Other.inc")) + var doc = try AssemblyWorkspaceDocument.open(entry, folder: false) + XCTAssertEqual(doc.mainPath, "Game.asm") + XCTAssertEqual(Set(doc.paths), ["Game.asm", "Data.inc"]) + doc.buffers.append(.init(path: "Data.inc", text: "Start LDA #2\n", saved: saved)) + let snap = try doc.snapshot() + XCTAssertEqual(snap.files["Data.inc"], Data("Start LDA #2\n".utf8)) + XCTAssertEqual(try String(contentsOf: include, encoding: .utf8), saved) + try Data("external edit".utf8).write(to: include) + XCTAssertThrowsError(try doc.snapshot()) + // An alias inside the selected folder must still be refused. + let alias = dir.appendingPathComponent("Linked.inc") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: include) + XCTAssertThrowsError(try doc.checkedURL("Linked.inc")) + } + + func testRecoveryPreservesTwoIndependentUnsavedExamplesAndTheirTargets() throws { + let dir = try temporaryFolder(); defer { try? FileManager.default.removeItem(at: dir) } + let one = AssemblyWorkspaceDocument.example(title: "First", source: "Start LDA #1", cpu: .mc6809) + var two = AssemblyWorkspaceDocument.example(title: "Wide", source: "Start LDW #$1234", cpu: .hd6309) + two.breakpoints.insert(.init(path: "main.asm", line: 1)) + let url = dir.appendingPathComponent("Recovery.json") + try AssemblyRecovery(documents: [one, two], active: two.id).write(to: url) + let restored = try AssemblyRecovery.read(from: url) + XCTAssertEqual(restored.active, two.id) + XCTAssertEqual(restored.documents.map(\.cpu), [.mc6809, .hd6309]) + XCTAssertEqual(restored.documents.map { $0.buffers[0].text }, ["Start LDA #1", "Start LDW #$1234"]) + XCTAssertNotEqual(restored.documents[0].buffers[0].id, restored.documents[1].buffers[0].id) + XCTAssertEqual(restored.documents[1].breakpoints, two.breakpoints) + } + + @MainActor func testLineNavigationAndTokenizationPreserveUTF16AndCase() throws { + let source = "; é🖥\nEntry lda #$8f ; start here\n fcc \";Label\"\n" + let words: Set = ["LDA", "FCC"] + let range = try XCTUnwrap(AssemblyDevelopmentModel.lineRange(2, text: source)) + XCTAssertEqual((source as NSString).substring(with: range), "Entry lda #$8f ; start here\n") + XCTAssertEqual(AssemblyEditorSyntax.labels(in: source, vocabulary: words).map(\.0), ["Entry"]) + XCTAssertEqual(AssemblyEditorSyntax.token(in: source, offset: range.location + 2, vocabulary: words), "Entry") + let literal = (source as NSString).range(of: ";Label") + XCTAssertNil(AssemblyEditorSyntax.token(in: source, offset: literal.location + 2, vocabulary: words)) + } + + @MainActor func testAmbiguousSourceAndAddressCannotArmStops() { + let source = " org $3f00\nstart lda #$8f\n sta $0400\n" + let snapshot = AssemblyProjectSnapshot.single(source: source) + let instructions: [AssemblyInstructionLocation] = [ + .init(path: "main.asm", line: 2, address: 0x3f00, bytes: [0x86, 0x8f]), + .init(path: "main.asm", line: 3, address: 0x3f02, bytes: [0xb7, 4, 0]), + .init(path: "main.asm", line: 3, address: 0x3f05, bytes: [0x20, 0xfe]), + .init(path: "other.inc", line: 1, address: 0x3f05, bytes: [0x20, 0xfe])] + let artifact = AssemblyBuildArtifact(id: UUID(), snapshot: snapshot, binaryData: Data(), entry: 0x3f00, ranges: [], + listing: "", symbols: "", buildLog: "", instructions: instructions) + XCTAssertNil(AssemblyDevelopmentModel.location(.init(path: "main.asm", line: 1), in: artifact)) + XCTAssertEqual(AssemblyDevelopmentModel.location(.init(path: "main.asm", line: 2), in: artifact)?.address, 0x3f00) + XCTAssertNil(AssemblyDevelopmentModel.location(.init(path: "main.asm", line: 3), in: artifact)) + XCTAssertNil(AssemblyDevelopmentModel.location(.init(path: "other.inc", line: 1), in: artifact)) + XCTAssertNil(AssemblyDevelopmentModel.codeGuards(instructions)[0x3f05]) + } +} diff --git a/platforms/macos/Tests/AssemblyReferenceTests.swift b/platforms/macos/Tests/AssemblyReferenceTests.swift new file mode 100644 index 0000000..86bf86d --- /dev/null +++ b/platforms/macos/Tests/AssemblyReferenceTests.swift @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import XCTest + +final class AssemblyReferenceTests: XCTestCase { + private let catalog = AssemblyReference.shared + private var root: URL { + URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + } + + func testVocabularyAgainstBundledAssemblerAndDecoder() throws { + func matches(_ expression: String, _ file: String) throws -> [[String]] { + let text = try String(contentsOf: root.appendingPathComponent(file), encoding: .utf8) as NSString + let regex = try NSRegularExpression(pattern: expression) + return regex.matches(in: text as String, range: NSRange(location: 0, length: text.length)).map { match in + (1.. [String] { + catalog.completions(in: source, at: (source as NSString).length, target6309: hd) + } + XCTAssertEqual(catalog.search("BHS", target6309: false, category: nil).first?.name, "BCC") + XCTAssertTrue(catalog.search("TFM", target6309: false, category: .instructions).isEmpty) + XCTAssertTrue(catalog.search(",X+", target6309: nil, category: .addressing).contains { $0.name == "Indexed" }) + XCTAssertTrue(catalog.search("copy a byte", target6309: false, category: nil).contains { $0.name == "LDA" }) + XCTAssertEqual(complete(" tfr a,b"), ["B"]) + XCTAssertFalse(complete(" tfr a,").contains("X")) + XCTAssertTrue(complete(" lda ,", true).contains("W")) + XCTAssertFalse(complete(" lda ,").contains("W")) + XCTAssertTrue(complete("save fcb 0\n sta #s").isEmpty) + XCTAssertTrue(complete(" lda E,").isEmpty) + XCTAssertFalse(complete(" lda A,", true).contains("W")) + XCTAssertFalse(complete(" pshs ").contains("S")) + XCTAssertTrue(complete(" pshu ").contains("S")) + XCTAssertEqual(complete(" tfm x-,y", true), ["Y-"]) + XCTAssertTrue(complete(" fcc /ld").isEmpty) + XCTAssertTrue(complete(" lda #1 ; ld").isEmpty) + XCTAssertTrue(complete(" lda #1 ld").isEmpty) + XCTAssertTrue(complete(" i\u{0301} ; ld").isEmpty) + XCTAssertEqual(complete("myTable fcb 1\n lda myT"), ["myTable"]) + XCTAssertEqual(catalog.topic(in: "start lda ,x+", at: 10, target6309: false), "LDA") + XCTAssertNil(catalog.topic(in: " ldw #1", at: 10, target6309: false)) + let lesson = AssemblyReferenceLesson.all[0] + XCTAssertNotEqual(lesson.request.id, lesson.request.id) + } + + /// All teaching listings use one DECB load block and an entry at $3F00. + private func assemble(_ lesson: AssemblyReferenceLesson, hd: Bool, folder: URL) throws -> (Int32, Data) { + let candidates = [Bundle.main.resourceURL?.appendingPathComponent("Toolchain/bin/lwasm"), + root.appendingPathComponent("platforms/macos/LocalResources/ToolchainBundle/bin/lwasm"), + root.appendingPathComponent(".build/toolchain/install/bin/lwasm")].compactMap { $0 } + guard let tool = candidates.first(where: { FileManager.default.isExecutableFile(atPath: $0.path) }) else { + throw XCTSkip("A local or bundled LWASM is required to assemble the reference lessons.") + } + let source = folder.appendingPathComponent(lesson.id + ".asm") + let output = folder.appendingPathComponent(UUID().uuidString + ".bin") + try lesson.source.write(to: source, atomically: true, encoding: .utf8) + let process = Process() + process.executableURL = tool + process.arguments = [hd ? "--6309" : "--6809","--format=decb","--output=" + output.path,source.path] + try process.run() + process.waitUntilExit() + return (process.terminationStatus, (try? Data(contentsOf: output)) ?? Data()) + } + + @MainActor func testAssembledLessonsExecuteOnDeclaredProcessorsAndModes() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { cont in operation { cont.resume(returning: $0) } } + } + for lesson in AssemblyReferenceLesson.all { + if lesson.hd { XCTAssertNotEqual(try assemble(lesson, hd: false, folder: folder).0, 0) } + for hd in (lesson.hd ? [true] : [false,true]) { + let (status, bin) = try assemble(lesson, hd: hd, folder: folder) + XCTAssertEqual(status, 0) + guard bin.count >= 10 else { XCTFail(lesson.id); continue } + XCTAssertEqual(Array(bin.prefix(1)), [0]) + XCTAssertEqual(Array(bin[3...4]), [0x3F,0]) + XCTAssertEqual(Array(bin.suffix(5)), [0xFF,0,0,0x3F,0]) + let code = Data(bin.dropFirst(5).dropLast(5)) + XCTAssertEqual(code.count, Int(bin[1]) * 256 + Int(bin[2])) + if lesson.id == "cell" { XCTAssertEqual(Array(code), [0x86,0x8F,0xB7,4,0,0x20,0xFE]) } + for native in (hd ? [false,true] : [false]) { + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command { controller.loadDiagnostic(use6309: hd, completion: $0) } + if native { + _ = await command { controller.debuggerWriteMemory(address: 0x3E00, data: Data([0x11,0x3D,1]), completion: $0) } + _ = await command { controller.debuggerSetPC(0x3E00, completion: $0) } + _ = await command(controller.debuggerStep) + } + _ = await command { controller.debuggerWriteMemory(address: 0x3F00, data: code, completion: $0) } + _ = await command { controller.debuggerSetPC(0x3F00, completion: $0) } + let steps = ["cell":2,"count":7,"call":6,"page":2,"signed":4,"word":1,"transfer":4][lesson.id]! + for _ in 0.. Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { continuation in body { continuation.resume(returning: $0) } } + } + private func read(_ controller: VCCMachineController) async -> (String?, String?) { + await withCheckedContinuation { continuation in + controller.basicReadSource { source, snapshot in continuation.resume(returning: (source, snapshot.errorMessage)) } + } + } + private func export(_ controller: VCCMachineController, source: String, name: String = "HELLO", cassette: Bool) async -> (Data?, VCCMachineSnapshot) { + await withCheckedContinuation { continuation in + controller.basicExportSource(source, name: name, cassette: cassette) { data, snapshot in + continuation.resume(returning: (data, snapshot)) + } + } + } + private func assertExportPreservesSession(_ after: VCCMachineSnapshot, _ before: VCCMachineSnapshot, + file: StaticString = #filePath, line: UInt = #line) { + XCTAssertEqual(after.state, before.state, file: file, line: line) + XCTAssertEqual(after.generation, before.generation, file: file, line: line) + XCTAssertEqual(after.debuggerProgramRevision, before.debuggerProgramRevision, file: file, line: line) + XCTAssertEqual(after.debuggerMappingFingerprint, before.debuggerMappingFingerprint, file: file, line: line) + XCTAssertEqual(after.use6309, before.use6309, file: file, line: line) + XCTAssertEqual(after.ramConfiguration, before.ramConfiguration, file: file, line: line) + XCTAssertEqual(after.audioEnabled, before.audioEnabled, file: file, line: line) + XCTAssertEqual(after.pasteRemaining, before.pasteRemaining, file: file, line: line) + XCTAssertEqual(after.disks[0].name, before.disks[0].name, file: file, line: line) + XCTAssertEqual(after.disks[0].mounted, before.disks[0].mounted, file: file, line: line) + XCTAssertEqual(after.disks[0].dirty, before.disks[0].dirty, file: file, line: line) + XCTAssertEqual(after.disks[0].writeProtected, before.disks[0].writeProtected, file: file, line: line) + XCTAssertEqual(after.tapeMounted, before.tapeMounted, file: file, line: line) + XCTAssertEqual(after.tapeDirty, before.tapeDirty, file: file, line: line) + XCTAssertEqual(after.tapeMode, before.tapeMode, file: file, line: line) + XCTAssertEqual(after.tapePosition, before.tapePosition, file: file, line: line) + XCTAssertEqual(after.tapeLength, before.tapeLength, file: file, line: line) + XCTAssertEqual(after.cartridgeKinds, before.cartridgeKinds, file: file, line: line) + XCTAssertEqual(after.physicalSlot, before.physicalSlot, file: file, line: line) + XCTAssertEqual(after.romSlot, before.romSlot, file: file, line: line) + XCTAssertEqual(after.ioSlot, before.ioSlot, file: file, line: line) + } + private func memory(_ controller: VCCMachineController) async -> VCCDebuggerSnapshot { + await withCheckedContinuation { continuation in + controller.debuggerSnapshot(address: 0, followPC: false, memoryAddress: 0) { continuation.resume(returning: $0) } + } + } + private func programBytes(_ controller: VCCMachineController) async throws -> Data { + let capture = await memory(controller) + let bytes = [UInt8](capture.logicalMemory) + XCTAssertEqual(bytes.count, 65536) + guard bytes.count == 65536 else { throw Failure.invalidMemory } + let start = Int(bytes[0x19]) * 256 + Int(bytes[0x1a]) + let end = Int(bytes[0x1b]) * 256 + Int(bytes[0x1c]) + guard start >= 0x600, end >= start, end < 0x8000 else { throw Failure.invalidMemory } + return Data(bytes[start.. String { + await withCheckedContinuation { continuation in + controller.copyScreenText { text, _ in continuation.resume(returning: text ?? "") } + } + } + private func waitForScreen(_ text: String, controller: VCCMachineController, context: String = "") async throws { + for _ in 0..<300 { + if await screen(controller).contains(text) { return } + try await Task.sleep(nanoseconds: 20_000_000) + } + let current = await screen(controller) + XCTFail("\(context) BASIC screen did not contain \(text): \(current)") + throw Failure.timeout + } + private func settle(_ controller: VCCMachineController, frames: UInt64 = 20) async throws { + let before = await command(controller.snapshot) + if before.state != .running { _ = await command(controller.resume) } + for _ in 0..<300 { + if await command(controller.snapshot).frames >= before.frames + frames { return } + try await Task.sleep(nanoseconds: 20_000_000) + } + throw Failure.timeout + } + private func withBASIC(_ body: (VCCMachineController) async throws -> Void) async throws { + let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + let roms = mac.appendingPathComponent("LocalResources/ROMs") + let system = roms.appendingPathComponent("coco3.rom"), disk = roms.appendingPathComponent("disk11.rom") + try XCTSkipUnless(FileManager.default.fileExists(atPath: system.path) && FileManager.default.fileExists(atPath: disk.path), + "Stage the licensed local CoCo 3 and Disk BASIC ROMs for direct BASIC integration checks") + let systemBytes = try Data(contentsOf: system), diskBytes = try Data(contentsOf: disk) + let starter = mac.appendingPathComponent("Resources/StarterMedia") + for use6309 in [false, true] { + let controller = VCCMachineController() + do { + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command { controller.loadDiskROM(diskBytes, name: "Disk BASIC", completion: $0) } + _ = await command { controller.configureCartridges([2, 0, 0, 0, 2], roms: Array(repeating: Data(), count: 5), names: Array(repeating: "", count: 5), multiPak: true, physicalSlot: 4, completion: $0) } + let image = try Data(contentsOf: starter.appendingPathComponent("Hello World.dsk")) + let cassette = try Data(contentsOf: starter.appendingPathComponent("Hello World.cas")) + _ = await command { controller.mountDisk(image, drive: 0, name: "Preserved.dsk", readOnly: true, completion: $0) } + _ = await command { controller.mountTape(cassette, wav: false, completion: $0) } + let loaded = await command { controller.loadROM(systemBytes, use6309: use6309, completion: $0) } + XCTAssertNil(loaded.errorMessage) + _ = await command(controller.resume) + try await waitForScreen("OK", controller: controller) + try await settle(controller) + try await body(controller) + _ = await command(controller.shutdown) + } catch { + _ = await command(controller.shutdown) + throw error + } + } + } + private func basicProfileStore(mac: URL, root: URL) throws -> StartupStore { + let kit = StarterKit(directory: root.appendingPathComponent("Kit")) + try FileManager.default.createDirectory(at: kit.directory, withIntermediateDirectories: true) + for name in ["coco3.rom", "disk11.rom", "rgbdos.rom", "sdcdos.rom"] { + let input = mac.appendingPathComponent("LocalResources/ROMs/" + name) + try XCTSkipUnless(FileManager.default.fileExists(atPath: input.path), "Stage optional private ROM: " + name) + try FileManager.default.copyItem(at: input, to: kit.directory.appendingPathComponent(name)) + } + for name in ["Hello World.dsk", "Hello World.cas", "Blank Disk.dsk", "Hello Hard Disk.dsk", "Blank OS9 Header.bin"] { + try FileManager.default.copyItem(at: mac.appendingPathComponent("Resources/StarterMedia/" + name), + to: kit.directory.appendingPathComponent(name)) + } + return StartupStore(directory: root.appendingPathComponent("Support"), kit: kit) + } + + func testSharedMachineStatusReportsGuestAndRunBlockersWithoutChangingMedia() async throws { + try await withBASIC { controller in + let snapshot = await self.command(controller.assistantReadiness) + XCTAssertEqual(snapshot.assistantEmptyBASIC, true) + let status = MCPMachineStatus.result(snapshot, workspace: .cmoc(needsFloppy: true), buildBlockers: [], runBlockers: [], + lastBuild: ["build_id": "last", "revision": 1, "status": "failed", "diagnostics": ["detail"]]) + XCTAssertEqual(status["processor"] as? String, snapshot.use6309 ? "HD6309" : "MC6809") + let build = try XCTUnwrap(status["build"] as? [String: Any]) + XCTAssertEqual(build["available"] as? Bool, true) + let last = try XCTUnwrap(build["last_build"] as? [String: Any]) + XCTAssertEqual(last["build_id"] as? String, "last") + XCTAssertEqual(last["status"] as? String, "failed") + XCTAssertNil(last["diagnostics"]) + let disks = try XCTUnwrap(status["floppy_drives"] as? [[String: Any]]) + XCTAssertEqual(disks[0]["mounted"] as? Bool, true) + XCTAssertEqual(disks[0]["write_protected"] as? Bool, true) + XCTAssertNil(disks[0]["name"]) + let run = try XCTUnwrap(status["run"] as? [String: Any]) + let reasons = try XCTUnwrap(run["blockers"] as? [String]) + XCTAssertTrue(reasons.contains { $0.contains("cassette") }) + XCTAssertTrue(reasons.contains { $0.contains("drive 0") }) + _ = await self.command(controller.discardTape) + let observed = await self.command(controller.assistantReadiness) + let assembly = MCPMachineStatus.result(observed, workspace: .assembly(needs6309: true), + buildBlockers: [], runBlockers: []) + let assemblyRun = try XCTUnwrap(assembly["run"] as? [String: Any]) + XCTAssertEqual(assemblyRun["ready_for_native_run"] as? Bool, snapshot.use6309) + XCTAssertEqual(observed.disks.first?.name, snapshot.disks.first?.name) + XCTAssertEqual(observed.generation, snapshot.generation) + XCTAssertEqual(observed.debuggerProgramRevision, snapshot.debuggerProgramRevision) + + let ordinary = MCPMachineStatus.result(observed, workspace: .cmoc(needsFloppy: false), buildBlockers: [], runBlockers: []) + let ordinaryRun = try XCTUnwrap(ordinary["run"] as? [String: Any]) + let ordinaryReasons = try XCTUnwrap(ordinaryRun["blockers"] as? [String]) + XCTAssertFalse(ordinaryReasons.contains { $0.contains("drive 0") }) + XCTAssertEqual(ordinary["basic_program_loaded"] as? Bool, false) + + let source = "10 PRINT \"KEEP MY PROGRAM\"" + let loaded = await self.command { controller.basicLoadSource(source, run: false, completion: $0) } + XCTAssertNil(loaded.errorMessage) + let occupied = await self.command(controller.assistantReadiness) + let blocked = MCPMachineStatus.result(occupied, workspace: .cmoc(needsFloppy: false), buildBlockers: [], runBlockers: []) + XCTAssertEqual(blocked["basic_program_loaded"] as? Bool, true) + let blockers = try XCTUnwrap((blocked["run"] as? [String: Any])?["blockers"] as? [String]) + XCTAssertTrue(blockers.contains(MCPMachineStatus.occupiedBASICGuidance)) + let denied = await self.command { controller.startReviewedC(Data(), disk: nil, name: "", stop: 0x2800, expected: occupied, completion: $0) } + XCTAssertEqual(denied.errorMessage, "occupied_basic_program") + let retained: String? = await withCheckedContinuation { done in + controller.basicReadSource { text, _ in done.resume(returning: text) } + } + XCTAssertEqual(retained?.trimmingCharacters(in: .newlines), source) + XCTAssertEqual(denied.debuggerProgramRevision, occupied.debuggerProgramRevision) + XCTAssertEqual(denied.disks.first?.name, snapshot.disks.first?.name) + } + } + + func testReviewedBASICRunChecksRealMenuColorsPromptAndStaleSource() async throws { + let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + let roms = mac.appendingPathComponent("LocalResources/ROMs") + for file in ["coco3.rom", "disk11.rom"] { + try XCTSkipUnless(FileManager.default.fileExists(atPath: roms.appendingPathComponent(file).path), "Stage private BASIC ROMs") + } + let suite = "MCPGuestTests-" + UUID().uuidString + let dir = FileManager.default.temporaryDirectory.appendingPathComponent(suite) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: dir) } + let controller = VCCMachineController() + let machine = MachineModel(diskStore: .init(url: dir.appendingPathComponent("drives.json")), controller: controller, displayDefaults: defaults, + inputStore: .init(url: dir.appendingPathComponent("input.json"))) + do { + for _ in 0..<300 where machine.busy { try await Task.sleep(for: .milliseconds(20)) } + for use6309 in [false, true] { + for composite in [false, true] { + try await MCPBASICRun.bootFixture(machine, romDirectory: roms, use6309: use6309, composite: composite) + let model = BASICDevelopmentModel(machine: machine, directory: dir.appendingPathComponent(UUID().uuidString)) + model.source = model.source.replacingOccurrences(of: "Hello Cold Red Dot World!", with: "Bring a warm coat!") + let guest = MCPBASICRun() + await guest.start(model: model, bothChoices: true, isCurrent: { true }) + let branches = try XCTUnwrap(guest.receipt?["branches"] as? [[String: Any]], guest.status) + XCTAssertEqual(branches.compactMap { $0["key"] as? String }, ["2", "1"]) + XCTAssertEqual(guest.receipt?["verified"] as? Bool, !composite) + XCTAssertEqual(branches.compactMap { $0["color_matches"] as? Bool }, [!composite, true]) + XCTAssertEqual(branches.compactMap { ($0["cell"] as? [String: Int])?["palette_value"] }, [37, 10]) + XCTAssertEqual(branches.compactMap { $0["greeting"] as? String }, + ["Bring a warm coat!", "Hello Nice Blue Dot World!"]) + let runID = try XCTUnwrap(guest.runID) + let observation = await guest.handle(tool: "read_screen_text", arguments: ["run_id": runID], model: model) + XCTAssertNotNil(observation["result"]) + model.source += "200 REM UNSAVED EDIT\n" + let stale = await guest.handle(tool: "read_screen_text", arguments: ["run_id": runID], model: model) + XCTAssertNotNil(stale["error"]) + print("Reviewed BASIC guest", use6309 ? "HD6309" : "MC6809", composite ? "composite" : "RGB", + branches.compactMap { $0["background_rgb"] }) + } + } + try await MCPBASICRun.bootFixture(machine, romDirectory: roms) + let ordinary = BASICDevelopmentModel(machine: machine, directory: dir.appendingPathComponent("Menu")) + ordinary.source = """ + 10 PRINT "PRESS ANY KEY" + 20 FOR I=1 TO 10 + 30 K$=INKEY$:IF K$="" THEN 30 + 40 PRINT "GOT";I;" ";K$ + 50 NEXT I + 60 END + """ + let manual = MCPBASICRun() + let enabled = await command { controller.setDriveWireEnabled(true, completion: $0) } + XCTAssertTrue(enabled.driveWireEnabled) + let armed = await command(controller.startMacShell) + XCTAssertEqual(armed.macShellStatus, "ready") + await manual.start(model: ordinary, bothChoices: false, isCurrent: { true }) + XCTAssertNil(manual.runID) + XCTAssertTrue(manual.status.contains("Disable DriveWire"), manual.status) + _ = await command { controller.setDriveWireEnabled(false, completion: $0) } + await manual.start(model: ordinary, bothChoices: false, isCurrent: { true }) + let runID = try XCTUnwrap(manual.runID, manual.status) + for _ in 0..<80 { + let reply = await manual.handle(tool: "read_screen_text", arguments: ["run_id": runID], model: ordinary) + let screen = (reply["result"] as? [String: Any])?["text"] as? String ?? "" + if screen.contains("PRESS ANY KEY") { break } + try await Task.sleep(for: .milliseconds(50)) + } + func send(_ keys: String, request: String) async -> [String: Any] { + await manual.handle(tool: "send_keys", arguments: ["run_id": runID, "request_id": request, "keys": keys], model: ordinary) + } + let unsupported = await send("RUN\n", request: "command") + XCTAssertEqual(unsupported["error"] as? String, "invalid_arguments") + let first = await send("3", request: "one"), replay = await send("3", request: "one") + XCTAssertNotNil(first["result"], String(describing: first)) + XCTAssertTrue(NSDictionary(dictionary: first).isEqual(to: replay)) + let conflict = await send("2", request: "one") + XCTAssertEqual(conflict["error"] as? String, "request_conflict") + func expectScreen(_ expected: String, direct: Bool = false) async throws { + var text = "" + for _ in 0..<100 { + let reply = await manual.handle(tool: "read_screen_text", arguments: ["run_id": runID], model: ordinary) + let result = reply["result"] as? [String: Any] + text = result?["text"] as? String ?? String(describing: reply) + if text.contains(expected), result?["paste_remaining"] as? Int == 0, + result?["direct_prompt"] as? Bool == direct { return } + try await Task.sleep(for: .milliseconds(40)) + } + XCTFail("Expected \(expected) in \(text)") + } + try await expectScreen("GOT 1") + let network = await command { controller.setDriveWireEnabled(true, completion: $0) } + XCTAssertFalse(network.driveWireEnabled) + XCTAssertNotNil(network.errorMessage) + for index in 2...10 { + let key = index.isMultiple(of: 2) ? " " : "A" + let response = await send(key, request: "key-\(index)") + XCTAssertNotNil(response["result"], String(describing: response)) + try await expectScreen("GOT \(index)", direct: index == 10) + } + let atPrompt = await send("N", request: "after-end") + XCTAssertNotNil(atPrompt["error"]) + let probe = await send("PRINT 7\n", request: "probe") + XCTAssertNotNil(probe["result"], String(describing: probe)) + try await expectScreen("PRINT 7", direct: true) + manual.reset() + let revoked = await send("1", request: "two") + XCTAssertEqual(revoked["error"] as? String, "no_run") + // The local-model trial edited the Earth assignment while leaving Mars intact. + // A plausible replacement sentence in the source is insufficient to pass. + try await MCPBASICRun.bootFixture(machine, romDirectory: roms) + let wrong = BASICDevelopmentModel(machine: machine, directory: dir.appendingPathComponent("WrongBranch")) + wrong.source = wrong.source.replacingOccurrences(of: "Hello Nice Blue Dot World!", with: "Bring a warm coat!") + let rejected = MCPBASICRun() + await rejected.start(model: wrong, bothChoices: true, isCurrent: { true }) + XCTAssertNil(rejected.receipt) + XCTAssertTrue(rejected.status.contains("Expected “Bring a warm coat!â€� for choice 2"), rejected.status) + XCTAssertTrue(rejected.status.contains("Hello Cold Red Dot World!"), rejected.status) + } catch { + await withCheckedContinuation { c in machine.shutdown { c.resume() } } + throw error + } + await withCheckedContinuation { c in machine.shutdown { c.resume() } } + } + + func testPlanetEditorStartersAcceptKeyboardAndReturnToBASIC() async throws { + let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + let tools = mac.appendingPathComponent("LocalResources/ToolchainBundle") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/lwasm").path)) + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/cmoc").path)) + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: root) } + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + let service = CMOCBuildService(toolchain: tools, buildRoot: root.appendingPathComponent("Builds")) + let c = try await service.build(project: project, overlays: [:]) + let assembly = try await AssemblyBuildService(toolchain: tools).build(.single(source: AssemblyWorkspaceDocument.starterSource)) + let cEntry = c.binaryData.suffix(2).reduce(UInt16(0)) { ($0 << 8) | UInt16($1) } + try await withBASIC { controller in + func type(_ text: String) async throws { + let keys = try CocoPaste(text, mode: .text) + let sent = await command { controller.pasteChords(keys.chords.map { NSNumber(value: $0) }, completion: $0) } + XCTAssertNil(sent.errorMessage) + for _ in 0..<300 { + if await command(controller.snapshot).pasteRemaining == 0 { return } + try await Task.sleep(nanoseconds: 20_000_000) + } + throw Failure.timeout + } + enum Language: CaseIterable { case basic, assembly, c } + for language in Language.allCases { + for (choice, greeting) in [("1", "Hello Nice Blue Dot World!"), ("2", "Hello Cold Red Dot World!")] { + let launched: VCCMachineSnapshot + switch language { + case .assembly: + let before = await command(controller.snapshot) + launched = await command { controller.launchAssembly(assembly.binaryData, points: [], addresses: [], bytes: [], + pauseAtEntry: false, requires6309: false, generation: before.generation, revision: before.debuggerProgramRevision, + mapping: before.debuggerMappingFingerprint, completion: $0) } + case .c: + // C Development's Run arms the entry while loading, then releases it. + let prepared = await command { controller.debuggerLoadBinary(c.binaryData, breakpoint: cEntry, completion: $0) } + XCTAssertNil(prepared.errorMessage) + _ = await command(controller.debuggerClearDevelopmentBreakpoints) + launched = await command(controller.resume) + case .basic: + launched = await command { controller.basicLoadSource(BASICLanguage.sample, run: true, completion: $0) } + } + XCTAssertNil(launched.errorMessage) + try await waitForScreen("What planet do you live on?\n1) Earth\n2) Mars", controller: controller) + try await type("3" + choice) + try await waitForScreen(greeting, controller: controller, context: "\(language) Direct Run") + // Clearing the screen also prevents a previous run from satisfying the next check. + try await type("CLS\nPRINT 7\n") + try await waitForScreen("PRINT 7\n 7", controller: controller) + try await settle(controller) + } + // A real EXEC inside a BASIC program must resume on the following line. + if language != .basic { + let entry = language == .c ? cEntry : assembly.entry + let caller = String(format: "10 EXEC &H%04X\n20 PRINT \"BACK FROM EXEC\"\n", entry) + let started = await command { controller.basicLoadSource(caller, run: true, completion: $0) } + XCTAssertNil(started.errorMessage) + try await waitForScreen("2) Mars", controller: controller) + try await type("1") + try await waitForScreen("Hello Nice Blue Dot World!\nBACK FROM EXEC", controller: controller) + try await settle(controller) + } + } + } + } + + func testExportedBootDisksRunByDOSAndByTheirManualCommands() async throws { + let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + let tools = mac.appendingPathComponent("LocalResources/ToolchainBundle") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/cmoc").path)) + let service = AssemblyBuildService(toolchain: tools) + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let store = try basicProfileStore(mac: mac, root: root) + let build = try await service.build(.single(source: " org $3f00\nstart lda #$8f\n sta $0400\nhold bra hold\n end start\n")) + let machineDisk = try await service.diskImage(for: build, name: "ASMTEST", dosBoot: true) + for binary in [false, true] { + for shortcut in [false, true] { + var profile = try store.systemProfile(.diskBasic) + profile.sound = false + profile.machine.use6309 = shortcut + let request = try PreparedProfile.read(profile).request() + let controller = VCCMachineController() + do { + let ready: Bool = await withCheckedContinuation { c in + controller.applyProfile(request) { ok, _ in c.resume(returning: ok) } + } + XCTAssertTrue(ready) + _ = await command(controller.resume) + try await waitForScreen("OK", controller: controller) + try await settle(controller) + let image: Data + if binary { image = machineDisk } + else { + let result = await export(controller, source: "10 PRINT \"BOOTED BASIC\"\n", name: "BASICTST", cassette: false) + let plain = try XCTUnwrap(result.0) + image = try await service.tools.bootableBASICDisk(plain, name: "BASICTST") + let fat = 17 * 18 * 256 + 256 + 66 + XCTAssertEqual(Array(plain[fat..= 0 { + XCTFail("\(context): \(state.basicErrorCode) error on line \(state.basicErrorLine)") + throw Failure.invalidMemory + } + if await screen(controller).contains(example.expectedOutput) { finished = true; break } + try await Task.sleep(nanoseconds: 20_000_000) + } + if !finished { + let output = await screen(controller) + XCTFail("\(context): expected \(example.expectedOutput), received \(output)") + throw Failure.timeout + } + // Ensure END has reached the direct prompt before replacing + // the example, and catch errors that follow a printed result. + try await settle(controller) + let final = await command(controller.snapshot) + XCTAssertEqual(final.basicErrorLine, -1, context) + XCTAssertEqual(final.generation, baseline.generation, context) + XCTAssertTrue(final.disks.allSatisfy { !$0.dirty && $0.writeEvents == 0 }, context) + XCTAssertTrue(final.hardDisks.allSatisfy { !$0.dirty && $0.writeEvents == 0 }, context) + XCTAssertEqual(final.sdcWriteCount, 0, context) + XCTAssertFalse(final.tapeDirty, context) + if example.dialect == "disk" || example.dialect == "rgbdos" { + XCTAssertGreaterThan(final.disks.reduce(UInt64(0)) { $0 + $1.readEvents }, + before.disks.reduce(UInt64(0)) { $0 + $1.readEvents }, context) + } + if example.dialect == "rgbdos" { + XCTAssertGreaterThan(final.hardDisks.reduce(UInt64(0)) { $0 + $1.readEvents }, + before.hardDisks.reduce(UInt64(0)) { $0 + $1.readEvents }, context) + } + if example.dialect == "sdcdos" { XCTAssertGreaterThan(final.sdcReadCount, before.sdcReadCount, context) } + } + _ = await command(controller.shutdown) + } catch { _ = await command(controller.shutdown); throw error } + } + } + } + private func stagedArchive() throws -> ArchiveLibraryCatalog { + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + let url = root.appendingPathComponent("media/knowledge-base/archive-library/ArchiveLibrary.sqlite") + try XCTSkipUnless(FileManager.default.fileExists(atPath: url.path), "Stage the full Archive Library index") + return ArchiveLibraryCatalog(url: url) + } + + func testArchiveSearchWhileGuestRuns() async throws { + try await withBASIC { controller in + let catalog = try self.stagedArchive() + let before = await self.command(controller.snapshot) + var times: [Double] = [] + for _ in 0..<3 { + for query in ["OS-9 level II module directory", "JOYSTK", "TFM", "GIME", "WIDTH 80", "disk basic", "the"] { + let start = DispatchTime.now().uptimeNanoseconds + let hits = try await catalog.search(query: query, collection: nil, limit: 10, offset: 0) + times.append(Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000) + XCTAssertFalse(hits.isEmpty) + if query.hasPrefix("OS-9") { + XCTAssertTrue(hits.contains { $0.page == 79 && $0.document.memberPath == "Complete Rainbow Guide to OS-9 Level II.pdf" }) + } + } + } + let year = "Magazines/Rainbow, The/1983" + let collections = try await catalog.collections() + XCTAssertTrue(collections.contains(year)) + let issues = try await catalog.browse(collection: year, limit: 50, offset: 0) + XCTAssertTrue(issues.contains { $0.title.contains("November 1983") }) + XCTAssertTrue(issues.allSatisfy { $0.title.contains("1983") }) + let after = await self.command(controller.snapshot) + XCTAssertGreaterThan(after.frames, before.frames) + XCTAssertEqual(after.debuggerProgramRevision, before.debuggerProgramRevision) + XCTAssertEqual(after.disks.map(\.name), before.disks.map(\.name)) + let warm = times.dropFirst().sorted() + print("Archive query milliseconds, guest \(after.use6309 ? "6309" : "6809"): first \(times[0]), warm median \(warm[9]), warm P95 \(warm[18])") + } + } + + func testReviewedArchiveBASICExamplesOnSharedPage() async throws { + let catalog = try stagedArchive() + let issue = "5f3398c7ad84af7f564d5e941014d2be36fd97ec5abc3176594fedb8e025936f" + for title in ["Mini Data Base", "Pill"] { + try await withBASIC { controller in + let before = await self.command(controller.snapshot) + let choices = try await catalog.examples(documentID: issue, page: 13) + XCTAssertEqual(choices.map(\.title), ["Mini Data Base", "Pill"]) + let unchanged = await self.command(controller.snapshot) + XCTAssertEqual(unchanged.debuggerProgramRevision, before.debuggerProgramRevision) + XCTAssertEqual(unchanged.state, before.state) + XCTAssertEqual(unchanged.disks.map(\.name), before.disks.map(\.name)) + let example = try XCTUnwrap(choices.first { $0.title == title }) + let recovered = try await catalog.basicExample(sourceSHA256: example.sourceSHA256) + XCTAssertEqual(recovered?.source, example.source) + if example.title == "Mini Data Base" { + // Stop once the form is drawn, before Disk BASIC opens the data file. + let loaded = await self.command { controller.basicLoadSource(example.source, run: true, breakpoints: [130], completion: $0) } + XCTAssertNil(loaded.errorMessage) + _ = try await self.waitForBASICStop(controller, line: 130) + let screen = await self.screen(controller) + XCTAssertTrue(screen.contains("SURNAME")) + } else { + // PCLEAR relocates the program. Observe CURLIN in the Disk BASIC ROM + // instead of attaching a breakpoint across the memory-map change. + let loaded = await self.command { controller.basicLoadSource(example.source, run: true, completion: $0) } + XCTAssertNil(loaded.errorMessage) + var line = -1 + for _ in 0..<250 { + let ram = await self.memory(controller).logicalMemory + line = Int(ram[0x68]) * 256 + Int(ram[0x69]) + if line == 108 || line == 110 { break } + try await Task.sleep(nanoseconds: 20_000_000) + } + XCTAssertTrue([108,110].contains(line), "Expected Pill's title-screen key loop, observed BASIC line \(line)") + } + } + } + } + private func waitForBASICStop(_ controller: VCCMachineController, line: Int) async throws -> VCCMachineSnapshot { + for _ in 0..<300 { + let snapshot = await command(controller.snapshot) + if snapshot.state == .paused && snapshot.basicStoppedLine == line { return snapshot } + if let error = snapshot.errorMessage { XCTFail(error); throw Failure.timeout } + try await Task.sleep(nanoseconds: 10_000_000) + } + let last = await command(controller.snapshot) + XCTFail("No BASIC stop at \(line): \(last.basicDebugStatus), PC \(last.programCounter)") + throw Failure.timeout + } + private func basicStep(_ controller: VCCMachineController, source: String, over: Bool = false) async throws -> VCCMachineSnapshot { + let started = await command { controller.basicStep(source: source, over: over, completion: $0) } + XCTAssertNil(started.errorMessage) + for _ in 0..<400 { + let state = await command(controller.snapshot) + if state.state == .paused && !state.basicStepping { return state } + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTFail("BASIC step did not stop"); throw Failure.timeout + } + private func inspect(_ controller: VCCMachineController, source: String) async -> ([BASICVariable]?, VCCMachineSnapshot) { + await withCheckedContinuation { continuation in + controller.basicInspect(source: source) { rows, snapshot in + continuation.resume(returning: (rows?.compactMap(BASICVariable.init), snapshot)) + } + } + } + private func stepOut(_ controller: VCCMachineController, source: String) async throws -> VCCMachineSnapshot { + let started = await command { controller.basicStepOut(source: source, completion: $0) } + XCTAssertNil(started.errorMessage) + for _ in 0..<400 { + let state = await command(controller.snapshot) + if state.state == .paused && !state.basicStepping { return state } + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTFail("Step Out did not stop"); throw Failure.timeout + } + func testBASICStepOutNestedForFramesAndBreakpointPrecedence() async throws { + try await withBASIC { controller in + let source = "10 GOSUB 100:POKE &H4000,9:END\n100 FOR I=1 TO 2\n110 GOSUB 200\n120 NEXT I\n130 RETURN\n200 A=A+1\n210 RETURN\n" + _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [110,200], completion: $0) } + let stopped = try await waitForBASICStop(controller, line: 110) + XCTAssertTrue(stopped.basicCanStepOut, "GOSUB frame under a FOR frame") + let stale = await command { controller.basicStepOut(source: source + "300 END\n", completion: $0) } + XCTAssertNotNil(stale.errorMessage); XCTAssertEqual(stale.cycles, stopped.cycles) + var result = try await stepOut(controller, source: source) + XCTAssertEqual(result.basicStoppedLine, 200, "Explicit breakpoint wins inside nested call") + _ = await command { controller.basicSetBreakpoints([], source: source, completion: $0) } + result = try await stepOut(controller, source: source) + XCTAssertEqual(result.basicStoppedLine, 120); XCTAssertTrue(result.basicCanStepOut) + result = try await stepOut(controller, source: source) + XCTAssertEqual(result.basicStoppedLine, 10); XCTAssertFalse(result.basicCanStepOut) + assertToken(result, source: source, token: "POKE") + let values = await inspect(controller, source: source) + XCTAssertEqual(BASICWatch("A")?.value(in: values.0 ?? []), "2") + let rejected = await command { controller.basicStepOut(source: source, completion: $0) } + XCTAssertNotNil(rejected.errorMessage); XCTAssertEqual(rejected.cycles, result.cycles) + } + } + func testBASICStepOutRecursionReturnsOneFrameAtATime() async throws { + try await withBASIC { controller in + let source = "10 N=3:GOSUB 100:END\n100 N=N-1\n110 IF N>0 THEN GOSUB 100\n120 N=N+1:RETURN\n" + _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [120], completion: $0) } + _ = try await waitForBASICStop(controller, line: 120) + _ = await command { controller.basicSetBreakpoints([], source: source, completion: $0) } + for expected in [1,2,3] { + let state = try await stepOut(controller, source: source) + XCTAssertEqual(state.basicStoppedLine, expected == 3 ? 10 : 120) + XCTAssertEqual(state.basicCanStepOut, expected != 3) + let values = await inspect(controller, source: source) + XCTAssertEqual(BASICWatch("N")?.value(in: values.0 ?? []), String(expected)) + } + } + } + func testBASICRuntimeErrorsCaptureActualROMCodeAndPreserveTraps() async throws { + try await withBASIC { controller in + for (statement, code) in [("A=1/0", "/0"), ("PRINT (", "SN"), ("READ A", "OD"), ("A=\"X\"", "TM"), ("OPEN \"I\",#1,\"MISSING\"", "NE")] { + let source = "10 A=1\n20 " + statement + "\n30 END\n" + let start = await command { controller.basicLoadSource(source, run: true, completion: $0) } + XCTAssertNil(start.errorMessage) + let failed = try await waitForBASICStop(controller, line: -1) + XCTAssertEqual(failed.programCounter, 0xac7c) + XCTAssertEqual(failed.basicErrorLine, 20); XCTAssertEqual(failed.basicErrorCode, code) + XCTAssertFalse(failed.basicCanStepOut); XCTAssertFalse(failed.basicStepping) + let text = await screen(controller) + XCTAssertTrue(text.contains(code + " ERROR"), text) + let continued = await command { controller.basicContinue(source: source, completion: $0) } + XCTAssertNil(continued.errorMessage) + try await settle(controller) + } + let source = "10 ON ERR GOTO 100\n20 A=1/0\n30 END\n100 A=42\n110 END\n" + _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [110], completion: $0) } + let caught = try await waitForBASICStop(controller, line: 110) + XCTAssertEqual(caught.basicErrorLine, -1); XCTAssertEqual(caught.basicErrorCode, "") + let values = await inspect(controller, source: source) + XCTAssertEqual(BASICWatch("A")?.value(in: values.0 ?? []), "42") + } + } + + func testBASICVariablesAndArraysMatchInterpreterWithoutMutation() async throws { + try await withBASIC { controller in + let source = "10 A=-1.5:ZERO=0:BIG=1E20:SMALL=1E-20\n20 NAME$=\"Mixed Case\":E$=\"\":B$=CHR$(0)+CHR$(255)\n30 DIM M(1,2),S$(2):M(0,1)=12:M(1,0)=21:M(1,2)=99:S$(2)=NAME$\n40 DEF FN F(X)=X+1\n50 A=A+1\n60 END\n" + _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10, 50], completion: $0) } + _ = try await waitForBASICStop(controller, line: 10) + let empty = await inspect(controller, source: source) + XCTAssertNil(empty.1.errorMessage); XCTAssertEqual(empty.0, []) + _ = await command { controller.basicContinue(source: source, completion: $0) } + let stopped = try await waitForBASICStop(controller, line: 50) + let before = await memory(controller) + let inspected = await inspect(controller, source: source) + XCTAssertNil(inspected.1.errorMessage) + let values = try XCTUnwrap(inspected.0) + func value(_ name: String) -> String? { BASICWatch(name)?.value(in: values) } + XCTAssertEqual(value("A"), "-1.5"); XCTAssertEqual(value("ZERO"), "0") + XCTAssertEqual(Double(try XCTUnwrap(value("BIG")))! / 1e20, 1, accuracy: 1e-9) + XCTAssertEqual(Double(try XCTUnwrap(value("SMALL")))! / 1e-20, 1, accuracy: 1e-9) + XCTAssertEqual(value("NAME$"), "\"Mixed Case\""); XCTAssertEqual(value("E$"), "\"\"") + XCTAssertEqual(value("B$"), "\"\\x00\\xFF\"") + XCTAssertEqual(value("M(0,1)"), "12"); XCTAssertEqual(value("M(1,0)"), "21") + XCTAssertEqual(value("M(1,2)"), "99"); XCTAssertEqual(value("M(0,0)"), "0") + XCTAssertEqual(value("S$(2)"), "\"Mixed Case\"") + XCTAssertEqual(value("UNSET"), "Not assigned") + XCTAssertEqual(value("Q(1)"), "Not dimensioned") + XCTAssertEqual(value("M(2,0)"), "Subscript out of range") + XCTAssertEqual(value("M(1)"), "Wrong number of subscripts") + XCTAssertTrue(values.contains { $0.kind == "Function" && $0.value.contains("not evaluated") }) + let array = try XCTUnwrap(values.first { $0.name == "M" && !$0.dimensions.isEmpty }) + XCTAssertEqual(array.dimensions, [2, 3]); XCTAssertEqual(array.elementName(5), "M(1,2)") + let after = await memory(controller) + XCTAssertEqual(before.logicalMemory, after.logicalMemory) + XCTAssertEqual(inspected.1.cycles, stopped.cycles) + assertExportPreservesSession(inspected.1, stopped) + let next = try await basicStep(controller, source: source) + XCTAssertEqual(next.basicStoppedLine, 60) + let changed = await inspect(controller, source: source) + XCTAssertEqual(BASICWatch("A")?.value(in: changed.0 ?? []), "-0.5") + _ = try await basicStep(controller, source: source) + let ended = await inspect(controller, source: source) + XCTAssertNil(ended.1.errorMessage, "Completed program retains inspectable values") + } + } + func testBASICInspectionRejectsStaleRunningAndInvalidTables() async throws { + try await withBASIC { controller in + let source = "10 A=1\n20 INPUT B\n30 END\n" + _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [20], completion: $0) } + let stopped = try await waitForBASICStop(controller, line: 20) + let stale = await inspect(controller, source: "10 A=2\n20 INPUT B\n30 END\n") + XCTAssertNil(stale.0); XCTAssertNotNil(stale.1.errorMessage); XCTAssertEqual(stale.1.cycles, stopped.cycles) + let original = [UInt8]((await memory(controller)).logicalMemory) + _ = await command { controller.debuggerWriteMemory(address: 0x1d, data: Data([0xff, 0xff]), completion: $0) } + let invalid = await inspect(controller, source: source) + XCTAssertNil(invalid.0); XCTAssertNotNil(invalid.1.errorMessage) + _ = await command { controller.debuggerWriteMemory(address: 0x1d, data: Data(original[0x1d...0x1e]), completion: $0) } + _ = await command { controller.basicContinue(source: source, completion: $0) } + let running = await inspect(controller, source: source) + XCTAssertNil(running.0); XCTAssertNotNil(running.1.errorMessage) + _ = await command(controller.pause) + let pausedMidStatement = await inspect(controller, source: source) + XCTAssertNil(pausedMidStatement.0); XCTAssertNotNil(pausedMidStatement.1.errorMessage) + } + } + private func assertToken(_ state: VCCMachineSnapshot, source: String, token: String, occurrence: Int = 0, + file: StaticString = #filePath, line: UInt = #line) { + let text = source as NSString + var search = NSRange(location: 0, length: text.length), range = NSRange(location: NSNotFound, length: 0) + for _ in 0...occurrence { + range = text.range(of: token, options: [], range: search) + guard range.location != NSNotFound else { XCTFail("Missing fixture token", file: file, line: line); return } + search = NSRange(location: NSMaxRange(range), length: text.length - NSMaxRange(range)) + } + XCTAssertEqual(state.basicSourceOffset, range.location, file: file, line: line) + XCTAssertGreaterThan(state.basicSourceLength, 0, file: file, line: line) + } + func testBASICStepColonStatementsAndForLoopWithExactSourceMapping() async throws { + try await withBASIC { controller in + let source = "30 POKE &H4001,I\r\n10 poke &H4000,1:POKE &H4000,2\r\n20 FOR I=1 TO 2\r\n40 NEXT I\r\n50 END\r\n" + _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } + let initial = try await waitForBASICStop(controller, line: 10) + assertToken(initial, source: source, token: "poke") + var stopped = try await basicStep(controller, source: source) + XCTAssertEqual(stopped.basicStoppedLine, 10) + assertToken(stopped, source: source, token: "POKE &H4000,2") + var bytes = [UInt8]((await memory(controller)).logicalMemory) + XCTAssertEqual(bytes[0x4000], 1) + stopped = try await basicStep(controller, source: source, over: true) + XCTAssertEqual(stopped.basicStoppedLine, 20) + assertToken(stopped, source: source, token: "FOR") + for expected in [30, 40, 30, 40, 50] { + stopped = try await basicStep(controller, source: source, over: true) + XCTAssertEqual(stopped.basicStoppedLine, expected, "FOR frames must not be treated as GOSUB frames") + } + bytes = [UInt8]((await memory(controller)).logicalMemory) + XCTAssertEqual(bytes[0x4000], 2); XCTAssertEqual(bytes[0x4001], 2) + stopped = try await basicStep(controller, source: source) + XCTAssertEqual(stopped.basicStoppedLine, -1) + XCTAssertTrue(stopped.basicDebugStatus.contains("OK prompt")) + XCTAssertEqual(stopped.generation, initial.generation) + XCTAssertEqual(stopped.debuggerProgramRevision, initial.debuggerProgramRevision) + } + } + func testBASICStepOverRecursiveAndOnGosub() async throws { + try await withBASIC { controller in + let source = "10 A=0:GOSUB 100:POKE &H4000,A\n20 ON 1 GOSUB 200:POKE &H4001,A\n30 END\n100 A=A+1\n110 IF A<3 THEN GOSUB 100\n120 RETURN\n200 A=A+10:RETURN\n" + _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } + _ = try await waitForBASICStop(controller, line: 10) + var stopped = try await basicStep(controller, source: source) + assertToken(stopped, source: source, token: "GOSUB") + stopped = try await basicStep(controller, source: source, over: true) + XCTAssertEqual(stopped.basicStoppedLine, 10) + assertToken(stopped, source: source, token: "POKE &H4000") + stopped = try await basicStep(controller, source: source) + XCTAssertEqual(stopped.basicStoppedLine, 20) + stopped = try await basicStep(controller, source: source, over: true) + XCTAssertEqual(stopped.basicStoppedLine, 20) + assertToken(stopped, source: source, token: "POKE &H4001") + _ = try await basicStep(controller, source: source) + let bytes = [UInt8]((await memory(controller)).logicalMemory) + XCTAssertEqual(bytes[0x4000], 3); XCTAssertEqual(bytes[0x4001], 13) + } + } + func testBASICStepIntoAndExplicitBreakpointInterruptsStepOver() async throws { + try await withBASIC { controller in + let source = "10 GOSUB 100:END\n100 A=1\n110 GOSUB 200\n120 RETURN\n200 A=2\n210 RETURN\n" + _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10, 200], completion: $0) } + _ = try await waitForBASICStop(controller, line: 10) + var stopped = try await basicStep(controller, source: source) + XCTAssertEqual(stopped.basicStoppedLine, 100) + stopped = try await basicStep(controller, source: source) + XCTAssertEqual(stopped.basicStoppedLine, 110) + stopped = try await basicStep(controller, source: source, over: true) + XCTAssertEqual(stopped.basicStoppedLine, 200, "Explicit breakpoints take precedence inside a stepped-over call") + stopped = try await basicStep(controller, source: source) + XCTAssertEqual(stopped.basicStoppedLine, 210) + stopped = try await basicStep(controller, source: source, over: true) + XCTAssertEqual(stopped.basicStoppedLine, 120) + } + } + func testBASICStepRejectsStaleSourceAndCancelsInputWait() async throws { + try await withBASIC { controller in + let source = "10 INPUT A\n20 END\n" + _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } + let stopped = try await waitForBASICStop(controller, line: 10) + let rejected = await command { controller.basicStep(source: "10 END\n", over: false, completion: $0) } + XCTAssertNotNil(rejected.errorMessage); XCTAssertEqual(rejected.cycles, stopped.cycles) + let started = await command { controller.basicStep(source: source, over: false, completion: $0) } + XCTAssertNil(started.errorMessage); XCTAssertTrue(started.basicStepping) + try await Task.sleep(nanoseconds: 150_000_000) + let paused = await command(controller.pause) + XCTAssertFalse(paused.basicStepping); XCTAssertEqual(paused.state, .paused) + XCTAssertEqual(paused.basicStoppedLine, -1); XCTAssertTrue(paused.basicDebugAttached) + let invalidStep = await command { controller.basicStep(source: source, over: true, completion: $0) } + XCTAssertNotNil(invalidStep.errorMessage) + let resumed = await command { controller.basicContinue(source: source, completion: $0) } + XCTAssertNil(resumed.errorMessage); XCTAssertEqual(resumed.state, .running) + XCTAssertFalse(resumed.basicStepping) + } + } + + func testBASICStepOverHasExecutionBoundAndPreservesManualBreakpoints() async throws { + try await withBASIC { controller in + let source = "10 GOSUB 100:END\n100 A=A+1:GOTO 100\n" + _ = await command { controller.debuggerSetBreakpoints([0xbfff], completion: $0) } + _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } + let before = try await waitForBASICStop(controller, line: 10) + _ = await command { controller.basicStep(source: source, over: true, completion: $0) } + var result = await command(controller.snapshot) + for _ in 0..<1400 { + result = await command(controller.snapshot) + if result.state == .paused { break } + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertEqual(result.state, .paused); XCTAssertFalse(result.basicStepping) + XCTAssertTrue(result.basicDebugStatus.contains("10 emulated seconds")) + XCTAssertGreaterThanOrEqual(result.frames - before.frames, 600) + XCTAssertEqual(result.generation, before.generation) + XCTAssertEqual(result.basicStoppedLine, -1) + let manual = await memory(controller) + XCTAssertEqual(manual.breakpoints, [NSNumber(value: 0xbfff)]) + let resumed = await command { controller.basicContinue(source: source, completion: $0) } + XCTAssertNil(resumed.errorMessage); XCTAssertEqual(resumed.state, .running) + } + } + func testBASICStepIfElseAndRuntimeErrorFinishAtPrompt() async throws { + try await withBASIC { controller in + let source = "10 IF 0 THEN POKE &H4000,9 ELSE POKE &H4000,3\n20 A=1/0\n30 END\n" + _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } + _ = try await waitForBASICStop(controller, line: 10) + var stopped = try await basicStep(controller, source: source) + XCTAssertEqual(stopped.basicStoppedLine, 10) + assertToken(stopped, source: source, token: "POKE &H4000,3") + stopped = try await basicStep(controller, source: source) + XCTAssertEqual(stopped.basicStoppedLine, 20) + let mem = await memory(controller) + XCTAssertEqual([UInt8](mem.logicalMemory)[0x4000], 3) + stopped = try await basicStep(controller, source: source) + XCTAssertEqual(stopped.basicStoppedLine, -1) + XCTAssertTrue(stopped.basicDebugStatus.contains("OK prompt")) + let output = await screen(controller) + XCTAssertTrue(output.contains("/0 ERROR IN 20")) + } + } + + func testBASICBreakpointsSurviveVideoPageSwitches() async throws { + try await withBASIC { controller in + let source = "10 WIDTH 40\n20 FOR I=1 TO 8:CLS:NEXT I\n30 PRINT \"READY\"\n40 END\n" + let started = await command { controller.basicLoadSource(source, run: true, breakpoints: [30], completion: $0) } + XCTAssertNil(started.errorMessage) + let stopped = try await waitForBASICStop(controller, line: 30) + XCTAssertTrue(stopped.basicDebugAttached) + let before = await screen(controller) + XCTAssertFalse(before.contains("READY")) + let resumed = await command { controller.basicContinue(source: source, completion: $0) } + XCTAssertNil(resumed.errorMessage) + try await waitForScreen("READY", controller: controller) + } + } + + func testBASICStepStopsIfProgramModifiesItsOwnTokens() async throws { + try await withBASIC { controller in + let source = "10 POKE PEEK(25)*256+PEEK(26)+4,138\n20 END\n" + _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } + _ = try await waitForBASICStop(controller, line: 10) + let stopped = try await basicStep(controller, source: source) + XCTAssertFalse(stopped.basicDebugAttached); XCTAssertFalse(stopped.basicStepping) + XCTAssertEqual(stopped.basicStoppedLine, -1); XCTAssertEqual(stopped.basicSourceOffset, -1) + XCTAssertTrue(stopped.basicDebugStatus.contains("changed")) + let rejected = await command { controller.basicContinue(source: source, completion: $0) } + XCTAssertNotNil(rejected.errorMessage) + } + } + + /// Scanlines from the same 640x480 buffer passed to Metal. The stock BASIC + /// text mode has sixteen 32-character rows in its 512x384 active picture. + private func basicPixelRows(_ snapshot: VCCMachineSnapshot) throws -> [Data] { + let capture = try ScreenCapture(pixels: snapshot.pixels, area: snapshot.activeVideoRect) + let area = capture.area + guard area.size == CGSize(width: 512, height: 384) else { + XCTFail("Expected the stock BASIC active picture, got \(area)") + throw Failure.invalidMemory + } + return (0..<16).map { row in + var pixels = Data() + let y = Int(area.minY) + row * 24 + for scanline in y..<(y + 24) { + let start = (scanline * 640 + Int(area.minX)) * 4 + pixels.append(capture.pixels[start..<(start + 512 * 4)]) + } + return pixels + } + } + + func testBASICSamplePresentsCurrentPixelsAtEveryLine40Breakpoint() async throws { + try await assertBASICSamplePixels(line: 40, nextStatement: "PRINT \"COUNT\"", countsShown: 0...4, frameInterval: 1) + } + + func testBASICSamplePresentsCurrentPixelsAtEveryLine50Breakpoint() async throws { + try await assertBASICSamplePixels(line: 50, nextStatement: "NEXT I", countsShown: 1...5, frameInterval: 6) + } + + private func assertBASICSamplePixels(line: Int, nextStatement: String, countsShown: ClosedRange, + frameInterval: Int) async throws { + try await withBASIC { controller in + let source = "10 CLS\n20 PRINT \"HELLO FROM VCC PLUS\"\n30 FOR I=1 TO 5\n40 PRINT \"COUNT\";I\n50 NEXT I\n60 END\n" + let output = ["HELLO FROM VCC PLUS"] + (1...5).map { "COUNT \($0)" } + let initial = await command(controller.snapshot) + let configured = await command { + controller.configureMachine(use6309: initial.use6309, ram: Int(initial.ramConfiguration), + overclock: Int(initial.cpuOverclock), frameInterval: frameInterval, + fastForward: initial.fastForward, completion: $0) + } + XCTAssertNil(configured.errorMessage) + XCTAssertEqual(configured.generation, initial.generation) + XCTAssertEqual(Int(configured.frameInterval), frameInterval) + var previousRevision = configured.pixelRevision + var stops: [VCCMachineSnapshot] = [] + let started = await command { controller.basicLoadSource(source, run: true, breakpoints: [NSNumber(value: line)], completion: $0) } + XCTAssertNil(started.errorMessage) + for (i, count) in zip(1...5, countsShown) { + let stop = try await waitForBASICStop(controller, line: line) + let context = "\(stop.use6309 ? "6309" : "6809"), stopped before \(nextStatement) with I=\(i)" + assertToken(stop, source: source, token: nextStatement) + let values = await inspect(controller, source: source) + XCTAssertNil(values.1.errorMessage, context) + XCTAssertEqual(BASICWatch("I")?.value(in: values.0 ?? []), String(i), context) + let text = await screen(controller) + XCTAssertEqual(text.split(separator: "\n").map(String.init), Array(output.prefix(1 + count)), context) + XCTAssertGreaterThan(stop.pixelRevision, previousRevision, context) + let reread = await command(controller.snapshot) + XCTAssertEqual(reread.pixelRevision, stop.pixelRevision, context) + XCTAssertEqual(reread.cycles, stop.cycles, context) + XCTAssertEqual(reread.frames, stop.frames, context) + stops.append(stop) + previousRevision = stop.pixelRevision + let resumed = await command { controller.basicContinue(source: source, completion: $0) } + XCTAssertNil(resumed.errorMessage, context) + } + + // Let ordinary raster timing draw all five counts. Its distinct + // glyph rows and a known empty row are the pixel references for + // the earlier stops, independent of the paused presentation path. + try await waitForScreen("OK", controller: controller) + try await settle(controller) + let finalText = await screen(controller) + XCTAssertEqual(Array(finalText.split(separator: "\n").map(String.init).prefix(6)), output) + let final = await command(controller.snapshot) + let reference = try basicPixelRows(final) + let blank = reference[15] + XCTAssertEqual(Set(reference.prefix(6) + [blank]).count, 7, "The running raster must distinguish every expected text row and blank") + for (stop, count) in zip(stops, countsShown) { + XCTAssertEqual(stop.activeVideoRect, final.activeVideoRect) + let rows = try basicPixelRows(stop) + for row in rows.indices { + let printed = row <= count + let expected = printed ? reference[row] : blank + XCTAssertTrue(rows[row] == expected, + "\(stop.use6309 ? "6309" : "6809"), before \(nextStatement), \(count) counts printed, raster row \(row + 1) should show \(printed ? output[row] : "a blank line")") + } + } + } + } + + func testBASICBreakpointsStopBeforeLineAndContinueLoopWithoutReset() async throws { + try await withBASIC { controller in + let source = "10 POKE &H4000,1\n20 POKE &H4000,2\n30 GOTO 20\n" + let before = await command(controller.snapshot) + let started = await command { controller.basicLoadSource(source, run: true, breakpoints: [20], completion: $0) } + XCTAssertNil(started.errorMessage) + let stopped = try await waitForBASICStop(controller, line: 20) + XCTAssertTrue(stopped.basicDebugAttached) + XCTAssertEqual(stopped.generation, before.generation) + XCTAssertEqual(stopped.disks[0].name, before.disks[0].name) + XCTAssertEqual(stopped.tapeLength, before.tapeLength) + let first = await memory(controller) + XCTAssertEqual([UInt8](first.logicalMemory)[0x4000], 1, "Breakpoint precedes the line's side effects") + XCTAssertFalse(first.breakpoints.contains(NSNumber(value: 0xadc6)), "BASIC hooks must not become manual CPU breakpoints") + let resumed = await command { controller.basicContinue(source: source, completion: $0) } + XCTAssertNil(resumed.errorMessage) + let again = try await waitForBASICStop(controller, line: 20) + XCTAssertGreaterThan(again.cycles, stopped.cycles) + let second = await memory(controller) + XCTAssertEqual([UInt8](second.logicalMemory)[0x4000], 2) + XCTAssertEqual(again.debuggerProgramRevision, stopped.debuggerProgramRevision) + let cleared = await command { controller.basicSetBreakpoints([], source: source, completion: $0) } + XCTAssertNil(cleared.errorMessage) + let continued = await command { controller.basicContinue(source: source, completion: $0) } + XCTAssertNil(continued.errorMessage) + try await settle(controller, frames: 5) + let running = await command(controller.snapshot) + XCTAssertEqual(running.state, .running) + XCTAssertEqual(running.basicStoppedLine, -1) + } + } + func testBASICContinuePreservesSubroutineStackVariablesAndManualBreakpoints() async throws { + try await withBASIC { controller in + let source = "10 A=1\n20 GOSUB 100\n30 POKE &H4000,A\n40 END\n100 A=A+1:POKE &H4001,A\n110 RETURN\n" + _ = await command { controller.debuggerSetBreakpoints([0xbfff], completion: $0) } + let loaded = await command { controller.basicLoadSource(source, run: true, breakpoints: [30, 100], completion: $0) } + XCTAssertNil(loaded.errorMessage) + _ = try await waitForBASICStop(controller, line: 100) + let before = await memory(controller) + XCTAssertTrue(before.breakpoints.contains(NSNumber(value: 0xbfff))) + let continued = await command { controller.basicContinue(source: source, completion: $0) } + XCTAssertNil(continued.errorMessage) + _ = try await waitForBASICStop(controller, line: 30) + let returned = await memory(controller) + XCTAssertEqual([UInt8](returned.logicalMemory)[0x4001], 2, "Colon statement executes without a second line-entry stop") + let resumed = await command { controller.basicContinue(source: source, completion: $0) } + XCTAssertNil(resumed.errorMessage) + try await settle(controller, frames: 5) + let result = await memory(controller) + XCTAssertEqual([UInt8](result.logicalMemory)[0x4000], 2, "Variables and the GOSUB return stack survive Continue") + XCTAssertTrue(result.breakpoints.contains(NSNumber(value: 0xbfff))) + // Explicitly redirecting the CPU must not retain a stale BASIC stop. + _ = await command(controller.pause) + _ = await command { controller.debuggerSetPC(0xa000, completion: $0) } + let detached = await command(controller.snapshot) + XCTAssertFalse(detached.basicDebugAttached) + } + } + func testBASICDebugRejectsStaleSourceAndDetachesAfterMemoryEditOrReset() async throws { + try await withBASIC { controller in + let source = "10 POKE &H4000,1\n20 GOTO 10\n" + let previous = try await programBytes(controller) + let refused = await command { controller.basicLoadSource(source, run: true, breakpoints: [999], completion: $0) } + XCTAssertNotNil(refused.errorMessage) + let unchanged = try await programBytes(controller); XCTAssertEqual(unchanged, previous) + _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } + let stopped = try await waitForBASICStop(controller, line: 10) + let rejected = await command { controller.basicContinue(source: "10 END\n", completion: $0) } + XCTAssertNotNil(rejected.errorMessage) + XCTAssertEqual(rejected.state, .paused); XCTAssertEqual(rejected.cycles, stopped.cycles) + let capture = await memory(controller), bytes = [UInt8](capture.logicalMemory) + let start = UInt16(bytes[0x19]) * 256 + UInt16(bytes[0x1a]) + _ = await command { controller.debuggerWriteMemory(address: start + 4, data: Data([0x80]), completion: $0) } + let edited = await command(controller.snapshot) + XCTAssertFalse(edited.basicDebugAttached); XCTAssertEqual(edited.basicStoppedLine, -1) + XCTAssertTrue(edited.basicDebugStatus.contains("changed")) + _ = await command(controller.softReset) + let reset = await command(controller.snapshot) + XCTAssertFalse(reset.basicDebugAttached); XCTAssertEqual(reset.basicStoppedLine, -1) + } + } + func testDirectLoadReadAndRunPreserveMachineAndMediaOnBothProcessors() async throws { + try await withBASIC { controller in + _ = await command(controller.pause) + let before = await command(controller.snapshot) + let loaded = await command { controller.basicLoadSource("10 PRINT 6*7\n20 END\n", run: false, completion: $0) } + XCTAssertNil(loaded.errorMessage) + XCTAssertEqual(loaded.state, .paused, "Loading while paused must not execute guest instructions") + XCTAssertEqual(loaded.cycles, before.cycles) + XCTAssertEqual(loaded.generation, before.generation) + XCTAssertEqual(loaded.pasteRemaining, 0, "Direct BASIC loading must not enqueue keyboard input") + let (source, error) = await read(controller) + XCTAssertNil(error); XCTAssertTrue(source?.contains("10 PRINT 6*7") == true) + XCTAssertTrue(source?.contains("20 END") == true) + let running = await command { controller.basicLoadSource("10 PRINT 6*7\n20 END\n", run: true, completion: $0) } + XCTAssertNil(running.errorMessage); XCTAssertEqual(running.state, .running) + XCTAssertEqual(running.pasteRemaining, 0) + try await waitForScreen("42", controller: controller) + try await settle(controller) + let after = await command(controller.snapshot) + XCTAssertEqual(after.generation, before.generation) + XCTAssertEqual(after.use6309, before.use6309) + XCTAssertEqual(after.ramConfiguration, before.ramConfiguration) + XCTAssertEqual(after.audioEnabled, before.audioEnabled) + XCTAssertTrue(after.disks[0].mounted); XCTAssertFalse(after.disks[0].dirty) + XCTAssertEqual(after.disks[0].name, "Preserved.dsk") + XCTAssertTrue(after.disks[0].writeProtected) + XCTAssertTrue(after.tapeMounted); XCTAssertFalse(after.tapeDirty) + XCTAssertEqual(after.tapeMode, before.tapeMode) + } + } + func testRejectedSourceLeavesThePreviousProgramIntactOnBothProcessors() async throws { + try await withBASIC { controller in + let loaded = await command { controller.basicLoadSource("10 PRINT 42\n", run: false, completion: $0) } + XCTAssertNil(loaded.errorMessage) + let original = try await programBytes(controller) + let oversized = (1...500).map { "\($0) REM " + String(repeating: "X", count: 120) }.joined(separator: "\n") + for source in ["PRINT 42\n", "64000 PRINT 42\n", "10 PRINT \u{0000}\n", oversized] { + let failed = await command { controller.basicLoadSource(source, run: false, completion: $0) } + XCTAssertNotNil(failed.errorMessage) + XCTAssertEqual(failed.generation, loaded.generation) + let preserved = try await programBytes(controller) + XCTAssertEqual(preserved, original, "Validation must precede RAM replacement") + } + } + } + func testDirectTokenizationMatchesActualROMEntryOnBothProcessors() async throws { + try await withBASIC { controller in + // This source is intentionally entered through the original ROM first. + // No handcrafted token table supplies the expected output. + let source = """ + 10 REM PRINT "KEEP":DATA + 20 DATA "PRINT:REM",12:PRINT "A:B"; + 30 ? LEFT$("ABC",1):IF 1 THEN 50 ELSE 40 + 40 'PRINT SIN(1) + 50 HSCREEN 0:DIR + """ + "\n" + let paste = try CocoPaste(source, mode: .newBASIC) + let started = await command { controller.pasteChords(paste.chords.map { NSNumber(value: $0) }, completion: $0) } + XCTAssertNil(started.errorMessage) + var finished = false + for _ in 0..<2500 { + if await command(controller.snapshot).pasteRemaining == 0 { finished = true; break } + try await Task.sleep(nanoseconds: 20_000_000) + } + XCTAssertTrue(finished) + try await settle(controller) + let expected = try await programBytes(controller) + XCTAssertGreaterThan(expected.count, 20) + let loaded = await command { controller.basicLoadSource(source, run: false, completion: $0) } + XCTAssertNil(loaded.errorMessage) + let installed = try await programBytes(controller) + XCTAssertEqual(installed, expected) + let (roundTrip, error) = await read(controller) + XCTAssertNil(error) + let second = await command { controller.basicLoadSource(roundTrip ?? "", run: false, completion: $0) } + XCTAssertNil(second.errorMessage) + let reloaded = try await programBytes(controller) + XCTAssertEqual(reloaded, expected, "Read-back must remain a lossless source representation") + } + } + func testExecutingAndInputProgramsCannotBeReplacedOnBothProcessors() async throws { + try await withBASIC { controller in + for source in ["10 GOTO 10\n", "10 INPUT \"VALUE\";A\n20 GOTO 10\n"] { + let started = await command { controller.basicLoadSource(source, run: true, completion: $0) } + XCTAssertNil(started.errorMessage) + try await settle(controller) + let original = try await programBytes(controller) + let refused = await command { controller.basicLoadSource("10 PRINT 99\n", run: false, completion: $0) } + XCTAssertNotNil(refused.errorMessage, "Running BASIC and INPUT are not the direct-mode prompt") + let after = try await programBytes(controller) + XCTAssertEqual(after, original) + XCTAssertEqual(refused.generation, started.generation) + _ = await command(controller.softReset) + _ = await command(controller.resume) + try await settle(controller, frames: 60) + } + } + } + func testDiskAndCassetteExportPreservePausedAndRunningSessionsOnBothProcessors() async throws { + try await withBASIC { controller in + _ = await command(controller.pause) + let loaded = await command { controller.basicLoadSource("10 GOTO 10\n", run: false, completion: $0) } + XCTAssertNil(loaded.errorMessage) + let original = await memory(controller) + let source = "10 PRINT \"EXPORTED, NOT LOADED\"\n20 END\n" + var payloads: [Bool: Data] = [:] + for cassette in [false, true] { + let (bytes, after) = await export(controller, source: source, name: "hello", cassette: cassette) + XCTAssertNil(after.errorMessage) + let payload = try XCTUnwrap(bytes) + if cassette { XCTAssertGreaterThan(payload.count, 256) } + else { XCTAssertEqual(payload.count, 35 * 18 * 256) } + payloads[cassette] = payload + assertExportPreservesSession(after, loaded) + XCTAssertEqual(after.cycles, loaded.cycles) + let afterMemory = await memory(controller) + XCTAssertEqual(afterMemory.logicalMemory, original.logicalMemory) + XCTAssertEqual(afterMemory.registers, original.registers) + } + let running = await command { controller.basicLoadSource("10 GOTO 10\n", run: true, completion: $0) } + XCTAssertNil(running.errorMessage) + try await settle(controller) + let originalProgram = try await programBytes(controller) + for cassette in [false, true] { + let before = await command(controller.snapshot) + let (bytes, after) = await export(controller, source: source, cassette: cassette) + XCTAssertNil(after.errorMessage) + XCTAssertEqual(bytes, payloads[cassette], "Export bytes are independent of the running program and filename case") + assertExportPreservesSession(after, before) + let afterProgram = try await programBytes(controller) + XCTAssertEqual(afterProgram, originalProgram) + } + } + } + func testInvalidExportLeavesProgramAndMountedMediaUntouchedOnBothProcessors() async throws { + try await withBASIC { controller in + _ = await command(controller.pause) + let before = await command { controller.basicLoadSource("10 PRINT 42\n", run: false, completion: $0) } + XCTAssertNil(before.errorMessage) + let original = await memory(controller) + for cassette in [false, true] { + let cases = [("PRINT 42\n", "HELLO"), ("10 PRINT 42\n", ""), + ("10 PRINT 42\n", "../BAD"), ("10 PRINT 42\n", "TOOLONG99"), + ("10 PRINT 42\n", "BAD.BAS"), ("10 PRINT 42\n", "HÉLLO")] + for (source, name) in cases { + let (bytes, failed) = await export(controller, source: source, name: name, cassette: cassette) + XCTAssertNil(bytes) + XCTAssertNotNil(failed.errorMessage) + assertExportPreservesSession(failed, before) + XCTAssertEqual(failed.cycles, before.cycles) + } + } + let after = await memory(controller) + XCTAssertEqual(after.logicalMemory, original.logicalMemory) + XCTAssertEqual(after.registers, original.registers) + } + } + func testUnsupportedMachineDoesNotAcceptDirectBASICMemoryWrites() async throws { + let controller = VCCMachineController() + let empty = await command { controller.basicLoadSource("10 PRINT 42\n", run: true, completion: $0) } + XCTAssertNotNil(empty.errorMessage) + let loaded = await command(controller.loadDiagnostic) + let before = await memory(controller) + let rejected = await command { controller.basicLoadSource("10 PRINT 42\n", run: true, completion: $0) } + XCTAssertNotNil(rejected.errorMessage) + XCTAssertEqual(rejected.generation, loaded.generation) + XCTAssertEqual(rejected.state, loaded.state) + let after = await memory(controller) + XCTAssertEqual(after.logicalMemory, before.logicalMemory) + let (source, error) = await read(controller) + XCTAssertNil(source); XCTAssertNotNil(error) + for cassette in [false, true] { + let (bytes, refused) = await export(controller, source: "10 PRINT 42\n", cassette: cassette) + XCTAssertNil(bytes); XCTAssertNotNil(refused.errorMessage) + assertExportPreservesSession(refused, rejected) + } + // A valid CPU ROM is not necessarily a recognized BASIC interpreter. + var synthetic = Data(repeating: 0x12, count: 32768) + synthetic[0] = 0x20; synthetic[1] = 0xfe + synthetic[32766] = 0x80; synthetic[32767] = 0 + let otherROM = await command { controller.loadROM(synthetic, use6309: false, completion: $0) } + XCTAssertNil(otherROM.errorMessage) + let customBefore = await memory(controller) + let customRejected = await command { controller.basicLoadSource("10 PRINT 42\n", run: true, completion: $0) } + XCTAssertNotNil(customRejected.errorMessage) + let customAfter = await memory(controller) + XCTAssertEqual(customAfter.logicalMemory, customBefore.logicalMemory) + XCTAssertEqual(customRejected.generation, otherROM.generation) + let (customSource, customError) = await read(controller) + XCTAssertNil(customSource); XCTAssertNotNil(customError) + _ = await command(controller.shutdown) + } +} diff --git a/platforms/macos/Tests/BASICReferenceTests.swift b/platforms/macos/Tests/BASICReferenceTests.swift new file mode 100644 index 0000000..7d56179 --- /dev/null +++ b/platforms/macos/Tests/BASICReferenceTests.swift @@ -0,0 +1,562 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import XCTest +import WebKit + +// Content qualification may skip only an explicitly declared lookup edition. +// Missing or malformed manifests remain test failures, never silent skips. +enum TestBuildContent { + struct Manifest: Decodable { + let schemaVersion: Int + let profile: String + let manuals: String + } + + static func read(resources: URL) throws -> Manifest { + let bytes = try Data(contentsOf: resources.appendingPathComponent("BuildContent.json")) + let value = try JSONDecoder().decode(Manifest.self, from: bytes) + guard value.schemaVersion == 1, + (value.profile == "normal" && value.manuals == "full") || + (value.profile == "source" && value.manuals == "lookup") else { + throw CocoaError(.fileReadCorruptFile) + } + return value + } + + static func requireFullManuals(resources: URL) throws { + if try read(resources: resources).manuals == "lookup" { + throw XCTSkip("This content profile includes BASIC and Assembly lookup; full-manual qualification is omitted.") + } + } +} + +final class BASICReferenceTests: XCTestCase { + private func requireFullManualEdition() throws { + let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) + let resources = try XCTUnwrap(app.resourceURL) + try TestBuildContent.requireFullManuals(resources: resources) + } + + func testContentQualificationRequiresAValidExplicitManifest() throws { + let resources = FileManager.default.temporaryDirectory.appendingPathComponent("VCCContentManifest-" + UUID().uuidString) + try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: resources) } + let manifest = resources.appendingPathComponent("BuildContent.json") + XCTAssertThrowsError(try TestBuildContent.read(resources: resources), "Missing content metadata is a failure") + for (profile, manuals) in [("normal", "full"), ("source", "lookup")] { + let bytes = try JSONSerialization.data(withJSONObject: ["schemaVersion": 1, "profile": profile, "manuals": manuals]) + try bytes.write(to: manifest) + XCTAssertEqual(try TestBuildContent.read(resources: resources).manuals, manuals) + } + for invalid in ["{}", "not json", "{\"schemaVersion\":true,\"profile\":\"source\",\"manuals\":\"lookup\"}", + "{\"schemaVersion\":2,\"profile\":\"source\",\"manuals\":\"lookup\"}", + "{\"schemaVersion\":1,\"profile\":\"normal\",\"manuals\":\"lookup\"}"] { + try Data(invalid.utf8).write(to: manifest) + XCTAssertThrowsError(try TestBuildContent.read(resources: resources), invalid) + } + } + + func testBASICAndAssemblyLookupTopicsAreReadableThroughTheNativeMCPIndex() async throws { + let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) + let resources = try XCTUnwrap(app.resourceURL) + _ = try TestBuildContent.read(resources: resources) + let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) + let index = MCPHelpIndex(root: root) + for (query, prefix) in [("PRINT", "programming-in-coco-basic/"), ("LDA", "assembly-language-programming/"), + ("BHS", "assembly-language-programming/"), ("LBHS", "assembly-language-programming/")] { + let hits = try await index.search(query) + let hit = try XCTUnwrap(hits.first { $0.id.hasPrefix(prefix) }, query) + let topic = try await index.read(hit.id) + XCTAssertFalse(try XCTUnwrap(topic).text.isEmpty) + } + } + + func testPackagedCollectionsRemainReadableForSelectedContentProfile() async throws { + let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) + let resources = try XCTUnwrap(app.resourceURL) + let content = try TestBuildContent.read(resources: resources) + let catalog = try await SoftwareLibraryCatalog.load(from: resources.appendingPathComponent("SoftwareLibrary/catalog.sqlite")) + if content.profile == "source" { + XCTAssertTrue(catalog.titles.isEmpty) + XCTAssertEqual(catalog.releaseCount, 0) + } + let archiveURL = app.url(forResource: "ArchiveLibrary", withExtension: "sqlite", subdirectory: "ArchiveLibrary") + // Normal source checkouts can deliberately omit the optional index. + if archiveURL == nil && content.profile == "normal" { return } + let archive = ArchiveLibraryCatalog(url: try XCTUnwrap(archiveURL)) + let collections = try await archive.collections() + let documents = try await archive.browse(collection: nil, limit: 10, offset: 0) + let matches = try await archive.search(query: "PRINT", collection: nil, limit: 10, offset: 0) + if content.profile == "source" { + XCTAssertTrue(collections.isEmpty) + XCTAssertTrue(documents.isEmpty) + XCTAssertTrue(matches.isEmpty) + } + } + + func testManualExamplesResolveOnlyInsideTheBook() throws { + let files = FileManager.default + let temporary = files.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? files.removeItem(at: temporary) } + let root = temporary.appendingPathComponent("ManualLibrary") + let examples = root.appendingPathComponent("first-book/examples") + try files.createDirectory(at: examples, withIntermediateDirectories: true) + let signal = examples.appendingPathComponent("SIGNAL.bas") + try Data("10 END".utf8).write(to: signal) + let content = ManualLibraryContent(root: root) + XCTAssertEqual(content.relativePath(for: signal), "first-book/examples/SIGNAL.bas") + XCTAssertEqual(content.exampleURL(for: "first-book/examples/SIGNAL.bas"), signal.resolvingSymlinksInPath()) + + let outside = temporary.appendingPathComponent("personal.bas") + try Data().write(to: outside) + try files.createSymbolicLink(at: examples.appendingPathComponent("outside.bas"), withDestinationURL: outside) + XCTAssertNil(content.exampleURL(for: "first-book/examples/outside.bas")) + XCTAssertNil(content.exampleURL(for: "first-book/examples/../../../personal.bas")) + XCTAssertNil(content.exampleURL(for: "first-book/examples/missing.bas")) + XCTAssertNil(content.relativePath(for: outside)) + } + + func testPackagedDevelopmentExamplesOfferCopiesAndDoNotUseTheBASICEditor() throws { + try requireFullManualEdition() + let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) + let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) + let content = ManualLibraryContent(root: root) + let assembly = "your-first-6809-programs/examples/byte.asm" + XCTAssertEqual(content.copyTitle(for: assembly), "Save Assembly Example") + XCTAssertNil(content.exampleURL(for: assembly)) + let source = "programming-in-c/examples/cargo.c" + XCTAssertEqual(content.copyTitle(for: source), "Save C Example") + XCTAssertNil(content.exampleURL(for: source)) + XCTAssertEqual(content.copyTitle(for: "programming-in-c/examples/HelloDisk.zip"), "Save Example Project") + let advanced = "assembly-language-programming/examples/" + XCTAssertEqual(content.copyTitle(for: advanced + "bankwalk.asm"), "Save Assembly Example") + XCTAssertEqual(content.copyTitle(for: advanced + "Dispatch.zip"), "Save Example Project") + XCTAssertNil(content.exampleURL(for: advanced + "Dispatch.zip")) + let os9 = "working-with-os9/examples/" + XCTAssertEqual(content.copyTitle(for: os9 + "beacon.a"), "Save Assembly Example") + XCTAssertEqual(content.copyTitle(for: os9 + "night.b09"), "Save BASIC09 Example") + XCTAssertEqual(content.copyTitle(for: os9 + "watch.c"), "Save C Example") + XCTAssertNil(content.exampleURL(for: os9 + "night.b09")) + let hardware = "inside-the-coco-3/examples/" + XCTAssertEqual(content.copyTitle(for: hardware + "pixel-mask.asm"), "Save Assembly Example") + XCTAssertNotNil(content.exampleURL(for: hardware + "BEACON.bas")) + XCTAssertNil(content.copyTitle(for: "programming-in-c/examples/missing.c")) + XCTAssertNil(content.copyTitle(for: "programming-in-c/examples/../book-index.js")) + XCTAssertNil(content.copyTitle(for: "meet-your-color-computer/examples/SIGNAL.bas")) + let starter = "vibe-coding-with-chatgpt/examples/" + XCTAssertEqual(content.copyTitle(for: starter + "ProjectStarter.zip"), "Save Example Project") + XCTAssertEqual(content.copyTitle(for: starter + "PROJECT_SETUP_PREAMBLE.txt"), "Save Example Text") + XCTAssertNil(content.exampleURL(for: starter + "PROJECT_SETUP_PREAMBLE.txt")) + let reference = "toolchain-reference/sources/" + XCTAssertEqual(content.copyTitle(for: reference + "cmoc-manual.markdown"), "Save Original Manual Source") + XCTAssertEqual(content.copyTitle(for: reference + "lwtools-manual.docbook.sgml"), "Save Original Manual Source") + XCTAssertNil(content.copyTitle(for: reference + "lwtools-manual.pdf"), "PDFs remain readable in the library") + for help in ["cmoc-help.txt", "lwasm-help.txt", "lwlink-help.txt"] { + XCTAssertEqual(content.copyTitle(for: reference + help), "Save Command-Line Help") + } + XCTAssertTrue(content.allowsExternalReference(URL(string: "http://sarrazip.com/dev/cmoc.html")!)) + XCTAssertTrue(content.allowsExternalReference(URL(string: "https://learn.chatgpt.com/docs/extend/mcp?surface=cli")!)) + XCTAssertFalse(content.allowsExternalReference(URL(string: "https://example.com/unlisted")!)) + XCTAssertFalse(content.allowsExternalReference(URL(fileURLWithPath: "/tmp/private.txt"))) + } + + func testOriginalToolReferencesAreReadableThroughTheNativeMCPIndex() async throws { + try requireFullManualEdition() + let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) + let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) + let index = MCPHelpIndex(root: root) + for query in ["CMOC --initial-s", "LWASM --project-map", "LWLINK --sysroot"] { + let hits = try await index.search(query) + let hit = try XCTUnwrap(hits.first { $0.id.hasPrefix("toolchain-reference/") }, query) + let read = try await index.read(hit.id) + XCTAssertFalse(try XCTUnwrap(read).text.isEmpty) + } + let source = try String(contentsOf: root.appendingPathComponent("toolchain-reference/book-index.js"), encoding: .utf8) + let payload = source.dropFirst("(globalThis.manualBooks ??= []).push(".count).dropLast(3) + let record = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(payload.utf8)) as? [String: Any]) + for chapter in try XCTUnwrap(record["chapters"] as? [[String: Any]]) { + let page = try XCTUnwrap(chapter["page"] as? String) + for topic in try XCTUnwrap(chapter["sections"] as? [[String: Any]]) { + let id = try XCTUnwrap(topic["id"] as? String) + let read = try await index.read("toolchain-reference/\(page)#\(id)") + XCTAssertLessThanOrEqual(try XCTUnwrap(read).text.utf8.count, 12 * 1024, + "Every original-manual section must fit a complete read_topic response") + } + } + } + + func testEveryBASICQuickReferenceTopicHasItsOwnBundledManualAnchor() throws { + let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) + let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) + let content = ManualLibraryContent(root: root) + let catalog = try BASICReferenceCatalog.bundled.get() + var pages: [String: String] = [:] + var links = Set() + for entry in catalog.entries { + let url = try XCTUnwrap(content.basicTopicURL(for: entry)) + let page = try XCTUnwrap(content.relativePath(for: url), entry.id) + let anchor = try XCTUnwrap(url.fragment, entry.id) + if pages[page] == nil { + pages[page] = try String(contentsOf: root.appendingPathComponent(page), encoding: .utf8) + } + XCTAssertTrue(links.insert(url).inserted, "Duplicate link for " + entry.id) + XCTAssertTrue(pages[page]?.contains("id=\"\(anchor)\"") == true, entry.id) + } + } + + @MainActor + func testHandbookKeyboardModeLabelsFitAtCompactAndDesktopWidths() async throws { + try requireFullManualEdition() + let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) + let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) + let page = root.appendingPathComponent("users-handbook/keyboard.html") + for width in [320, 1024] { + let reader = ManualReader(content: ManualLibraryContent(root: root)) + reader.webView.frame = CGRect(x: 0, y: 0, width: width, height: 800) + reader.webView.loadFileURL(page, allowingReadAccessTo: root) + let deadline = ContinuousClock.now + .seconds(8) + while reader.webView.url != page || reader.webView.isLoading { + guard ContinuousClock.now < deadline else { + return XCTFail("Keyboard chapter did not load") + } + try await Task.sleep(for: .milliseconds(40)) + } + let measurements = try await reader.webView.evaluateJavaScript(""" + (() => { + const rows = document.querySelectorAll('#keyboard-modes tr'); + const lines = Array.from(rows, row => { + const range = document.createRange(); + range.selectNodeContents(row.cells[0].querySelector('strong') || row.cells[0]); + return new Set(Array.from(range.getClientRects(), rect => rect.top)).size; + }); + return [innerWidth, document.documentElement.scrollWidth, ...lines]; + })() + """) + XCTAssertEqual(measurements as? [Int], [width, width, 1, 1, 1, 1], + "The page should fit and each of its four mode labels should occupy one line") + } + } + + @MainActor + func testKeywordSearchUsesAllBundledBooksAndOpensLiteralCommand() async throws { + try requireFullManualEdition() + let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) + let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) + let reader = ManualReader(content: ManualLibraryContent(root: root)) + let web = reader.webView + reader.showLibrarySearch() + let limit = ContinuousClock.now + .seconds(10) + while web.isLoading || web.url == nil { + guard ContinuousClock.now < limit else { return XCTFail("The manual shelf did not load") } + try await Task.sleep(for: .milliseconds(30)) + } + let indexed = try await web.evaluateJavaScript("globalThis.manualBooks.map(book => book.book)") + let shelved = try await web.evaluateJavaScript("Array.from(document.querySelectorAll('.shelf-catalog dt a'), link => link.textContent)") + XCTAssertEqual(try XCTUnwrap(indexed as? [String]), try XCTUnwrap(shelved as? [String])) + + func search(_ query: String) async throws -> [String] { + let result = try await web.callAsyncJavaScript(""" + const field = document.getElementById("manual-query"); + field.value = query; + field.dispatchEvent(new Event("input")); + return Array.from(document.querySelectorAll("#search-results a"), link => link.href); + """, arguments: ["query": query], in: nil, contentWorld: .page) + return try XCTUnwrap(result as? [String]) + } + let capitals = try await search("What happened on the M2") + XCTAssertTrue(try XCTUnwrap(capitals.first).hasSuffix("/vibe-coding-with-chatgpt/06-capitals.html#m2-results")) + let cmoc = try await search("--initial-s") + XCTAssertTrue(cmoc.contains { $0.contains("/toolchain-reference/") }, "Bundled CMOC help must be searchable") + let lwasm = try await search("--listcol") + XCTAssertTrue(lwasm.contains { $0.contains("/toolchain-reference/") }, "Bundled LWASM help must be searchable") + let forward = try await search("joystick keyboard") + let reversed = try await search("KEYBOARD joystick") + XCTAssertFalse(forward.isEmpty) + XCTAssertEqual(Set(forward), Set(reversed)) + let missing = try await search("joystick zzNoSuchKeyword") + XCTAssertTrue(missing.isEmpty) + let broad = try await search("CoCo") + let total = try await web.evaluateJavaScript("parseInt(document.getElementById('search-status').textContent, 10)") + XCTAssertGreaterThan(try XCTUnwrap(total as? Int), broad.count) + let more = try await web.evaluateJavaScript("document.querySelector('#search-results + button').click(); document.querySelectorAll('#search-results a').length") + XCTAssertGreaterThan(try XCTUnwrap(more as? Int), broad.count) + let command = try await search("print@") + let first = try XCTUnwrap(command.first) + XCTAssertTrue(first.contains("/programming-in-coco-basic/reference.html#term-print-at"), first) + let highlight = try await web.evaluateJavaScript("document.querySelector('#search-results a mark')?.textContent") + XCTAssertEqual(highlight as? String, "PRINT@") + _ = try await web.evaluateJavaScript("document.querySelector('#search-results a').click()") + let pageLimit = ContinuousClock.now + .seconds(5) + while web.url?.absoluteString != first || web.isLoading { + guard ContinuousClock.now < pageLimit else { return XCTFail("The matching section did not open") } + try await Task.sleep(for: .milliseconds(30)) + } + let heading = try await web.evaluateJavaScript("document.querySelector(':target h2').textContent") + XCTAssertEqual(heading as? String, "PRINT@") + } + + @MainActor + func testPackagedReaderOpensSignalAndKeepsChapter() async throws { + try requireFullManualEdition() + let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) + let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) + let reader = ManualReader(content: ManualLibraryContent(root: root)) + func waitForPage(_ name: String) async throws { + let limit = ContinuousClock.now + .seconds(8) + while reader.webView.url?.lastPathComponent != name || reader.webView.isLoading { + guard ContinuousClock.now < limit else { + XCTFail("Timed out loading " + name + ": " + (reader.error ?? "no navigation error")) + throw CocoaError(.fileReadUnknown) + } + try await Task.sleep(for: .milliseconds(40)) + } + } + reader.showHome() + try await waitForPage("index.html") + _ = try await reader.webView.evaluateJavaScript("document.querySelector('.shelf-routes a').click(); true") + try await waitForPage("template.html") + _ = try await reader.webView.evaluateJavaScript("document.querySelector('a[href*=catch-the-computer]').click(); true") + try await waitForPage("catch-the-computer.html") + let chapter = reader.webView.url + let opened = expectation(description: "Open the bundled example in BASIC") + reader.openExample = { path in + XCTAssertEqual(path, "meet-your-color-computer/examples/SIGNAL.bas") + opened.fulfill() + } + _ = try await reader.webView.evaluateJavaScript("document.querySelector('a[href$=\"SIGNAL.bas\"]').click(); true") + await fulfillment(of: [opened], timeout: 5) + XCTAssertEqual(reader.webView.url, chapter) + XCTAssertTrue(reader.webView.canGoBack) + } + + @MainActor + func testUpdatedHandbookAndCapitalQuestFitAndLoadFigures() async throws { + try requireFullManualEdition() + let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) + let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) + let pages = ["users-handbook/desk.html", "users-handbook/media.html", + "users-handbook/workbenches.html", "vibe-coding-with-chatgpt/04-c.html", + "vibe-coding-with-chatgpt/06-capitals.html", "vibe-coding-with-chatgpt/08-field-guide.html", + "vibe-coding-with-chatgpt/09-start-a-project.html", "toolchain-reference/index.html", + "toolchain-reference/cmoc.html", "toolchain-reference/lwtools.html", "toolchain-reference/command-line.html"] + for width in [420, 1024] { + for path in pages { + let reader = ManualReader(content: ManualLibraryContent(root: root)) + let web = reader.webView + web.frame = CGRect(x: 0, y: 0, width: width, height: 850) + let page = root.appendingPathComponent(path) + web.loadFileURL(page, allowingReadAccessTo: root) + let deadline = ContinuousClock.now + .seconds(12) + while web.url != page || web.isLoading { + guard ContinuousClock.now < deadline else { return XCTFail("Manual did not load: " + path) } + try await Task.sleep(for: .milliseconds(40)) + } + let images = try await web.callAsyncJavaScript(""" + await document.fonts.ready; + await Promise.all(Array.from(document.images, image => image.decode().catch(() => {}))); + return Array.from(document.images).filter(image => !image.complete || image.naturalWidth === 0).map(image => image.getAttribute('src')); + """, contentWorld: .page) + XCTAssertEqual(images as? [String], [], "Every figure must load: " + path) + let size = try await web.evaluateJavaScript("[innerWidth, document.documentElement.scrollWidth]") + XCTAssertEqual(size as? [Int], [width, width], "The complete page must fit the reader: " + path) + if width == 1024, ["users-handbook/desk.html", "users-handbook/media.html", "vibe-coding-with-chatgpt/06-capitals.html"].contains(path) { + let anchor = path.contains("desk") ? "archive-reviewed-code" : path.contains("media") ? "disk-image-editor" : "capital-quest" + _ = try await web.callAsyncJavaScript("document.getElementById(anchor).scrollIntoView();", arguments: ["anchor": anchor], contentWorld: .page) + let image = try await web.takeSnapshot(configuration: nil) + let attachment = XCTAttachment(image: image) + attachment.name = "Updated manual — " + path + attachment.lifetime = .keepAlways + add(attachment) + } + } + } + } + + private func lookup(_ marked: String) -> String? { + let marker = (marked as NSString).range(of: "|") + precondition(marker.location != NSNotFound) + let source = (marked as NSString).replacingCharacters(in: marker, with: "") + return BASICReferenceContext.keyword(in: source, at: marker.location) + } + + func testContextResolvesCompositeCommandsAndTokenBoundaries() { + let cases: [(String, String)] = [ + ("10 LOA|DM \"PROGRAM\"", "LOADM"), ("10 SAVEM| \"PROGRAM\",100,200,100", "SAVEM"), + ("10 CLOADM| \"PROGRAM\"", "CLOADM"), ("10 CSAVE|M \"PROGRAM\",100,200,100", "CSAVEM"), + ("10 LINE IN|PUT A$", "LINE INPUT"), ("10 LINEINPUT A$|", "LINE INPUT"), + ("10 ON ER|R GOTO 100", "ON ERR"), ("10 ONERRGOTO 100|", "ON ERR"), + ("10 DEF F|NX(A)=A*2", "DEF FN"), ("10 PRINT US|ING \"###\";A", "PRINT USING"), + ("10 PRINT@ 100, A|", "PRINT@"), ("10 PRINT @ 100, A|", "PRINT@"), + ("10 GO TO 100|", "GOTO"), ("10 GOSUB 100|", "GOSUB"), + ("10 go sub 100|", "GOSUB"), ("10 PRINT| A", "PRINT"), + ("10 DATA|", "DATA"), ("10 REM|", "REM") + ] + for (source, expected) in cases { XCTAssertEqual(lookup(source), expected, source) } + } + + func testContextPrefersPointedFunctionAndOtherwiseUsesOwningStatement() { + XCTAssertEqual(lookup("10 PRINT LE|FT$(A$,2)"), "LEFT$") + XCTAssertEqual(lookup("10 PRINT LEFT$(A$,2|)"), "PRINT") + XCTAssertEqual(lookup("10 A=RN|D(6)"), "RND") + XCTAssertEqual(lookup("10 A=RND(6|)"), "LET") + XCTAssertEqual(lookup("10 A=42|"), "LET") + XCTAssertEqual(lookup("10 FOR I=1 TO 10|"), "FOR") + XCTAssertEqual(lookup("10 FOR I=1 TO 10:PRINT I|"), "PRINT") + XCTAssertEqual(lookup("10 IF A THEN PRINT A| ELSE PRINT B"), "PRINT") + XCTAssertEqual(lookup("10 IF A THEN PRINT A ELSE B=RND(6|)"), "LET") + XCTAssertEqual(lookup("10 IF A THEN 100|"), "IF") + XCTAssertEqual(lookup("10 ON A GOSUB 100,200|"), "ON") + XCTAssertEqual(lookup("10 INPUT \"TIME: \";A|"), "INPUT") + } + + func testContextIgnoresLiteralCommentAndDataContents() { + for source in ["10 PRINT \"LE|FT$\"", "10 PRINT \"UNFINISHED|", "10 REM PRI|NT 1", "10 'PRI|NT 1", + "10 DATA PRINT,LOAD|", "10 DATA \"PRINT:|LOAD\",1", "10 PRINT 1|:PRINT 2"] { + XCTAssertNil(lookup(source), source) + } + XCTAssertEqual(lookup("10 DATA \"PRINT:LOAD\",1:PR|INT A"), "PRINT") + XCTAssertEqual(lookup("10 PRINT \"A:B\":SOUND 100,2|"), "SOUND") + XCTAssertEqual(lookup("10 REM 😀\r\n20 PR|INT A"), "PRINT") + XCTAssertNil(lookup("10| PRINT 1")) + XCTAssertNil(lookup("10 PRINT 1\n|")) + } + + func testContextRejectsInvalidOrExcessiveOffsetsWithoutChangingSource() { + let source = "10 PRINT 1\n" + XCTAssertNil(BASICReferenceContext.keyword(in: source, at: -1)) + XCTAssertNil(BASICReferenceContext.keyword(in: source, at: Int.max)) + XCTAssertNil(BASICReferenceContext.keyword(in: "", at: 0)) + XCTAssertNil(BASICReferenceContext.keyword(in: String(repeating: "A", count: BASICLanguage.maximumSourceBytes + 1), at: 1)) + XCTAssertEqual(source, "10 PRINT 1\n") + } + + private func fixture() throws -> BASICReferenceCatalog { + let rows: [(String, String, String, String)] = [ + ("PRINT", "PRINT", "common", "Text"), ("DRIVE", "DRIVE", "disk", "Storage"), + ("RGB.DRIVE", "DRIVE", "rgbdos", "Storage"), ("SDC.DRIVE", "DRIVE", "sdcdos", "Storage"), + ("ERROR.SN", "SN", "common", "Errors") + ] + let entries: [[String: Any]] = rows.map { id, keyword, dialect, category in + ["id": id, "keyword": keyword, "title": id, "category": category, "dialect": dialect, + "summary": id == "SDC.DRIVE" ? "Mount an image in a drive." : "Reference for " + keyword, + "syntax": [keyword], "parameters": [], "sample": keyword, "related": id == "PRINT" ? ["DRIVE"] : [], + "notes": [], "source": "basicGuide", "sourcePage": "1"] + } + let data = try JSONSerialization.data(withJSONObject: ["entries": entries, "examples": []]) + return try JSONDecoder().decode(BASICReferenceCatalog.self, from: data) + } + + func testEveryTopicCitesAnOfflineWorkWithItsOriginalPageConvention() throws { + let catalog = try BASICReferenceCatalog.bundled.get() + XCTAssertEqual(Set(catalog.entries.map(\.source)), Set(BASICReferenceWork.allCases)) + let rgb = try XCTUnwrap(catalog.entries.first { $0.source == .rgbdos }) + XCTAssertTrue(rgb.citation.contains("Krupski")) + XCTAssertTrue(rgb.citation.contains("PDF page")) + XCTAssertTrue(catalog.entries.contains { $0.citation.contains("1986. p. 27.") }) + XCTAssertTrue(catalog.entries.allSatisfy { !$0.citation.contains("://") }) + } + + @MainActor func testBrowserLookupSelectsDialectAndClearsFilters() throws { + let model = BASICReferenceModel(catalog: try fixture()) + model.category = "Text"; model.search = "print" + model.show(keyword: "drive", dialect: .sdcdos) + XCTAssertEqual(model.selectedID, "SDC.DRIVE") + XCTAssertNil(model.category); XCTAssertEqual(model.search, "") + model.show(keyword: "DRIVE", dialect: .rgbdos) + XCTAssertEqual(model.selectedID, "RGB.DRIVE") + model.show(keyword: "DRIVE") + XCTAssertEqual(model.selectedID, "DRIVE") + model.showError(code: "sn") + XCTAssertEqual(model.selectedID, "ERROR.SN") + } + + @MainActor func testBrowserSearchCategoriesAndPinnedSelection() throws { + let model = BASICReferenceModel(catalog: try fixture()) + model.show(keyword: "DRIVE", dialect: .sdcdos) + _ = BASICReferenceContext.keyword(in: "10 PRINT 42", at: 5) + XCTAssertEqual(model.selectedID, "SDC.DRIVE", "Reading cursor context must not replace a pinned topic") + model.search = "mount IMAGE" + XCTAssertEqual(model.filteredEntries.map(\.id), ["SDC.DRIVE"]) + model.category = "Text" + XCTAssertTrue(model.filteredEntries.isEmpty); XCTAssertNil(model.selectedID) + model.category = nil; model.search = "" + XCTAssertEqual(model.filteredEntries.count, 5) + XCTAssertEqual(model.relatedEntry("DRIVE")?.id, "DRIVE") + XCTAssertNil(model.relatedEntry("not-a-topic")) + } + + func testBundledCatalogCoverageLinksAndExampleStructure() throws { + let catalog = try BASICReferenceCatalog.bundled.get() + let ids = Set(catalog.entries.map(\.id)) + XCTAssertEqual(ids.count, catalog.entries.count, "Topic identifiers must be unique") + let keywords = Set(catalog.entries.map { $0.keyword.uppercased() }) + XCTAssertTrue(Set(BASICLanguage.words).subtracting(keywords).isEmpty, + "Every completion keyword should have a reference topic") + for keyword in ["LOADM", "SAVEM", "CLOADM", "CSAVEM", "LINE INPUT", "ON ERR", "DEF FN", "PRINT USING", "PRINT@"] { + XCTAssertTrue(keywords.contains(keyword), keyword) + } + let exampleIDs = Set(catalog.examples.map(\.id)) + XCTAssertEqual(exampleIDs.count, catalog.examples.count) + XCTAssertFalse(catalog.examples.isEmpty) + for entry in catalog.entries { + XCTAssertFalse(entry.summary.isEmpty, entry.id) + XCTAssertFalse(entry.citation.isEmpty, entry.id) + XCTAssertTrue(Set(entry.related).isSubset(of: ids), "Broken related topic in " + entry.id) + if let exampleID = entry.exampleID { XCTAssertTrue(exampleIDs.contains(exampleID), entry.id) } + } + for example in catalog.examples { + let analysis = BASICLanguage.analyze(example.source) + XCTAssertFalse(analysis.hasErrors, example.id) + XCTAssertFalse(analysis.lines.isEmpty, example.id) + XCTAssertFalse(example.expectedOutput.isEmpty, example.id) + } + } + + @MainActor func testExampleWorkspaceKeepsOriginalDraftAndMachineOwnership() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("BASICReference-" + UUID().uuidString) + let suite = "BASICReference-" + UUID().uuidString + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: directory) } + let machine = MachineModel(diskStore: .init(url: directory.appendingPathComponent("disks.json")), + displayDefaults: defaults, inputStore: .init(url: directory.appendingPathComponent("input.json"))) + let originalDirectory = directory.appendingPathComponent("original") + let exampleDirectory = directory.appendingPathComponent("example") + let original = BASICDevelopmentModel(machine: machine, directory: originalDirectory) + original.source = "10 PRINT \"MY UNSAVED WORK\"\n" + original.persistDraft() + machine.basicWorkspaceOwner = original.workspaceID + let source = "10 PRINT 42\n20 END\n" + let example = BASICDevelopmentModel(machine: machine, directory: exampleDirectory, + initialSource: source, title: "Reference Example") + XCTAssertEqual(example.source, source) + XCTAssertEqual(example.title, "Reference Example") + XCTAssertFalse(example.dirty) + XCTAssertNil(example.fileURL) + XCTAssertNotEqual(original.workspaceID, example.workspaceID) + example.source = "10 PRINT 43\n20 END\n" + example.persistDraft() + XCTAssertEqual(machine.basicWorkspaceOwner, original.workspaceID) + XCTAssertEqual(original.source, "10 PRINT \"MY UNSAVED WORK\"\n") + XCTAssertTrue(original.dirty) + XCTAssertNil(original.fileURL) + let restoredExample = BASICDevelopmentModel(machine: machine, directory: exampleDirectory, + initialSource: source, title: "Reference Example") + let restoredOriginal = BASICDevelopmentModel(machine: machine, directory: originalDirectory) + XCTAssertEqual(restoredExample.source, example.source) + XCTAssertTrue(restoredExample.dirty) + XCTAssertEqual(restoredOriginal.source, original.source) + XCTAssertTrue(restoredOriginal.dirty) + XCTAssertEqual(machine.basicWorkspaceOwner, original.workspaceID) + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } +} diff --git a/platforms/macos/Tests/BASICWorkspaceTests.swift b/platforms/macos/Tests/BASICWorkspaceTests.swift new file mode 100644 index 0000000..7a9b7de --- /dev/null +++ b/platforms/macos/Tests/BASICWorkspaceTests.swift @@ -0,0 +1,479 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest +import AppKit +import SwiftUI + +final class BASICWorkspaceTests: XCTestCase { + @MainActor func testBlankAndReopenedDevelopmentEditorsLayOutWholeLinesAndRevealTheApprovedChange() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + let suite = UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let machine = MachineModel(diskStore: .init(url: directory.appendingPathComponent("disks.json")), + displayDefaults: defaults, inputStore: .init(url: directory.appendingPathComponent("input.json"))) + let source = (1...60).map { "\($0 * 10) PRINT \"LINE \($0)\"" }.joined(separator: "\n") + let model = BASICDevelopmentModel(machine: machine, directory: directory, initialSource: "") + for (size, appearance) in [(NSSize(width: 1050, height: 760), NSAppearance.Name.aqua), + (NSSize(width: 850, height: 560), .darkAqua)] { + let host = NSHostingView(rootView: BASICDevelopmentView(model: model)) + let window = NSWindow(contentRect: NSRect(origin: .zero, size: size), + styleMask: [.titled, .resizable], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + defer { window.close() } + window.appearance = NSAppearance(named: appearance) + window.contentView = host + host.layoutSubtreeIfNeeded() + let editor = try XCTUnwrap(model.assistantEditor) + let scroll = try XCTUnwrap(editor.enclosingScrollView) + let ruler = try XCTUnwrap(scroll.verticalRulerView as? BASICBreakpointRuler) + model.source = source + for _ in 0..<100 where editor.string != source { + try await Task.sleep(for: .milliseconds(10)) + host.layoutSubtreeIfNeeded() + } + XCTAssertEqual(editor.string, source) + let layout = try XCTUnwrap(editor.layoutManager) + let container = try XCTUnwrap(editor.textContainer) + func verifyFirstLineFits(_ text: String, file: StaticString = #filePath, line: UInt = #line) { + layout.ensureLayout(for: container) + let end = (text as NSString).range(of: "\n").location - 1 + let lastGlyph = layout.glyphIndexForCharacter(at: end) + XCTAssertEqual(layout.lineFragmentRect(forGlyphAt: 0, effectiveRange: nil).minY, + layout.lineFragmentRect(forGlyphAt: lastGlyph, effectiveRange: nil).minY, + "An empty editor must grow past a single character column.", file: file, line: line) + } + // Ordinary source updates and subsequently approved replacements both + // use the same editor. A wide final line must remain horizontally scrollable. + verifyFirstLineFits(source) + let revised = "5 REM NEW TITLE\n" + source + "\n610 REM " + String(repeating: "W", count: 192) + let change = BASICEditorAction(expectedSource: source, operation: .replace(source: revised, undoName: "Approve Title")) + XCTAssertTrue(editor.applyEditorAction(change, revealReplacementAt: 0)) + host.layoutSubtreeIfNeeded() + verifyFirstLineFits(revised) + XCTAssertGreaterThan(layout.usedRect(for: container).width, scroll.contentView.bounds.width) + XCTAssertGreaterThan(scroll.contentView.bounds.width, size.width * 0.90) + XCTAssertEqual(editor.selectedRange(), NSRange(location: 0, length: 0)) + XCTAssertTrue(ruler.visibleRows().contains { $0.number == 5 }) + XCTAssertLessThanOrEqual(scroll.contentView.bounds.origin.x, 1) + } + } + + /// Exercise native buttons and their real hit regions without moving the desktop pointer. + @MainActor func testBreakpointGutterHitTargetsTrackLineStateAndScrolling() throws { + for basic in [true, false] { + let size = NSSize(width: 450, height: 170) + let host = NSView(frame: NSRect(origin: .zero, size: size)) + let scroll = NSScrollView(frame: host.bounds) + host.addSubview(scroll) + let editor = BASICTextView(frame: NSRect(x: 0, y: 0, width: 400, height: 1400)) + editor.font = .monospacedSystemFont(ofSize: 14, weight: .regular) + editor.string = (1...64).map { basic ? "\($0 * 10) PRINT \($0)" : "print(\($0));" }.joined(separator: "\n") + scroll.documentView = editor + let ruler: BreakpointRuler = basic + ? BASICBreakpointRuler(textView: editor) + : CLineRuler(scrollView: scroll, orientation: .verticalRuler) + scroll.verticalRulerView = ruler + scroll.hasVerticalRuler = true; scroll.rulersVisible = true + scroll.tile() + var pressed: [Int] = [] + ruler.onClick = { pressed.append($0) } + if basic { + editor.configureDebug(points: [], stoppedLine: nil, toggle: { pressed.append($0) }) + } + ruler.layoutSubtreeIfNeeded() + func marker(_ line: Int) -> NSButton? { + ruler.subviews.compactMap { $0 as? NSButton }.first { $0.tag == line } + } + let first = basic ? 10 : 1 + let second = first * 2 + let button = try XCTUnwrap(marker(second)) + XCTAssertEqual(button.toolTip, "Set breakpoint on line \(second)") + XCTAssertEqual(button.accessibilityLabel(), button.toolTip) + XCTAssertTrue(ruler.isAccessibilityElement()) + XCTAssertTrue(ruler.accessibilityChildren()?.contains { ($0 as? NSButton) === button } == true) + XCTAssertEqual(button.accessibilityIdentifier(), "breakpoint.gutter.line.\(second)") + let center = ruler.convert(NSPoint(x: button.bounds.midX, y: button.bounds.midY), from: button) + XCTAssertIdentical(ruler.hitTest(ruler.convert(center, to: ruler.superview)), button) + button.performClick(nil) + XCTAssertEqual(pressed, [second]) + + ruler.points = [second] + ruler.layoutSubtreeIfNeeded() + XCTAssertEqual(button.toolTip, "Remove breakpoint on line \(second)") + XCTAssertEqual(marker(first)?.toolTip, "Set breakpoint on line \(first)") + XCTAssertEqual(button.accessibilityLabel(), button.toolTip) + ruler.active = false + ruler.layoutSubtreeIfNeeded() + XCTAssertFalse(button.isEnabled) + ruler.active = true + scroll.contentView.scroll(to: NSPoint(x: 0, y: 520)) + scroll.reflectScrolledClipView(scroll.contentView) + ruler.layoutSubtreeIfNeeded() + XCTAssertNil(marker(first)) + let scrolled = try XCTUnwrap(ruler.subviews.compactMap { $0 as? NSButton }.first) + XCTAssertGreaterThan(scrolled.tag, second) + XCTAssertEqual(scrolled.toolTip, "Set breakpoint on line \(scrolled.tag)") + } + } + @MainActor func testToolbarBreakpointHelpMatchesTheActiveBASICLine() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + let suite = UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let machine = MachineModel(diskStore: .init(url: directory.appendingPathComponent("disks.json")), + displayDefaults: defaults, inputStore: .init(url: directory.appendingPathComponent("input.json"))) + let model = BASICDevelopmentModel(machine: machine, directory: directory) + model.source = " 10 PRINT 1\r\n40 PRINT 2\r\n" + model.cursorChanged((model.source as NSString).range(of: "PRINT 2").location) + XCTAssertEqual(model.cursorBreakpointHelp, "Set breakpoint on line 40") + model.toggleBreakpointAtCursor() + XCTAssertEqual(model.cursorBreakpointHelp, "Remove breakpoint on line 40") + model.cursorChanged(0) + XCTAssertEqual(model.cursorBreakpointHelp, "Set breakpoint on line 10") + model.cursorChanged((model.source as NSString).length) + XCTAssertTrue(model.cursorBreakpointHelp.contains("numbered BASIC statement")) + XCTAssertEqual(model.breakpoints, [40]) + } + func testBASICWatchSyntaxAndCanonicalNames() throws { + XCTAssertEqual(BASICWatch("longname$")?.canonical, "LO$") + XCTAssertEqual(BASICWatch(" a(1, 2) ")?.canonical, "A(1,2)") + XCTAssertEqual(BASICWatch("A0")?.canonical, "A0") + for invalid in ["", "A+1", "PEEK(1024)", "RND(1)", "FN F(2)", "A(-1)", "A(1.5)", "A()", "A(32768)", "A(1):PRINT 1", "A=1", "1A", "A(9999999999999999999999999)"] { + // Keyword names are rejected by the parser, even when shaped like an array. + XCTAssertNil(BASICWatch(invalid), invalid) + } + } + @MainActor private final class UndoDelegate: NSObject, NSTextViewDelegate { + let manager=UndoManager() + func undoManager(for view:NSTextView) -> UndoManager? { manager } + } + @MainActor func testUntouchedSampleDoesNotPromptAndRecoveryPreservesEdits() async throws { + let directory=FileManager.default.temporaryDirectory.appendingPathComponent("BASICWorkspace-"+UUID().uuidString) + let suite="BASICWorkspace-"+UUID().uuidString + let defaults=UserDefaults(suiteName:suite)! + defer { defaults.removePersistentDomain(forName:suite); try? FileManager.default.removeItem(at:directory) } + let machine=MachineModel(diskStore:.init(url:directory.appendingPathComponent("disks.json")), displayDefaults:defaults, inputStore:.init(url:directory.appendingPathComponent("input.json"))) + let model=BASICDevelopmentModel(machine:machine,directory:directory.appendingPathComponent("draft")) + XCTAssertFalse(model.dirty) + XCTAssertTrue(model.confirmDiscard()) + model.source="10 PRINT 42\n" + model.watchEntry = "name$"; model.addWatch() + model.watchEntry = "NAME$"; model.addWatch() + model.watchEntry = "A(2, 1)"; model.addWatch() + model.persistDraft() + let restored=BASICDevelopmentModel(machine:machine,directory:directory.appendingPathComponent("draft")) + XCTAssertEqual(restored.source,"10 PRINT 42\n") + XCTAssertEqual(restored.watches, ["NA$", "A(2,1)"]) + XCTAssertTrue(restored.dirty) + XCTAssertNil(restored.fileURL) + // Undoing to the saved source and quitting before the debounce fires + // must not bring back an older dirty recovery copy next launch. + model.source = BASICLanguage.sample + XCTAssertTrue(model.confirmDiscard()) + let clean=BASICDevelopmentModel(machine:machine,directory:directory.appendingPathComponent("draft")) + XCTAssertFalse(clean.dirty) + XCTAssertEqual(clean.source,BASICLanguage.sample) + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + + @MainActor func testStatementHighlightMovesWithinOneLineWithoutEditingOrMovingSelection() { + let view = BASICTextView(frame: NSRect(x: 0, y: 0, width: 600, height: 200)) + let source = "10 GOSUB 100:PRINT A\n100 RETURN\n" + view.string = source; view.setSelectedRange(NSRange(location: 0, length: 0)) + let first = (source as NSString).range(of: "GOSUB"), second = (source as NSString).range(of: "PRINT") + view.configureDebug(points: [10], stoppedLine: 10, token: first, toggle: { _ in }) + let firstColor = view.layoutManager?.temporaryAttribute(.backgroundColor, atCharacterIndex: first.location, effectiveRange: nil) as? NSColor + view.configureDebug(points: [10], stoppedLine: 10, token: second, toggle: { _ in }) + let secondColor = view.layoutManager?.temporaryAttribute(.backgroundColor, atCharacterIndex: second.location, effectiveRange: nil) as? NSColor + XCTAssertEqual(firstColor, secondColor) + XCTAssertNotEqual(view.layoutManager?.temporaryAttribute(.backgroundColor, atCharacterIndex: first.location, effectiveRange: nil) as? NSColor, secondColor) + XCTAssertEqual(view.string, source); XCTAssertEqual(view.selectedRange(), NSRange(location: 0, length: 0)) + view.configureDebug(points: [10], stoppedLine: nil, toggle: { _ in }) + XCTAssertNil(view.layoutManager?.temporaryAttribute(.backgroundColor, atCharacterIndex: second.location, effectiveRange: nil)) + } + + func testExportNamesUseSafeCoCoDirectoryAndCassetteNames() { + XCTAssertEqual(BASICExportName.normalized(" hello2 "), "HELLO2") + XCTAssertEqual(BASICExportName.normalized("ABCDEFG8"), "ABCDEFG8") + for invalid in ["", " ", "ABCDEFGHI", "HELLO.BAS", "../FOO", "A/B", "A B", "é", "ß", "😀"] { + XCTAssertNil(BASICExportName.normalized(invalid), invalid) + } + XCTAssertEqual(BASICExportName.suggestion(for: nil), "HELLO") + XCTAssertEqual(BASICExportName.suggestion(for: URL(fileURLWithPath: "/tmp/My Game 2026.bas")), "MYGAME20") + XCTAssertEqual(BASICExportName.suggestion(for: URL(fileURLWithPath: "/tmp/😀.bas")), "HELLO") + } + + @MainActor func testRejectedExportPreservesSourceBindingAndExistingDestination() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("BASICExport-" + UUID().uuidString) + let draftDirectory = directory.appendingPathComponent("draft") + let suite = "BASICExport-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: directory) } + try FileManager.default.createDirectory(at: draftDirectory, withIntermediateDirectories: true) + let sourceURL = directory.appendingPathComponent("Working.bas") + try Data("10 PRINT 1\n".utf8).write(to: sourceURL) + let source = "10 PRINT 42\n" + let draft = BASICDevelopmentModel.Draft(source: source, savedSource: "10 PRINT 1\n", filePath: sourceURL.path, fingerprint: nil) + try JSONEncoder().encode(draft).write(to: draftDirectory.appendingPathComponent("Draft.json")) + let machine = MachineModel(diskStore: .init(url: directory.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: directory.appendingPathComponent("input.json"))) + let model = BASICDevelopmentModel(machine: machine, directory: draftDirectory) + func settled() async throws { + for _ in 0..<1000 { + if !machine.busy { return } + try await Task.sleep(nanoseconds: 10_000_000) + } + throw NSError(domain: "BASICExportTimeout", code: 1) + } + do { + try await settled(); machine.loadDiagnostic(); try await settled() + let destination = directory.appendingPathComponent("Existing.dsk") + let untouched = Data("Existing destination must survive a rejected export".utf8) + try untouched.write(to: destination) + // A diagnostic machine is valid/runnable but has no recognized BASIC + // ROM dictionary. The actual core must reject this before any write. + let result = await model.exportImage(.disk, name: "HELLO", to: destination) + XCTAssertFalse(result) + XCTAssertNotNil(model.message) + XCTAssertEqual(try Data(contentsOf: destination), untouched) + XCTAssertEqual(model.source, source) + XCTAssertEqual(model.fileURL, sourceURL) + XCTAssertTrue(model.dirty) + XCTAssertFalse(model.busy) + XCTAssertEqual(machine.state, .paused) + XCTAssertEqual(try String(contentsOf: sourceURL, encoding: .utf8), "10 PRINT 1\n") + } catch { + await withCheckedContinuation { done in machine.shutdown { done.resume() } }; throw error + } + await withCheckedContinuation { done in machine.shutdown { done.resume() } } + } + + func testInlineSuggestionRequiresUniquePartialKeywordAndSafeContext() { + XCTAssertEqual(BASICLanguage.inlineCompletion("10 PRI", at: 6)?.suffix, "NT") + XCTAssertEqual(BASICLanguage.inlineCompletion("10 pri", at: 6)?.word, "PRINT") + for text in ["10 P", "10 GO", "10 PRINT", "10 REM PRI", "10 DATA PRI", "10 PRINT \"PRI", "10 A1PRI"] { + XCTAssertNil(BASICLanguage.inlineCompletion(text, at: (text as NSString).length), text) + } + XCTAssertNil(BASICLanguage.inlineCompletion("10 PRI X", at: 6)) + XCTAssertNil(BASICLanguage.inlineCompletion("10 PRINT", at: 6)) + XCTAssertEqual(BASICLanguage.inlineCompletion("10PRI", at: 5)?.word, "PRINT") + XCTAssertEqual(BASICLanguage.inlineCompletion("10 PRI\n20 END", at: 6)?.suffix, "NT") + } + func testReturnNumberingFollowsIncrementAndFitsWithoutCollisions() { + func next(_ source: String, _ caret: Int? = nil) -> String? { + BASICLanguage.nextLineInsertion(source, at: caret ?? (source as NSString).length) + } + XCTAssertEqual(next("10 PRINT 1"), "\n20 ") + XCTAssertEqual(next("100 CLS\n125 END"), "\n150 ") + XCTAssertEqual(next("10 CLS\n20 END", 6), "\n15 ") + XCTAssertEqual(next("10 CLS\n12 END", 6), "\n11 ") + XCTAssertNil(next("10 CLS\n11 END", 6)) + XCTAssertNil(next("10 CLS\n5 END", 6)) + XCTAssertNil(next("10 ")) + XCTAssertNil(next("PRINT 1")) + XCTAssertNil(next("10 PRINT 1", 5)) + XCTAssertNil(next("63999 END")) + XCTAssertEqual(next("63998 END"), "\n63999 ") + XCTAssertEqual(next("10 CLS\r\n20 END"), "\r\n30 ") + // Out-of-order earlier rows must not cause a duplicate label. + XCTAssertEqual(next("30 END\n10 CLS\n20 PRINT 1"), "\n31 ") + } + @MainActor func testInlinePreviewAcceptanceDismissalSelectionAndUndo() throws { + let delegate = UndoDelegate() + let editor = BASICTextView(frame: NSRect(x: 0, y: 0, width: 400, height: 200)) + editor.delegate = delegate; editor.allowsUndo = true; editor.string = "10 PRI" + editor.setSelectedRange(NSRange(location: 6, length: 0)); editor.refreshInlineSuggestion() + XCTAssertEqual(editor.inlineSuggestion?.suffix, "NT") + XCTAssertEqual(editor.string, "10 PRI"); XCTAssertFalse(delegate.manager.canUndo) + editor.cancelOperation(nil); editor.refreshInlineSuggestion() + XCTAssertNil(editor.inlineSuggestion) + editor.setSelectedRange(NSRange(location: 5, length: 0)) + editor.setSelectedRange(NSRange(location: 6, length: 0)); editor.refreshInlineSuggestion() + editor.insertTab(nil) + XCTAssertEqual(editor.string, "10 PRINT") + delegate.manager.undo(); XCTAssertEqual(editor.string, "10 PRI") + XCTAssertFalse(delegate.manager.canUndo) + editor.setSelectedRange(NSRange(location: 3, length: 3)); editor.refreshInlineSuggestion() + XCTAssertNil(editor.inlineSuggestion) + editor.setSelectedRange(NSRange(location: 6, length: 0)); editor.isEditable = false; editor.refreshInlineSuggestion() + XCTAssertNil(editor.inlineSuggestion) + } + @MainActor func testAutomaticNumberAndNewlineAreOneUndoableEditAndPasteIsUntouched() { + let delegate = UndoDelegate() + let editor = BASICTextView(frame: NSRect(x: 0, y: 0, width: 400, height: 200)) + editor.delegate = delegate; editor.allowsUndo = true; editor.string = "10 PRINT 1" + editor.setSelectedRange(NSRange(location: 10, length: 0)) + editor.insertNewline(nil) + XCTAssertEqual(editor.string, "10 PRINT 1\n20 ") + delegate.manager.undo(); XCTAssertEqual(editor.string, "10 PRINT 1") + XCTAssertFalse(delegate.manager.canUndo) + editor.insertText("10 PRINT 1\n20 END\n", replacementRange: NSRange(location: 0, length: 10)) + XCTAssertEqual(editor.string, "10 PRINT 1\n20 END\n") + } + + func testHighlightingKeepsStringsCommentsAndDataOpaque() { + let source = "10 PRINT \"FOR REM DATA\":REM PRINT\n20 DATA PRINT,\"A:B\",12:PRINT 3\n30 'PRINT" + let spans = BASICLanguage.spans(source) + XCTAssertEqual(spans.filter { $0.kind == .keyword }.map(\.word), ["PRINT", "REM", "DATA", "PRINT"]) + XCTAssertTrue(spans.contains { $0.kind == .string && (source as NSString).substring(with: $0.range) == "\"FOR REM DATA\"" }) + XCTAssertTrue(spans.contains { $0.kind == .data && (source as NSString).substring(with: $0.range).contains("A:B") }) + XCTAssertEqual(spans.filter { $0.kind == .comment }.count, 2) + XCTAssertEqual(BASICLanguage.spans("10 FORI=1TO5:NEXTI").filter { $0.kind == .keyword }.map(\.word), ["FOR", "TO", "NEXT"]) + } + func testCompletionUsesCaretRangeAndSkipsLiteralContexts() throws { + let text = "10 priZZ\n20 END" + let suggestion = try XCTUnwrap(BASICLanguage.completion(text, at: 6)) + XCTAssertEqual(suggestion.range, NSRange(location: 3, length: 5)) + XCTAssertEqual(suggestion.words, ["PRINT"]) + XCTAssertNil(BASICLanguage.completion("10 REM PRI", at: 10)) + XCTAssertNil(BASICLanguage.completion("10 PRINT \"PRI", at: 13)) + XCTAssertNil(BASICLanguage.completion("10 DATA PRI", at: 11)) + XCTAssertEqual(BASICLanguage.completion("10 DATA \"A:B\":PRI", at: 17)?.words, ["PRINT"]) + XCTAssertTrue(try XCTUnwrap(BASICLanguage.completion("10 GO", at: 5)).words.contains("GOSUB")) + XCTAssertNil(BASICLanguage.completion("10 PRINT", at: -1)) + } + func testParameterHintsFollowCurrentStatementAndFunctions() { + XCTAssertEqual(BASICLanguage.hint("10 PRINT MID$(A$,", at: 17), BASICLanguage.signatures["MID$"]) + XCTAssertEqual(BASICLanguage.hint("10 FOR I=1 TO ", at: 14), BASICLanguage.signatures["FOR"]) + XCTAssertNil(BASICLanguage.hint("10 PRINT 1\n20 ", at: 14)) + } + @MainActor func testFileReaderRejectsBinaryAndNormalizesLineEndings() throws { + let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".bas") + defer { try? FileManager.default.removeItem(at: url) } + try Data("10 PRINT 1\r\n20 END\r".utf8).write(to:url) + XCTAssertEqual(try BASICDevelopmentModel.readText(url).0, "10 PRINT 1\n20 END\n") + try Data([0xff,0,0]).write(to:url) + XCTAssertThrowsError(try BASICDevelopmentModel.readText(url)) + } + @MainActor func testNativeCompletionAcceptanceIsOneUndoableEdit() throws { + let delegate = UndoDelegate() + let editor = BASICTextView(frame:NSRect(x:0,y:0,width:400,height:200)) + editor.delegate=delegate; editor.allowsUndo=true; editor.string="10 PRI"; editor.setSelectedRange(NSRange(location:6,length:0)) + // Preparing the menu off-window does not change the source. A final + // choice uses NSTextView's normal insertion and Undo machinery. + XCTAssertTrue(editor.prepareCompletion()) + let range=editor.rangeForUserCompletion + XCTAssertEqual(range,NSRange(location:3,length:3)) + var selection = -1 + XCTAssertEqual(editor.completions(forPartialWordRange:range,indexOfSelectedItem:&selection),["PRINT"]) + XCTAssertEqual(selection,0,"Return should accept the highlighted first suggestion") + editor.insertCompletion("PRINT",forPartialWordRange:range,movement:NSTextMovement.down.rawValue,isFinal:false) + XCTAssertEqual(editor.string,"10 PRI") + editor.insertCompletion("PRINT",forPartialWordRange:range,movement:NSTextMovement.return.rawValue,isFinal:true) + XCTAssertEqual(editor.string,"10 PRINT") + XCTAssertTrue(delegate.manager.canUndo) + delegate.manager.undo() + XCTAssertEqual(editor.string,"10 PRI") + XCTAssertFalse(delegate.manager.canUndo) + } + func testSourceCheckReportsPhysicalRowsAndPreciseRanges() { + let text="10 PRINT 1\r\n\r\n010 END\r\nPRINT 2\r\n64000 END\r\n20 PRINT\"é\"\r\n30 GOTO999\r\n40\r\n" + let report=BASICLanguage.analyze(text) + XCTAssertTrue(report.hasErrors) + XCTAssertEqual(report.diagnostics.filter { $0.severity == .error }.map(\.row),[3,4,5,6]) + XCTAssertTrue(report.diagnostics.contains { $0.row == 7 && $0.severity == .warning && $0.message.contains("999") }) + XCTAssertTrue(report.diagnostics.contains { $0.row == 8 && $0.severity == .warning }) + let duplicate=report.diagnostics.first { $0.row == 3 }! + XCTAssertEqual((text as NSString).substring(with:duplicate.range),"010") + XCTAssertNil(BASICLanguage.lineRange(for:10,in:text)) + let valid="0 PRINT\"UNCLOSED\n10 REM " + String(repeating:"X",count:242) + XCTAssertFalse(BASICLanguage.analyze(valid).hasErrors,"EOL closes a BASIC string; exactly249characters are allowed") + XCTAssertTrue(BASICLanguage.analyze(valid+"X").hasErrors) + XCTAssertTrue(BASICLanguage.analyze("10 PRINT\u{01}").hasErrors) + XCTAssertFalse(BASICLanguage.analyze("\t10\tPRINT 1\n").hasErrors) + } + func testRenumberPreservesControlFlowAndOpaqueLiterals() throws { + let text="10 FORI=1TO2:ONI GOTO30,40\n20 IF A THEN30ELSE40\n30 GO SUB40:RUN10\n40 PRINT\"GOTO10\":DATA 10,\"RUN20:ELSE30\":REM GOTO20\n50 LIST1-9999:LLIST-40:DEL30-:EDIT20\n60 ON ERR GOTO0:ON BRK GO TO40\n70 XGOTO=10:PRINT20:POKE100,20\n80 'GOTO10\n" + XCTAssertTrue(BASICLanguage.analyze(text).diagnostics.isEmpty) + let result=try BASICLanguage.renumber(text,start:100,step:100) + XCTAssertEqual(result.lineCount,8) + XCTAssertEqual(result.source,"100 FORI=1TO2:ONI GOTO300,400\n200 IF A THEN300ELSE400\n300 GO SUB400:RUN100\n400 PRINT\"GOTO10\":DATA 10,\"RUN20:ELSE30\":REM GOTO20\n500 LIST100-800:LLIST-400:DEL300-:EDIT200\n600 ON ERR GOTO0:ON BRK GO TO400\n700 XGOTO=10:PRINT20:POKE100,20\n800 'GOTO10\n") + XCTAssertGreaterThan(result.changedReferences,10) + } + func testRenumberKeepsPhysicalRowsAndMapsNumericExecutionOrder() throws { + let source=" 30 END\r\n\r\n\t0 GOTO30\r\n10 PRINT 123\r\n" + let result=try BASICLanguage.renumber(source) + XCTAssertEqual(result.source," 30 END\r\n\r\n\t10 GOTO30\r\n20 PRINT 123\r\n") + let range=try XCTUnwrap(BASICLanguage.lineRange(for:0,in:source)) + XCTAssertEqual((source as NSString).substring(with:range),"\t0 GOTO30") + XCTAssertNil(BASICLanguage.lineRange(for:123,in:source)) + XCTAssertEqual(try BASICLanguage.renumber("\n\r\n").source,"\n\r\n") + } + func testRenumberRejectsAmbiguityOrMissingTargetsWithoutChangingSource() { + for text in ["10 GOTO999\n20 END", "10 GOTO20+1\n20 END", "10 ON X GOTO20,\n20 END", + "10 GO TOX\n20 END", "10 RUN A$\n20 END", "10 RENUM\n20 END", "10\n20 GOTO10", + "10 LIST11-19\n20 END", "10 LIST999999999999999999999-\n20 END", + "10 LLIST-999999999999999999999\n20 END", "10 PRINT1\n010 END", "PRINT1"] { + XCTAssertThrowsError(try BASICLanguage.renumber(text),text) + } + let source="10 GOTO100\n20 END" + XCTAssertFalse(BASICLanguage.analyze(source).hasErrors,"An unresolved conditional branch is a warning, not a load blocker") + XCTAssertThrowsError(try BASICLanguage.renumber(source,start:100,step:100),"Must not accidentally capture orphan100 as new firstline") + for (start,step) in [(-1,10),(10,0),(64000,10),(63999,1),(10,Int.max)] { + XCTAssertThrowsError(try BASICLanguage.renumber("10 END\n20 END",start:start,step:step)) + } + let boundary="1 REM "+String(repeating:"X",count:243) + XCTAssertFalse(BASICLanguage.analyze(boundary).hasErrors) + XCTAssertThrowsError(try BASICLanguage.renumber(boundary,start:63999),"Expanded labels must not exceed inputline limit") + } + func testRenumberRangeBoundsPreserveIncludedLinesAndTrapZero() throws { + let source="0 END\n10 LIST1-29:LLIST-29:DEL1-\n20 ONERRGOTO0:ONBRKGOTO0\n30 IF1THENPRINT20ELSE10\n" + let value=try BASICLanguage.renumber(source,start:100,step:100).source + XCTAssertEqual(value,"100 END\n200 LIST200-300:LLIST-300:DEL200-\n300 ONERRGOTO0:ONBRKGOTO0\n400 IF1THENPRINT20ELSE200\n") + let literals="10 DATA GOTO999,\"ELSE888:RUN777\":PRINT10\n20 REM RUN999\n30 PRINT\"GOTO999\"\n40 XGOTO=999:PRINT20\n" + XCTAssertTrue(BASICLanguage.analyze(literals).diagnostics.isEmpty) + XCTAssertNoThrow(try BASICLanguage.renumber(literals)) + } + @MainActor func testExplicitEditorActionsUseOneUndoAndRejectStaleRequests() throws { + let delegate=UndoDelegate(), editor=BASICTextView(frame:NSRect(x:0,y:0,width:500,height:300)) + editor.delegate=delegate; editor.allowsUndo=true + let original="10 GOTO20\n20 END\n", changed=try BASICLanguage.renumber(original,start:100,step:100).source + editor.string=original + let action=BASICEditorAction(expectedSource:original,operation:.replace(source:changed,undoName:"Renumber BASIC")) + XCTAssertTrue(editor.applyEditorAction(action)); XCTAssertEqual(editor.string,changed) + XCTAssertEqual(delegate.manager.undoActionName,"Renumber BASIC") + delegate.manager.undo(); XCTAssertEqual(editor.string,original); XCTAssertFalse(delegate.manager.canUndo) + delegate.manager.redo(); XCTAssertEqual(editor.string,changed) + XCTAssertFalse(editor.applyEditorAction(action)); XCTAssertEqual(editor.string,changed) + XCTAssertFalse(editor.applyEditorAction(.init(expectedSource:changed,operation:.select(NSRange(location:NSNotFound,length:2))))) + XCTAssertTrue(editor.applyEditorAction(.init(expectedSource:changed,operation:.select(NSRange(location:0,length:3))))) + XCTAssertEqual(editor.selectedRange(),NSRange(location:0,length:3)) + editor.isEditable=false + XCTAssertFalse(editor.applyEditorAction(.init(expectedSource:changed,operation:.replace(source:original,undoName:"Change")))) + } + @MainActor func testModelAssistanceQueuesEditsAndNavigatesDiagnostics() async throws { + let directory=FileManager.default.temporaryDirectory.appendingPathComponent("BASICAssistance-"+UUID().uuidString) + let suite="BASICAssistance-"+UUID().uuidString, defaults=UserDefaults(suiteName:suite)! + defer { defaults.removePersistentDomain(forName:suite); try? FileManager.default.removeItem(at:directory) } + let machine=MachineModel(diskStore:.init(url:directory.appendingPathComponent("disks.json")),displayDefaults:defaults,inputStore:.init(url:directory.appendingPathComponent("input.json"))) + let model=BASICDevelopmentModel(machine:machine,directory:directory.appendingPathComponent("draft")) + model.source="10 GOTO999\n20 END\n"; model.checkSource() + XCTAssertEqual(model.diagnostics.count,1) + if let diagnostic=model.diagnostics.first { + model.selectDiagnostic(diagnostic) + if let action=model.editorAction { + if case .select(let range)=action.operation { XCTAssertEqual((model.source as NSString).substring(with:range),"999") } else { XCTFail("Expected selection") } + model.editorActionHandled(id:action.id,applied:true) + } else { XCTFail("Missing diagnostic action") } + } + model.renumber(start:100,increment:100) + XCTAssertNil(model.editorAction); XCTAssertNotNil(model.message) + let source="10 GOTO20\n20 END\n"; model.source=source + model.renumber(start:100,increment:100) + XCTAssertEqual(model.source,source,"Source changes only through the native undoable edit") + if let action=model.editorAction { + if case .replace(let newSource,let name)=action.operation { XCTAssertEqual(newSource,"100 GOTO200\n200 END\n"); XCTAssertEqual(name,"Renumber BASIC") } else { XCTFail("Expected replacement") } + model.editorActionHandled(id:action.id,applied:false) + } else { XCTFail("Missing renumber action") } + model.goToLine(20) + if let action=model.editorAction { + if case .select(let range)=action.operation { XCTAssertEqual((source as NSString).substring(with:range),"20 END") } else { XCTFail("Expected line selection") } + model.editorActionHandled(id:action.id,applied:true) + } else { XCTFail("Missing navigation action") } + model.renumber(start:63999,increment:1); XCTAssertNil(model.editorAction); XCTAssertEqual(model.source,source) + await withCheckedContinuation { done in machine.shutdown { done.resume() } } + } + +} diff --git a/platforms/macos/Tests/BinaryTests.swift b/platforms/macos/Tests/BinaryTests.swift new file mode 100644 index 0000000..4a2b4c7 --- /dev/null +++ b/platforms/macos/Tests/BinaryTests.swift @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class BinaryTests: XCTestCase { + // Authored RAM program: LDA #$6B; STA $5000; BRA *, then transfer to $3000. + private let binary = Data([0,0,7,0x30,0,0x86,0x6b,0xb7,0x50,0,0x20,0xfe,255,0,0,0x30,0]) + @MainActor private func step(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { done in operation { done.resume(returning: $0) } } + } + @MainActor private func until(_ condition: () -> Bool) async throws { + for _ in 0..<500 { + if condition() { return }; try await Task.sleep(nanoseconds: 10_000_000) + } + XCTFail("Binary operation timed out"); throw NSError(domain: "TestTimeout", code: 1) + } + func testFileBoundsCasePathsAndReadOnlyInput() throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let url = folder.appendingPathComponent("Program é.BIN") + try binary.write(to: url) + try FileManager.default.setAttributes([.posixPermissions: 0o444], ofItemAtPath: url.path) + XCTAssertEqual(try BinaryFile.read(url), binary) + let link = folder.appendingPathComponent("Linked.bin") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: url) + XCTAssertEqual(try BinaryFile.read(link), binary) + XCTAssertThrowsError(try BinaryFile.read(folder)) + XCTAssertThrowsError(try BinaryFile.read(folder.appendingPathComponent("Missing.bin"))) + let bad = folder.appendingPathComponent("bad.bin") + for bytes in [Data(),Data(repeating: 0,count:BinaryFile.limit+1)] { + try bytes.write(to: bad); XCTAssertThrowsError(try BinaryFile.read(bad)) + } + let wrong = folder.appendingPathComponent("Program.rom"); try binary.write(to: wrong) + XCTAssertThrowsError(try BinaryFile.read(wrong)) + XCTAssertEqual(try Data(contentsOf: url),binary, "Loading never writes the host binary") + } + @MainActor func testBridgeQuickLoadAndRejectionOnBothCPUs() async throws { + for cpu in [false,true] { + let controller = VCCMachineController() + var state = await step { controller.quickLoadBinary(binary, completion: $0) } + XCTAssertEqual(state.state,.empty); XCTAssertNotNil(state.errorMessage) + _ = await step { controller.setAudioEnabled(false,volume:0,completion:$0) } + state = await step { controller.loadDiagnostic(use6309:cpu,completion:$0) } + let generation = state.generation + state = await step { controller.quickLoadBinary(binary,completion:$0) } + XCTAssertNil(state.errorMessage); XCTAssertEqual(state.state,.running); XCTAssertEqual(state.programCounter,0x3000) + XCTAssertEqual(state.generation,generation) + // The callback is captured before the next timer frame. Poll until executed. + for _ in 0..<200 { + state = await step(controller.snapshot) + if state.frames>0 { break }; try await Task.sleep(nanoseconds:10_000_000) + } + XCTAssertGreaterThan(state.frames,0); XCTAssertEqual(state.programCounter,0x3005) + state = await step(controller.pause); let before = state + for bytes in [Data(),binary.dropLast(),binary+Data([0]),Data(repeating:0,count:BinaryFile.limit+1)] { + state = await step { controller.quickLoadBinary(Data(bytes),completion:$0) } + XCTAssertNotNil(state.errorMessage); XCTAssertEqual(state.state,.paused) + XCTAssertEqual(state.programCounter,before.programCounter); XCTAssertEqual(state.cycles,before.cycles) + } + _ = await step(controller.shutdown) + state = await step { controller.quickLoadBinary(binary,completion:$0) } + XCTAssertEqual(state.state,.closed); XCTAssertNotNil(state.errorMessage) + } + } + @MainActor func testModelStartsBinaryAndLeavesFailuresPaused() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories:true) + defer { try? FileManager.default.removeItem(at:folder) } + let url=folder.appendingPathComponent("Probe.BIN"), bad=folder.appendingPathComponent("Truncated.bin") + try binary.write(to:url); try binary.dropLast().write(to:bad) + let suite = "VCCBinaryTests-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + for cpu in [false,true] { + let controller=VCCMachineController() + let model=MachineModel(diskStore:.init(url:folder.appendingPathComponent("settings.json")),controller:controller, displayDefaults:defaults) + do { + XCTAssertFalse(model.canQuickLoad) + try await until { !model.busy }; XCTAssertFalse(model.canQuickLoad) + model.loadDiagnostic(); try await until { !model.busy } + var settings = model.settings; settings.use6309 = cpu + model.applyMachineSettings(settings); try await until { !model.busy } + XCTAssertTrue(model.canQuickLoad) + let focus=model.focusRequest, epoch=model.inputEpoch + model.loadBinary(url); XCTAssertFalse(model.canQuickLoad) + try await until { !model.busy } + XCTAssertEqual(model.state,.running); XCTAssertEqual(model.binaryName,"Probe.BIN") + XCTAssertNil(model.error); XCTAssertNil(model.fileError) + XCTAssertGreaterThan(model.focusRequest,focus); XCTAssertGreaterThan(model.inputEpoch,epoch) + model.loadBinary(bad); try await until { !model.busy } + XCTAssertEqual(model.state,.paused); XCTAssertNotNil(model.error) + XCTAssertEqual(model.binaryName,"Probe.BIN"); XCTAssertTrue(model.canQuickLoad) + model.loadBinary(folder.appendingPathComponent("Missing.bin")); try await until { !model.busy } + XCTAssertEqual(model.state,.paused); XCTAssertNotNil(model.fileError) + model.loadBinary(url); try await until { !model.busy } + XCTAssertNil(model.fileError); XCTAssertNil(model.error); XCTAssertEqual(model.state,.running) + model.reset(); try await until { !model.busy }; XCTAssertNil(model.binaryName) + } catch { + await withCheckedContinuation { c in model.shutdown { c.resume() } }; throw error + } + await withCheckedContinuation { c in model.shutdown { c.resume() } } + XCTAssertFalse(model.canQuickLoad) + } + } +} diff --git a/platforms/macos/Tests/CMOCBuildHistoryTests.swift b/platforms/macos/Tests/CMOCBuildHistoryTests.swift new file mode 100644 index 0000000..fddc351 --- /dev/null +++ b/platforms/macos/Tests/CMOCBuildHistoryTests.swift @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CMOCBuildHistoryTests: XCTestCase { + private var root: URL! + private var builds: URL { root.appendingPathComponent("Builds") } + private var project: URL { root.appendingPathComponent("Project") } + private var trash: URL { root.appendingPathComponent("Trash") } + override func setUpWithError() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOC-History-" + UUID().uuidString) + for url in [builds, project, trash] { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) } + } + override func tearDownWithError() throws { try? FileManager.default.removeItem(at: root) } + private func history() -> CMOCBuildHistory { + let destination = trash + return CMOCBuildHistory(root: builds) { url in + try FileManager.default.moveItem(at: url, to: destination.appendingPathComponent(url.lastPathComponent)) + } + } + private func artifact(_ name: String = "main.bin") throws -> CMOCBuildArtifact { + let id = UUID(), directory = builds.appendingPathComponent(id.uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let source = Data("int main(void) { return 0; }".utf8), binary = Data([0, 1, 2, 3]) + try source.write(to: directory.appendingPathComponent("main.c")) + try binary.write(to: directory.appendingPathComponent(name)) + return CMOCBuildArtifact(id: id, directory: directory, source: String(decoding: source, as: UTF8.self), + sourceData: source, sourceSHA256: CMOCProject.sha256(source), binaryData: binary, buildLog: "", + diskRelativePath: name.hasSuffix(".dsk") ? name : nil) + } + func testCompletedHistoryPersistsAndProtectsLiveSessions() throws { + let artifact = try artifact(), owner = history(), other = history() + try owner.record(artifact, project: project) + let entries = try owner.entries(project: project) + XCTAssertEqual(entries.count, 1) + XCTAssertEqual(entries[0].id, artifact.id) + XCTAssertEqual(entries[0].byteCount, Int64(artifact.sourceData.count + artifact.binaryData.count)) + XCTAssertNil(entries[0].protectionReason) + XCTAssertNotNil(try other.entries(project: project)[0].protectionReason) + XCTAssertTrue(try other.remove(ids: [artifact.id], project: project, protectedIDs: []).removedIDs.isEmpty) + XCTAssertTrue(try owner.remove(ids: [artifact.id], project: project, protectedIDs: [artifact.id]).removedIDs.isEmpty) + XCTAssertTrue(FileManager.default.fileExists(atPath: artifact.directory.path)) + XCTAssertTrue(try other.entries(project: root.appendingPathComponent("OtherProject")).isEmpty) + } + func testEligibleCleanupMovesOnlyCompletedSnapshotAndPreservesRunDisk() throws { + let artifact = try artifact("hello.dsk") + var owner: CMOCBuildHistory? = history() + try owner!.record(artifact, project: project) + let run = root.appendingPathComponent("Development Runs/Run-1/hello.dsk") + try FileManager.default.createDirectory(at: run.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data([9, 8, 7]).write(to: run) + try Data("Finder metadata".utf8).write(to: artifact.directory.appendingPathComponent(".DS_Store")) + owner = nil // Simulate quitting the app; an abandoned flock is released. + let reopened = history() + XCTAssertNil(try reopened.entries(project: project)[0].protectionReason) + let removed = try reopened.remove(ids: [artifact.id], project: project, protectedIDs: []) + XCTAssertEqual(removed.removedIDs, [artifact.id]); XCTAssertTrue(removed.retained.isEmpty) + XCTAssertFalse(FileManager.default.fileExists(atPath: artifact.directory.path)) + XCTAssertTrue(FileManager.default.fileExists(atPath: trash.appendingPathComponent(artifact.id.uuidString + "/hello.dsk").path)) + XCTAssertEqual(try Data(contentsOf: run), Data([9, 8, 7])) + } + func testChangedMediaAddedHiddenFilesAndMissingFilesAreRetained() throws { + let owner = history() + let changed = try artifact("hello.dsk"), added = try artifact(), missing = try artifact() + for artifact in [changed, added, missing] { try owner.record(artifact, project: project) } + try Data([4, 5, 6]).write(to: changed.directory.appendingPathComponent("hello.dsk")) + try Data("keep".utf8).write(to: added.directory.appendingPathComponent(".user-notes")) + try FileManager.default.removeItem(at: missing.sourceURL) + XCTAssertTrue(try owner.entries(project: project).allSatisfy { $0.protectionReason != nil }) + let result = try owner.remove(ids: [changed.id, added.id, missing.id], project: project, protectedIDs: []) + XCTAssertTrue(result.removedIDs.isEmpty); XCTAssertEqual(result.retained.count, 3) + for artifact in [changed, added, missing] { XCTAssertTrue(FileManager.default.fileExists(atPath: artifact.directory.path)) } + } + func testUnrecognizedLinkedAndForeignDirectoriesAreNeverCleaned() throws { + let owner = history(), unknown = try artifact(), foreign = try artifact(), linked = UUID() + try owner.record(foreign, project: root.appendingPathComponent("Other")) + try FileManager.default.createSymbolicLink(at: builds.appendingPathComponent(linked.uuidString), withDestinationURL: project) + XCTAssertTrue(try owner.entries(project: project).isEmpty) + let result = try owner.remove(ids: [unknown.id, foreign.id, linked], project: project, protectedIDs: []) + XCTAssertTrue(result.removedIDs.isEmpty); XCTAssertEqual(result.retained.count, 3) + XCTAssertTrue(FileManager.default.fileExists(atPath: project.path)) + XCTAssertTrue(FileManager.default.fileExists(atPath: unknown.directory.path)) + } + func testReservedNamesAndReplacedLeaseFailClosed() throws { + let owner = history(), collision = try artifact() + try Data("recipe output".utf8).write(to: collision.directory.appendingPathComponent(CMOCBuildHistory.manifestName)) + XCTAssertThrowsError(try owner.record(collision, project: project)) + XCTAssertEqual(try String(contentsOf: collision.directory.appendingPathComponent(CMOCBuildHistory.manifestName)), "recipe output") + let artifact = try artifact() + try owner.record(artifact, project: project) + let lease = artifact.directory.appendingPathComponent(CMOCBuildHistory.leaseName) + try FileManager.default.removeItem(at: lease) + try Data().write(to: lease) + XCTAssertNotNil(try owner.entries(project: project).first { $0.id == artifact.id }?.protectionReason) + XCTAssertTrue(try owner.remove(ids: [artifact.id], project: project, protectedIDs: []).removedIDs.isEmpty) + } + func testServiceRecordsSuccessfulBuildsButNotFailedAttempts() async throws { + let project = try CMOCProject.create(at: root.appendingPathComponent("Build Project")) + let toolchain = root.appendingPathComponent("Tools"), bin = toolchain.appendingPathComponent("bin") + try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true) + for name in ["make", "cmoc", "cpp", "lwasm", "lwlink"] { + let script = name == "make" ? "for ext in bin o s lst map link; do printf fixture > main.$ext; done" : "exit 0" + let url = bin.appendingPathComponent(name) + try Data(("#!/bin/sh\n" + script + "\n").utf8).write(to: url) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path) + } + let service = CMOCBuildService(toolchain: toolchain, buildRoot: builds) + let first = try await service.build(project: project, source: project.readSource()) + let second = try await service.build(project: project, overlays: [:]) + XCTAssertEqual(Set(try service.history(project: project.directory).map(\.id)), [first.id, second.id]) + try Data("#!/bin/sh\nexit 2\n".utf8).write(to: bin.appendingPathComponent("make")) + do { _ = try await service.build(project: project, overlays: [:]); XCTFail("Expected recipe failure") } + catch { XCTAssertTrue(error.localizedDescription.contains("exit 2")) } + XCTAssertEqual(Set(try service.history(project: project.directory).map(\.id)), [first.id, second.id]) + } + +} diff --git a/platforms/macos/Tests/CMOCBuildServiceTests.swift b/platforms/macos/Tests/CMOCBuildServiceTests.swift new file mode 100644 index 0000000..091dd4a --- /dev/null +++ b/platforms/macos/Tests/CMOCBuildServiceTests.swift @@ -0,0 +1,2177 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest +import AppKit +import SwiftUI + +final class CMOCBuildServiceTests: XCTestCase { + private var folder: URL! + override func setUpWithError() throws { + folder = FileManager.default.temporaryDirectory.appendingPathComponent("CMOC tests " + UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + } + override func tearDownWithError() throws { try? FileManager.default.removeItem(at: folder) } + + private func project() throws -> CMOCProject { try CMOCProject.create(at: folder.appendingPathComponent("My Project")) } + private func toolchain(make: String) throws -> URL { + let root = folder.appendingPathComponent("Tool Chain") + let bin = root.appendingPathComponent("bin") + try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true) + for name in ["make", "cmoc", "cpp", "lwasm", "lwlink"] { + let url = bin.appendingPathComponent(name) + let script = name == "make" ? make : "exit 0\n" + try Data(("#!/bin/sh\n" + script).utf8).write(to: url) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path) + } + return root + } + private let successful = """ + test "$1" = '--no-print-directory' || exit 71 + test "$4" = 'MAKE=make' || exit 72 + test -x "$CMOC" || exit 73 + printf 'compiler stdout\\n' + printf 'compiler stderr\\n' >&2 + for ext in bin o s lst map link; do printf 'fixture' > "main.$ext"; done + """ + + func testPublicPlaytestProcessorSelectionIsCanonicalAndDefaultsToMC6809() throws { + XCTAssertEqual(try MCPPlaytestProcessor.selected(nil), .mc6809) + XCTAssertEqual(try MCPPlaytestProcessor.selected("MC6809").workerCPU, "6809") + XCTAssertEqual(try MCPPlaytestProcessor.selected("HD6309").workerCPU, "6309") + for invalid: Any in ["6809", "6309", "hd6309", "", NSNull(), true, 9, [], [:]] { + XCTAssertThrowsError(try MCPPlaytestProcessor.selected(invalid)) + } + } + + @MainActor func testAcceptedPlaytestStartupRemainsPollableAndLaunchesOnlyOnce() async throws { + let start = MCPOwnedPlaytestStart(identity: "exact-selection", requestID: "start-once", + projectID: "project", revision: 7, artifactID: "artifact", processor: .hd6309) + let began = expectation(description: "Preparation reached suspended work") + var resume: CheckedContinuation? + var launches = 0 + start.launch { operation in + launches += 1 + operation.updatePhase("booting") + await withCheckedContinuation { resume = $0; began.fulfill() } + return ["run_id": operation.runID, "field_clock": 61, "png_base64": "not-for-metadata"] + } + let accepted = start.fields + XCTAssertEqual(accepted["status"] as? String, "starting") + XCTAssertEqual(accepted["requested_processor"] as? String, "HD6309") + XCTAssertNil(accepted["execution_mode"], "Preparation cannot claim an observed guest CPU mode") + XCTAssertEqual(accepted["run_id"] as? String, start.runID) + XCTAssertNotNil(UUID(uuidString: start.runID)) + XCTAssertEqual(accepted["poll_tool"] as? String, "get_run") + XCTAssertEqual(accepted["busy"] as? Bool, true) + await fulfillment(of: [began], timeout: 2) + XCTAssertEqual(start.fields["phase"] as? String, "booting") + // Retrying an accepted operation cannot dispatch another worker. + start.launch { _ in launches += 1; return [:] } + XCTAssertEqual(launches, 1) + XCTAssertEqual(start.fields["status"] as? String, "starting") + try XCTUnwrap(resume).resume() + await start.waitForCompletion() + XCTAssertEqual(start.fields["status"] as? String, "ready") + XCTAssertEqual(start.fields["busy"] as? Bool, false) + let receipt = try XCTUnwrap(start.fields["receipt"] as? [String: Any]) + XCTAssertEqual(receipt["field_clock"] as? Int, 61) + XCTAssertNil(receipt["png_base64"]) + XCTAssertNil(start.fields["poll_tool"]) + } + + @MainActor func testPendingPlaytestCancellationCannotBecomeReadyAfterLateCompletion() async throws { + let start = MCPOwnedPlaytestStart(identity: "exact-selection", requestID: "cancel-me", + projectID: "project", revision: 7, artifactID: "artifact") + let began = expectation(description: "Boot is in flight") + var resume: CheckedContinuation? + var lateCleanup = 0 + start.launch { operation in + operation.updatePhase("booting") + // This fixture intentionally does not cooperate with cancellation + // until its external work returns, like a worker initialization. + await withCheckedContinuation { resume = $0; began.fulfill() } + if !operation.acceptingResult { lateCleanup += 1 } + return ["run_id": operation.runID, "field_clock": 61] + } + await fulfillment(of: [began], timeout: 2) + let reserved = start.runID + start.cancel(); start.cancel() + XCTAssertEqual(start.fields["status"] as? String, "cancelling") + XCTAssertEqual(start.fields["busy"] as? Bool, true, "Replacement must wait for late-worker cleanup") + XCTAssertEqual(start.fields["run_id"] as? String, reserved) + try XCTUnwrap(resume).resume() + await start.waitForCompletion() + XCTAssertEqual(lateCleanup, 1) + XCTAssertEqual(start.fields["status"] as? String, "cancelled") + XCTAssertEqual(start.fields["busy"] as? Bool, false) + XCTAssertNil(start.fields["receipt"], "A late result must not overwrite cancellation") + } + + @MainActor func testPlaytestStartupCancelledBeforeSchedulingSettlesWithoutEnteringPreparation() async throws { + let start = MCPOwnedPlaytestStart(identity: "cancel-before-schedule", requestID: "cancel-before-schedule", + projectID: "project", revision: 7, artifactID: "artifact") + var preparations = 0 + // Capture the previous cleanup before dispatch. A later cleanup that + // waits on this start must never become this start's own dependency. + let priorCleanup = Task { } + start.launch { operation in + guard operation.acceptingResult else { throw CancellationError() } + await priorCleanup.value + guard operation.acceptingResult else { throw CancellationError() } + preparations += 1 + return [:] + } + // No suspension has occurred, so the launch task has not begun yet. + start.cancel() + let retiredCleanup = Task { await start.waitForCompletion() } + await retiredCleanup.value + XCTAssertEqual(preparations, 0) + XCTAssertEqual(start.fields["status"] as? String, "cancelled") + XCTAssertEqual(start.fields["busy"] as? Bool, false) + } + + @MainActor func testPlaytestStartupFailureRetainsPhaseAndRedactedReasonForPolling() async throws { + let start = MCPOwnedPlaytestStart(identity: "exact-selection", requestID: "will-fail", + projectID: "project", revision: 7, artifactID: "artifact", redactionRoots: [folder]) + let privatePath = folder.appendingPathComponent("disk.dsk").path + start.launch { operation in + operation.updatePhase("reading_artifact") + throw CMOCBuildError.message("Artifact disk changed: " + privatePath) + } + await start.waitForCompletion() + XCTAssertEqual(start.fields["status"] as? String, "failed") + XCTAssertEqual(start.fields["phase"] as? String, "reading_artifact") + XCTAssertEqual(start.fields["busy"] as? Bool, false) + XCTAssertEqual(start.fields["error"] as? String, "Artifact disk changed: /disk.dsk") + XCTAssertNil(start.fields["receipt"]) + } + + func testAssistantBuildsOrdinarySourcesWithOnlyItsOwnRecipe() async throws { + let runtime = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("LocalResources/ToolchainBundle") + guard FileManager.default.isExecutableFile(atPath: runtime.appendingPathComponent("bin/cmoc").path) else { + throw XCTSkip("Stage the bundled CMOC tools") + } + let project = try self.project() + let marker = folder.appendingPathComponent("custom-recipe-ran") + try Data("$(shell touch '\(marker.path)')\n$(error custom makefile executed)\n".utf8).write(to: project.makefileURL) + let service = CMOCBuildService(toolchain: runtime, buildRoot: folder.appendingPathComponent("Artifacts")) + let examples = [ + ["main.c": CMOCProject.starterSource], + ["main.c": "#include \"value.h\"\nint main(void) { return value(); }\n", + "include/value.h": "#ifndef VALUE_H\n#define VALUE_H\nint value(void);\n#endif /* VALUE_H */\n", + "root.h": "#define BASE 7\n", + "src/value.c": "#include \"value.h\"\n#include \"root.h\"\n#define TWICE(n) ((n) * 2)\nint value(void) { return TWICE(BASE); }\n"] + ] + for inputs in examples { + let scope = try MCPCMOCProject(project: project, files: Array(inputs.keys) + ["Makefile", "private.txt"]) + XCTAssertFalse(scope.helloDisk) + XCTAssertEqual(scope.paths, inputs.keys.sorted()) + for (path, source) in inputs { try scope.validate(source, path: path) } + let snapshot = try scope.snapshotProject(at: folder.appendingPathComponent(UUID().uuidString), inputs: inputs) + let artifact = try await service.build(project: snapshot, overlays: inputs, action: .build) + XCTAssertTrue(artifact.hasBinary) + XCTAssertFalse(artifact.hasDisk) + XCTAssertEqual(artifact.entrySourcePath, "main.c") + XCTAssertFalse(FileManager.default.fileExists(atPath: marker.path)) + } + } + + func testAssistantSourceDirectivesCannotReachUnsharedFiles() throws { + let project = try self.project() + let scope = try MCPCMOCProject(project: project, files: ["main.c", "include/defs.h"]) + XCTAssertNoThrow(try scope.validate("/* note */ #include \"defs.h\" // local\n#if defined(FLAG)\n#endif\n", path: "main.c")) + XCTAssertNoThrow(try scope.validate("#define MIN(a,b) ((a)<(b)?(a):(b))\n", path: "main.c")) + for attack in ["/* comment\n*/ #include \"/etc/passwd\"", "#include \"../secret.h\"", "#include SECRET", + "#include ", "#pragma asm", "#define JOIN(x,y) x ## y", "/*\n*/ %:include \"/etc/passwd\"", + "#inc\\ \nlude \"/etc/passwd\"", "asm { incbin /etc/passwd }", "_CMOC_CONCAT(a,sm) { incbin blah }", "#define __GNUC__ 1", "#line 1 \"host-path\""] { + XCTAssertThrowsError(try scope.validate(attack, path: "main.c"), attack) + } + XCTAssertThrowsError(try MCPCMOCProject(project: project, files: ["main.c", "bad$(touch).c"])) + } + + func testCustomMakeAssistantAcceptsProjectAssemblyWithoutWeakeningOrdinarySourceRules() throws { + let project = try self.project() + let files = ["main.c", "video.h", "drawing.asm", "Makefile"] + let ordinary = try MCPCMOCProject(project: project, files: files) + let custom = try MCPCMOCProject(project: project, files: files, customMake: true) + let source = """ + #include + #include "video.h" + #if !defined(TERRAIN_BANK) + #error Select the terrain bank before building + #endif + static asm void draw(void) { asm { rts } } + """ + XCTAssertThrowsError(try ordinary.validate(source, path: "main.c")) + XCTAssertNoThrow(try custom.validate(source, path: "main.c")) + XCTAssertTrue(custom.paths.contains("drawing.asm")) + XCTAssertTrue(custom.paths.contains("Makefile")) + XCTAssertThrowsError(try custom.validate("int main;\0", path: "main.c")) + } + + func testRestrictedAssistantDirectiveFailureIdentifiesFileAndLine() throws { + let project = try self.project() + let scope = try MCPCMOCProject(project: project, files: ["main.c"]) + XCTAssertThrowsError(try scope.validate("/* ordinary project */\n\n#pragma asm\n", path: "main.c")) { error in + XCTAssertTrue(error.localizedDescription.contains("unsupported_source_directive")) + XCTAssertTrue(error.localizedDescription.contains("main.c:3"), error.localizedDescription) + } + } + + func testCustomMakeRecipeIdentityBindsDeclaredRecipeAndExecutableHelpersButNotCChanges() { + func captured(recipe: String = "build:\n\ttools/generate > main.bin\n", + helper: String = "#!/bin/sh\nprintf first\n", + source: String = "int main(void) { return 0; }\n", + helperMode: Int = 0o755) -> MCPCMOCMakeInputs { + MCPCMOCMakeInputs(makefile: "build.recipe", files: [ + "build.recipe": Data(recipe.utf8), "tools/generate": Data(helper.utf8), "main.c": Data(source.utf8) + ], permissions: ["build.recipe": 0o644, "tools/generate": helperMode, "main.c": 0o644], + support: CMOCBuildSupportSnapshot(files: [:], permissions: [:])) + } + let original = captured() + let changedRecipe = captured(recipe: "build:\n\ttools/generate > another.bin\n") + let changedHelper = captured(helper: "#!/bin/sh\nprintf second\n") + let changedMode = captured(helperMode: 0o744) + let changedC = captured(source: "int main(void) { return 42; }\n") + XCTAssertNotEqual(original.recipeID, changedRecipe.recipeID, "A configured Makefile may have an arbitrary filename") + XCTAssertNotEqual(original.recipeID, changedHelper.recipeID, "An executable helper need not have a script extension") + XCTAssertNotEqual(original.recipeID, changedMode.recipeID) + XCTAssertEqual(original.recipeID, changedC.recipeID, "Ordinary source changes invalidate the revision without changing recipe consent") + XCTAssertNotEqual(original, changedC) + } + + func testCustomMakeSnapshotPreservesGeneratedInputTimestampOrderingAndRefreshesDrafts() throws { + let project = try self.project() + let source = try project.readSource() + let makefile = try project.readText(relativePath: "Makefile") + let scope = try MCPCMOCProject(project: project, files: ["main.c", "Makefile", "loader.asm"], customMake: true) + let generatedDate = Date(timeIntervalSince1970: 1_000_000_000) + let assemblyDate = generatedDate.addingTimeInterval(60) + let savedSourceDate = generatedDate.addingTimeInterval(-60) + let draft = source + "\n/* editor draft */\n" + let snapshot = try scope.snapshotProject(at: folder.appendingPathComponent("Captured Project"), inputs: ["main.c": draft], + buildInputs: ["main.c": Data(source.utf8), "Makefile": Data(makefile.utf8), + "loader.asm": Data(" rts\n".utf8), "build/loader.raw": Data([0x39])], + support: nil, permissions: [:], + modificationDates: ["main.c": savedSourceDate, "loader.asm": assemblyDate, "build/loader.raw": generatedDate], + overlayPaths: ["main.c"]) + func date(_ path: String) throws -> Date { + let values = try FileManager.default.attributesOfItem(atPath: snapshot.directory.appendingPathComponent(path).path) + return try XCTUnwrap(values[.modificationDate] as? Date) + } + XCTAssertEqual(try date("build/loader.raw").timeIntervalSince1970, generatedDate.timeIntervalSince1970, accuracy: 0.001) + XCTAssertEqual(try date("loader.asm").timeIntervalSince1970, assemblyDate.timeIntervalSince1970, accuracy: 0.001) + XCTAssertLessThan(try date("build/loader.raw"), try date("loader.asm"), "Make must see the same dependency ordering in a new snapshot") + XCTAssertGreaterThan(try date("main.c"), assemblyDate, "An editor overlay must not inherit an old saved-file timestamp") + XCTAssertEqual(try snapshot.readSource(), draft) + XCTAssertEqual(try project.readSource(), source) + } + + @MainActor func testAssistantPatchIsOneRevisionAndPreservesEveryDraftOnConflict() throws { + _ = NSApplication.shared + let project = try self.project() + let a = try project.readSource(), b = "int value(void);\n" + try Data(b.utf8).write(to: project.directory.appendingPathComponent("value.h")) + let suite = UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let machine = MachineModel(diskStore: .init(url: folder.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: folder.appendingPathComponent("input.json"))) + let model = CMOCDevelopmentModel(machine: machine, defaults: defaults, buildRoot: folder.appendingPathComponent("build"), + recoveryRoot: folder.appendingPathComponent("recovery")) + try model.adopt(project) + let epoch = model.assistantEditEpoch, id = model.assistantProjectID + let first = MCPCMOCEdit(path: "main.c", before: a, after: "int main(void) { return 1; }\n") + let second = MCPCMOCEdit(path: "value.h", before: b, after: "int answer(void);\n") + let disk = ["main.c": a, "value.h": b] + XCTAssertThrowsError(try model.applyAssistantEdits([first, .init(path: "value.h", before: "", after: "wrong")], + disk: disk, projectID: id, epoch: epoch)) + XCTAssertEqual(model.source, a) + XCTAssertEqual(model.documents.count, 1) + XCTAssertEqual(model.assistantEditEpoch, epoch) + try model.applyAssistantEdits([first, second], disk: disk, projectID: id, epoch: epoch) + XCTAssertEqual(model.assistantEditEpoch, epoch + 1) + XCTAssertEqual(model.overlays, ["main.c": first.after, "value.h": second.after]) + XCTAssertEqual(try project.readSource(), a) + XCTAssertEqual(try project.readText(relativePath: "value.h"), b) + XCTAssertThrowsError(try model.applyAssistantEdits([first], disk: disk, projectID: id, epoch: epoch)) + } + + @MainActor func testGroupedPatchUndoPreservesEarlierNativeTypingAndSelection() throws { + let original = "int value;" + var draft = original + var editor: NSTextView? + var pool: CSourceEditor.Coordinator? + let view = CSourceEditor(text: Binding(get: { draft }, set: { draft = $0 }), currentLine: nil, + attach: { _, text, coordinator in editor = text; pool = coordinator }) + let host = NSHostingView(rootView: view) + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 500, height: 180), + styleMask: [.titled], backing: .buffered, defer: false) + window.contentView = host; host.layoutSubtreeIfNeeded() + let text = try XCTUnwrap(editor), buffers = try XCTUnwrap(pool) + let manager = try XCTUnwrap(text.undoManager) + manager.groupsByEvent = false + manager.beginUndoGrouping() + text.insertText(" /* local */", replacementRange: NSRange(location: original.utf16.count, length: 0)) + text.breakUndoCoalescing() + manager.endUndoGrouping() + let local = text.string, selection = text.selectedRange() + let changed = "int answer;" + buffers.setReviewedBuffers([.init(path: "main.c", before: local, after: changed)], undoing: false) + XCTAssertEqual(text.string, changed) + XCTAssertFalse(text.undoManager === manager) + buffers.setReviewedBuffers([.init(path: "main.c", before: changed, after: local)], undoing: true) + XCTAssertEqual(text.string, local) + XCTAssertEqual(text.selectedRange(), selection) + XCTAssertIdentical(text.undoManager, manager) + XCTAssertTrue(manager.canUndo) + manager.undo() + XCTAssertEqual(text.string, original) + } + + func testOrdinaryProjectCreateOpenSaveAndExternalChangeGuard() throws { + let value = try project() + XCTAssertEqual(try CMOCProject.open(at: value.directory), value) + let original = try value.readSource() + XCTAssertEqual(original, CMOCProject.starterSource) + XCTAssertThrowsError(try CMOCProject.create(at: value.directory)) + let hash = CMOCProject.sha256(Data(original.utf8)) + XCTAssertEqual(try value.saveSource("int main(void) { return 1; }\n", replacingSHA256: hash), + CMOCProject.sha256(Data("int main(void) { return 1; }\n".utf8))) + XCTAssertThrowsError(try value.saveSource(original, replacingSHA256: hash)) + XCTAssertTrue(try value.readSource().contains("return 1")) + } + + func testOpeningNeverExecutesMakefileAndRejectsInvalidText() throws { + let value = try project() + let marker = folder.appendingPathComponent("should-not-exist") + try Data("build:\n\ttouch '\(marker.path)'\n".utf8).write(to: value.makefileURL) + _ = try CMOCProject.open(at: value.directory) + XCTAssertFalse(FileManager.default.fileExists(atPath: marker.path)) + try Data([0xff, 0x00]).write(to: value.sourceURL) + XCTAssertThrowsError(try CMOCProject.open(at: value.directory)) + XCTAssertThrowsError(try value.saveSource(String(repeating: "x", count: CMOCProject.maximumSourceBytes + 1))) + } + + func testBuildUsesEditorSnapshotAndFreshOutputWithoutChangingProject() async throws { + let value = try project() + let saved = try value.readSource() + let tools = try toolchain(make: successful) + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Build Results")) + let draft = "int main(void) { return 42; }\n" + let first = try await service.build(project: value, source: draft) + let second = try await service.build(project: value, source: draft) + XCTAssertNotEqual(first.id, second.id) + XCTAssertNotEqual(first.directory, second.directory) + XCTAssertEqual(first.sourceData, Data(draft.utf8)) + XCTAssertEqual(try String(contentsOf: first.sourceURL), draft) + XCTAssertEqual(try value.readSource(), saved) + XCTAssertTrue(first.matches(source: draft)) + XCTAssertFalse(first.matches(source: draft + "\n")) + XCTAssertTrue(first.buildLog.contains("compiler stdout")) + XCTAssertTrue(first.buildLog.contains("compiler stderr")) + XCTAssertEqual(first.binaryData, Data("fixture".utf8)) + } + + func testFailedBuildDoesNotReuseEarlierOutputAndRetainsDiagnostics() async throws { + let value = try project() + let tools = try toolchain(make: successful) + let outputs = folder.appendingPathComponent("Outputs") + let service = CMOCBuildService(toolchain: tools, buildRoot: outputs) + let good = try await service.build(project: value, source: "int main(void) { return 0; }") + try Data("#!/bin/sh\nprintf 'main.c:3: error: missing semicolon\\n' >&2\nexit 2\n".utf8) + .write(to: tools.appendingPathComponent("bin/make")) + do { _ = try await service.build(project: value, source: "bad source"); XCTFail("Build should fail") } + catch let error as CMOCBuildError { + XCTAssertTrue(error.localizedDescription.contains("missing semicolon")) + XCTAssertTrue(error.localizedDescription.contains("exit 2")) + } + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: outputs.path), [good.id.uuidString]) + XCTAssertEqual(try Data(contentsOf: good.binaryURL), Data("fixture".utf8)) + } + + func testMissingArtifactsAndModifiedSourceCannotBecomeSuccessfulBuilds() async throws { + let value = try project() + let tools = try toolchain(make: "printf bin > main.bin\n") + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Outputs")) + do { _ = try await service.build(project: value, source: "int main(void){}"); XCTFail("Missing files must fail") } + catch { XCTAssertTrue(error.localizedDescription.contains("main.o")) } + try Data(("#!/bin/sh\n" + successful + "\nprintf rewritten > main.c\n").utf8) + .write(to: tools.appendingPathComponent("bin/make")) + do { _ = try await service.build(project: value, source: "int main(void){}"); XCTFail("Changed source must fail") } + catch { XCTAssertTrue(error.localizedDescription.contains("modified main.c")) } + } + + func testLargeOutputIsDrainedAndBounded() async throws { + let value = try project() + let script = "dd if=/dev/zero bs=1024 count=600 2>/dev/null | tr '\\000' X\n" + successful + let tools = try toolchain(make: script) + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Outputs")) + let result = try await service.build(project: value, source: "int main(void){}") + XCTAssertTrue(result.buildLog.contains("Build output truncated")) + XCTAssertLessThanOrEqual(result.buildLog.utf8.count, 512 * 1024) + XCTAssertTrue(result.buildLog.contains("compiler stderr"), "The final output must survive a verbose compiler") + } + + func testFailedVerboseBuildRetainsFinalLinkerFailureAndHonestCombinedOutput() async throws { + let script = """ + printf 'main.c:7: warning: fixture warning\\n' + dd if=/dev/zero bs=1024 count=600 2>/dev/null | tr '\\000' X + printf '\\nlwlink: fatal: section code exceeds 16-bit address space\\n' >&2 + printf 'make: *** [fixture-link] Error 37\\n' >&2 + exit 2 + """ + let value = try project() + let service = CMOCBuildService(toolchain: try toolchain(make: script), buildRoot: folder.appendingPathComponent("Outputs")) + do { + _ = try await service.build(project: value, source: "int main(void) { return 0; }") + XCTFail("The authored linker failure must fail the build") + } catch { + let report = CMOCBuildFailureReport.fields(for: error, redacting: [folder]) + let log = try XCTUnwrap(report["log"] as? String) + XCTAssertEqual(report["exit_code"] as? Int, 2) + XCTAssertTrue(log.contains("main.c:7: warning: fixture warning")) + XCTAssertTrue(log.contains("lwlink: fatal: section code exceeds 16-bit address space")) + XCTAssertTrue(log.contains("make: *** [fixture-link] Error 37")) + XCTAssertTrue(error.localizedDescription.contains("exit 2"), "Native errors still explain the failure") + XCTAssertEqual(report["log_truncated"] as? Bool, true) + XCTAssertEqual(report["process_output_truncated"] as? Bool, true) + XCTAssertGreaterThan(try XCTUnwrap(report["process_output_bytes"] as? Int), 600 * 1024) + XCTAssertLessThanOrEqual(log.utf8.count, 32_000) + XCTAssertEqual(report["output_streams"] as? String, "combined") + XCTAssertTrue(report["stdout"] is NSNull) + XCTAssertTrue(report["stderr"] is NSNull) + XCTAssertFalse(log.contains(folder.path)) + } + } + + func testFailureReportRedactsScratchAliasesAndBoundsUnicodeWithoutHidingTail() throws { + let root = URL(fileURLWithPath: "/private/tmp/Build scratch fixture", isDirectory: true) + let alias = URL(fileURLWithPath: "/tmp/Build scratch fixture", isDirectory: true) + let header = "\(root.path)/main.c:7: warning: fixture\n\(alias.absoluteString)main.o\n" + let text = header + String(repeating: "界🛠", count: 10_000) + "\nlwlink: fatal: too much code\n" + let capture = CMOCBuildOutput(text: text, byteCount: text.utf8.count, truncated: false, workingDirectory: root) + let report = CMOCBuildFailureReport.fields(for: CMOCBuildError.failed(status: 37, log: text, capture: capture), maximumLogBytes: 1_024) + let log = try XCTUnwrap(report["log"] as? String) + XCTAssertEqual(report["exit_code"] as? Int, 37) + XCTAssertTrue(log.contains("/main.c:7")) + XCTAssertTrue(log.contains("/main.o")) + XCTAssertFalse(log.contains("/private/tmp/")) + XCTAssertFalse(log.contains("/tmp/")) + XCTAssertFalse(log.contains("file:///")) + XCTAssertFalse(log.contains("�"), "Clipping valid Unicode must not invent replacement scalars") + XCTAssertTrue(log.hasSuffix("lwlink: fatal: too much code\n")) + XCTAssertLessThanOrEqual(log.utf8.count, 1_024) + XCTAssertEqual(report["log_truncated"] as? Bool, true) + XCTAssertEqual(report["process_output_truncated"] as? Bool, false) + + let ordinary = CMOCBuildFailureReport.fields(for: CMOCBuildError.message(text), redacting: [root], maximumLogBytes: 1_024) + XCTAssertTrue(ordinary["exit_code"] is NSNull) + XCTAssertLessThanOrEqual(try XCTUnwrap(ordinary["reason"] as? String).utf8.count, 2_048) + XCTAssertEqual(ordinary["reason_truncated"] as? Bool, true) + } + + func testRealMakeLinkerFailureKeepsSourceWarningFatalAndMakeStatus() async throws { + var settings = CMOCProjectConfiguration() + settings.buildTarget = "build" + let makefile = """ + .PHONY: build + build: + \t@printf 'main.c:7: warning: fixture warning\\n' + \t@printf 'lwlink: fatal: section code exceeds 16-bit address space\\n' >&2; exit 37 + """ + let value = try configuredProject(settings, files: ["Makefile": makefile]) + let service = CMOCBuildService(toolchain: try makeTools(), buildRoot: folder.appendingPathComponent("Outputs")) + do { + _ = try await service.build(project: value, overlays: [:], action: .build) + XCTFail("The authored linker-limit fixture must fail") + } catch { + let report = CMOCBuildFailureReport.fields(for: error, redacting: [folder]) + let log = try XCTUnwrap(report["log"] as? String) + XCTAssertEqual(report["exit_code"] as? Int, 2, "GNU Make reports its failure independently of the recipe status") + XCTAssertTrue(log.contains("main.c:7: warning: fixture warning")) + XCTAssertTrue(log.contains("lwlink: fatal: section code exceeds 16-bit address space")) + XCTAssertTrue(log.contains("Error 37")) + XCTAssertEqual(report["log_truncated"] as? Bool, false) + XCTAssertFalse(log.contains(folder.path)) + } + } + + func testBuildReportSeparatesWarningsFromErrorsAcrossToolFormats() throws { + let samples: [(String, String, String?, Int?)] = [ + ("main.c:7:2: error: missing semicolon", "compiler", "main.c", 7), + ("main.asm(9) : ERROR : Bad opcode", "assembler", "main.asm", 9), + ("lwlink: fatal: section code exceeds limit", "linker", nil, nil), + ("External symbol _absent not found in main.o:code", "linker", nil, nil), + ("Makefile:3: *** missing separator. Stop.", "make", "Makefile", 3), + ("make: *** No rule to make target 'missing.h', needed by 'main.o'. Stop.", "make", nil, nil) + ] + for (failure, stage, path, number) in samples { + let log = "main.c:2: warning: unused local\n" + failure + "\n" + let report = CMOCBuildReport(error: CMOCBuildError.failed(status: 2, log: log), visiblePaths: ["main.c", "main.asm", "Makefile"]) + let fields = report.fields(), diagnostic = try XCTUnwrap(fields["first_error"] as? [String: Any]) + XCTAssertEqual(diagnostic["severity"] as? String, "error") + XCTAssertEqual(diagnostic["raw"] as? String, failure) + XCTAssertEqual(diagnostic["stage"] as? String, stage) + XCTAssertEqual(diagnostic["path"] as? String, path) + XCTAssertEqual(diagnostic["line"] as? Int, number) + XCTAssertEqual(fields["failure_stage"] as? String, stage) + XCTAssertEqual((fields["diagnostics"] as? [[String: Any]])?.first?["severity"] as? String, "warning") + } + let echoed = "printf 'main.c:2: error: this is command text\\n'\nmain.c:5: error: expected token before 'warning:'\n" + let actual = CMOCBuildReport(error: CMOCBuildError.failed(status: 2, log: echoed), visiblePaths: ["main.c"]).fields() + XCTAssertEqual((actual["first_error"] as? [String: Any])?["line"] as? Int, 5, + "Echoed commands and quoted warning text cannot replace an actual error") + let warningFlood = String(repeating: "main.c:2: warning: repeated warning\n", count: 300) + "main.c:8: error: actual failing declaration\n" + let report = CMOCBuildReport(error: CMOCBuildError.failed(status: 2, log: warningFlood), visiblePaths: ["main.c"]) + let fields = report.fields() + XCTAssertEqual(fields["diagnostics_total"] as? Int, 301) + XCTAssertEqual(fields["diagnostics_truncated"] as? Bool, true) + XCTAssertEqual((fields["first_error"] as? [String: Any])?["line"] as? Int, 8, + "A flood of earlier warnings must not hide the actual error") + } + + func testBuildReportPagedLogRetainsRedactedUnicodeWithoutRepeatingOrSkippingBytes() throws { + let root = URL(fileURLWithPath: "/private/tmp/diagnostic source", isDirectory: true) + let original = root.path + "/main.c:3: warning: sample\n" + String(repeating: "界🛠a\n", count: 10_000) + "lwlink: fatal: final failure\n" + let capture = CMOCBuildOutput(text: original, byteCount: original.utf8.count, truncated: false, workingDirectory: root, + invocation: [root.appendingPathComponent("bin/make").path, "-f", "Makefile"], exitCode: 2) + let report = CMOCBuildReport(error: CMOCBuildError.failed(status: 2, log: original, capture: capture), visiblePaths: ["main.c"]) + let fields = report.fields(maximumLogBytes: 512) + XCTAssertEqual(fields["log_truncated"] as? Bool, true) + XCTAssertEqual(fields["process_output_truncated"] as? Bool, false) + XCTAssertEqual(fields["invocation"] as? [String], ["/bin/make", "-f", "Makefile"]) + var offset = 0, rebuilt = "", hash: String? + repeat { + let page = try report.logPage(offset: offset, limit: 1_003) + let text = try XCTUnwrap(page["log"] as? String) + XCTAssertFalse(text.contains(root.path)); XCTAssertFalse(text.contains("�")) + rebuilt += text + if let previous = hash { XCTAssertEqual(page["sha256"] as? String, previous) } + hash = page["sha256"] as? String + guard let next = page["next_offset"] as? Int else { break } + XCTAssertGreaterThan(next, offset); offset = next + } while true + XCTAssertEqual(rebuilt, report.log) + XCTAssertEqual(hash, CMOCProject.sha256(Data(rebuilt.utf8))) + XCTAssertTrue(rebuilt.hasSuffix("lwlink: fatal: final failure\n")) + XCTAssertThrowsError(try report.logPage(offset: Int.max)) + XCTAssertThrowsError(try report.logPage(offset: -1)) + XCTAssertThrowsError(try report.logPage(offset: 0, limit: 32_769)) + let unicode = CMOCBuildReport(error: CMOCBuildError.message("界🛠")) + XCTAssertThrowsError(try unicode.logPage(offset: 1)) + XCTAssertEqual(try unicode.logPage(offset: 0, limit: 1)["next_offset"] as? Int, 3) + } + + func testBuildReportIncludesSuccessfulWarningsAndHonestCommandEvidence() async throws { + let value = try project() + let tools = try toolchain(make: "printf 'main.c:2: warning: retained successful warning\\n'\n" + successful) + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Outputs")) + let artifact = try await service.build(project: value, source: "int main(void) { return 0; }") + let fields = CMOCBuildReport(artifact: artifact, redacting: [folder], visiblePaths: ["main.c"]).fields() + XCTAssertEqual(fields["exit_code"] as? Int, 0) + XCTAssertEqual((fields["diagnostics"] as? [[String: Any]])?.first?["severity"] as? String, "warning") + XCTAssertTrue(fields["first_error"] is NSNull) + XCTAssertTrue(fields["failure_stage"] is NSNull) + XCTAssertTrue(fields["failing_command"] is NSNull) + XCTAssertFalse((fields["invocation"] as? [String])?.isEmpty ?? true) + let log = "cmoc -c main.c\nmain.c:2: warning: old warning\nlwasm -o main.o main.asm\nmain.asm(3) : ERROR : Bad opcode\nmake: *** [build] Error 1\n" + let failure = CMOCBuildReport(error: CMOCBuildError.failed(status: 2, log: log)).fields() + XCTAssertEqual(failure["failing_command"] as? String, "lwasm -o main.o main.asm") + XCTAssertEqual(failure["failing_command_evidence"] as? String, "echoed_before_first_retained_error") + let silentRecipe = CMOCBuildReport(error: CMOCBuildError.failed(status: 2, log: "main.c:2: error: failing hidden recipe\n")).fields() + XCTAssertTrue(silentRecipe["failing_command"] is NSNull, "Do not invent the command hidden by @ recipes") + } + + func testMissingInputsAndPostMakeValidationHaveDifferentFailureStages() async throws { + let missing = CMOCProject(directory: folder.appendingPathComponent("missing-project")) + let tools = try toolchain(make: successful) + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Outputs")) + do { + _ = try await service.build(project: missing, overlays: [:]); XCTFail("A missing project cannot build") + } catch { + let fields = CMOCBuildReport(error: error, redacting: [folder]).fields() + XCTAssertEqual(fields["failure_stage"] as? String, "preparation") + XCTAssertTrue(fields["exit_code"] is NSNull) + XCTAssertNotNil(fields["first_error"] as? [String: Any]) + } + let value = try project() + try Data("#!/bin/sh\nprintf success-without-artifacts\n".utf8).write(to: tools.appendingPathComponent("bin/make")) + do { + _ = try await service.build(project: value, source: "int main(void) { return 0; }"); XCTFail("Missing output cannot be successful") + } catch { + let fields = CMOCBuildReport(error: error, redacting: [folder]).fields() + XCTAssertEqual(fields["failure_stage"] as? String, "validation") + XCTAssertEqual(fields["failure_kind"] as? String, "validation") + XCTAssertEqual(fields["exit_code"] as? Int, 0, "The process succeeded; validation rejected its outputs") + XCTAssertTrue((fields["log"] as? String)?.contains("main.bin") == true) + } + } + + func testRealBundledToolsExposeCompilerAssemblerLinkerAndMakeFailures() async throws { + let runtime = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources/ToolchainBundle") + try XCTSkipUnless(CMOCBuildService.requiredExecutables.allSatisfy { + FileManager.default.isExecutableFile(atPath: runtime.appendingPathComponent("bin/" + $0).path) + }, "Stage the bundled CMOC/LWTools/Make runtime") + let cases: [(String, String, String)] = [ + ("compiler", "int main(void) { return definitely_missing; }\n", "cmoc --coco --intermediate -c main.c"), + ("assembler", "int main(void) { return 0; }\n", "lwasm --6809 --format=obj -o main.o broken.asm"), + ("linker", "extern void absent(void); int main(void) { absent(); return 0; }\n", "cmoc --coco --intermediate main.c"), + ("make", "int main(void) { return 0; }\n", "$(MAKE) --no-print-directory -f Makefile definitely_missing_target") + ] + for (stage, source, command) in cases { + var settings = CMOCProjectConfiguration(); settings.buildTarget = "build" + let value = try configuredProject(settings, files: [ + "main.c": source, "broken.asm": " bogusop #1\n", + "Makefile": ".PHONY: build\nbuild:\n\t@printf 'main.c:1: warning: authored warning before failure\\n'\n\t" + command + "\n" + ], at: folder.appendingPathComponent("Project " + stage)) + let service = CMOCBuildService(toolchain: runtime, buildRoot: folder.appendingPathComponent("Real " + stage)) + do { + _ = try await service.build(project: value, overlays: [:]); XCTFail("The authored " + stage + " failure must fail") + } catch { + let fields = CMOCBuildReport(error: error, redacting: [folder, runtime], visiblePaths: ["main.c", "broken.asm", "Makefile"]).fields() + let first = try XCTUnwrap(fields["first_error"] as? [String: Any], String(describing: fields)) + XCTAssertEqual(first["severity"] as? String, "error") + XCTAssertEqual(fields["failure_stage"] as? String, stage, String(describing: fields)) + XCTAssertEqual(fields["exit_code"] as? Int, 2) + XCTAssertTrue((fields["log"] as? String)?.contains("authored warning before failure") == true) + } + } + } + + func testCancellationStopsCompilerChildrenAndRejectsConcurrentBuild() async throws { + let value = try project() + let marker = folder.appendingPathComponent("child-finished") + let tools = try toolchain(make: "(sleep 2; touch '\(marker.path)') &\nwait\n" + successful) + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Outputs")) + let task = Task { try await service.build(project: value, source: "int main(void){}") } + try await Task.sleep(nanoseconds: 150_000_000) + do { _ = try await service.build(project: value, source: "second"); XCTFail("Concurrent build must fail") } + catch { XCTAssertTrue(error.localizedDescription.contains("already running")) } + task.cancel() + do { _ = try await task.value; XCTFail("Cancelled build must fail") } + catch { XCTAssertTrue(error is CancellationError) } + try await Task.sleep(nanoseconds: 2_100_000_000) + XCTAssertFalse(FileManager.default.fileExists(atPath: marker.path), "Child compiler process must not outlive cancellation") + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: service.buildRoot.path), []) + } + + func testTimeoutAndMissingBundledToolsAreExplicit() async throws { + let value = try project() + let tools = try toolchain(make: "sleep 10\n" + successful) + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Outputs"), timeout: 0.15) + do { _ = try await service.build(project: value, source: "int main(void){}"); XCTFail("Timeout must fail") } + catch { XCTAssertTrue(error.localizedDescription.contains("time limit")) } + try FileManager.default.removeItem(at: tools.appendingPathComponent("bin/cpp")) + do { _ = try await service.build(project: value, source: "int main(void){}"); XCTFail("Missing tools must fail") } + catch { XCTAssertTrue(error.localizedDescription.contains("missing cpp")) } + } + private func configuredProject(_ settings: CMOCProjectConfiguration, files: [String: String], at directory: URL? = nil) throws -> CMOCProject { + let value: CMOCProject + if let directory { value = try CMOCProject.create(at: directory) } + else { value = try project() } + let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + try encoder.encode(settings).write(to: value.directory.appendingPathComponent(CMOCProject.configurationFilename)) + for (path, text) in files { + let url = value.directory.appendingPathComponent(path) + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: url) + } + return try CMOCProject.open(at: value.directory) + } + + private func makeTools() throws -> URL { + let runtime = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("LocalResources/ToolchainBundle/bin/make") + guard FileManager.default.isExecutableFile(atPath: runtime.path) else { throw XCTSkip("Stage bundled GNU Make for real Make integration") } + return try toolchain(make: "exec '\(runtime.path.replacingOccurrences(of: "'", with: "'\\''"))' \"$@\"\n") + } + + func testAdditionalPlaytestDisksRoundTripAndRejectAmbiguousOrEscapingDeclarations() throws { + var settings = CMOCProjectConfiguration() + settings.diskImage = "HOME.dsk" + settings.playtestDisks = ["build/world.dsk", "build/wrong.OS9"] + XCTAssertEqual(try settings.validated().playtestDisks, settings.playtestDisks) + XCTAssertEqual(try JSONDecoder().decode(CMOCProjectConfiguration.self, from: JSONEncoder().encode(settings)), settings) + let defaults = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: Data("{}".utf8)) + XCTAssertTrue(defaults.playtestDisks.isEmpty) + XCTAssertFalse(String(decoding: try JSONEncoder().encode(defaults), as: UTF8.self).contains("playtestDisks")) + for paths in [["../world.dsk"], ["/tmp/world.dsk"], ["build//world.dsk"], ["a/../world.dsk"], + ["build\\world.dsk"], [".git/world.dsk"], ["nested/.svn/world.dsk"], ["world.zip"], + ["WORLD.dsk", "world.DSK"], ["home.DSK"], (0..<9).map { "world\($0).dsk" }] { + var invalid = settings; invalid.playtestDisks = paths + XCTAssertThrowsError(try invalid.validated(), paths.joined(separator: ", ")) + } + var boundary = settings; boundary.playtestDisks = (0..<8).map { "world\($0).dsk" } + XCTAssertNoThrow(try boundary.validated()) + var invalid = settings; invalid.playtestDisks = ["world.dsk"]; invalid.resourceInputs = ["WORLD.DSK"] + XCTAssertThrowsError(try invalid.validated()) + invalid.resourceInputs = []; invalid.generatedInputs = ["world.dsk"] + XCTAssertThrowsError(try invalid.validated()) + invalid.generatedInputs = []; invalid.binary = "world.dsk" + XCTAssertThrowsError(try invalid.validated()) + invalid.binary = "main.bin"; invalid.debugManifest = "world.dsk" + XCTAssertThrowsError(try invalid.validated()) + invalid.debugManifest = nil; var recipe = CMOCMakefileSettings(); recipe.diskFiles = ["world.dsk"]; invalid.makefileSettings = recipe + XCTAssertThrowsError(try invalid.validated()) + } + + func testAdditionalPlaytestDisksAreGeneratedOutputsAndChangeTheReviewedRecipeIdentity() throws { + var settings = CMOCProjectConfiguration(); settings.diskImage = "home.dsk"; settings.playtestDisks = ["world.dsk"] + let value = try configuredProject(settings, files: ["home.dsk": "stale home", "world.dsk": "stale world"]) + let manifest = try CMOCProjectInputManifest.capture(project: value) + XCTAssertNil(manifest.files["home.dsk"]); XCTAssertNil(manifest.files["world.dsk"]) + XCTAssertEqual(manifest.entries.first { $0.path == "world.dsk" }?.role, "generated_output") + XCTAssertNil(CMOCProject.filteredInputs(["world.dsk": Data("stale".utf8)], configuration: settings)["world.dsk"]) + var changed = value; changed.configuration.playtestDisks = ["other.dsk"] + let next = try CMOCProjectInputManifest.capture(project: changed, readConfigurationFile: false) + XCTAssertNotEqual(next.identity, manifest.identity, "Additional media must be part of native reviewed recipe identity") + try Data("edited externally".utf8).write(to: value.directory.appendingPathComponent("world.dsk")) + XCTAssertEqual(try value.currentFileHashes(), manifest.files.mapValues(CMOCProject.sha256), "Stale generated media cannot change source revision") + } + + func testBuildRetainsHashBoundAdditionalPlaytestDisksWithoutTouchingProjectMedia() async throws { + var settings = CMOCProjectConfiguration(); settings.diskImage = "home.dsk"; settings.playtestDisks = ["media/world.dsk", "media/wrong.os9"] + let value = try configuredProject(settings, files: ["home.dsk": "user home", "media/world.dsk": "user world"]) + let tools = try toolchain(make: "test ! -e home.dsk || exit 81\ntest ! -e media/world.dsk || exit 82\nmkdir -p media\nprintf binary > main.bin\nprintf home > home.dsk\nprintf world > media/world.dsk\nprintf wrong > media/wrong.os9\n") + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Artifacts")) + let artifact = try await service.build(project: value, overlays: [:]) + XCTAssertEqual(artifact.playtestDiskProducts.map(\.relativePath), settings.playtestDisks) + for product in artifact.playtestDiskProducts { + let expected = Data((product.relativePath.hasSuffix("world.dsk") ? "world" : "wrong").utf8) + XCTAssertEqual(product.byteCount, expected.count); XCTAssertEqual(product.sha256, CMOCProject.sha256(expected)) + XCTAssertEqual(try artifact.playtestDiskData(for: product), expected) + XCTAssertTrue(artifact.outputPaths.contains(product.relativePath)) + } + XCTAssertEqual(artifact.diskSHA256, CMOCProject.sha256(Data("home".utf8))) + XCTAssertEqual(try artifact.playtestPrimaryDiskData(), Data("home".utf8)) + XCTAssertEqual(try Data(contentsOf: value.directory.appendingPathComponent("home.dsk")), Data("user home".utf8)) + XCTAssertEqual(try Data(contentsOf: value.directory.appendingPathComponent("media/world.dsk")), Data("user world".utf8)) + let product = try XCTUnwrap(artifact.playtestDiskProducts.first) + try Data("other".utf8).write(to: artifact.fileURL(product.relativePath)) + XCTAssertThrowsError(try artifact.playtestDiskData(for: product), "Exact-sized changed bytes cannot reuse a build receipt") + XCTAssertEqual(try artifact.playtestDiskData(for: artifact.playtestDiskProducts[1]), Data("wrong".utf8)) + XCTAssertThrowsError(try artifact.playtestDiskData(for: CMOCPlaytestDiskProduct(relativePath: "media/unknown.dsk", sha256: product.sha256, byteCount: product.byteCount))) + try Data("fake".utf8).write(to: XCTUnwrap(artifact.diskURL)) + XCTAssertThrowsError(try artifact.playtestPrimaryDiskData(), "A changed primary cannot reuse the original artifact hash") + } + + func testDeclaredPlaytestDiskReadRejectsSymbolicLeafAndParentEvenWithMatchingBytes() async throws { + var settings = CMOCProjectConfiguration(); settings.playtestDisks = ["media/world.dsk"] + let value = try configuredProject(settings, files: [:]) + let service = CMOCBuildService(toolchain: try toolchain(make: "mkdir -p media\nprintf binary > main.bin\nprintf world > media/world.dsk\n"), buildRoot: folder.appendingPathComponent("Artifacts")) + let artifact = try await service.build(project: value, overlays: [:]) + let product = try XCTUnwrap(artifact.playtestDiskProducts.first) + let disk = artifact.fileURL(product.relativePath), other = artifact.fileURL("world-copy.dsk") + try FileManager.default.moveItem(at: disk, to: other) + try FileManager.default.createSymbolicLink(at: disk, withDestinationURL: other) + XCTAssertThrowsError(try artifact.playtestDiskData(for: product)) + try FileManager.default.removeItem(at: disk) + try FileManager.default.moveItem(at: other, to: disk) + let media = artifact.fileURL("media"), moved = artifact.fileURL("media-original") + try FileManager.default.moveItem(at: media, to: moved) + try FileManager.default.createSymbolicLink(at: media, withDestinationURL: moved) + XCTAssertThrowsError(try artifact.playtestDiskData(for: product)) + } + + func testMissingOrOversizedAdditionalMediaFailsWithoutReplacingEarlierArtifact() async throws { + var settings = CMOCProjectConfiguration(); settings.diskImage = "home.dsk"; settings.playtestDisks = ["world.dsk"] + let value = try configuredProject(settings, files: [:]) + let tools = try toolchain(make: "printf binary > main.bin\nprintf home > home.dsk\nprintf world > world.dsk\n") + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Artifacts")) + let first = try await service.build(project: value, overlays: [:]) + let original = try XCTUnwrap(first.playtestDiskProducts.first) + for extra in ["rm -f world.dsk", ": > world.dsk", "dd if=/dev/zero of=world.dsk bs=524289 count=1 2>/dev/null"] { + try Data(("#!/bin/sh\nprintf binary > main.bin\nprintf home > home.dsk\n" + extra + "\n").utf8).write(to: tools.appendingPathComponent("bin/make")) + do { _ = try await service.build(project: value, overlays: [:]); XCTFail("Invalid declared media must fail: " + extra) } + catch { XCTAssertTrue(error.localizedDescription.contains("declared playtest disk world.dsk"), error.localizedDescription) } + XCTAssertEqual(try first.playtestDiskData(for: original), Data("world".utf8)) + XCTAssertEqual(try Data(contentsOf: XCTUnwrap(first.diskURL)), Data("home".utf8)) + } + } + + func testNewPlaytestMediaDeclarationCannotReuseAnIncidentalCachedDisk() async throws { + let settings = CMOCProjectConfiguration() + let value = try configuredProject(settings, files: [:]) + let tools = try toolchain(make: "printf binary > main.bin\nprintf incidental > world.dsk\n") + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Artifacts")) + let first = try await service.build(project: value, overlays: [:]) + XCTAssertTrue(first.playtestDiskProducts.isEmpty) + XCTAssertTrue(first.outputPaths.contains("world.dsk")) + var changed = settings; changed.playtestDisks = ["world.dsk"] + try JSONEncoder().encode(changed).write(to: value.directory.appendingPathComponent(CMOCProject.configurationFilename)) + try Data("#!/bin/sh\nprintf binary > main.bin\n".utf8).write(to: tools.appendingPathComponent("bin/make")) + do { _ = try await service.build(project: value, overlays: [:]); XCTFail("A new declaration needs a fresh produced disk") } + catch { XCTAssertTrue(error.localizedDescription.contains("declared playtest disk world.dsk"), error.localizedDescription) } + XCTAssertEqual(try Data(contentsOf: first.fileURL("world.dsk")), Data("incidental".utf8)) + } + + func testSuccessfulRecipeCannotDeclareASymbolicLinkAsPlaytestMedia() async throws { + var settings = CMOCProjectConfiguration(); settings.playtestDisks = ["world.dsk"] + let value = try configuredProject(settings, files: [:]) + let service = CMOCBuildService(toolchain: try toolchain(make: "printf binary > main.bin\nprintf world > real-media.raw\nln -s real-media.raw world.dsk\n"), buildRoot: folder.appendingPathComponent("Artifacts")) + do { _ = try await service.build(project: value, overlays: [:]); XCTFail("A declared disk must be a regular output, not a link") } + catch { + XCTAssertEqual(error.localizedDescription, "Copy linked resources into the project before building: world.dsk") + } + XCTAssertFalse(FileManager.default.fileExists(atPath: value.directory.appendingPathComponent("world.dsk").path)) + } + + func testCustomUtilityTargetDoesNotAdvertiseUnpromisedPlaytestMedia() async throws { + var settings = CMOCProjectConfiguration(); settings.playtestDisks = ["world.dsk"] + let value = try configuredProject(settings, files: [:]) + let service = CMOCBuildService(toolchain: try toolchain(make: "printf utility > utility.txt\n"), buildRoot: folder.appendingPathComponent("Artifacts")) + let artifact = try await service.build(project: value, overlays: [:], action: .custom, target: "utility") + XCTAssertTrue(artifact.playtestDiskProducts.isEmpty) + XCTAssertFalse(artifact.hasDisk); XCTAssertFalse(artifact.hasBinary) + } + + func testBuildSupportDirectoriesAreExplicitAndRoundTripWithoutExpandingScope() throws { + var settings = CMOCProjectConfiguration() + settings.buildSupportDirectories = ["../tools"] + XCTAssertEqual(try settings.validated().buildSupportDirectories, ["../tools"]) + let restored = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: JSONEncoder().encode(settings)) + XCTAssertEqual(restored, settings) + XCTAssertTrue(try JSONDecoder().decode(CMOCProjectConfiguration.self, from: Data("{}".utf8)).buildSupportDirectories.isEmpty) + for paths in [["tools"], ["/tmp/tools"], ["../../tools"], ["../tools/subfolder"], ["../"], ["../tools", "../tools"]] { + var invalid = settings + invalid.buildSupportDirectories = paths + XCTAssertThrowsError(try invalid.validated(), paths.joined(separator: ", ")) + } + } + + func testDeclaredSiblingSupportBuildsCustomMakeTargetsAndPreservesOriginals() async throws { + var settings = CMOCProjectConfiguration() + settings.buildSupportDirectories = ["../tools"] + settings.buildTarget = "build" + settings.diskTarget = "disk" + settings.diskImage = "game.dsk" + settings.configurations = [.init(name: "Debug", makeArguments: ["VCC_CONFIGURATION=Debug"]), + .init(name: "Release", makeArguments: ["VCC_CONFIGURATION=Release"])] + let makefile = """ + .PHONY: build disk + build: main.c ../tools/helper.sh + \t../tools/helper.sh '$(VCC_CONFIGURATION)' > main.bin + disk: build + \tcat main.bin > game.dsk + """ + let project = try configuredProject(settings, files: ["Makefile": makefile, "main.c": "int main(void) { return 0; }\n"]) + let support = folder.appendingPathComponent("tools") + try FileManager.default.createDirectory(at: support, withIntermediateDirectories: true) + let helper = support.appendingPathComponent("helper.sh") + let helperBytes = Data("#!/bin/sh\nprintf 'SUPPORT-v1:%s' \"$1\"\n".utf8) + try helperBytes.write(to: helper) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: helper.path) + let unrelated = folder.appendingPathComponent("private-reference") + try FileManager.default.createDirectory(at: unrelated, withIntermediateDirectories: true) + try Data("not a build input".utf8).write(to: unrelated.appendingPathComponent("private.txt")) + let sourceInputs = try project.inputFiles() + let originalHashes = try project.currentFileHashes() + let service = CMOCBuildService(toolchain: try makeTools(), buildRoot: folder.appendingPathComponent("Artifacts")) + let debug = try await service.build(project: project, overlays: [:], action: .build, configuration: "Debug") + let release = try await service.build(project: project, overlays: [:], action: .disk, configuration: "Release") + XCTAssertEqual(debug.binaryData, Data("SUPPORT-v1:Debug".utf8)) + XCTAssertEqual(release.binaryData, Data("SUPPORT-v1:Release".utf8)) + XCTAssertEqual(try Data(contentsOf: XCTUnwrap(release.diskURL)), release.binaryData) + XCTAssertNil(debug.diskSHA256) + XCTAssertEqual(release.diskSHA256, CMOCProject.sha256(release.binaryData)) + XCTAssertEqual(debug.fileHashes, originalHashes) + XCTAssertEqual(release.fileHashes, originalHashes) + XCTAssertFalse(originalHashes.keys.contains(where: { $0.contains("private-reference") })) + XCTAssertNotEqual(debug.compilationDirectory, release.compilationDirectory) + XCTAssertEqual(try project.inputFiles(), sourceInputs) + XCTAssertEqual(try Data(contentsOf: helper), helperBytes) + XCTAssertFalse(FileManager.default.fileExists(atPath: project.directory.appendingPathComponent("main.bin").path)) + XCTAssertFalse(FileManager.default.fileExists(atPath: project.directory.appendingPathComponent("game.dsk").path)) + let diskURL = try XCTUnwrap(release.diskURL) + try Data("changed after build".utf8).write(to: diskURL) + XCTAssertNotEqual(CMOCProject.sha256(try Data(contentsOf: diskURL)), release.diskSHA256, + "Artifact ownership must use the build's captured output digest, rather than trusting retained file contents") + + let changedBytes = Data("#!/bin/sh\nprintf 'SUPPORT-v2:%s' \"$1\"\n".utf8) + try changedBytes.write(to: helper) + let changedHashes = try project.currentFileHashes() + XCTAssertNotEqual(changedHashes, originalHashes) + let changed = try await service.build(project: project, overlays: [:], configuration: "Debug") + XCTAssertEqual(changed.binaryData, Data("SUPPORT-v2:Debug".utf8)) + XCTAssertEqual(changed.fileHashes, changedHashes) + XCTAssertEqual(debug.binaryData, Data("SUPPORT-v1:Debug".utf8), "Earlier artifacts must remain immutable") + try FileManager.default.setAttributes([.posixPermissions: 0o744], ofItemAtPath: helper.path) + XCTAssertNotEqual(try project.currentFileHashes(), changedHashes, "A helper's executable permissions are part of the approved build input") + } + + func testBuildSupportSnapshotsRejectSymlinkRootsAndLinkedMembers() throws { + var settings = CMOCProjectConfiguration() + settings.buildSupportDirectories = ["../tools"] + let project = try configuredProject(settings, files: [:]) + let manager = FileManager.default + let support = folder.appendingPathComponent("tools") + let outside = folder.appendingPathComponent("outside") + try manager.createDirectory(at: outside, withIntermediateDirectories: true) + try Data("private".utf8).write(to: outside.appendingPathComponent("secret.txt")) + try manager.createSymbolicLink(at: support, withDestinationURL: outside) + XCTAssertThrowsError(try project.currentFileHashes()) + try manager.removeItem(at: support) + try manager.createDirectory(at: support, withIntermediateDirectories: true) + try manager.createSymbolicLink(at: support.appendingPathComponent("linked.txt"), withDestinationURL: outside.appendingPathComponent("secret.txt")) + XCTAssertThrowsError(try project.currentFileHashes()) + } + + func testSupportManifestExcludesEvidenceButPreservesHelpersAndIgnoresNestedProjectAuthority() throws { + var settings = CMOCProjectConfiguration(); settings.buildSupportDirectories = ["../tools"] + let value = try configuredProject(settings, files: [:]) + let tools = folder.appendingPathComponent("tools") + let evidence = tools.appendingPathComponent("evidence") + let captures = tools.appendingPathComponent("captures") + let manager = FileManager.default + for directory in [tools, evidence, captures] { + try manager.createDirectory(at: directory, withIntermediateDirectories: true) + } + let helper = tools.appendingPathComponent("helper.sh") + try Data("#!/bin/sh\nprintf original\n".utf8).write(to: helper) + try manager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: helper.path) + // An intentionally retained native helper remains an input in this + // explicitly approved support root, even though ordinary host build + // products in a project are excluded from source identity. + let native = tools.appendingPathComponent("native-helper") + try Data([0xcf, 0xfa, 0xed, 0xfe, 0, 0, 0, 0]).write(to: native) + try manager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: native.path) + let nested = tools.appendingPathComponent(CMOCProject.configurationFilename) + try Data("{\"buildSupportDirectories\":[\"../unapproved-neighbor\"],\"resourceInputs\":[\"../private.txt\"]}".utf8).write(to: nested) + // No such neighbor exists. Its settings are plain retained bytes; + // parsing them would either fail or expand beyond the approved root. + let first = try value.supportSnapshot() + let originalManifest = try CMOCProjectInputManifest.capture(project: value) + XCTAssertNotNil(first.files["../tools/helper.sh"]) + XCTAssertNotNil(first.files["../tools/native-helper"]) + XCTAssertNotNil(first.files["../tools/" + CMOCProject.configurationFilename]) + try Data(repeating: 0x41, count: 128 * 1024).write(to: evidence.appendingPathComponent("notes.json")) + try Data(repeating: 0x42, count: 128 * 1024).write(to: captures.appendingPathComponent("frame.png")) + try Data("{\"result\":\"observed\"}".utf8).write(to: tools.appendingPathComponent("trial-receipt.json")) + XCTAssertEqual(try value.supportSnapshot(), first) + XCTAssertEqual(try CMOCProjectInputManifest.capture(project: value).identity, originalManifest.identity) + XCTAssertEqual(try value.supportFileHashes(), first.hashes) + try Data("#!/bin/sh\nprintf revised\n".utf8).write(to: helper) + XCTAssertNotEqual(try value.supportSnapshot(), first) + XCTAssertNotEqual(try CMOCProjectInputManifest.capture(project: value).identity, originalManifest.identity) + XCTAssertEqual(try Data(contentsOf: native), first.files["../tools/native-helper"]) + } + + func testBuildCannotAcceptAnArtifactAfterMutatingItsCopiedSupportInputs() async throws { + var settings = CMOCProjectConfiguration() + settings.buildSupportDirectories = ["../tools"] + settings.buildTarget = "build" + let value = try configuredProject(settings, files: ["Makefile": """ + .PHONY: build + build: + \tprintf changed > ../tools/input.txt + \tprintf binary > main.bin + """]) + let support = folder.appendingPathComponent("tools") + try FileManager.default.createDirectory(at: support, withIntermediateDirectories: true) + let original = Data("original support input".utf8) + let input = support.appendingPathComponent("input.txt") + try original.write(to: input) + let service = CMOCBuildService(toolchain: try makeTools(), buildRoot: folder.appendingPathComponent("Artifacts")) + do { + _ = try await service.build(project: value, overlays: [:]) + XCTFail("A recipe that changes copied support inputs cannot establish build identity") + } catch { + XCTAssertTrue(error.localizedDescription.contains("modified its build-support files"), error.localizedDescription) + } + XCTAssertEqual(try Data(contentsOf: input), original, "The original support folder must never be the build working copy") + XCTAssertFalse(FileManager.default.fileExists(atPath: value.directory.appendingPathComponent("main.bin").path)) + } + + func testBuildRejectsMutationOfCustomNamedMakefileAndPreservesTheOriginal() async throws { + var settings = CMOCProjectConfiguration() + settings.makefile = "build.recipe" + settings.buildTarget = "build" + let recipe = """ + .PHONY: build + build: + \tprintf replaced > build.recipe + \tprintf binary > main.bin + """ + let project = try configuredProject(settings, files: ["build.recipe": recipe]) + let service = CMOCBuildService(toolchain: try makeTools(), buildRoot: folder.appendingPathComponent("Artifacts")) + do { + _ = try await service.build(project: project, overlays: [:]) + XCTFail("A configured Makefile must remain part of the verified input identity regardless of its filename") + } catch { + XCTAssertTrue(error.localizedDescription.contains("modified build.recipe"), error.localizedDescription) + } + XCTAssertEqual(try project.readText(relativePath: "build.recipe"), recipe) + XCTAssertFalse(FileManager.default.fileExists(atPath: project.directory.appendingPathComponent("main.bin").path)) + } + + func testMultiFileConfigurationDiscoveryAndSafeDocumentPaths() throws { + var settings = CMOCProjectConfiguration() + settings.entrySource = "source/start.c"; settings.binary = "output/game.bin"; settings.buildTarget = "all" + settings.diskTarget = "disk"; settings.diskImage = "output/game.dsk"; settings.launchMode = .disk + settings.debugManifest = "output/game.debug.json" + settings.launchCommands = ["DOS"]; settings.jobs = 4 + let value = try configuredProject(settings, files: ["source/start.c": "int main(void) { return 0; }\n", "include/game.h": "#define VALUE 1\n", "assets/data.txt": "WORDS\n"]) + XCTAssertEqual(value.configuration, settings) + XCTAssertEqual(try value.readSource(), "int main(void) { return 0; }\n") + XCTAssertTrue(try value.fileEntries().contains(where: { $0.relativePath == "include/game.h" && $0.isEditable })) + XCTAssertThrowsError(try value.fileURL(relativePath: "../outside.c")) + let original = try value.readText(relativePath: "include/game.h") + let hash = CMOCProject.sha256(Data(original.utf8)) + _ = try value.saveText("#define VALUE 2\n", relativePath: "include/game.h", replacingSHA256: hash) + XCTAssertThrowsError(try value.saveText(original, relativePath: "include/game.h", replacingSHA256: hash)) + try FileManager.default.createSymbolicLink(at: value.directory.appendingPathComponent("linked"), withDestinationURL: folder) + XCTAssertThrowsError(try value.fileURL(relativePath: "linked/outside.c")) + XCTAssertThrowsError(try value.fileEntries()) + } + + func testBankedManifestIsGeneratedOutputAndDoesNotFailAnOtherwiseSuccessfulBuild() async throws { + var settings = CMOCProjectConfiguration() + settings.debugManifest = "game.debug.json" + let value = try configuredProject(settings, files: ["main.c": "int main(void) { return 0; }\n", "game.debug.json": "stale local manifest"]) + XCTAssertFalse(try value.fileEntries().contains { $0.relativePath == "game.debug.json" }) + let tools = try toolchain(make: "test ! -e game.debug.json || exit 92\nprintf packed > main.bin\nprintf malformed > game.debug.json\n") + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Artifacts")) + let artifact = try await service.build(project: value, overlays: [:]) + XCTAssertEqual(artifact.debugManifestRelativePath, "game.debug.json") + XCTAssertEqual(artifact.binaryData, Data("packed".utf8)) + XCTAssertThrowsError(try artifact.bankedDebugLayout()) + XCTAssertThrowsError(try CMOCProjectSourceMap.parse(artifact: artifact), "A configured invalid manifest must never fall back to flat mapping") + XCTAssertEqual(try String(contentsOf: value.directory.appendingPathComponent("game.debug.json"), encoding: .utf8), "stale local manifest") + settings.debugManifest = "../escape.json" + XCTAssertThrowsError(try settings.validated()) + settings.debugManifest = "main.c" + XCTAssertThrowsError(try settings.validated()) + } + + func testProjectWithoutMainOrMetadataDiscoversCEntryWithoutExecutingMake() throws { + let value = try project() + try FileManager.default.moveItem(at: value.sourceURL, to: value.directory.appendingPathComponent("game.c")) + let opened = try CMOCProject.open(at: value.directory) + XCTAssertEqual(opened.configuration.entrySource, "game.c") + XCTAssertEqual(opened.configuration.binary, "game.bin") + XCTAssertEqual(opened.configuration.buildTarget, "") + var bad = CMOCProjectConfiguration(); bad.binary = "../wrong.bin" + XCTAssertThrowsError(try bad.validated()) + bad = .init(); bad.configurations = [.init(name: "Bad", makeArguments: ["--eval=anything"])] + XCTAssertThrowsError(try bad.validated()) + } + + func testImportedMakefilesDelegateDefaultGoalToMakeWithoutChangingSources() async throws { + let tools = try makeTools() + let cases: [(String, String, String?)] = [ + ("first", """ + package-image: + \tprintf FIRST > main.bin + build: + \t@exit 91 + """, nil), + ("included", """ + include goals.mk + wrong-first: + \t@exit 92 + $(PRODUCT_GOAL): + \tprintf INCLUDED > main.bin + """, "PRODUCT_GOAL = selected-by-include\n.DEFAULT_GOAL := $(PRODUCT_GOAL)\n"), + ("conditional", """ + ifeq ($(VCC_CONFIGURATION),Release) + .DEFAULT_GOAL := shipping + else + .DEFAULT_GOAL := development + endif + development: + \tprintf DEBUG > main.bin + shipping: + \tprintf RELEASE > main.bin + """, nil) + ] + for (name, makefile, include) in cases { + let root = folder.appendingPathComponent(name) + let original = try CMOCProject.create(at: root) + let text = makefile + "\nclean:\n\trm -f main.bin\n" + try Data(text.utf8).write(to: original.makefileURL) + if let include { try Data(include.utf8).write(to: root.appendingPathComponent("goals.mk")) } + let opened = try CMOCProject.open(at: root) + XCTAssertTrue(opened.configuration.buildTarget.isEmpty) + let inputs = try opened.inputFiles() + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Results-" + name)) + let result = try await service.build(project: opened, overlays: [:]) + let expected = name == "first" ? "FIRST" : name == "included" ? "INCLUDED" : "DEBUG" + XCTAssertEqual(result.binaryData, Data(expected.utf8)) + let rebuilt = try await service.build(project: opened, overlays: [:], action: .rebuild) + XCTAssertEqual(rebuilt.binaryData, result.binaryData) + XCTAssertTrue(rebuilt.buildLog.contains("rm -f main.bin")) + if name == "conditional" { + let release = try await service.build(project: opened, overlays: [:], configuration: "Release") + XCTAssertEqual(release.binaryData, Data("RELEASE".utf8)) + } + XCTAssertEqual(try opened.inputFiles(), inputs, "Import and build leave the original project unchanged") + XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent(CMOCProject.configurationFilename).path)) + } + } + + func testExplicitBuildTargetOverridesMakeDefaultAndMissingTargetMeansDefault() async throws { + let tools = try makeTools() + let makefile = """ + .DEFAULT_GOAL := other + other: + \tprintf DEFAULT > main.bin + requested: + \tprintf EXPLICIT > main.bin + """ + var settings = CMOCProjectConfiguration(); settings.buildTarget = "requested" + let project = try configuredProject(settings, files: ["Makefile": makefile]) + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Results")) + let explicit = try await service.build(project: project, overlays: [:]) + XCTAssertEqual(explicit.binaryData, Data("EXPLICIT".utf8)) + let missing = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: Data("{}".utf8)) + XCTAssertTrue(try missing.validated().buildTarget.isEmpty) + let useDefault = try await service.build(project: project, overlays: [CMOCProject.configurationFilename: "{}"]) + XCTAssertEqual(useDefault.binaryData, Data("DEFAULT".utf8)) + var invalid = missing; invalid.cleanTarget = "" + XCTAssertThrowsError(try invalid.validated()) + invalid = missing; invalid.diskTarget = "" + XCTAssertThrowsError(try invalid.validated()) + invalid = missing; invalid.buildTarget = "--eval=unsafe" + XCTAssertThrowsError(try invalid.validated()) + } + + func testBundledLibraryBindingsArePortableVerifiedAndPreserveMakeFlags() async throws { + let tools = try makeTools(), manager = FileManager.default + let archive = Data("ARCHIVE".utf8), header = Data("/* HEADER */".utf8) + for (path, bytes) in ["share/cmoc/lib/libexample.a": archive, "share/cmoc/include/example.h": header, "LICENSES/NOTICE.txt": Data("Test notice".utf8)] { + let url = tools.appendingPathComponent(path) + try manager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try bytes.write(to: url) + } + let manifest: [String: Any] = ["libraries": ["example": ["version": "1.2.3", "license": "Test fixture", "filesSHA256": [ + "share/cmoc/lib/libexample.a": CMOCProject.sha256(archive), "share/cmoc/include/example.h": CMOCProject.sha256(header)]]]] + try JSONSerialization.data(withJSONObject: manifest).write(to: tools.appendingPathComponent("manifest.json")) + var settings = CMOCProjectConfiguration() + settings.bundledLibraries = [.init(library: "example", minimumVersion: "1.2", directoryVariable: "EXAMPLE_DIR", linkVariable: "LIBS")] + let makefile = """ + EXAMPLE_DIR = missing + LIBS = -loriginal + all: $(EXAMPLE_DIR)/libexample.a + \tcp $(EXAMPLE_DIR)/libexample.a main.bin + \tprintf '%s' '$(LIBS)' > flags.txt + \tcmp $(EXAMPLE_DIR)/example.h expected.h + """ + let project = try configuredProject(settings, files: ["Makefile": makefile, "expected.h": String(decoding: header, as: UTF8.self)]) + let before = try project.inputFiles() + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Build Products With Spaces")) + let artifact = try await service.build(project: project, overlays: [:]) + XCTAssertEqual(artifact.binaryData, archive) + let flags = try String(contentsOf: artifact.fileURL("flags.txt"), encoding: .utf8) + XCTAssertTrue(flags.hasPrefix("-loriginal -L")); XCTAssertTrue(flags.hasSuffix(" -lexample")) + XCTAssertFalse(flags.contains("Tool Chain"), "Make must receive an isolated space-free copy, never an app-bundle path") + XCTAssertEqual(try project.inputFiles(), before) + XCTAssertEqual(try Data(contentsOf: tools.appendingPathComponent("share/cmoc/lib/libexample.a")), archive) + XCTAssertEqual(try JSONDecoder().decode(CMOCProjectConfiguration.self, from: JSONEncoder().encode(settings)), settings) + XCTAssertTrue(try String(contentsOf: artifact.fileURL(".vccplus-libraries/LICENSES/NOTICE.txt"), encoding: .utf8).contains("Test notice")) + for bad in [CMOCBundledLibraryBinding(library: "example", minimumVersion: "2.0", directoryVariable: "EXAMPLE_DIR"), + CMOCBundledLibraryBinding(library: "absent", directoryVariable: "EXAMPLE_DIR")] { + var changed = settings; changed.bundledLibraries = [bad] + do { + _ = try await service.build(project: project, overlays: [CMOCProject.configurationFilename: String(decoding: JSONEncoder().encode(changed), as: UTF8.self)]) + XCTFail("Unavailable or incompatible libraries must fail") + } catch { XCTAssertTrue(error.localizedDescription.contains("library") || error.localizedDescription.contains("version")) } + } + try Data("CORRUPT".utf8).write(to: tools.appendingPathComponent("share/cmoc/lib/libexample.a")) + do { _ = try await service.build(project: project, overlays: [:]); XCTFail("Changed archive must fail integrity validation") } + catch { XCTAssertTrue(error.localizedDescription.contains("integrity")) } + } + + func testBundledLibraryVariableValidation() throws { + let minimal = try JSONDecoder().decode(CMOCBundledLibraryBinding.self, from: Data(#"{"library":"decbfile","directoryVariable":"DISK_LIB"}"#.utf8)) + XCTAssertEqual(minimal, .init(library: "decbfile", directoryVariable: "DISK_LIB")) + var settings = CMOCProjectConfiguration() + for binding in [CMOCBundledLibraryBinding(library: "../escape", directoryVariable: "LIBDIR"), + .init(library: "one", directoryVariable: "SHELL"), .init(library: "one", directoryVariable: "X\nY"), + .init(library: "one", minimumVersion: "1.x", directoryVariable: "LIBDIR"), .init(library: "one")] { + settings.bundledLibraries = [binding]; XCTAssertThrowsError(try settings.validated()) + } + settings.bundledLibraries = [.init(library: "one", directoryVariable: "DIR"), .init(library: "two", directoryVariable: "DIR")] + XCTAssertThrowsError(try settings.validated()) + settings.bundledLibraries = [.init(library: "one", directoryVariable: "DIR", linkVariable: "DIR")] + XCTAssertThrowsError(try settings.validated()) + settings.bundledLibraries = [.init(library: "one", directoryVariable: "DIR")] + settings.configurations = [.init(name: "Debug", makeArguments: ["DIR=elsewhere"])] + XCTAssertThrowsError(try settings.validated()) + XCTAssertTrue(CMOCBundledLibrary.atLeast("0.1.13", "0.1.6")) + XCTAssertTrue(CMOCBundledLibrary.atLeast("1.2", "1.2.0")) + XCTAssertFalse(CMOCBundledLibrary.atLeast("1.2", "1.2.1")) + } + + func testBundledLibrariesBuildUnmodifiedCoCoLettersMakefile() async throws { + let repo = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + let runtime = repo.appendingPathComponent("platforms/macos/LocalResources/ToolchainBundle") + try XCTSkipUnless(FileManager.default.fileExists(atPath: runtime.appendingPathComponent("share/cmoc/lib/libdskcon-standalone.a").path), "Stage the optional standalone disk library") + let root = folder.appendingPathComponent("CoCo Letters") + try FileManager.default.copyItem(at: repo.appendingPathComponent("third_party/examples/coco-letters"), to: root) + var config = CMOCProjectConfiguration() + config.binary = "letters.bin"; config.diskImage = "coco-letters-0.1.0.dsk"; config.diskTarget = "all" + config.launchMode = .disk; config.launchCommands = ["DOS"] + config.configurations = [.init(name: "Debug", makeArguments: ["INTERMEDIATE=--intermediate"])] + config.bundledLibraries = [ + .init(library: "decbfile", minimumVersion: "0.1.13", directoryVariable: "DECBFILE_LIB_DIR"), + .init(library: "bcontrol", minimumVersion: "0.1.6", directoryVariable: "BCONTROL_LIB_DIR"), + .init(library: "bsound", minimumVersion: "0.1.4", directoryVariable: "BSOUND_LIB_DIR"), + .init(library: "dskcon-standalone", linkVariable: "LIBS")] + try JSONEncoder().encode(config).write(to: root.appendingPathComponent(CMOCProject.configurationFilename)) + let project = try CMOCProject.open(at: root), before = try project.inputFiles() + let service = CMOCBuildService(toolchain: runtime, buildRoot: folder.appendingPathComponent("Game Build")) + let result = try await service.build(project: project, overlays: [:]) + XCTAssertTrue(result.hasBinary); XCTAssertTrue(result.hasDisk) + XCTAssertEqual(try Data(contentsOf: XCTUnwrap(result.diskURL)).count, 35 * 18 * 256) + let mapping = try CMOCProjectSourceMap.parse(artifact: result) + XCTAssertTrue(mapping.instructions.contains { $0.sourcePath == "main.c" }) + XCTAssertGreaterThan(Set(mapping.instructions.map(\.sourcePath)).count, 5) + XCTAssertEqual(try project.inputFiles(), before) + try await verifyBundledGameExecution(result, mapping: mapping, runtime: runtime) + let repeated = try await service.build(project: project, overlays: [:]) + XCTAssertEqual(repeated.binaryData, result.binaryData) + XCTAssertFalse(repeated.buildLog.contains("cmoc -c"), repeated.buildLog) + XCTAssertFalse(repeated.buildLog.contains("cmoc -o"), repeated.buildLog) + } + + @MainActor private func verifyBundledGameExecution(_ build: CMOCBuildArtifact, mapping: CMOCProjectSourceMap, runtime: URL) async throws { + let roms = runtime.deletingLastPathComponent().appendingPathComponent("ROMs") + try XCTSkipUnless(FileManager.default.fileExists(atPath: roms.appendingPathComponent("coco3.rom").path), "Stage licensed local ROMs for execution checks") + let rom = try Data(contentsOf: roms.appendingPathComponent("coco3.rom")) + let diskROM = try Data(contentsOf: roms.appendingPathComponent("disk11.rom")) + let disk = try Data(contentsOf: XCTUnwrap(build.diskURL)) + // The presentation's first keyboard poll is reached after the full dictionary + // has been loaded through the standalone driver, not merely after LOADM. + let source = try String(contentsOf: build.fileURL("main.c"), encoding: .utf8).components(separatedBy: "\n") + let line = try XCTUnwrap(source.firstIndex { $0.contains("while ((key = pollKeyNoLowerCase()) != 'R'") }) + 1 + let point = try XCTUnwrap(mapping.instructions.first { $0.sourcePath == "main.c" && $0.sourceLine == line }) + func command(_ body: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { continuation in body { continuation.resume(returning: $0) } } + } + for cpu in [false, true] { + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command { controller.loadDiskROM(diskROM, name: "Disk BASIC", completion: $0) } + _ = await command { controller.configureCartridges([2,0,0,0,2], roms: Array(repeating: Data(), count: 5), names: Array(repeating: "", count: 5), multiPak: true, physicalSlot: 4, completion: $0) } + _ = await command { controller.mountDisk(disk, drive: 0, name: "Letters.dsk", readOnly: true, completion: $0) } + _ = await command { controller.loadROM(rom, use6309: cpu, completion: $0) } + _ = await command(controller.resume) + var ready = false + for _ in 0..<250 { + let text: String? = await withCheckedContinuation { c in controller.copyScreenText { text, _ in c.resume(returning: text) } } + if text?.contains("OK") == true { ready = true; break } + try await Task.sleep(nanoseconds: 40_000_000) + } + XCTAssertTrue(ready) + let visible = await command(controller.snapshot) + for _ in 0..<100 { + if await command(controller.snapshot).frames >= visible.frames + 18 { break } + try await Task.sleep(nanoseconds: 20_000_000) + } + _ = await command(controller.pause) + let armed = await command { controller.debuggerArmDevelopmentBreakpoints([NSNumber(value: point.address)], guardAddresses: mapping.instructions.map { NSNumber(value: $0.address) }, guardBytes: mapping.instructions.map { Data($0.bytes) }, completion: $0) } + XCTAssertNil(armed.errorMessage) + _ = await command(controller.resume) + let paste = try CocoPaste("DOS\n", mode: .text) + _ = await command { controller.pasteChords(paste.chords.map { NSNumber(value: $0) }, completion: $0) } + var stopped = await command(controller.snapshot) + for _ in 0..<1500 { + if stopped.state != .running { break } + try await Task.sleep(nanoseconds: 20_000_000) + stopped = await command(controller.snapshot) + } + XCTAssertEqual(stopped.state, .paused, "CoCo Letters must reach its presentation after loading dictionary; 6309=\(cpu)") + XCTAssertEqual(stopped.programCounter, point.address) + XCTAssertTrue(stopped.debuggerDevelopmentAttached) + XCTAssertGreaterThan(stopped.disks[0].readEvents, visible.disks[0].readEvents + 200) + XCTAssertFalse(stopped.disks[0].dirty) + let gameLine = try XCTUnwrap(source.firstIndex { $0.trimmingCharacters(in: .whitespaces) == "playGame();" }) + 1 + let gamePoint = try XCTUnwrap(mapping.instructions.first { $0.sourcePath == "main.c" && $0.sourceLine == gameLine }) + _ = await command { controller.debuggerArmDevelopmentBreakpoints([NSNumber(value: gamePoint.address)], guardAddresses: mapping.instructions.map { NSNumber(value: $0.address) }, guardBytes: mapping.instructions.map { Data($0.bytes) }, completion: $0) } + _ = await command(controller.resume) + for character in ["R", "E", "U"] { + controller.setKeyboardMask(try XCTUnwrap(CocoKeyboard.chord(for: character))) + try await Task.sleep(nanoseconds: 200_000_000) + controller.setKeyboardMask(0) + try await Task.sleep(nanoseconds: 500_000_000) + } + let playing = await command(controller.snapshot) + XCTAssertEqual(playing.state, .paused, "RGB/Easy/User inputs must reach gameplay") + XCTAssertEqual(playing.programCounter, gamePoint.address) + _ = await command(controller.shutdown) + } + } + + func testRealMakeIncrementalDependenciesGeneratedSourcesAndImmutableResults() async throws { + var settings = CMOCProjectConfiguration() + settings.binary = "out/game.bin"; settings.buildTarget = "all"; settings.jobs = 4 + let makefile = """ + .PHONY: all clean + all: out/game.bin + out/game.bin: out/a.o out/b.o out/generated.o + \tcat $^ > $@ + out/a.o: main.c include/common.h + \t@mkdir -p out + \t@echo CC-main + \tcat $^ > $@ + out/b.o: nested/other.c include/common.h + \t@mkdir -p out + \t@echo CC-other + \tcat $^ > $@ + generated.c: assets/words.txt + \tprintf '/* generated */\\n' > $@ + \tcat $< >> $@ + out/generated.o: generated.c + \t@mkdir -p out + \t@echo CC-generated + \tcp $< $@ + clean: + \trm -rf out generated.c + """ + let value = try configuredProject(settings, files: ["Makefile": makefile, "main.c": "int first;\n", "nested/other.c": "int second;\n", + "include/common.h": "#define COMMON 1\n", "assets/words.txt": "int generated;\n", "remove-me.txt": "temporary input\n"]) + let service = CMOCBuildService(toolchain: try makeTools(), buildRoot: folder.appendingPathComponent("Outputs")) + let first = try await service.build(project: value, overlays: [:]) + XCTAssertTrue(first.buildLog.contains("CC-main")); XCTAssertTrue(first.buildLog.contains("CC-other")) + XCTAssertTrue(first.sources.keys.contains("generated.c")) + XCTAssertEqual(first.fileHashes, try value.currentFileHashes()) + XCTAssertTrue(first.hasBinary) + let firstBytes = first.binaryData + let second = try await service.build(project: value, overlays: [:]) + XCTAssertEqual(first.compilationDirectory, second.compilationDirectory) + XCTAssertNotEqual(first.directory, second.directory) + XCTAssertFalse(second.buildLog.contains("CC-main")); XCTAssertFalse(second.buildLog.contains("CC-other")) + XCTAssertEqual(firstBytes, second.binaryData) + let edited = try await service.build(project: value, overlays: ["nested/other.c": "int changed;\n"]) + XCTAssertFalse(edited.buildLog.contains("CC-main")); XCTAssertTrue(edited.buildLog.contains("CC-other")) + XCTAssertEqual(try value.readText(relativePath: "nested/other.c"), "int second;\n", "Build must not save editor drafts") + XCTAssertEqual(try Data(contentsOf: first.binaryURL), firstBytes, "Earlier debug artifacts stay immutable") + let headerEdit = try await service.build(project: value, overlays: ["include/common.h": "#define COMMON 2\n"]) + XCTAssertTrue(headerEdit.buildLog.contains("CC-main")); XCTAssertTrue(headerEdit.buildLog.contains("CC-other")) + try FileManager.default.removeItem(at: value.directory.appendingPathComponent("remove-me.txt")) + let deleted = try await service.build(project: value, overlays: [:]) + XCTAssertFalse(deleted.outputPaths.contains("remove-me.txt")) + let rebuilt = try await service.build(project: value, overlays: [:], action: .rebuild) + XCTAssertEqual(rebuilt.binaryData, firstBytes) + XCTAssertTrue(rebuilt.buildLog.contains("CC-main")); XCTAssertTrue(rebuilt.buildLog.contains("CC-generated")) + let cleaned = try await service.build(project: value, overlays: [:], action: .clean) + XCTAssertFalse(cleaned.hasBinary); XCTAssertFalse(cleaned.hasDisk) + XCTAssertFalse(cleaned.outputPaths.contains("out/game.bin")) + } + + func testRealMakeRecursiveTargetsConfigurationAndDiskArtifact() async throws { + var settings = CMOCProjectConfiguration() + settings.buildTarget = "all"; settings.diskTarget = "disk"; settings.diskImage = "game.dsk"; settings.jobs = 4 + settings.configurations = [.init(name: "Debug", makeArguments: ["MESSAGE=debug build"]), .init(name: "Release", makeArguments: ["MESSAGE=release build"])] + let value = try configuredProject(settings, files: ["Makefile": """ + CMOC ?= cmoc + .PHONY: all disk clean helper + all: helper + \t$(CMOC) + \tprintf '%s' '$(MESSAGE)' > main.bin + helper: + \t$(MAKE) -C helper + disk: all + \tcat main.bin helper/asset > game.dsk + clean: + \trm -f main.bin game.dsk helper/asset + """, "helper/Makefile": "all:\n\tprintf data > asset\n"]) + let tools = try makeTools() + let bundledMake = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("LocalResources/ToolchainBundle/bin/make") + try FileManager.default.removeItem(at: tools.appendingPathComponent("bin/make")) + try FileManager.default.copyItem(at: bundledMake, to: tools.appendingPathComponent("bin/make")) + XCTAssertTrue(tools.path.contains(" ")) + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Outputs")) + let debug = try await service.build(project: value, overlays: [:], action: .disk, configuration: "Debug") + let release = try await service.build(project: value, overlays: [:], action: .disk, configuration: "Release") + XCTAssertTrue(debug.hasDisk); XCTAssertTrue(debug.hasBinary) + XCTAssertEqual(try Data(contentsOf: XCTUnwrap(debug.diskURL)), Data("debug builddata".utf8)) + XCTAssertEqual(try Data(contentsOf: XCTUnwrap(release.diskURL)), Data("release builddata".utf8)) + XCTAssertNotEqual(debug.compilationDirectory, release.compilationDirectory) + XCTAssertFalse(FileManager.default.fileExists(atPath: value.directory.appendingPathComponent("game.dsk").path)) + } + + func testMultiFileFailureClearsPartialCacheAndCannotExposeStaleExecutable() async throws { + let value = try project() + let tools = try toolchain(make: "printf good > main.bin\n") + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Outputs")) + let original = try await service.build(project: value, overlays: [:]) + try Data("#!/bin/sh\nprintf corrupt > main.bin\nprintf 'nested/file.c:7: failure\\n'\nexit 2\n".utf8).write(to: tools.appendingPathComponent("bin/make")) + do { _ = try await service.build(project: value, overlays: [:]); XCTFail("Failed Make must fail the build") } + catch { XCTAssertTrue(error.localizedDescription.contains("nested/file.c:7")) } + XCTAssertFalse(FileManager.default.fileExists(atPath: original.compilationDirectory.path)) + XCTAssertEqual(try Data(contentsOf: original.binaryURL), Data("good".utf8)) + try Data("#!/bin/sh\nexit 0\n".utf8).write(to: tools.appendingPathComponent("bin/make")) + do { _ = try await service.build(project: value, overlays: [:]); XCTFail("No stale output may survive a failed build") } + catch { XCTAssertTrue(error.localizedDescription.contains("did not produce main.bin")) } + } + + func testBuildOnlyTargetDoesNotRequireDebugIntermediates() async throws { + var settings = CMOCProjectConfiguration(); settings.binary = nil + let value = try configuredProject(settings, files: [:]) + let service = CMOCBuildService(toolchain: try toolchain(make: "printf library > libgame.a\n"), buildRoot: folder.appendingPathComponent("Outputs")) + let artifact = try await service.build(project: value, overlays: [:]) + XCTAssertFalse(artifact.hasBinary) + XCTAssertTrue(artifact.outputPaths.contains("libgame.a")) + XCTAssertEqual(artifact.sources["main.c"], Data(CMOCProject.starterSource.utf8)) + } + func testGeneratedMakefileBuildsMultipleCFilesDependenciesResourcesAndDiskWithBundledTools() async throws { + let runtime = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources/ToolchainBundle") + guard FileManager.default.isExecutableFile(atPath: runtime.appendingPathComponent("bin/perl").path) else { throw XCTSkip("Stage the complete bundled compiler and Perl runtime") } + var generated = CMOCMakefileSettings() + generated.sources = ["main.c", "src/game.c", "generated/data.c"] + generated.includePaths = ["include"] + generated.libraryProjects = [.init(directory: "libraries/helper", target: "libhelper.a", archive: "libraries/helper/libhelper.a")] + generated.diskImage = "HELLO.dsk"; generated.diskFiles = ["assets/data.txt"]; generated.diskBootMode = .program + generated.generatedResources = [.init(outputs: ["generated/data.c"], inputs: ["assets/data.txt"], command: "printf 'int generated(void) { return 3; }\\n' > generated/data.c")] + var settings = CMOCProjectConfiguration(); settings.makefileSettings = generated + settings.diskImage = generated.diskImage; settings.diskTarget = "disk"; settings.jobs = 4 + let value = try configuredProject(settings, files: [ + "main.c": "#include \n#include \"game.h\"\nint generated(void);\nint helper(void);\nint main(void) { printf(\"%d %d %d\\n\", game(), generated(), helper()); return 0; }\n", + "generated/data.c": "int generated(void) { return 999; }\n", + "src/game.c": "#include \"game.h\"\nint game(void) { return VALUE; }\n", + "include/game.h": "#define VALUE 4\nint game(void);\n", "assets/data.txt": "DATA\n", "Makefile": try generated.generateMakefile(), + "libraries/helper/helper.c": "int helper(void) { return 7; }\n", + "libraries/helper/Makefile": "libhelper.a: helper.o\n\tlwar -c $@ $<\nhelper.o: helper.c\n\t\"$(CMOC)\" --coco -O0 --intermediate -c -o $@ $<\nclean:\n\trm -f libhelper.a helper.o helper.s helper.lst\n" + ]) + let service = CMOCBuildService(toolchain: runtime, buildRoot: folder.appendingPathComponent("Outputs")) + let first = try await service.build(project: value, overlays: [:], action: .disk) + XCTAssertTrue(first.hasBinary); XCTAssertTrue(first.hasDisk) + XCTAssertFalse(first.fileHashes.keys.contains("generated/data.c")) + XCTAssertEqual(first.sources["generated/data.c"], Data("int generated(void) { return 3; }\n".utf8)) + XCTAssertEqual(try value.readText(relativePath: "generated/data.c"), "int generated(void) { return 999; }\n") + XCTAssertEqual(try Data(contentsOf: XCTUnwrap(first.diskURL)).count, 35 * 18 * 256) + for path in ["obj/main.o", "obj/src/game.o", "obj/generated/data.o", "obj/src/game.lst", "obj/main.d", "generated/data.c"] { + XCTAssertTrue(first.outputPaths.contains(path), "Missing generated product \(path)") + } + let second = try await service.build(project: value, overlays: [:], action: .disk) + XCTAssertEqual(first.binaryData, second.binaryData) + XCTAssertFalse(second.buildLog.contains(" -c -o "), "No-op Make must not recompile") + XCTAssertFalse(second.buildLog.contains(" --dos "), "No-op Make must not rebuild the loader") + let disk = try Data(contentsOf: XCTUnwrap(first.diskURL)) + XCTAssertEqual(disk.subdata(in: (34 * 18 * 256)..<(34 * 18 * 256 + 2)), Data("OS".utf8)) + let fat = 17 * 18 * 256 + 256 + 66 + XCTAssertEqual(disk.subdata(in: fat..<(fat + 2)), Data([0xc0, 0xc0]), "Both boot-track granules must be unavailable to disk files") + XCTAssertFalse(first.fileHashes.keys.contains("obj/vcc-dos-boot/loader.c")) + XCTAssertFalse(FileManager.default.fileExists(atPath: value.directory.appendingPathComponent("obj/vcc-dos-boot/loader.c").path)) + let header = try await service.build(project: value, overlays: ["include/game.h": "#define VALUE 9\nint game(void);\n"], action: .disk) + XCTAssertTrue(header.buildLog.contains(" -c -o obj/main.o ")) + XCTAssertTrue(header.buildLog.contains(" -c -o obj/src/game.o ")) + XCTAssertFalse(header.buildLog.contains(" -c -o obj/generated/data.o ")) + XCTAssertNotEqual(first.binaryData, header.binaryData) + let libraryEdit = try await service.build(project: value, overlays: ["libraries/helper/helper.c": "int helper(void) { return 12; }\n"], action: .disk) + XCTAssertTrue(libraryEdit.buildLog.contains(" -c -o helper.o ")) + XCTAssertNotEqual(first.binaryData, libraryEdit.binaryData, "Changed library must relink the executable") + XCTAssertEqual(try value.readText(relativePath: "include/game.h"), "#define VALUE 4\nint game(void);\n") + XCTAssertFalse(FileManager.default.fileExists(atPath: value.directory.appendingPathComponent("HELLO.dsk").path)) + } + + func testGeneratedMakefileRejectsAmbiguousOrUnsafeNamesAndRetainsNativeSettings() throws { + var generated = CMOCMakefileSettings() + generated.sources = ["source name.c"] + XCTAssertThrowsError(try generated.generateMakefile()) + generated.sources = ["first.c", "first.c"] + XCTAssertThrowsError(try generated.generateMakefile()) + generated.sources = ["first.c"] + generated.generatedResources = [.init(outputs: ["generated.c"], inputs: [], command: "echo first"), .init(outputs: ["generated.c"], inputs: [], command: "echo second")] + XCTAssertThrowsError(try generated.generateMakefile()) + generated.generatedResources = [] + generated.libraryProjects = [.init(directory: "libraries/game", target: "libgame.a", archive: "libraries/game/libgame.a")] + let makefile = try generated.generateMakefile() + XCTAssertTrue(makefile.contains("$(MAKE) -C libraries/game libgame.a")) + var settings = CMOCProjectConfiguration(); settings.makefileSettings = generated + XCTAssertEqual(try JSONDecoder().decode(CMOCProjectConfiguration.self, from: JSONEncoder().encode(settings)), settings) + } + func testGeneratedMakefileProtectsDiskNamesAndSourceOutputCollisions() throws { + var settings = CMOCMakefileSettings(); settings.executable = "GAME.bin"; settings.diskImage = "GAME.dsk" + settings.diskFiles = ["assets/game.BIN"] + XCTAssertThrowsError(try settings.generateMakefile(), "Disk BASIC is case-insensitive; the data must not overwrite the executable") + settings.diskFiles = ["assets/longfilename.dat"] + XCTAssertThrowsError(try settings.generateMakefile()) + settings.diskFiles = ["assets/A.DAT", "other/a.dat"] + XCTAssertThrowsError(try settings.generateMakefile()) + settings.diskFiles = ["assets/WORDS.DAT"] + XCTAssertNoThrow(try settings.generateMakefile()) + settings.diskImage = "main.c" + XCTAssertThrowsError(try settings.generateMakefile()) + settings.diskImage = "GAME.dsk"; settings.executable = "Makefile" + XCTAssertThrowsError(try settings.generateMakefile()) + settings.executable = "GAME.bin" + settings.generatedResources = [.init(outputs: ["vccplus-project.json"], inputs: [], command: "echo invalid")] + XCTAssertThrowsError(try settings.generateMakefile()) + settings.generatedResources = [.init(outputs: ["GAME.bin"], inputs: [], command: "echo invalid")] + XCTAssertThrowsError(try settings.generateMakefile()) + settings.generatedResources = [] + let custom = try settings.generateMakefile(makefileName: "GNUmakefile") + XCTAssertTrue(custom.contains("main.c GNUmakefile")) + XCTAssertFalse(custom.contains(" main.c Makefile")) + } + func testDOSBootModesPreserveLegacyConfigurationAndRejectInvalidGeneratedTargets() throws { + let plain = try JSONDecoder().decode(CMOCMakefileSettings.self, from: Data("{}".utf8)) + XCTAssertEqual(plain.diskBootMode, .none) + var legacy = try JSONDecoder().decode(CMOCMakefileSettings.self, from: Data(#"{"diskImage":"GAME.dsk","diskBootLoader":"boot.bin"}"#.utf8)) + XCTAssertEqual(legacy.diskBootMode, .custom) + XCTAssertTrue(try legacy.generateMakefile().contains("$(INSTALL_LOADER) $@ boot.bin")) + legacy.diskBootMode = .none + XCTAssertFalse(try legacy.generateMakefile().contains("$(INSTALL_LOADER) $@")) + legacy.diskBootMode = .program + legacy.executable = "output/GAME.bin" + XCTAssertEqual(legacy.programBootCommand, "LOADM\"GAME.BIN\":EXEC") + XCTAssertEqual(try JSONDecoder().decode(CMOCMakefileSettings.self, from: JSONEncoder().encode(legacy)), legacy) + let generated = try legacy.generateMakefile() + XCTAssertTrue(generated.contains("$(INSTALL_LOADER) $@ obj/vcc-dos-boot/loader.bin")) + XCTAssertFalse(generated.contains("$(INSTALL_LOADER) $@ boot.bin")) + legacy.origin = "2600" + XCTAssertThrowsError(try legacy.generateMakefile()) + legacy.origin = "2800"; legacy.diskImage = nil + XCTAssertThrowsError(try legacy.generateMakefile()) + legacy.diskImage = "GAME.dsk" + legacy.generatedResources = [.init(outputs: ["obj/vcc-dos-boot/loader.c"], inputs: [], command: "echo collision")] + XCTAssertThrowsError(try legacy.generateMakefile()) + var configuration = CMOCProjectConfiguration() + configuration.makefileSettings = plain + let externalProducts = ["main.c": Data("int main(void) { return 0; }".utf8), + "obj/vcc-dos-boot/loader.c": Data("stale helper".utf8)] + XCTAssertNil(CMOCProject.filteredInputs(externalProducts, configuration: configuration)["obj/vcc-dos-boot/loader.c"], + "A prior command-line loader remains a build product even after DOS boot is turned off") + XCTAssertNotNil(CMOCProject.filteredInputs(externalProducts, configuration: configuration)["main.c"]) + legacy.generatedResources = []; legacy.diskBootMode = .custom; legacy.diskBootLoader = nil + XCTAssertThrowsError(try legacy.generateMakefile()) + } + + func testHelloDiskTemplateCreatesIndependentSourceOnlyProjectsWithoutOverwriting() throws { + let template = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("examples/cmoc/HelloDisk") + let original = try CMOCProject.open(at: template) + let hashes = try original.currentFileHashes() + let destination = folder.appendingPathComponent("My Hello Disk") + let copied = try CMOCProject.createHelloDisk(at: destination, templateDirectory: template) + XCTAssertEqual(copied.configuration.launchMode, .disk) + XCTAssertEqual(copied.configuration.binary, "HELLO.bin") + XCTAssertEqual(copied.configuration.diskImage, "HELLO.dsk") + XCTAssertEqual(copied.configuration.launchCommands, ["DOS"]) + let recipe = try XCTUnwrap(copied.configuration.makefileSettings) + XCTAssertEqual(recipe.diskBootMode, .program) + XCTAssertEqual(try copied.readText(relativePath: "Makefile"), try recipe.generateMakefile()) + XCTAssertEqual(try copied.currentFileHashes(), hashes) + XCTAssertFalse(try copied.fileEntries().contains(where: { ["bin", "dsk", "o", "lst"].contains(URL(fileURLWithPath: $0.relativePath).pathExtension) })) + _ = try copied.saveText("MY OWN WORDS\n", relativePath: "assets/words.txt") + XCTAssertEqual(try original.currentFileHashes(), hashes, "Creating/editing a project must not modify the installed source template") + XCTAssertThrowsError(try CMOCProject.createHelloDisk(at: destination, templateDirectory: template)) + XCTAssertEqual(try copied.readText(relativePath: "assets/words.txt"), "MY OWN WORDS\n") + } + + private func packagedAppResources() throws -> URL { + let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) + return try XCTUnwrap(app.resourceURL) + } + + func testPackagedTalkingLanderCopiesOnlySourcesAndRegeneratesTheSameMakefile() throws { + let template = try packagedAppResources().appendingPathComponent("DevelopmentTemplates/TalkingPlanetLander") + let original = try CMOCProject.open(at: template) + let destination = folder.appendingPathComponent("My Lander") + let project = try CMOCProject.createTalkingLander(at: destination, templateDirectory: template) + let expected: Set = [".gitignore", "Makefile", "README.md", "main.c", CMOCProject.configurationFilename] + XCTAssertEqual(Set(try FileManager.default.contentsOfDirectory(atPath: destination.path)), expected) + let recipe = try XCTUnwrap(project.configuration.makefileSettings) + XCTAssertEqual(recipe.libraries, ["ssc", "orch90", "bcontrol", "vcccompat"]) + XCTAssertEqual(project.configuration.launchMode, .quickload) + XCTAssertEqual(project.configuration.binary, "LANDER.bin") + XCTAssertEqual(project.configuration.diskImage, "LANDER.dsk") + XCTAssertEqual(try project.readText(relativePath: "Makefile"), try recipe.generateMakefile()) + XCTAssertEqual(try project.currentFileHashes(), try original.currentFileHashes()) + _ = try project.saveSource("int main(void) { return 0; }\n") + XCTAssertNotEqual(try project.readSource(), try original.readSource()) + XCTAssertThrowsError(try CMOCProject.createTalkingLander(at: destination, templateDirectory: template)) + } + + func testTalkingLanderBuildDiskAndHeaderNavigationUseTheSelectedGuestSDK() async throws { + let resources = try packagedAppResources() + let toolchain = resources.appendingPathComponent("Toolchain") + guard FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) else { + throw XCTSkip("This app was built without the optional CMOC runtime.") + } + let project = try CMOCProject.createTalkingLander(at: folder.appendingPathComponent("My Lander"), + templateDirectory: resources.appendingPathComponent("DevelopmentTemplates/TalkingPlanetLander")) + let service = CMOCBuildService(toolchain: toolchain, buildRoot: folder.appendingPathComponent("Builds")) + let hashes = try project.currentFileHashes() + let quickload = try await service.build(project: project, overlays: [:]) + XCTAssertEqual(quickload.binaryURL.lastPathComponent, "LANDER.bin") + XCTAssertEqual(quickload.binaryData.first, 0, "Disk BASIC LOADM header") + XCTAssertGreaterThan(quickload.binaryData.count, 5) + let disk = try await service.build(project: project, overlays: [:], action: .disk) + XCTAssertEqual(disk.binaryData, quickload.binaryData) + let bytes = try Data(contentsOf: XCTUnwrap(disk.diskURL)) + XCTAssertEqual(bytes.count, 35 * 18 * 256) + let directory = 17 * 18 * 256 + 2 * 256 + XCTAssertEqual(bytes.subdata(in: directory..<(directory + 11)), Data("LANDER BIN".utf8)) + XCTAssertEqual(try project.currentFileHashes(), hashes) + + let inputs = try CMOCIndexInputs.load(project: project, toolchain: toolchain, configurationName: "Debug", + overlays: [:], generated: [:]) + let index = CMOCProjectIndex(documents: inputs.documents, defines: inputs.defines, includePaths: inputs.includePaths) + for (symbol, header) in [("orch90_play", "vcc/orch90.h"), ("ssc_begin_phrase", "vcc/ssc.h"), + ("snprintf", "vcc/compat/stdio.h"), ("fopen", "vcc/compat/stdio.h"), + ("fread", "vcc/compat/stdio.h")] { + let path = CMOCIndexInputs.libraryPrefix + header + XCTAssertTrue(inputs.referencePaths.contains(path)) + XCTAssertEqual(index.definitions(named: symbol, from: "main.c", line: 1, column: 1).map(\.path), [path]) + } + + // A project that drops the compatibility library must not accidentally + // resolve a host stdio.h, or build using a cached LANDER.bin. + var configuration = project.configuration + var recipe = try XCTUnwrap(configuration.makefileSettings) + recipe.libraries.removeAll { $0 == "vcccompat" } + configuration.makefileSettings = recipe + try JSONEncoder().encode(configuration).write(to: project.directory.appendingPathComponent(CMOCProject.configurationFilename)) + try Data(recipe.generateMakefile().utf8).write(to: project.makefileURL) + let ordinary = try CMOCProject.open(at: project.directory) + let ordinaryInputs = try CMOCIndexInputs.load(project: ordinary, toolchain: toolchain, configurationName: "Debug", + overlays: [:], generated: [:]) + XCTAssertFalse(ordinaryInputs.referencePaths.contains(CMOCIndexInputs.libraryPrefix + "vcc/compat/stdio.h")) + XCTAssertTrue(ordinaryInputs.referencePaths.contains(CMOCIndexInputs.libraryPrefix + "vcc/ssc.h")) + do { + _ = try await service.build(project: ordinary, overlays: [:]) + XCTFail("The unchanged source requires its opt-in guest stdio.h.") + } catch { + XCTAssertTrue(error.localizedDescription.contains("stdio.h"), error.localizedDescription) + } + } + + func testPackagedGraphicsLanderBuildsAndResolvesThePageFlipDeclaration() async throws { + try await checkAuthoredExample("lander.c", libraries: ["gime", "bgraph", "bcontrol"], + symbol: "gime_present", header: "vcc/gime.h") + } + + func testPackagedSurveyProbeBuildsAndResolvesTheInputDeclaration() async throws { + try await checkAuthoredExample("probe.c", libraries: ["gime", "input", "bcontrol"], + symbol: "input_sample", header: "vcc/input.h") + } + + func testPackagedBankedTerrainBuildsAndResolvesItsHeader() async throws { + try await checkAuthoredExample("ridge.c", libraries: ["bank", "gime", "hirestxt"], + symbol: "bank_read", header: "vcc/bank.h") + } + + func testPackagedFieldLogBuildsAndResolvesFlush() async throws { + try await checkAuthoredExample("fieldlog.c", libraries: ["vcccompat", "decbfile"], + symbol: "fflush", header: "vcc/compat/stdio.h") + } + + func testPackagedPlanetAtlasBuildsAndResolvesFilePositioning() async throws { + try await checkAuthoredExample("atlas.c", libraries: ["vcccompat", "decbfile"], + symbol: "fseek", header: "vcc/compat/stdio.h") + } + + func testPackagedAtlasBackupBuildsAndResolvesRename() async throws { + try await checkAuthoredExample("atlasbackup.c", libraries: ["vcccompat", "decbfile"], + symbol: "rename", header: "vcc/compat/stdio.h") + } + + func testPackagedReturnTripBuildsAndResolvesFormattedOutput() async throws { + try await checkAuthoredExample("returntrip.c", libraries: ["vcccompat", "decbfile"], + symbol: "fprintf", header: "vcc/compat/stdio.h") + } + + func testPackagedMissionAnnouncerBuildsAndResolvesSpeechHeader() async throws { + try await checkAuthoredExample("announcer.c", libraries: ["ssc", "input", "bcontrol"], + symbol: "ssc_store_allophones", header: "vcc/ssc.h") + } + + func testPackagedDescentComputerBuildsAndResolvesDecimalHeader() async throws { + try await checkAuthoredExample("descent.c", libraries: ["vcccompat"], + symbol: "vcc_fixed", header: "vcc/decimal.h") + } + + func testPackagedStereoFlybyBuildsAndResolvesOrchestraHeader() async throws { + try await checkAuthoredExample("flyby.c", libraries: ["orch90", "input", "bcontrol"], + symbol: "orch90_start", header: "vcc/orch90.h") + } + + func testPackagedFlightRecorderBuildsAndResolvesCassetteHeader() async throws { + try await checkAuthoredExample("flightrecorder.c", libraries: ["vcccompat"], + symbol: "vcc_tape_open_write", header: "vcc/cassette.h") + } + + func testPackagedFlightReportBuildsAndResolvesPrinterHeader() async throws { + try await checkAuthoredExample("flightreport.c", libraries: ["vcccompat"], + symbol: "vcc_printer_printf", header: "vcc/printer.h") + } + + @MainActor func testFlightReportAppearsInNativePrinterOutput() async throws { + let rom = try packagedAppResources().appendingPathComponent("StarterKit/coco3.rom") + try XCTSkipUnless(FileManager.default.fileExists(atPath: rom.path), "Stage the CoCo 3 ROM to exercise its printer routine.") + let romData = try Data(contentsOf: rom) + let build = try await checkAuthoredExample("flightreport.c", libraries: ["vcccompat"], + symbol: "vcc_printer_printf", header: "vcc/printer.h") + let controller = VCCMachineController() + let printer = PrinterModel(controller: controller) + func command(_ body: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { continuation in body { continuation.resume(returning: $0) } } + } + func waitForScreen(_ marker: String) async throws { + for _ in 0..<250 { + let text: String? = await withCheckedContinuation { c in controller.copyScreenText { text, _ in c.resume(returning: text) } } + if text?.contains(marker) == true { return } + try await Task.sleep(nanoseconds: 40_000_000) + } + throw NSError(domain: "FlightReportTest", code: 1, userInfo: [NSLocalizedDescriptionKey: "Timed out waiting for " + marker]) + } + defer { controller.shutdown { _ in } } + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command { controller.loadROM(romData, use6309: false, completion: $0) } + _ = await command(controller.resume) + try await waitForScreen("OK") + let entry = build.binaryData.suffix(2).reduce(UInt16(0)) { $0 << 8 | UInt16($1) } + let loaded = await command { controller.debuggerLoadBinary(build.binaryData, breakpoint: entry, completion: $0) } + XCTAssertNil(loaded.errorMessage) + _ = await command(controller.debuggerClearDevelopmentBreakpoints) + _ = await command(controller.resume) + try await waitForScreen("PRESS SPACE") + printer.setCapture(true) + let started = await command(controller.snapshot) + XCTAssertTrue(started.printerEnabled) + controller.setKeyboardMask(try XCTUnwrap(CocoKeyboard.chord(for: " "))) + try await Task.sleep(nanoseconds: 100_000_000) + controller.setKeyboardMask(0) + try await waitForScreen("REPORT SENT TO PRINTER PORT") + printer.setCapture(false) + let expected = "TP-10 FLIGHT REPORT\n01 EARTH BLUE SEA\n02 MARS RED RIDGE\nEND OF REPORT\n" + for _ in 0..<50 { + printer.observe(await command(controller.snapshot)) + if !printer.busy && printer.preview == expected { break } + try await Task.sleep(nanoseconds: 20_000_000) + } + XCTAssertEqual(printer.preview, expected) + XCTAssertEqual(printer.byteCount, expected.utf8.count) + XCTAssertFalse(printer.enabled) + XCTAssertTrue(printer.unsaved) + + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 760, height: 550), + styleMask: [.borderless], backing: .buffered, defer: false) + window.appearance = NSAppearance(named: .aqua) + let view = NSHostingView(rootView: PrinterOutputView(printer: printer).background(Color(nsColor: .windowBackgroundColor))) + window.contentView = view + view.layoutSubtreeIfNeeded() + let pixels = try XCTUnwrap(view.bitmapImageRepForCachingDisplay(in: view.bounds)) + view.cacheDisplay(in: view.bounds, to: pixels) + let png = try XCTUnwrap(pixels.representation(using: .png, properties: [:])) + let attachment = XCTAttachment(data: png, uniformTypeIdentifier: "public.png") + attachment.name = "TP-10 Flight Report" + attachment.lifetime = .keepAlways + add(attachment) + } + + func testPackagedManualProjectsMatchCanonicalSources() throws { + let resources = try packagedAppResources() + try TestBuildContent.requireFullManuals(resources: resources) + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + for name in ["PlanetExpedition", "MissionRecorder", "PlanetSurvey"] { + let destination = folder.appendingPathComponent("Packaged-" + name) + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: false) + let extract = Process() + extract.executableURL = URL(fileURLWithPath: "/usr/bin/ditto") + extract.arguments = ["-x", "-k", resources.appendingPathComponent("ManualLibrary/programming-in-c/examples/\(name).zip").path, + destination.path] + try extract.run(); extract.waitUntilExit() + XCTAssertEqual(extract.terminationStatus, 0) + let packaged = try CMOCProject.open(at: destination.appendingPathComponent(name)) + let canonical = try CMOCProject.open(at: root.appendingPathComponent("examples/cmoc/\(name)")) + // Manual downloads may omit repository-only ignore rules. Every + // executable source, resource and project/build control must match. + let packagedHashes = try packaged.currentFileHashes().filter { $0.key != ".gitignore" } + let canonicalHashes = try canonical.currentFileHashes().filter { $0.key != ".gitignore" } + XCTAssertEqual(packagedHashes, canonicalHashes, name) + XCTAssertEqual(try Data(contentsOf: packaged.makefileURL), try Data(contentsOf: canonical.makefileURL), name) + } + } + + func testPackagedManualExercisesMatchAuthoredCompilerFixtures() throws { + let resources = try packagedAppResources() + try TestBuildContent.requireFullManuals(resources: resources) + let fixtures = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/ManualC") + for filename in ["lander.c", "probe.c", "ridge.c", "fieldlog.c", "atlas.c", "atlasbackup.c", + "returntrip.c", "announcer.c", "descent.c", "flyby.c", "flightrecorder.c", + "flightreport.c", "crew.c"] { + let packaged = resources.appendingPathComponent("ManualLibrary/programming-in-c/examples/\(filename)") + XCTAssertEqual(try Data(contentsOf: packaged), try Data(contentsOf: fixtures.appendingPathComponent(filename)), filename) + } + } + + @discardableResult + private func checkAuthoredExample(_ filename: String, libraries: [String], + symbol: String, header: String) async throws -> CMOCBuildArtifact { + let resources = try packagedAppResources() + let toolchain = resources.appendingPathComponent("Toolchain") + guard FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) else { + throw XCTSkip("Stage the optional CMOC toolchain to build the manual exercise.") + } + let example = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/ManualC/\(filename)") + let source = try String(contentsOf: example, encoding: .utf8) + var settings = CMOCProjectConfiguration() + settings.bundledLibraries = libraries.map { .init(library: $0, linkVariable: "LIBS") } + let project = try configuredProject(settings, files: ["main.c": source]) + let service = CMOCBuildService(toolchain: toolchain, buildRoot: folder.appendingPathComponent("Builds")) + let artifact = try await service.build(project: project, overlays: [:]) + XCTAssertTrue(artifact.hasBinary) + let inputs = try CMOCIndexInputs.load(project: project, toolchain: toolchain, configurationName: "Debug", + overlays: [:], generated: [:]) + let index = CMOCProjectIndex(documents: inputs.documents, defines: inputs.defines, includePaths: inputs.includePaths) + let definitions = index.definitions(named: symbol, from: "main.c", line: 1, column: 1) + XCTAssertEqual(definitions.map(\.path), [CMOCIndexInputs.libraryPrefix + header]) + return artifact + } + + func testPackagedHeapExerciseBuildsWithTheProjectLibrarySettings() async throws { + let resources = try packagedAppResources() + let source = try String(contentsOf: URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/ManualC/crew.c"), + encoding: .utf8) + let toolchain = resources.appendingPathComponent("Toolchain") + guard FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) else { + throw XCTSkip("Stage the optional CMOC toolchain to build the crew example.") + } + var settings = CMOCProjectConfiguration() + settings.bundledLibraries = [ + .init(library: "vcccompat", minimumVersion: "0.3.0", linkVariable: "LIBS"), + .init(library: "wydealloc", linkVariable: "LIBS") + ] + let project = try configuredProject(settings, files: ["main.c": source]) + let service = CMOCBuildService(toolchain: toolchain, buildRoot: folder.appendingPathComponent("Builds")) + let artifact = try await service.build(project: project, overlays: [:]) + XCTAssertTrue(artifact.hasBinary) + + let inputs = try CMOCIndexInputs.load(project: project, toolchain: toolchain, configurationName: "Debug", + overlays: [:], generated: [:]) + let index = CMOCProjectIndex(documents: inputs.documents, defines: inputs.defines, includePaths: inputs.includePaths) + let header = CMOCIndexInputs.libraryPrefix + "vcc/compat/stdlib.h" + for symbol in ["vcc_heap_init", "malloc", "calloc", "realloc", "free"] { + XCTAssertEqual(index.definitions(named: symbol, from: "main.c", line: 1, column: 1).map(\.path), [header], symbol) + } + } + + private func openAuthoredProject(_ name: String) throws -> CMOCProject { + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + let source = root.appendingPathComponent("examples/cmoc/\(name)") + let destination = folder.appendingPathComponent(name) + try FileManager.default.copyItem(at: source, to: destination) + return try CMOCProject.open(at: destination) + } + + func testManualPlanetExpeditionBuildsThePracticeCard() async throws { + let resources = try packagedAppResources() + let project = try openAuthoredProject("PlanetExpedition") + let toolchain = resources.appendingPathComponent("Toolchain") + guard FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) else { + throw XCTSkip("Stage the optional CMOC toolchain to build the manual exercise.") + } + let service = CMOCBuildService(toolchain: toolchain, buildRoot: folder.appendingPathComponent("Builds")) + let result = try await service.build(project: project, overlays: [:], action: .build) + XCTAssertTrue(result.hasBinary) + let card = result.directory.appendingPathComponent("EXPED") + for (image, firstFile) in [("EXPLORE", "EXPLORE BIN"), ("EARTH", "LANDING TXT"), ("MARS", "LANDING TXT")] { + let disk = try Data(contentsOf: card.appendingPathComponent(image + ".DSK")) + XCTAssertEqual(disk.count, 35 * 18 * 256, image) + let directory = (17 * 18 + 2) * 256 + XCTAssertEqual(disk.subdata(in: directory..<(directory + 11)), Data(firstFile.utf8), image) + } + let inputs = try CMOCIndexInputs.load(project: project, toolchain: toolchain, configurationName: "Debug", + overlays: [:], generated: [:]) + let index = CMOCProjectIndex(documents: inputs.documents, defines: inputs.defines, includePaths: inputs.includePaths) + let completions = index.completionSymbols(from: "expedition.c", offset: 0, prefix: "sdc_m") + XCTAssertEqual(Set(completions.map(\.name)), ["sdc_mount", "sdc_mounted"]) + let definitions = index.definitions(named: "sdc_mount", from: "expedition.c", line: 1, column: 1) + XCTAssertEqual(definitions.map(\.path), [CMOCIndexInputs.libraryPrefix + "vcc/sdc.h"]) + } + + func testManualMissionRecorderBuildsAndPackagesItsFlightDisk() async throws { + let resources = try packagedAppResources() + let project = try openAuthoredProject("MissionRecorder") + XCTAssertEqual(project.configuration.launchMode, .quickload, "Keep the pilot's practice disk mounted on Run.") + XCTAssertEqual(project.configuration.buildTarget, "build") + let settings = try XCTUnwrap(project.configuration.makefileSettings) + XCTAssertEqual(try project.readText(relativePath: "Makefile"), try settings.generateMakefile()) + let toolchain = resources.appendingPathComponent("Toolchain") + guard FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) else { + throw XCTSkip("Stage the optional CMOC toolchain to build the manual exercise.") + } + let service = CMOCBuildService(toolchain: toolchain, buildRoot: folder.appendingPathComponent("Builds")) + let result = try await service.build(project: project, overlays: [:], action: .disk) + XCTAssertEqual(result.binaryURL.lastPathComponent, "RECORDER.bin") + let disk = try Data(contentsOf: XCTUnwrap(result.diskURL)) + guard disk.count == 35 * 18 * 256 else { + return XCTFail("Expected a standard 35-track flight disk.") + } + let directory = (17 * 18 + 2) * 256 + XCTAssertEqual(disk.subdata(in: directory..<(directory + 11)), Data("RECORDERBIN".utf8)) + XCTAssertEqual(disk[directory + 32], 0xff, "The pilot creates the first flight log.") + } + + func testManualPlanetSurveyBuildsThroughTheWorkspaceWithItsDataDisk() async throws { + let resources = try packagedAppResources() + let project = try openAuthoredProject("PlanetSurvey") + let recipe = try XCTUnwrap(project.configuration.makefileSettings) + XCTAssertEqual(recipe.libraries, ["vcccompat", "decbfile"]) + XCTAssertEqual(try project.readText(relativePath: "Makefile"), try recipe.generateMakefile()) + + let toolchain = resources.appendingPathComponent("Toolchain") + guard FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) else { + throw XCTSkip("Stage the optional CMOC runtime to build the manual example.") + } + let service = CMOCBuildService(toolchain: toolchain, buildRoot: folder.appendingPathComponent("Builds")) + let result = try await service.build(project: project, overlays: [:], action: .disk) + XCTAssertEqual(result.binaryURL.lastPathComponent, "SURVEY.bin") + let disk = try Data(contentsOf: XCTUnwrap(result.diskURL)) + XCTAssertEqual(disk.count, 35 * 18 * 256) + let directory = (17 * 18 + 2) * 256 + XCTAssertEqual(disk.subdata(in: directory..<(directory + 11)), Data("SURVEY BIN".utf8)) + XCTAssertEqual(disk.subdata(in: (directory + 32)..<(directory + 43)), Data("PLANETS TXT".utf8)) + + let inputs = try CMOCIndexInputs.load(project: project, toolchain: toolchain, configurationName: "Debug", + overlays: [:], generated: [:]) + let index = CMOCProjectIndex(documents: inputs.documents, defines: inputs.defines, includePaths: inputs.includePaths) + let header = CMOCIndexInputs.libraryPrefix + "vcc/compat/string.h" + XCTAssertEqual(index.definitions(named: "strtok_r", from: "main.c", line: 1, column: 1).map(\.path), [header]) + XCTAssertEqual(index.completionSymbols(from: "main.c", offset: 0, prefix: "strtok_r").map(\.path), [header]) + } + + func testHelloDiskTemplateRejectsUnexpectedProductsAndLinkedFiles() throws { + let original = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("examples/cmoc/HelloDisk") + let template = folder.appendingPathComponent("Template") + try FileManager.default.copyItem(at: original, to: template) + let extra = template.appendingPathComponent("personal.dsk") + try Data([0, 1, 2]).write(to: extra) + let destination = folder.appendingPathComponent("New Project") + XCTAssertThrowsError(try CMOCProject.createHelloDisk(at: destination, templateDirectory: template)) + XCTAssertFalse(FileManager.default.fileExists(atPath: destination.path)) + try FileManager.default.removeItem(at: extra) + let source = template.appendingPathComponent("main.c") + try FileManager.default.removeItem(at: source) + try FileManager.default.createSymbolicLink(at: source, withDestinationURL: original.appendingPathComponent("main.c")) + XCTAssertThrowsError(try CMOCProject.createHelloDisk(at: destination, templateDirectory: template)) + XCTAssertFalse(FileManager.default.fileExists(atPath: destination.path)) + } + func testGeneratedDefinitionsAndOptionsReachCompilerAsLiteralArguments() async throws { + var generated = CMOCMakefileSettings() + let definition = "DISPLAY_NAME=\"It's #$5 \\# and $(printf never-executed)\"" + generated.defines = [definition, "MAX_WORD_LEN=5"] + generated.compilerOptions = ["-Werror", "-fomit-frame-pointer"] + generated.linkerOptions = ["--verbose"] + generated.limit = "7F80" + var settings = CMOCProjectConfiguration(); settings.makefileSettings = generated + let value = try configuredProject(settings, files: ["Makefile": try generated.generateMakefile()]) + let tools = try makeTools() + let fakeCompiler = """ + #!/bin/sh + printf '%s\\n' BEGIN "$@" END >> arguments.txt + output= + while test "$#" -gt 0; do + if test "$1" = -o; then shift; output="$1"; fi + shift + done + test -n "$output" || exit 80 + printf compiled > "$output" + """ + try Data(fakeCompiler.utf8).write(to: tools.appendingPathComponent("bin/cmoc")) + let service = CMOCBuildService(toolchain: tools, buildRoot: folder.appendingPathComponent("Results")) + let artifact = try await service.build(project: value, overlays: [:]) + let arguments = try String(contentsOf: artifact.fileURL("arguments.txt"), encoding: .utf8).components(separatedBy: "\n") + XCTAssertTrue(arguments.contains("-D" + definition), "Quotes, dollars, hashes, apostrophes and backslashes must survive Make and the shell unchanged") + for argument in ["-DMAX_WORD_LEN=5", "-Werror", "-fomit-frame-pointer", "--verbose", "--limit=7F80"] { XCTAssertTrue(arguments.contains(argument)) } + XCTAssertEqual(try JSONDecoder().decode(CMOCMakefileSettings.self, from: JSONEncoder().encode(generated)), generated) + generated.defines = ["9INVALID=1"] + XCTAssertThrowsError(try generated.generateMakefile()) + generated.defines = []; generated.compilerOptions = ["-O0\nrm anything"] + XCTAssertThrowsError(try generated.generateMakefile()) + generated.compilerOptions = []; generated.limit = "not-hex" + XCTAssertThrowsError(try generated.generateMakefile()) + } + func testExistingCompilerProductsCannotMasqueradeAsFreshBuildInputs() async throws { + let value = try project() + let makefile = """ + build: main.bin + main.bin: main.o Makefile + \tcp main.o main.bin + main.o: main.c + \t@echo REBUILT-SOURCE + \tcp main.c main.o + clean: + \trm -f main.bin main.o main.d + -include main.d + """ + try Data(makefile.utf8).write(to: value.makefileURL) + let files = ["main.o": "STALE OBJECT", "main.bin": "STALE EXECUTABLE", "main.d": "main.o: /outside/project/old-source.c\n", + "main.s": "STALE COMPILER ASSEMBLY", "main.lst": "STALE LISTING", "main.map": "STALE MAP", + "standalone.s": " rts\n", "libprebuilt.a": "INTENTIONAL ARCHIVE", "assets.dat": "GAME DATA"] + for (path, text) in files { + let url = value.directory.appendingPathComponent(path) + try Data(text.utf8).write(to: url) + try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSinceNow: 3600)], ofItemAtPath: url.path) + } + let inputs = try value.inputFiles() + for path in ["main.o", "main.bin", "main.d", "main.s", "main.lst", "main.map"] { XCTAssertNil(inputs[path]) } + for path in ["standalone.s", "libprebuilt.a", "assets.dat"] { XCTAssertNotNil(inputs[path]) } + let service = CMOCBuildService(toolchain: try makeTools(), buildRoot: folder.appendingPathComponent("Outputs")) + let artifact = try await service.build(project: value, overlays: [:]) + XCTAssertTrue(artifact.buildLog.contains("REBUILT-SOURCE")) + XCTAssertEqual(artifact.binaryData, Data(CMOCProject.starterSource.utf8)) + XCTAssertEqual(artifact.fileHashes, try value.currentFileHashes()) + XCTAssertEqual(try String(contentsOf: value.directory.appendingPathComponent("main.bin"), encoding: .utf8), "STALE EXECUTABLE", "The user's old external build products remain untouched") + let before = try value.currentFileHashes() + try Data("EXTERNAL REBUILD".utf8).write(to: value.directory.appendingPathComponent("main.bin")) + XCTAssertEqual(before, try value.currentFileHashes(), "Generated output changes do not alter source identity") + } + + func testAbsoluteSnapshotDependenciesRebuildSafelyAfterHeaderEditAndSnapshotRemoval() async throws { + let oldSnapshot = folder.appendingPathComponent("Prior Source Snapshot") + try FileManager.default.createDirectory(at: oldSnapshot, withIntermediateDirectories: true) + let oldHeader = oldSnapshot.appendingPathComponent("value.h") + try Data("old snapshot header\n".utf8).write(to: oldHeader) + let escapedHeader = oldHeader.path.replacingOccurrences(of: " ", with: "\\ ") + var settings = CMOCProjectConfiguration(); settings.buildTarget = "build" + let makefile = """ + build: main.bin + main.bin: main.c value.h Makefile + \t@printf 'COMPILED-HEADER\\n' + \tcat value.h > main.bin + \tcp dependency.template main.d + -include main.d + """ + let value = try configuredProject(settings, files: ["Makefile": makefile, "value.h": "#define VALUE 1\n", + "dependency.template": "main.bin: " + escapedHeader + "\n"]) + let before = try value.inputFiles() + let service = CMOCBuildService(toolchain: try makeTools(), buildRoot: folder.appendingPathComponent("Artifacts")) + let first = try await service.build(project: value, overlays: [:]) + XCTAssertEqual(first.binaryData, Data("#define VALUE 1\n".utf8)) + let second = try await service.build(project: value, overlays: [:]) + XCTAssertTrue(second.buildLog.contains("generated dependencies refer outside the captured workspace"), second.buildLog) + XCTAssertTrue(second.buildLog.contains("COMPILED-HEADER"), "An old external snapshot must never decide cache freshness") + XCTAssertEqual(second.binaryData, first.binaryData) + let header = value.directory.appendingPathComponent("value.h") + try Data("#define VALUE 2\n".utf8).write(to: header) + try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSince1970: 1)], ofItemAtPath: header.path) + let edited = try await service.build(project: value, overlays: [:]) + XCTAssertEqual(edited.binaryData, Data("#define VALUE 2\n".utf8)) + try FileManager.default.removeItem(at: oldSnapshot) + let recovered = try await service.build(project: value, overlays: [:]) + XCTAssertEqual(recovered.binaryData, edited.binaryData, "Make must not read a dependency on the deleted snapshot") + XCTAssertTrue(recovered.buildLog.contains("Rebuilding isolated cache")) + XCTAssertEqual(first.binaryData, Data("#define VALUE 1\n".utf8), "Earlier receipts remain immutable") + XCTAssertFalse(FileManager.default.fileExists(atPath: value.directory.appendingPathComponent("main.bin").path)) + XCTAssertFalse(FileManager.default.fileExists(atPath: value.directory.appendingPathComponent("main.d").path)) + let after = try value.inputFiles() + XCTAssertEqual(after["Makefile"], before["Makefile"]) + XCTAssertEqual(after["dependency.template"], before["dependency.template"], "Do not rewrite authored dependency data") + } + + func testRemovedHeaderInvalidatesGeneratedDependenciesWhileRelativeCacheRemainsIncremental() async throws { + var settings = CMOCProjectConfiguration(); settings.buildTarget = "build" + let makefile = """ + build: main.bin + main.bin: main.c Makefile + \t@printf 'COMPILED-INPUTS\\n' + \tcp main.c main.bin + \tprintf 'main.bin: main.c' > main.d + \t@if test -f obsolete.h; then cat obsolete.h >> main.bin; printf ' obsolete.h' >> main.d; fi + \tprintf '\\n' >> main.d + -include main.d + """ + let value = try configuredProject(settings, files: ["Makefile": makefile, "obsolete.h": "original header\n"]) + let service = CMOCBuildService(toolchain: try makeTools(), buildRoot: folder.appendingPathComponent("Artifacts")) + let first = try await service.build(project: value, overlays: [:]) + let unchanged = try await service.build(project: value, overlays: [:]) + XCTAssertFalse(unchanged.buildLog.contains("COMPILED-INPUTS"), "Safe relative dependencies should keep incremental builds") + XCTAssertEqual(unchanged.binaryData, first.binaryData) + try FileManager.default.removeItem(at: value.directory.appendingPathComponent("obsolete.h")) + let removed = try await service.build(project: value, overlays: [:]) + XCTAssertTrue(removed.buildLog.contains("a previously captured input was removed"), removed.buildLog) + XCTAssertEqual(removed.binaryData, Data(try value.readSource().utf8)) + XCTAssertTrue(String(decoding: first.binaryData, as: UTF8.self).hasSuffix("original header\n")) + let again = try await service.build(project: value, overlays: [:]) + XCTAssertEqual(again.binaryData, removed.binaryData) + XCTAssertFalse(again.buildLog.contains("COMPILED-INPUTS")) + } + + func testPopulatedCacheWithoutValidInputReceiptIsRebuiltRatherThanTrusted() async throws { + var settings = CMOCProjectConfiguration(); settings.buildTarget = "build" + let value = try configuredProject(settings, files: ["Makefile": """ + build: main.bin + main.bin: main.c + \t@printf 'COMPILED-RECEIPT\\n' + \tcp main.c main.bin + """]) + let service = CMOCBuildService(toolchain: try makeTools(), buildRoot: folder.appendingPathComponent("Artifacts")) + let first = try await service.build(project: value, overlays: [:]) + let receipt = first.compilationDirectory.deletingLastPathComponent().appendingPathComponent("inputs.json") + try Data("not a valid cache input receipt".utf8).write(to: receipt) + let rebuilt = try await service.build(project: value, overlays: [:]) + XCTAssertTrue(rebuilt.buildLog.contains("the previous input receipt is missing or invalid")) + XCTAssertTrue(rebuilt.buildLog.contains("COMPILED-RECEIPT")) + XCTAssertEqual(rebuilt.binaryData, first.binaryData) + } + + func testExplicitInputOutputDeclarationsRoundTripAndRejectAmbiguousRoles() throws { + var settings = CMOCProjectConfiguration() + settings.outputDirectories = ["build"] + settings.resourceInputs = ["build/seed.raw"] + settings.generatedInputs = ["build/generated.s"] + XCTAssertNoThrow(try settings.validated(), "Explicit inputs may override an otherwise excluded output folder") + XCTAssertEqual(try JSONDecoder().decode(CMOCProjectConfiguration.self, from: JSONEncoder().encode(settings)), settings) + let defaults = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: Data("{}".utf8)) + XCTAssertTrue(defaults.resourceInputs.isEmpty && defaults.generatedInputs.isEmpty && defaults.outputDirectories.isEmpty) + for path in ["../outside", "/absolute", "a/../b", "a//b", "a\\b", ".git/config", "nested/.svn/entries"] { + var invalid = settings; invalid.resourceInputs = [path] + XCTAssertThrowsError(try invalid.validated(), path) + } + var duplicate = settings; duplicate.generatedInputs = ["BUILD/SEED.RAW"] + XCTAssertThrowsError(try duplicate.validated()) + var conflicting = settings; conflicting.resourceInputs = ["main.bin"] + XCTAssertThrowsError(try conflicting.validated()) + conflicting.resourceInputs = []; conflicting.generatedInputs = ["main.bin"] + XCTAssertThrowsError(try conflicting.validated()) + } + + func testBuildPreservesExplicitResourcesAndPreGeneratedInputsInsideOutputFolders() async throws { + var settings = CMOCProjectConfiguration(); settings.buildTarget = "build" + settings.outputDirectories = ["build"] + settings.resourceInputs = ["build/seed.raw"] + settings.generatedInputs = ["build/generated.s"] + let recipe = """ + .PHONY: build + build: + \tcat build/seed.raw build/generated.s > main.bin + \tprintf incidental > build/compiler-output.raw + """ + let value = try configuredProject(settings, files: ["Makefile": recipe, "build/seed.raw": "RESOURCE\n", + "build/generated.s": " rts\n", "build/old-output.raw": "stale output"]) + let inputs = try value.inputFiles() + XCTAssertNotNil(inputs["build/seed.raw"]) + XCTAssertNotNil(inputs["build/generated.s"]) + XCTAssertNil(inputs["build/old-output.raw"]) + let service = CMOCBuildService(toolchain: try makeTools(), buildRoot: folder.appendingPathComponent("Artifacts")) + let artifact = try await service.build(project: value, overlays: [:]) + XCTAssertEqual(artifact.binaryData, Data("RESOURCE\n rts\n".utf8)) + XCTAssertEqual(artifact.fileHashes, try value.currentFileHashes()) + XCTAssertEqual(try Data(contentsOf: value.directory.appendingPathComponent("build/seed.raw")), inputs["build/seed.raw"]) + XCTAssertFalse(FileManager.default.fileExists(atPath: value.directory.appendingPathComponent("build/compiler-output.raw").path)) + // Both explicit roles are captured inputs even where filename/parent + // heuristics would normally classify them as disposable products. + for path in ["build/seed.raw", "build/generated.s"] { + let mutating = recipe + "\tprintf changed > " + path + "\n" + try Data(mutating.utf8).write(to: value.makefileURL) + do { + _ = try await service.build(project: value, overlays: [:]) + XCTFail("A recipe cannot replace a captured input: " + path) + } catch { + XCTAssertTrue(error.localizedDescription.contains("The build modified " + path), error.localizedDescription) + } + XCTAssertEqual(try Data(contentsOf: value.directory.appendingPathComponent(path)), inputs[path]) + } + } +} diff --git a/platforms/macos/Tests/CMOCCallStackIntegrationTests.swift b/platforms/macos/Tests/CMOCCallStackIntegrationTests.swift new file mode 100644 index 0000000..3e185dc --- /dev/null +++ b/platforms/macos/Tests/CMOCCallStackIntegrationTests.swift @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +/// Qualifies stack recovery against real CMOC output and live guest frames. +final class CMOCCallStackIntegrationTests: XCTestCase { + private struct Fixture { + let root: URL + let artifact: CMOCBuildArtifact + let metadata: CMOCVariableDebug + let rom: Data + let sources: [String: String] + func line(_ marker: String, file: String) throws -> Int { + try XCTUnwrap(sources[file]?.components(separatedBy: "\n").firstIndex { $0.contains(marker) }) + 1 + } + func address(_ marker: String, file: String) throws -> UInt16 { + try XCTUnwrap(metadata.sourceMap.addresses(forLine: line(marker, file: file), in: file).first, marker) + } + } + private func fixture(optimized: Bool = false) async throws -> Fixture { + let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources") + let toolchain = resources.appendingPathComponent("ToolchainBundle") + let rom = resources.appendingPathComponent("ROMs/coco3.rom") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) + && FileManager.default.fileExists(atPath: rom.path), "Local licensed CoCo ROM and staged toolchain are required") + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCCallStack-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + do { + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + let sources = ["main.c": """ + #include + #include + unsigned int result; + unsigned int wrapper(unsigned int value); + int main(void) + { + unsigned int mainLocal = 7; + initCoCoSupport(); + result = wrapper(mainLocal); /* MAIN_CALL */ + for (;;) ++result; + return 0; + } + """, "helper.c": """ + extern unsigned int result; + unsigned int recurse(unsigned int n) + { + unsigned int local = n + 10; + if (n == 0) + { + result = local; /* LEAF_STOP */ + return local; + } + return recurse(n - 1) + local; /* RECURSIVE_CALL */ + } + unsigned int wrapper(unsigned int value) + { + unsigned int local = value + 5; + unsigned char byteLocal = 42; + result = recurse(value - 4); /* WRAPPER_CALL */ + return result + local + byteLocal; + } + """] + for (name, source) in sources { try Data(source.utf8).write(to: project.directory.appendingPathComponent(name)) } + let makefile = """ + CMOC ?= cmoc + build: main.bin + main.bin: main.o helper.o + \t"$(CMOC)" --coco --intermediate --org=2800 -o $@ main.o helper.o + main.o: main.c + \t"$(CMOC)" --coco --intermediate -O0 -fno-omit-frame-pointer -c -o $@ $< + helper.o: helper.c + \t"$(CMOC)" --coco --intermediate \(optimized ? "-O2" : "-O0") -fno-omit-frame-pointer -c -o $@ $< + """ + try Data(makefile.utf8).write(to: project.makefileURL) + let service = CMOCBuildService(toolchain: toolchain, buildRoot: root.appendingPathComponent("Builds")) + let artifact = try await service.build(project: project, overlays: [:]) + let map = try CMOCProjectSourceMap.parse(artifact: artifact) + let metadata = try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map) + return Fixture(root: root, artifact: artifact, metadata: metadata, rom: try Data(contentsOf: rom), sources: sources) + } catch { try? FileManager.default.removeItem(at: root); throw error } + } + @MainActor private func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { continuation in operation { continuation.resume(returning: $0) } } + } + @MainActor private func capture(_ controller: VCCMachineController) async -> VCCDebuggerSnapshot { + await withCheckedContinuation { continuation in + controller.debuggerSnapshot(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) } + } + } + @MainActor private func withStoppedProcessors(_ fixture: Fixture, + body: (VCCMachineController, VCCDebuggerSnapshot) async throws -> Void) async throws { + for use6309 in [false, true] { + let controller = VCCMachineController() + do { + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + let loaded = await command { controller.loadROM(fixture.rom, use6309: use6309, completion: $0) } + XCTAssertNil(loaded.errorMessage) + _ = await command(controller.resume) + try await Task.sleep(nanoseconds: 1_500_000_000) + _ = await command(controller.pause) + let breakpoint = try fixture.address("LEAF_STOP", file: "helper.c") + var state = await command { controller.debuggerLoadBinary(fixture.artifact.binaryData, breakpoint: breakpoint, completion: $0) } + for _ in 0..<1000 where state.state == .running { + try await Task.sleep(nanoseconds: 5_000_000) + state = await command(controller.snapshot) + } + XCTAssertNil(state.errorMessage) + XCTAssertEqual(state.state, .paused) + XCTAssertEqual(state.programCounter, breakpoint) + try await body(controller, await capture(controller)) + _ = await command(controller.shutdown) + } catch { _ = await command(controller.shutdown); throw error } + } + } + private func stack(_ fixture: Fixture, _ snapshot: VCCDebuggerSnapshot, + memory: Data? = nil, available: Data? = nil) throws -> CMOCCallStack { + CMOCCallStack.capture(metadata: fixture.metadata, pc: snapshot.machine.programCounter, + u: try XCTUnwrap(snapshot.registers["U"]?.uint16Value), s: try XCTUnwrap(snapshot.registers["S"]?.uint16Value), + memory: memory ?? snapshot.logicalMemory, available: available ?? snapshot.logicalMemoryAvailable) + } + private func assertValue(_ expression: String, _ expected: String, frame: CMOCCallStack.Frame, + fixture: Fixture, snapshot: VCCDebuggerSnapshot, + file: StaticString = #filePath, line: UInt = #line) { + let value = CMOCWatchEvaluator(metadata: fixture.metadata, context: .init(pc: frame.pc, u: frame.u, + memory: snapshot.logicalMemory, available: snapshot.logicalMemoryAvailable)).evaluate(expression) + XCTAssertNil(value.error, "\(expression): \(value.error ?? "")", file: file, line: line) + XCTAssertEqual(value.value, expected, expression, file: file, line: line) + } + @MainActor func testRealRecursiveCallersNavigateAndInspectTheirOwnFramesOnBothCPUs() async throws { + let fixture = try await fixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + try await withStoppedProcessors(fixture) { controller, snapshot in + let recovered = try stack(fixture, snapshot) + XCTAssertEqual(recovered.frames.map(\.functionName), ["recurse", "recurse", "recurse", "recurse", "wrapper", "main"], recovered.termination) + guard recovered.frames.count == 6 else { return } + XCTAssertTrue(recovered.frames.allSatisfy(\.localsInspectable)) + XCTAssertEqual(Set(recovered.frames.map(\.u)).count, 6, "Every invocation needs its own saved frame pointer") + for index in 0..<4 { + let frame = recovered.frames[index] + XCTAssertEqual(frame.sourcePath, "helper.c") + XCTAssertEqual(frame.sourceLine, try fixture.line(index == 0 ? "LEAF_STOP" : "RECURSIVE_CALL", file: "helper.c")) + assertValue("n", String(index), frame: frame, fixture: fixture, snapshot: snapshot) + assertValue("local", String(index + 10), frame: frame, fixture: fixture, snapshot: snapshot) + } + let wrapper = recovered.frames[4] + XCTAssertEqual(wrapper.sourceLine, try fixture.line("WRAPPER_CALL", file: "helper.c")) + assertValue("value", "7", frame: wrapper, fixture: fixture, snapshot: snapshot) + assertValue("local", "12", frame: wrapper, fixture: fixture, snapshot: snapshot) + assertValue("byteLocal", "42", frame: wrapper, fixture: fixture, snapshot: snapshot) + XCTAssertTrue(recovered.frames.contains { $0.u & 1 == 1 }, "A byte-sized local must not require word-aligned frames") + let main = recovered.frames[5] + XCTAssertEqual(main.sourcePath, "main.c") + XCTAssertEqual(main.sourceLine, try fixture.line("MAIN_CALL", file: "main.c")) + assertValue("mainLocal", "7", frame: main, fixture: fixture, snapshot: snapshot) + let afterInspection = await capture(controller) + XCTAssertEqual(afterInspection.machine.programCounter, snapshot.machine.programCounter) + XCTAssertEqual(afterInspection.machine.cycles, snapshot.machine.cycles) + XCTAssertEqual(afterInspection.logicalMemory, snapshot.logicalMemory, "Caller inspection cannot change execution or memory") + XCTAssertEqual(afterInspection.registers, snapshot.registers) + } + } + @MainActor func testLiveFramesStopAtCorruptUnavailableAndChangedCodeBoundaries() async throws { + let fixture = try await fixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + try await withStoppedProcessors(fixture) { _, snapshot in + let valid = try stack(fixture, snapshot) + XCTAssertEqual(valid.frames.count, 6, valid.termination) + let framePointer = Int(try XCTUnwrap(snapshot.registers["U"]?.uint16Value)) + var corrupt = snapshot.logicalMemory + corrupt[framePointer] = UInt8(framePointer >> 8) + corrupt[framePointer + 1] = UInt8(framePointer & 255) + let cycle = try stack(fixture, snapshot, memory: corrupt) + XCTAssertLessThanOrEqual(cycle.frames.count, 1, "A self-referential saved U must not fabricate callers") + XCTAssertFalse(cycle.termination.isEmpty) + var unavailable = snapshot.logicalMemoryAvailable + unavailable[framePointer + 2] = 0 + let hiddenReturn = try stack(fixture, snapshot, available: unavailable) + XCTAssertLessThanOrEqual(hiddenReturn.frames.count, 1) + XCTAssertFalse(hiddenReturn.termination.isEmpty) + var changedCode = snapshot.logicalMemory + let instruction = try XCTUnwrap(fixture.metadata.sourceMap.instructions.first) + changedCode[Int(instruction.address)] ^= 1 + let invalid = try stack(fixture, snapshot, memory: changedCode) + XCTAssertTrue(invalid.frames.isEmpty, "No frame should be attributed to stale executable metadata") + XCTAssertFalse(invalid.termination.isEmpty) + } + } + @MainActor func testOptimizedCompilerFrameReportsBoundaryInsteadOfInventingCallers() async throws { + let fixture = try await fixture(optimized: true) + defer { try? FileManager.default.removeItem(at: fixture.root) } + XCTAssertTrue(fixture.metadata.functions.contains { $0.name == "recurse" && !$0.frame }) + try await withStoppedProcessors(fixture) { _, snapshot in + let recovered = try stack(fixture, snapshot) + XCTAssertLessThanOrEqual(recovered.frames.count, 1) + XCTAssertFalse(recovered.frames.contains(where: \.localsInspectable)) + XCTAssertFalse(recovered.termination.isEmpty) + } + } +} diff --git a/platforms/macos/Tests/CMOCCallStackTests.swift b/platforms/macos/Tests/CMOCCallStackTests.swift new file mode 100644 index 0000000..4e30d66 --- /dev/null +++ b/platforms/macos/Tests/CMOCCallStackTests.swift @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CMOCCallStackTests: XCTestCase { + private struct Fixture { + var metadata: CMOCVariableDebug + var memory: Data + var available: Data + var pc: UInt16 = 0x2904 + var u: UInt16 = 0x4001 // Byte arguments/locals need not leave an even U. + var s: UInt16 = 0x3ff0 + mutating func word(_ at: Int, _ value: Int) { + memory[at] = UInt8(value >> 8); memory[at + 1] = UInt8(value & 255) + } + func capture(limit: Int = 64) -> CMOCCallStack { + CMOCCallStack.capture(metadata: metadata, pc: pc, u: u, s: s, + memory: memory, available: available, maximumFrames: limit) + } + } + private func fixture(optimized: Bool = false, interrupt: Bool = false, wrongTarget: Bool = false) -> Fixture { + var instructions: [CMOCProjectSourceMap.Instruction] = [] + func instruction(_ pc: UInt16, _ bytes: [UInt8], _ file: String, _ line: Int) { + instructions.append(.init(sourcePath: file, sourceLine: line, address: pc, bytes: bytes, assembly: "")) + } + for (entry, file) in [(UInt16(0x2800), "main.c"), (UInt16(0x2900), "helper.c")] { + instruction(entry, [0x34, 0x40], file, 2) + instruction(entry + 2, [0x33, 0xe4], file, 2) + instruction(entry + 4, [0x12], file, 5) + instruction(entry + 0x20, [0x32, 0xc4], file, 15) + if interrupt && entry == 0x2900 { + instruction(entry + 0x22, [0x35, 0x40], file, 15) + instruction(entry + 0x24, [0x3b], file, 15) + } else { instruction(entry + 0x22, [0x35, 0xc0], file, 15) } + } + instruction(0x2808, [0x17, 0x00, wrongTarget ? 0xf6 : 0xf5], "main.c", 12) + let map = CMOCProjectSourceMap(entryPoint: 0x2800, binarySHA256: "", sourceHashes: [:], instructions: instructions, + objectHashes: [:], listingHashes: [:], linkMapSHA256: "") + let integer = CMOCVariableDebug.CType.integer + let metadata = CMOCVariableDebug(functions: [ + .init(name: "parent", sourcePath: "main.c", entry: 0x2800, body: 0x2804, end: 0x2820, frame: true), + .init(name: "child", sourcePath: "helper.c", entry: 0x2900, body: 0x2904, end: 0x2920, frame: !optimized) + ], variables: [ + .init(name: "argument", sourcePath: "main.c", line: 2, type: integer, address: nil, offset: 4, scope: 0x2804..<0x2820, isStatic: false), + .init(name: "local", sourcePath: "main.c", line: 3, type: integer, address: nil, offset: -2, scope: 0x2804..<0x2820, isStatic: false), + .init(name: "argument", sourcePath: "helper.c", line: 2, type: integer, address: nil, offset: 4, scope: 0x2904..<0x2920, isStatic: false), + .init(name: "local", sourcePath: "helper.c", line: 3, type: integer, address: nil, offset: -2, scope: 0x2904..<0x2920, isStatic: false) + ], sourceMap: map) + var fixture = Fixture(metadata: metadata, memory: Data(repeating: 0, count: 65536), available: Data(repeating: 1, count: 65536)) + for item in instructions { for (index, byte) in item.bytes.enumerated() { fixture.memory[Int(item.address) + index] = byte } } + fixture.word(0x4001, 0x4021); fixture.word(0x4003, 0x280b) + fixture.word(0x4021, 0); fixture.word(0x4023, 0x1000) // Unmapped runtime caller. + fixture.word(0x4005, 9); fixture.word(0x3fff, 3) + fixture.word(0x4025, 7); fixture.word(0x401f, 5) + return fixture + } + func testCallerUsesCallSiteScopeAndRecoveredOddFramePointer() { + let fixture = fixture(), result = fixture.capture() + XCTAssertEqual(result.frames.map(\.functionName), ["child", "parent"]) + XCTAssertTrue(result.frames.allSatisfy(\.localsInspectable)) + XCTAssertEqual(result.frames[1].pc, 0x2808) + XCTAssertEqual(result.frames[1].sourceLine, 12) + XCTAssertEqual(result.frames[1].u, 0x4021) + for (index, expected) in [(0, ["argument":"9", "local":"3"]), (1, ["argument":"7", "local":"5"])] { + let frame = result.frames[index] + let evaluator = CMOCWatchEvaluator(metadata: fixture.metadata, context: .init(pc: frame.pc, u: frame.u, + memory: fixture.memory, available: fixture.available)) + for (name, value) in expected { + XCTAssertNil(evaluator.evaluate(name).error) + XCTAssertEqual(evaluator.evaluate(name).value, value) + } + } + XCTAssertTrue(result.termination.contains("caller")) + } + func testInvalidUnreadableRepeatedAndWrongCallLinksStopWithoutScanning() { + var fixture = fixture() + fixture.word(0x4001, 0x4001) + XCTAssertEqual(fixture.capture().frames.count, 1) + fixture.word(0x4001, 0x4003) + XCTAssertEqual(fixture.capture().frames.count, 1) + fixture.word(0x4001, 0xff00) + XCTAssertEqual(fixture.capture().frames.count, 1) + fixture.word(0x4001, 0x4021); fixture.word(0x4003, 0x280a) + XCTAssertEqual(fixture.capture().frames.count, 1) + fixture.word(0x4003, 0x280b); fixture.available[0x4021] = 0 + XCTAssertEqual(fixture.capture().frames.count, 1) + XCTAssertEqual(self.fixture(wrongTarget: true).capture().frames.count, 1) + fixture.available[0x4001] = 0 + XCTAssertFalse(fixture.capture().frames[0].localsInspectable) + fixture = self.fixture(); fixture.s = 0x4002 + XCTAssertFalse(fixture.capture().frames[0].localsInspectable) + // A plausible U and compiler metadata alone must not bypass the + // unwinder's rejection. Verified globals still need no stack frame. + let valid = self.fixture() + let metadata = CMOCVariableDebug(functions: valid.metadata.functions, + variables: valid.metadata.variables + [.init(name: "global", sourcePath: "helper.c", line: 1, + type: .integer, address: 0x4005, offset: nil, scope: nil, isStatic: false)], + sourceMap: valid.metadata.sourceMap) + let gated = CMOCWatchEvaluator(metadata: metadata, + context: .init(pc: valid.pc, u: valid.u, memory: valid.memory, available: valid.available), + frameLocalsAvailable: false) + XCTAssertNotNil(gated.evaluate("argument").error) + XCTAssertNotNil(gated.evaluate("local").error) + XCTAssertNotNil(gated.evaluate("&local").error) + XCTAssertNil(gated.evaluate("global").error) + XCTAssertEqual(gated.evaluate("global").value, "9") + } + func testOptimizedInterruptPrologueAndEpilogueDoNotInventCallerFrames() { + for fixture in [fixture(optimized: true), fixture(interrupt: true)] { + let result = fixture.capture() + XCTAssertEqual(result.frames.count, 1) + XCTAssertFalse(result.frames[0].localsInspectable) + XCTAssertTrue(result.termination.contains("unsupported")) + } + for pc: UInt16 in [0x2900, 0x2902, 0x2920, 0x2922] { + var fixture = fixture(); fixture.pc = pc + let result = fixture.capture() + XCTAssertEqual(result.frames.count, 1) + XCTAssertFalse(result.frames[0].localsInspectable) + XCTAssertTrue(result.termination.contains("prologue")) + } + // A plausible U and compiler frame flag do not override the caller's + // explicit determination that this paused frame cannot be inspected. + var fixture = fixture() + fixture.word(0x5000, 1234) + let metadata = CMOCVariableDebug(functions: fixture.metadata.functions, + variables: fixture.metadata.variables + [.init(name: "global", sourcePath: "helper.c", line: 1, + type: .integer, address: 0x5000, offset: nil, scope: nil, isStatic: false)], + sourceMap: fixture.metadata.sourceMap) + var evaluator = CMOCWatchEvaluator(metadata: metadata, context: .init(pc: fixture.pc, u: fixture.u, + memory: fixture.memory, available: fixture.available)) + XCTAssertEqual(evaluator.evaluate("argument").value, "9") + XCTAssertEqual(evaluator.evaluate("local").value, "3") + evaluator.frameLocalsAvailable = false + XCTAssertNotNil(evaluator.evaluate("argument").error) + XCTAssertNotNil(evaluator.evaluate("local").error) + XCTAssertNotNil(evaluator.visibleVariables().first { $0.name == "local" }?.error) + XCTAssertNil(evaluator.evaluate("global").error) + XCTAssertEqual(evaluator.evaluate("global").value, "1234") + XCTAssertEqual(evaluator.evaluate("1 + 2").value, "3") + } + func testUnverifiedCanonicalPrologueIsNotAcceptedFromLiveMemoryAlone() { + var fixture = fixture() + let original = fixture.metadata.sourceMap + let map = CMOCProjectSourceMap(entryPoint: original.entryPoint, binarySHA256: "", sourceHashes: [:], + instructions: original.instructions.filter { $0.address != 0x2900 }, objectHashes: [:], listingHashes: [:], linkMapSHA256: "") + fixture.metadata = CMOCVariableDebug(functions: fixture.metadata.functions, variables: fixture.metadata.variables, sourceMap: map) + let result = fixture.capture() + XCTAssertEqual(result.frames.count, 1) + XCTAssertFalse(result.frames[0].localsInspectable) + XCTAssertTrue(result.termination.contains("unsupported")) + } + func testSnapshotIdentityAndDepthLimits() { + var fixture = fixture() + fixture.memory[0x2904] = 0x39 + XCTAssertTrue(fixture.capture().frames.isEmpty) + fixture = self.fixture(); fixture.available[0x2904] = 0 + XCTAssertTrue(fixture.capture().frames.isEmpty) + fixture = self.fixture(); fixture.memory = Data() + XCTAssertTrue(fixture.capture().frames.isEmpty) + fixture = self.fixture() + let bounded = fixture.capture(limit: 1) + XCTAssertEqual(bounded.frames.count, 1) + XCTAssertTrue(bounded.termination.contains("1-frame")) + } +} diff --git a/platforms/macos/Tests/CMOCCompletionEditorTests.swift b/platforms/macos/Tests/CMOCCompletionEditorTests.swift new file mode 100644 index 0000000..cc0878e --- /dev/null +++ b/platforms/macos/Tests/CMOCCompletionEditorTests.swift @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest +import AppKit + +final class CMOCCompletionEditorTests: XCTestCase { + @MainActor private final class UndoDelegate: NSObject, NSTextViewDelegate { + let manager = UndoManager() + func undoManager(for view: NSTextView) -> UndoManager? { manager } + } + @MainActor private func fixture(_ body: (CMOCCompletionTextView, UndoManager) -> Void) { + let delegate = UndoDelegate() + let editor = CMOCEditingTextView(frame: NSRect(x: 0, y: 0, width: 400, height: 200)) + editor.delegate = delegate; editor.isRichText = false; editor.allowsUndo = true; editor.isEditable = true + editor.string = "int main(void) { prinOld; }" + editor.setSelectedRange(NSRange(location: 20, length: 0)) // pri|nOld + editor.completionProvider = { _, _ in [ + .init(name: "printf", detail: "Function", conditional: false, + replacementRange: NSRange(location: 17, length: 7), insertion: "printf") + ] } + body(editor, delegate.manager) + } + @MainActor func testFinalAcceptanceReplacesWholeIdentifierAndHasOneUndoRedo() { + fixture { editor, undo in + let original = editor.string + XCTAssertTrue(editor.prepareCompletion()) + let range = editor.rangeForUserCompletion + editor.insertCompletion("printf", forPartialWordRange: range, movement: NSTextMovement.return.rawValue, isFinal: true) + XCTAssertEqual(editor.string, "int main(void) { printf; }") + XCTAssertEqual(editor.selectedRange().location, 23) + XCTAssertTrue(undo.canUndo) + undo.undo(); XCTAssertEqual(editor.string, original) + XCTAssertFalse(undo.canUndo) + undo.redo(); XCTAssertEqual(editor.string, "int main(void) { printf; }") + } + } + @MainActor func testPreviewAndFinalCancellationDoNotModifyTextOrUndo() { + fixture { editor, undo in + let original = editor.string + XCTAssertTrue(editor.prepareCompletion()) + let range = editor.rangeForUserCompletion + editor.insertCompletion("printf", forPartialWordRange: range, movement: NSTextMovement.down.rawValue, isFinal: false) + XCTAssertEqual(editor.string, original); XCTAssertFalse(undo.canUndo) + editor.insertCompletion("printf", forPartialWordRange: range, movement: NSTextMovement.cancel.rawValue, isFinal: true) + XCTAssertEqual(editor.string, original); XCTAssertFalse(undo.canUndo) + } + } + @MainActor func testChangedTextOrCaretRejectsStaleCompletion() { + fixture { editor, _ in + XCTAssertTrue(editor.prepareCompletion()); let range = editor.rangeForUserCompletion + editor.setSelectedRange(NSRange(location: 0, length: 0)) + editor.insertCompletion("printf", forPartialWordRange: range, movement: NSTextMovement.return.rawValue, isFinal: true) + XCTAssertEqual(editor.string, "int main(void) { prinOld; }") + editor.setSelectedRange(NSRange(location: 20, length: 0)) + XCTAssertTrue(editor.prepareCompletion()) + editor.string = "extern int other;" + editor.insertCompletion("printf", forPartialWordRange: range, movement: NSTextMovement.return.rawValue, isFinal: true) + XCTAssertEqual(editor.string, "extern int other;") + } + } + @MainActor func testReadOnlySelectionAndInvalidatedRequestCannotInsert() { + fixture { editor, _ in + editor.isEditable = false; XCTAssertFalse(editor.prepareCompletion()) + editor.isEditable = true; editor.setSelectedRange(NSRange(location: 17, length: 7)) + XCTAssertFalse(editor.prepareCompletion()) + editor.setSelectedRange(NSRange(location: 20, length: 0)); XCTAssertTrue(editor.prepareCompletion()) + let range = editor.rangeForUserCompletion + editor.invalidateCompletion() + editor.insertCompletion("printf", forPartialWordRange: range, movement: NSTextMovement.return.rawValue, isFinal: true) + XCTAssertEqual(editor.string, "int main(void) { prinOld; }") + XCTAssertTrue(editor.prepareCompletion()); editor.isEditable = false + editor.insertCompletion("printf", forPartialWordRange: range, movement: NSTextMovement.return.rawValue, isFinal: true) + XCTAssertEqual(editor.string, "int main(void) { prinOld; }") + } + } + @MainActor func testUnlistedCandidateAndWrongReplacementRangeCannotInsert() { + fixture { editor, _ in + XCTAssertTrue(editor.prepareCompletion()); let range = editor.rangeForUserCompletion + editor.insertCompletion("system", forPartialWordRange: range, movement: NSTextMovement.return.rawValue, isFinal: true) + XCTAssertEqual(editor.string, "int main(void) { prinOld; }") + XCTAssertTrue(editor.prepareCompletion()) + editor.insertCompletion("printf", forPartialWordRange: NSRange(location: 0, length: 7), movement: NSTextMovement.return.rawValue, isFinal: true) + XCTAssertEqual(editor.string, "int main(void) { prinOld; }") + } + } + @MainActor func testOrdinaryTypingAndLineBreakUseNativeEditingWithoutAssistance() { + fixture { editor, undo in + editor.setSelectedRange(NSRange(location: (editor.string as NSString).length, length: 0)) + editor.insertText("\n\t", replacementRange: editor.selectedRange()) + XCTAssertTrue(editor.string.hasSuffix("\n\t")) + XCTAssertTrue(undo.canUndo) + } + } +} diff --git a/platforms/macos/Tests/CMOCCompletionTests.swift b/platforms/macos/Tests/CMOCCompletionTests.swift new file mode 100644 index 0000000..475c9e8 --- /dev/null +++ b/platforms/macos/Tests/CMOCCompletionTests.swift @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CMOCCompletionTests: XCTestCase { + private func fixture(_ marked: String, headers: [String: String] = [:]) -> (CMOCProjectIndex, String, Int) { + let offset = (marked as NSString).range(of: "|").location + XCTAssertNotEqual(offset, NSNotFound) + let text = marked.replacingOccurrences(of: "|", with: "") + return (CMOCProjectIndex(documents: headers.merging(["main.c": text]) { _, new in new }, includePaths: ["@toolchain/include"]), text, offset) + } + func testIncludedSymbolsKeywordsAndWholeTokenUnicodeReplacement() throws { + let (index, text, offset) = fixture("#include \n// 🙂\nint main(void) { pri|ntf; }", headers: [ + "@toolchain/include/cmoc.h": "int printf(const char *format, ...);", + "unrelated.h": "int private_unincluded(void);", + "other.c": "static int private_other(void) { return 0; }" + ]) + let suggestions = CMOCCompletion.suggestions(index: index, path: "main.c", text: text, offset: offset) + let candidate = try XCTUnwrap(suggestions.first { $0.name == "printf" }) + XCTAssertEqual(candidate.insertion, "printf") + XCTAssertEqual((text as NSString).substring(with: candidate.replacementRange), "printf") + XCTAssertEqual(candidate.replacementRange.location, offset - 3) + XCTAssertFalse(suggestions.contains { $0.name.hasPrefix("private") }) + let keywords = CMOCCompletion.suggestions(index: index, path: "main.c", text: text, offset: offset - 3) + XCTAssertTrue(keywords.contains { $0.name == "while" }) + } + func testLocalsShadowAndDoNotLeakAcrossScopesOrForLoops() throws { + let marked = "int shared; int main(int parameter) { { int shared; sha|red++; } return 0; } int other(void) { return 0; }" + let (index, text, offset) = fixture(marked) + let shared = try XCTUnwrap(CMOCCompletion.suggestions(index: index, path: "main.c", text: text, offset: offset).first) + XCTAssertEqual(shared.name, "shared") + XCTAssertTrue(shared.detail.contains("int shared")) + let other = (text as NSString).range(of: "return 0", options: .backwards).location + let outside = CMOCCompletion.suggestions(index: index, path: "main.c", text: text, offset: other) + XCTAssertFalse(outside.contains { $0.name == "parameter" }) + let (loopIndex, loopText, loopOffset) = fixture("int main(void) { for (int loopOnly = 0; loopOnly < 2; ++loopOnly) {} lo|; }") + XCTAssertFalse(CMOCCompletion.suggestions(index: loopIndex, path: "main.c", text: loopText, offset: loopOffset).contains { $0.name == "loopOnly" }) + } + func testNoSuggestionsInCommentsLiteralsDirectivesNumbersOrMembers() { + for marked in ["int main(void) { // pri|\n}", "int main(void) { /* pri| */ }", "int main(void) { \"pri|\"; }", "int main(void) { 'p|'; }", "#include \n", "#define X \\\npri|", "// continued \\\npri|", "int main(void) { object.pri|; }", "int main(void) { object->pri|; }", "int main(void) { 123|; }"] { + let (index, text, offset) = fixture(marked) + XCTAssertTrue(CMOCCompletion.suggestions(index: index, path: "main.c", text: text, offset: offset).isEmpty, marked) + } + } + func testStaleIdentifierEditMapsScopesWithoutRebuildingIndex() throws { + let old = "int main(int localCount) { loc; }" + let index = CMOCProjectIndex(documents: ["main.c": old]) + let text = old.replacingOccurrences(of: "loc;", with: "local;") + let offset = (text as NSString).range(of: "local;").location + 5 + let candidate = try XCTUnwrap(CMOCCompletion.suggestions(index: index, path: "main.c", text: text, offset: offset).first { $0.name == "localCount" }) + XCTAssertTrue(candidate.conditional) + let restructured = text.replacingOccurrences(of: " { local; }", with: " {} int other(void) { local; }") + let changedOffset = (restructured as NSString).range(of: "local;").location + 5 + XCTAssertFalse(CMOCCompletion.suggestions(index: index, path: "main.c", text: restructured, offset: changedOffset).contains { $0.name == "localCount" }) + let renamed = old.replacingOccurrences(of: "localCount", with: "differentName") + let renamedOffset = (renamed as NSString).range(of: "loc;").location + 3 + XCTAssertFalse(CMOCCompletion.suggestions(index: index, path: "main.c", text: renamed, offset: renamedOffset).contains { $0.name == "localCount" }) + } + func testNestedCallParametersIgnoreNonArgumentCommas() throws { + let (index, text, offset) = fixture("#include \"api.h\"\nint main(void) { outer(inner(1, 2), \"x,y\", items[i,j], (int[]){1,2}, |); }", headers: ["api.h": "int inner(int a, int b); int outer(int a, const char *b, int c, int *d, int e);"]) + let hint = try XCTUnwrap(CMOCCompletion.parameterHints(index: index, path: "main.c", text: text, offset: offset).first) + XCTAssertEqual(hint.name, "outer") + XCTAssertEqual(hint.parameters.count, 5) + XCTAssertEqual(hint.activeParameter, 4) + let innerOffset = (text as NSString).range(of: "inner(1, 2)").location + "inner(1, ".utf16.count + XCTAssertEqual(CMOCCompletion.parameterHints(index: index, path: "main.c", text: text, offset: innerOffset).first?.name, "inner") + XCTAssertEqual(CMOCCompletion.parameterHints(index: index, path: "main.c", text: text, offset: innerOffset).first?.activeParameter, 1) + } + func testGroupingCommentsAndEscapedStringsPreserveOuterParameter() throws { + let (index, text, offset) = fixture("#include \"api.h\"\nint main(void) { outer(\"a\\\",b\", /* , ) */ (1 + |)); }", headers: ["api.h": "int outer(const char *text, int value);"]) + let hint = try XCTUnwrap(CMOCCompletion.parameterHints(index: index, path: "main.c", text: text, offset: offset).first) + XCTAssertEqual(hint.name, "outer"); XCTAssertEqual(hint.activeParameter, 1) + } + func testVoidVariadicAndFunctionPointerParameterSignatures() throws { + let headers = ["api.h": "void clear(void); int printf(const char *format, ...); int apply(int (*callback)(int a, int b), int value);"] + for (marked, name, count, active) in [ + ("#include \"api.h\"\nint main(void) { clear(|); }", "clear", 0, 0), + ("#include \"api.h\"\nint main(void) { printf(\"%d%d\", 1, |); }", "printf", 2, 2), + ("#include \"api.h\"\nint main(void) { apply(callback, |); }", "apply", 2, 1) + ] { + let (index, text, offset) = fixture(marked, headers: headers) + let hint = try XCTUnwrap(CMOCCompletion.parameterHints(index: index, path: "main.c", text: text, offset: offset).first) + XCTAssertEqual(hint.name, name); XCTAssertEqual(hint.parameters.count, count); XCTAssertEqual(hint.activeParameter, active) + } + } + func testNoHintsForDeclarationsControlsMembersOrPointerCalls() { + for marked in ["int example(int |value);", "int main(void) { if (|) {} }", "int main(void) { sizeof(|); }", "int main(void) { object.example(|); }", "int main(void) { int (*example)(int); example(|); }", "Widget example(int |value);"] { + let (index, text, offset) = fixture(marked, headers: ["api.h": "int example(int value);"]) + XCTAssertTrue(CMOCCompletion.parameterHints(index: index, path: "main.c", text: text, offset: offset).isEmpty, marked) + } + } + func testConditionalMacroAndAlternativesRemainExplicit() throws { + let (index, text, offset) = fixture("#include \"api.h\"\nint main(void) { choose(|); }", headers: ["api.h": "#if SOMETHING\nint choose(int x);\n#else\nint choose(int x, int y);\n#endif"]) + let hints = CMOCCompletion.parameterHints(index: index, path: "main.c", text: text, offset: offset) + XCTAssertEqual(hints.count, 2); XCTAssertTrue(hints.allSatisfy(\.conditional)) + let (macroIndex, macroText, macroOffset) = fixture("#define MAXIMUM(a,b) ((a) > (b) ? (a) : (b))\nint main(void) { MAXIMUM(1, |); }") + let macro = try XCTUnwrap(CMOCCompletion.parameterHints(index: macroIndex, path: "main.c", text: macroText, offset: macroOffset).first) + XCTAssertEqual(macro.parameters, ["a", "b"]); XCTAssertTrue(macro.conditional) + } + func testLiteralArgumentKeepsHintAndObjectMacroIsNotCallable() throws { + let (index, text, offset) = fixture("#include \"api.h\"\nint main(void) { printf(\"value, |\"); }", headers: ["api.h": "int printf(const char *format, ...);"]) + let hint = try XCTUnwrap(CMOCCompletion.parameterHints(index: index, path: "main.c", text: text, offset: offset).first) + XCTAssertEqual(hint.name, "printf"); XCTAssertEqual(hint.activeParameter, 0) + XCTAssertTrue(CMOCCompletion.suggestions(index: index, path: "main.c", text: text, offset: offset).isEmpty) + let (objectIndex, objectText, objectOffset) = fixture("#define OBJECT (a,b)\nint main(void) { OBJECT(|); }") + XCTAssertTrue(CMOCCompletion.parameterHints(index: objectIndex, path: "main.c", text: objectText, offset: objectOffset).isEmpty) + } + func testBoundsMalformedInputsAndTruncatedSignatures() { + let (index, text, offset) = fixture("int main(void) { | }") + XCTAssertEqual(CMOCCompletion.suggestions(index: index, path: "main.c", text: text, offset: offset, limit: 3).count, 3) + XCTAssertTrue(CMOCCompletion.suggestions(index: index, path: "Makefile", text: text, offset: offset).isEmpty) + XCTAssertTrue(CMOCCompletion.suggestions(index: index, path: "main.c", text: text, offset: -1).isEmpty) + XCTAssertTrue(CMOCCompletion.parameterHints(index: index, path: "main.c", text: text, offset: text.utf16.count + 1).isEmpty) + let params = (0..<60).map { "int parameter\($0)" }.joined(separator: ",") + let (longIndex, longText, longOffset) = fixture("#include \"api.h\"\nint main(void) { huge(|); }", headers: ["api.h": "int huge(\(params));"]) + XCTAssertTrue(CMOCCompletion.parameterHints(index: longIndex, path: "main.c", text: longText, offset: longOffset).isEmpty) + let tooLarge = String(repeating: " ", count: CMOCProjectIndex.maximumFileBytes + 1) + XCTAssertTrue(CMOCCompletion.suggestions(index: index, path: "main.c", text: tooLarge, offset: 1).isEmpty) + } +} diff --git a/platforms/macos/Tests/CMOCDevelopmentTests.swift b/platforms/macos/Tests/CMOCDevelopmentTests.swift new file mode 100644 index 0000000..74ccf03 --- /dev/null +++ b/platforms/macos/Tests/CMOCDevelopmentTests.swift @@ -0,0 +1,753 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CMOCDevelopmentTests: XCTestCase { + @MainActor private func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { continuation in operation { continuation.resume(returning: $0) } } + } + @MainActor private func capture(_ controller: VCCMachineController, memory: UInt16 = 0x4000) async -> VCCDebuggerSnapshot { + await withCheckedContinuation { continuation in + controller.debuggerSnapshot(address: 0x4100, followPC: true, memoryAddress: memory) { + continuation.resume(returning: $0) + } + } + } + private func binary(address: UInt16 = 0x4100, entry: UInt16 = 0x4100, + bytes: [UInt8] = [0x86, 0x2A, 0xB7, 0x40, 0x00, 0x4C, 0xB7, 0x40, 0x01, 0x20, 0xFE]) -> Data { + Data([0, UInt8(bytes.count >> 8), UInt8(bytes.count & 255), UInt8(address >> 8), UInt8(address & 255)] + + bytes + [255, 0, 0, UInt8(entry >> 8), UInt8(entry & 255)]) + } + @MainActor private func waitForStop(_ controller: VCCMachineController) async -> VCCMachineSnapshot { + var result = await command(controller.snapshot) + for _ in 0..<200 where result.state == .running { + try? await Task.sleep(nanoseconds: 10_000_000) + result = await command(controller.snapshot) + } + XCTAssertEqual(result.state, .paused) + return result + } + @MainActor func testDevelopmentLoadArmsEntryAndLaterBreakpointsAtomicallyOnBothCPUs() async { + for use6309 in [false, true] { + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command { controller.loadDiagnostic(use6309: use6309, completion: $0) } + _ = await command { controller.debuggerWriteMemory(address: 0x4000, data: Data([0xA5, 0x5A]), completion: $0) } + _ = await command { controller.debuggerConfigureBreakpoints([0x4500], disabled: [0x4100, 0x4501], completion: $0) } + let before = await capture(controller) + let loaded = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4100, completion: $0) } + XCTAssertNil(loaded.errorMessage) + let entry = await waitForStop(controller) + let entryDetail = await capture(controller) + XCTAssertEqual(entry.programCounter, 0x4100) + XCTAssertEqual(entry.cycles, before.machine.cycles, "Entry breakpoint must stop before the very first instruction") + XCTAssertEqual(entry.generation, before.machine.generation, "Loading a build must preserve the machine session") + XCTAssertEqual(entryDetail.memory.prefix(2), Data([0xA5, 0x5A])) + XCTAssertEqual(Set(entryDetail.breakpoints.map(\.uint16Value)), Set([UInt16(0x4100), 0x4500])) + XCTAssertEqual(entryDetail.disabledBreakpoints, [0x4501], "Arming a disabled breakpoint must retain unrelated disabled addresses") + + _ = await command { controller.debuggerConfigureBreakpoints([0x4500], disabled: [0x4501], completion: $0) } + let loadedAgain = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4105, completion: $0) } + XCTAssertNil(loadedAgain.errorMessage) + let later = await waitForStop(controller) + let laterDetail = await capture(controller) + XCTAssertEqual(later.programCounter, 0x4105) + XCTAssertGreaterThan(later.cycles, entry.cycles) + XCTAssertEqual(laterDetail.memory.prefix(2), Data([0x2A, 0x5A]), "Only instructions before the selected breakpoint should execute") + XCTAssertEqual(Set(laterDetail.breakpoints.map(\.uint16Value)), Set([UInt16(0x4105), 0x4500])) + XCTAssertEqual(laterDetail.disabledBreakpoints, [0x4501]) + _ = await command(controller.shutdown) + } + } + @MainActor func testDevelopmentLoadRejectsInvalidImagesWithoutMutatingMachineOrBreakpoints() async { + for use6309 in [false, true] { + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command { controller.loadDiagnostic(use6309: use6309, completion: $0) } + _ = await command { controller.debuggerConfigureBreakpoints([0x4500], disabled: [0x4501], completion: $0) } + let before = await capture(controller) + let beforeProgram = await capture(controller, memory: 0x4100) + let invalid: [(Data, UInt16)] = [ + (Data(binary().dropLast(5)) + binary(address: 0xFF00, entry: 0x4100), 0x4100), + (Data([0, 0, 5, 0x41, 0, 0x86]), 0x4100), + (binary(), 0x4200), + (binary(entry: 0x4200), 0x4100), + (binary(address: 0xFF00, entry: 0xFF00), 0xFF00), + (binary(address: 0x8000, entry: 0x8000), 0x8000) + ] + for (image, breakpoint) in invalid { + let result = await command { controller.debuggerLoadBinary(image, breakpoint: breakpoint, completion: $0) } + XCTAssertNotNil(result.errorMessage) + let after = await capture(controller) + XCTAssertEqual(after.machine.state, .paused) + XCTAssertEqual(after.machine.programCounter, before.machine.programCounter) + XCTAssertEqual(after.machine.cycles, before.machine.cycles) + XCTAssertEqual(after.machine.generation, before.machine.generation) + XCTAssertEqual(after.machine.debuggerProgramRevision, before.machine.debuggerProgramRevision) + XCTAssertEqual(after.machine.debuggerMappingFingerprint, before.machine.debuggerMappingFingerprint) + XCTAssertEqual(after.memory, before.memory) + XCTAssertEqual(after.breakpoints, before.breakpoints) + XCTAssertEqual(after.disabledBreakpoints, before.disabledBreakpoints) + let afterProgram = await capture(controller, memory: 0x4100) + XCTAssertEqual(afterProgram.memory, beforeProgram.memory) + } + _ = await command(controller.shutdown) + } + } + @MainActor func testDevelopmentBreakpointOwnershipAndProgramRevision() async { + for use6309 in [false, true] { + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command { controller.loadDiagnostic(use6309: use6309, completion: $0) } + _ = await command { controller.debuggerConfigureBreakpoints([0x4500], disabled: [0x4100, 0x4501], completion: $0) } + let before = await capture(controller) + _ = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4100, completion: $0) } + let first = await waitForStop(controller) + XCTAssertGreaterThan(first.debuggerProgramRevision, before.machine.debuggerProgramRevision) + XCTAssertEqual(first.debuggerMappingFingerprint, before.machine.debuggerMappingFingerprint) + _ = await command(controller.debuggerStep) + let stepped = await capture(controller) + XCTAssertEqual(stepped.machine.debuggerProgramRevision, first.debuggerProgramRevision, "Execution must not invalidate its own source provenance") + _ = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4105, completion: $0) } + _ = await waitForStop(controller) + let second = await capture(controller) + XCTAssertEqual(Set(second.breakpoints.map(\.uint16Value)), Set([UInt16(0x4105), 0x4500])) + XCTAssertEqual(Set(second.disabledBreakpoints.map(\.uint16Value)), Set([UInt16(0x4100), 0x4501]), "Moving the development breakpoint must restore a user's disabled breakpoint") + _ = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4106, completion: $0) } + _ = await waitForStop(controller) + let third = await capture(controller) + XCTAssertEqual(Set(third.breakpoints.map(\.uint16Value)), Set([UInt16(0x4106), 0x4500]), "An obsolete development breakpoint must not stop the new build") + _ = await command { controller.debuggerWriteMemory(address: 0x4000, data: Data([0x55]), completion: $0) } + let edited = await capture(controller) + XCTAssertGreaterThan(edited.machine.debuggerProgramRevision, third.machine.debuggerProgramRevision) + _ = await command { controller.debuggerConfigureBreakpoints([0x4100, 0x4500], disabled: [0x4501], completion: $0) } + _ = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4100, completion: $0) } + _ = await waitForStop(controller) + _ = await command { controller.debuggerLoadBinary(binary(), breakpoint: 0x4105, completion: $0) } + _ = await waitForStop(controller) + let existing = await capture(controller) + XCTAssertEqual(Set(existing.breakpoints.map(\.uint16Value)), Set([UInt16(0x4100), 0x4105, 0x4500]), "The feature must not claim or remove a preexisting enabled breakpoint") + _ = await command(controller.shutdown) + } + } + @MainActor func testCompiledEditedProgramStopsAtVerifiedCLineOnBothCPUs() async throws { + let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources") + let toolchain = resources.appendingPathComponent("ToolchainBundle") + let romURL = resources.appendingPathComponent("ROMs/coco3.rom") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) + && FileManager.default.fileExists(atPath: romURL.path), "Local licensed CoCo ROM and staged toolchain are required") + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCExecutionTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: folder) } + let project = try CMOCProject.create(at: folder.appendingPathComponent("Project")) + let source = CMOCProject.starterSource.replacingOccurrences(of: "What planet do you live on?", with: "Which planet is yours?") + let artifact = try await CMOCBuildService(toolchain: toolchain, buildRoot: folder.appendingPathComponent("Builds")).build(project: project, source: source) + let mapping = try CMOCSourceMap.parse(source: artifact.sourceData, sourceName: artifact.sourceURL.path, + listing: Data(contentsOf: artifact.listingURL), object: Data(contentsOf: artifact.objectURL), objectName: "main.o", + linkMap: Data(contentsOf: artifact.mapURL), binary: artifact.binaryData) + let promptLine = try XCTUnwrap(source.components(separatedBy: "\n").firstIndex { $0.contains("Which planet is yours?") }) + 1 + let instruction = try XCTUnwrap(mapping.instructions.first { $0.sourceLine == promptLine }) + let rom = try Data(contentsOf: romURL) + for use6309 in [false, true] { + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + let loaded = await command { controller.loadROM(rom, use6309: use6309, completion: $0) } + XCTAssertNil(loaded.errorMessage) + _ = await command(controller.resume) + try await Task.sleep(nanoseconds: 1_500_000_000) + _ = await command(controller.pause) + let before = await capture(controller) + let result = await command { controller.debuggerLoadBinary(artifact.binaryData, breakpoint: instruction.address, completion: $0) } + XCTAssertNil(result.errorMessage) + let stopped = await waitForStop(controller) + let snapshot = await capture(controller) + XCTAssertEqual(stopped.programCounter, instruction.address) + XCTAssertEqual(mapping.line(at: stopped.programCounter), promptLine) + XCTAssertEqual(snapshot.instructions.first?.address, instruction.address) + XCTAssertEqual(snapshot.instructions.first?.bytes, Data(instruction.bytes), "The live machine must contain the exact relocated instruction verified by the C map") + XCTAssertEqual(stopped.generation, before.machine.generation) + XCTAssertGreaterThan(stopped.cycles, before.machine.cycles) + _ = await command(controller.shutdown) + } + } + @MainActor func testBundledDiskAPIWritesClosesReopensAndReadsAnIsolatedFloppyOnBothCPUs() async throws { + try await checkDiskAPIRoundTrip(standalone: false) + } + @MainActor func testStandaloneDiskAPIReadsAndWritesWithBASICBankedOutOnBothCPUs() async throws { + try await checkDiskAPIRoundTrip(standalone: true) + } + @MainActor private func checkDiskAPIRoundTrip(standalone: Bool) async throws { + let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + let resources = mac.appendingPathComponent("LocalResources") + let toolchain = resources.appendingPathComponent("ToolchainBundle") + let romURL = resources.appendingPathComponent("ROMs/coco3.rom") + let diskROMURL = resources.appendingPathComponent("ROMs/disk11.rom") + try XCTSkipUnless(FileManager.default.fileExists(atPath: toolchain.appendingPathComponent("share/cmoc/lib/libdecbfile.a").path) + && FileManager.default.fileExists(atPath: romURL.path) + && FileManager.default.fileExists(atPath: diskROMURL.path), "The local ROMs and bundled DECB file library are required") + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCDiskAPITests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: folder) } + let project = try CMOCProject.create(at: folder.appendingPathComponent("Project")) + // Authored fixture: use the public file API through the running Disk + // BASIC ROM. No host-side disk writer substitutes for guest file I/O. + var source = """ + #include + #include + DECBDrive drives[1]; + DECBFile file; + byte written[256], readBack[256]; + byte testResult; + byte roundTrip(void) + { + word i; + if (decb_init(drives, 1) != DECB_OK) return 1; + if (decb_registerDrive(0) != DECB_OK) return 2; + if (decb_createSectorFile(&file, 0, "ROUND.DAT", DECB_TYPE_BASIC_DATA, DECB_FORMAT_BINARY) != DECB_OK) return 3; + for (i = 0; i < 256; ++i) written[i] = (byte) (i ^ 0x5A); + if (decb_writeSector(&file, written, 0) != DECB_OK) return 4; + decb_setNumBytesUsedInLastSector(&file, 256); + if (decb_closeSectorFile(&file) != DECB_OK) return 5; + if (decb_openSectorFile(&file, 0, "ROUND.DAT") != DECB_OK) return 6; + if (decb_readSector(&file, readBack, 0) != DECB_OK) return 7; + if (memcmp(written, readBack, 256) != 0) return 8; + if (decb_closeSectorFile(&file) != DECB_OK) return 9; + return DECB_OK; + } + int main(void) + { + initCoCoSupport(); + setHighSpeed(FALSE); + testResult = roundTrip(); + if (decb_shutdown() != DECB_OK) testResult = 10; + printf("DISK ROUND TRIP RESULT: %u\\n", testResult); + return testResult; + } + """ + if standalone { + try XCTSkipUnless(FileManager.default.fileExists(atPath: toolchain.appendingPathComponent("share/cmoc/lib/libdskcon-standalone.a").path), "Stage the separately supplied standalone disk driver") + var makefile = try String(contentsOf: project.makefileURL) + makefile = makefile.replacingOccurrences(of: "LIBS ?= -ldecbfile", with: "LIBS ?= -ldecbfile -ldskcon-standalone") + try makefile.write(to: project.makefileURL, atomically: true, encoding: .utf8) + source = source.replacingOccurrences(of: "#include ", with: """ + #include + #include + interrupt asm void diskIRQ(void) + { + asm + { + _dskcon_irqService IMPORT + ldb $FF03 + bpl @done + ldb $FF02 + lbsr _dskcon_irqService + @done + } + } + """) + source = source.replacingOccurrences(of: "if (decb_registerDrive(0) != DECB_OK) return 2;", with: """ + if (*(volatile word *)0xC004 != 0x5A5A) return 11; + decb_setDskConAddresses(dskcon_processSector, (DECBDskConVariables *)&DCOPC); + if (decb_registerDrive(0) != DECB_OK) return 2; + """) + source = source.replacingOccurrences(of: "testResult = roundTrip();", with: """ + disableInterrupts(); + asm("CLR", "$FFDF"); + *(volatile word *)0xC004 = 0x5A5A; + { + byte *irq = *(byte **)0xFFF8; + *irq = 0x7E; + *(word *)(irq + 1) = (word)diskIRQ; + } + dskcon_init(dskcon_nmiService); + enableInterrupts(); + testResult = roundTrip(); + """) + } + let line = try XCTUnwrap(source.components(separatedBy: "\n").firstIndex { $0.contains("printf(") }) + 1 + let artifact = try await CMOCBuildService(toolchain: toolchain, buildRoot: folder.appendingPathComponent("Builds")).build(project: project, source: source) + let mapData = try Data(contentsOf: artifact.mapURL) + let mapping = try CMOCSourceMap.parse(source: artifact.sourceData, sourceName: artifact.sourceURL.path, + listing: Data(contentsOf: artifact.listingURL), object: Data(contentsOf: artifact.objectURL), objectName: "main.o", + linkMap: mapData, binary: artifact.binaryData) + let instruction = try XCTUnwrap(mapping.instructions.first { $0.sourceLine == line }) + let symbol = try XCTUnwrap(String(decoding: mapData, as: UTF8.self).components(separatedBy: "\n") + .first { $0.hasPrefix("Symbol: _testResult (main.o) = ") }) + let resultAddress = try XCTUnwrap(UInt16(try XCTUnwrap(symbol.split(separator: " ").last), radix: 16)) + let rom = try Data(contentsOf: romURL), diskROM = try Data(contentsOf: diskROMURL) + let blankURL = mac.appendingPathComponent("Resources/StarterMedia/Blank Disk.dsk") + let blank = try Data(contentsOf: blankURL) + for use6309 in [false, true] { + let localDisk = folder.appendingPathComponent(use6309 ? "6309.dsk" : "6809.dsk") + try blank.write(to: localDisk) + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + let configured = await command { controller.loadDiskROM(diskROM, name: "Disk BASIC", completion: $0) } + XCTAssertNil(configured.errorMessage) + let layout = await command { controller.configureCartridges([2,0,0,0,2], roms: Array(repeating: Data(), count: 5), + names: Array(repeating: "", count: 5), multiPak: true, physicalSlot: 4, completion: $0) } + XCTAssertNil(layout.errorMessage) + let mounted = await command { controller.mountDisk(blank, drive: 0, name: localDisk.lastPathComponent, readOnly: false, completion: $0) } + XCTAssertNil(mounted.errorMessage) + _ = await command { controller.loadROM(rom, use6309: use6309, completion: $0) } + _ = await command(controller.resume) + try await Task.sleep(nanoseconds: 1_500_000_000) + _ = await command(controller.pause) + let loaded = await command { controller.debuggerLoadBinary(artifact.binaryData, breakpoint: instruction.address, completion: $0) } + XCTAssertNil(loaded.errorMessage) + var stopped = loaded + for _ in 0..<1000 where stopped.state == .running { + try await Task.sleep(nanoseconds: 10_000_000) + stopped = await command(controller.snapshot) + } + XCTAssertEqual(stopped.state, .paused) + XCTAssertEqual(stopped.programCounter, instruction.address) + let snapshot = await capture(controller, memory: resultAddress) + XCTAssertEqual(snapshot.memory.first, 0, "Nonzero value identifies the failing guest disk API step") + XCTAssertEqual(snapshot.instructions.first?.bytes, Data(instruction.bytes)) + XCTAssertGreaterThan(stopped.disks[0].readEvents, 0) + XCTAssertGreaterThan(stopped.disks[0].writeEvents, 0) + let exported: Data? = await withCheckedContinuation { continuation in + controller.exportDisk(inDrive: 0) { bytes, _, _ in continuation.resume(returning: bytes) } + } + XCTAssertNotNil(exported) + if let exported { + XCTAssertNotEqual(exported, blank) + XCTAssertNotNil(exported.range(of: Data("ROUND DAT".utf8)), "The file must have a real DECB directory entry") + try exported.write(to: localDisk) + } + _ = await command(controller.shutdown) + } + XCTAssertEqual(try Data(contentsOf: blankURL), blank, "The repository's starter disk must remain pristine") + } + @MainActor func testCallerSelectionPreservesExecutionAndResetsOnStepOrStaleSource() async throws { + let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + let staged = mac.appendingPathComponent("LocalResources/ToolchainBundle") + let bundled = Bundle.main.resourceURL!.appendingPathComponent("Toolchain") + let toolchain = FileManager.default.isExecutableFile(atPath: bundled.appendingPathComponent("bin/cmoc").path) ? bundled : staged + let romURL = mac.appendingPathComponent("LocalResources/ROMs/coco3.rom") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) + && FileManager.default.fileExists(atPath: romURL.path), "Stage the local compiler and CoCo ROM") + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCCallerSelection-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let suite = "CMOCCallerSelection.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) } + let pageGlobals = (0..<40).map { String(format: "unsigned int page%02d;", $0) }.joined(separator: "\n") + let source = """ + #include + unsigned int score; + unsigned int grid[12][40]; + struct Info { unsigned int marker; unsigned int samples[2]; }; + \(pageGlobals) + unsigned int recurse(unsigned int n) + { + unsigned int local = n + 10; + unsigned int items[40]; + struct Info info; + items[0] = n + 20; + items[35] = n + 55; + info.marker = n + 30; + if (n == 0) { + score = local; /* LEAF_STOP */ + return local; /* NEXT_LEAF_LINE */ + } + local += recurse(n - 1); /* CALLER_SITE */ + return local; + } + int main(void) + { + score = recurse(2); + for (;;) ++score; + return 0; + } + """ + let lines = source.components(separatedBy: "\n") + let leafLine = try XCTUnwrap(lines.firstIndex { $0.contains("LEAF_STOP") }) + 1 + let nextLine = try XCTUnwrap(lines.firstIndex { $0.contains("NEXT_LEAF_LINE") }) + 1 + let callerLine = try XCTUnwrap(lines.firstIndex { $0.contains("CALLER_SITE") }) + 1 + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + try Data(source.utf8).write(to: project.sourceURL) + let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: root.appendingPathComponent("input.json"))) + let model = CMOCDevelopmentModel(machine: machine, toolchain: toolchain, defaults: defaults) + func snapshot() async throws -> VCCDebuggerSnapshot { + let result: VCCDebuggerSnapshot? = await withCheckedContinuation { continuation in + machine.readDebugger(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) } + } + return try XCTUnwrap(result) + } + func nodes(_ listing: CMOCVariableTreeListing) -> [CMOCWatchEvaluator.TreeNode] { + listing.rows.compactMap { row in if case .node(let node) = row.content { return node }; return nil } + } + let itemsPath = CMOCWatchEvaluator.TreePath(root: .variable("items")) + let infoPath = CMOCWatchEvaluator.TreePath(root: .variable("info")) + func expandedValues(offset: Int = 0) -> [CMOCWatchEvaluator.TreeNode] { + nodes(model.variableTree(watches: false, expanded: [itemsPath, infoPath], offsets: [itemsPath: offset], rootOffset: 0)) + } + do { + try model.adopt(project) + model.build() + for _ in 0..<3000 where model.building { try await Task.sleep(nanoseconds: 10_000_000) } + XCTAssertFalse(model.building) + XCTAssertNil(model.message) + XCTAssertTrue(model.buildMatchesEditor, model.log) + for _ in 0..<500 where machine.busy { try await Task.sleep(nanoseconds: 10_000_000) } + machine.installROM(try Data(contentsOf: romURL), url: romURL) + for _ in 0..<500 where machine.busy { try await Task.sleep(nanoseconds: 10_000_000) } + try await Task.sleep(nanoseconds: 1_500_000_000) + model.breakpointLine = leafLine + XCTAssertTrue(model.canRun) + model.run() + for _ in 0..<1000 where model.currentLine != leafLine || model.callStack == nil { + model.refresh(); try await Task.sleep(nanoseconds: 10_000_000) + } + let stack = try XCTUnwrap(model.callStack, model.message ?? model.execution) + XCTAssertEqual(stack.frames.map(\.functionName), ["recurse", "recurse", "recurse", "main"], stack.termination) + XCTAssertEqual(model.watchValue("n")?.value, "0") + XCTAssertEqual(model.watchValue("local")?.value, "10") + let initialInspection = try XCTUnwrap(model.variableInspectionIdentity) + XCTAssertEqual(expandedValues().first { $0.path == itemsPath.appending(.index(0)) }?.value, "20") + XCTAssertEqual(expandedValues(offset: 32).first { $0.path == itemsPath.appending(.index(35)) }?.value, "55") + XCTAssertEqual(expandedValues().first { $0.path == infoPath.appending(.member("marker")) }?.value, "30") + let firstPage = model.variableTree(watches: false, expanded: [], offsets: [:], rootOffset: 0) + let secondPage = model.variableTree(watches: false, expanded: [], offsets: [:], rootOffset: 32) + XCTAssertGreaterThan(firstPage.rootCount, 32) + XCTAssertEqual(nodes(firstPage).count, 32) + XCTAssertEqual(secondPage.rootOffset, 32) + XCTAssertTrue(Set(nodes(firstPage).map(\.path)).isDisjoint(with: nodes(secondPage).map(\.path))) + let gridPath = CMOCWatchEvaluator.TreePath(root: .variable("grid")) + let expandedGrid = Set([gridPath] + (0..<12).map { gridPath.appending(.index($0)) }) + let bounded = model.variableTree(watches: false, expanded: expandedGrid, offsets: [:], rootOffset: 0) + XCTAssertLessThanOrEqual(bounded.rows.count, 256) + XCTAssertTrue(bounded.rows.contains { $0.id == .limit }, "Broad trees must report the visible-row limit") + model.watchExpression = "items"; model.addWatch() + let watchPath = CMOCWatchEvaluator.TreePath(root: .watch("items")) + let executionPC = model.pc, executionLine = model.currentLine + let navigation = model.navigationRequest + let before = try await snapshot() + + model.selectFrame(1) + XCTAssertEqual(model.selectedFrameIndex, 1) + XCTAssertNotEqual(model.variableInspectionIdentity, initialInspection) + let callerInspection = model.variableInspectionIdentity + XCTAssertEqual(expandedValues().first { $0.path == itemsPath.appending(.index(0)) }?.value, "21") + XCTAssertEqual(expandedValues().first { $0.path == infoPath.appending(.member("marker")) }?.value, "31") + let callerWatch = model.variableTree(watches: true, expanded: [watchPath], offsets: [:], rootOffset: 0) + XCTAssertEqual(nodes(callerWatch).first { $0.path == watchPath.appending(.index(0)) }?.value, "21") + XCTAssertTrue(model.inspectingCaller) + XCTAssertEqual(model.navigationLine, callerLine) + XCTAssertNotEqual(model.navigationRequest, navigation) + XCTAssertEqual(model.selectedFile, "main.c") + XCTAssertEqual(model.watchValue("n")?.value, "1") + XCTAssertEqual(model.visibleVariables.first { $0.name == "local" }?.value, "11") + XCTAssertEqual(model.pc, executionPC, "Source navigation must not replace the paused execution PC") + XCTAssertEqual(model.currentLine, executionLine) + let after = try await snapshot() + XCTAssertEqual(after.machine.programCounter, before.machine.programCounter) + XCTAssertEqual(after.machine.cycles, before.machine.cycles) + XCTAssertEqual(after.registers, before.registers) + XCTAssertEqual(after.logicalMemory, before.logicalMemory) + let callerNavigation = model.navigationRequest + for _ in 0..<6 { model.refresh(); try await Task.sleep(nanoseconds: 20_000_000) } + XCTAssertEqual(model.selectedFrameIndex, 1, "Polling the same stop must preserve caller selection") + XCTAssertEqual(model.navigationRequest, callerNavigation, "Polling must not snap navigation back to frame zero") + XCTAssertEqual(model.watchValue("local")?.value, "11") + XCTAssertEqual(model.variableInspectionIdentity, callerInspection, "Same-stop refresh must not collapse the variable tree") + XCTAssertEqual(expandedValues().first { $0.path == itemsPath.appending(.index(0)) }?.value, "21") + + model.source += "\n/* edited source invalidates frame provenance */" + XCTAssertNil(model.callStack) + XCTAssertNil(model.inspectionFrame) + XCTAssertNil(model.watchValue("local")) + XCTAssertNil(model.variableInspectionIdentity) + XCTAssertTrue(model.variableTree(watches: false, expanded: [itemsPath], offsets: [:], rootOffset: 0).rows.isEmpty) + XCTAssertTrue(model.variableTree(watches: true, expanded: [watchPath], offsets: [:], rootOffset: 0).rows.isEmpty) + XCTAssertFalse(model.canStepC) + model.source = source + XCTAssertTrue(model.canStepC) + model.stepSource(.over) + for _ in 0..<1000 where model.currentLine != nextLine || model.commanding || model.callStack == nil { + model.refresh(); try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertEqual(model.currentLine, nextLine, model.message ?? model.execution) + XCTAssertNotEqual(model.pc, executionPC) + XCTAssertEqual(model.selectedFrameIndex, 0, "Execution invalidates the selected caller context") + XCTAssertFalse(model.inspectingCaller) + XCTAssertNotEqual(model.variableInspectionIdentity, initialInspection) + XCTAssertNotEqual(model.variableInspectionIdentity, callerInspection) + XCTAssertEqual(expandedValues().first { $0.path == itemsPath.appending(.index(0)) }?.value, "20") + XCTAssertEqual(model.watchValue("n")?.value, "0", "Step must control the innermost frame, not the selected caller") + XCTAssertEqual(model.watchValue("local")?.value, "10") + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } catch { + model.cancelBuild() + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + throw error + } + } + @MainActor func testDefaultHelloDiskLaunchRunsWithoutImplicitBreakpointAndHonorsExplicitStops() async throws { + let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + let resources = mac.appendingPathComponent("LocalResources") + let tools = resources.appendingPathComponent("ToolchainBundle") + let rom = resources.appendingPathComponent("ROMs/coco3.rom"), diskROM = resources.appendingPathComponent("ROMs/disk11.rom") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/cmoc").path) && + FileManager.default.fileExists(atPath: rom.path) && FileManager.default.fileExists(atPath: diskROM.path), "Stage local tools and ROMs") + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCNormalLaunch-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let suite = "CMOCNormalLaunch." + UUID().uuidString + // Use an isolated preferences domain and writable media directory. + let testDefaults = UserDefaults(suiteName: suite)! + defer { testDefaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) } + let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: testDefaults, + inputStore: .init(url: root.appendingPathComponent("input.json"))) + let model = CMOCDevelopmentModel(machine: machine, toolchain: tools, defaults: testDefaults) + func detail() async throws -> VCCDebuggerSnapshot { + let value: VCCDebuggerSnapshot? = await withCheckedContinuation { continuation in + machine.readDebugger(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) } + } + return try XCTUnwrap(value) + } + func idle() async throws { + for _ in 0..<1000 where machine.busy || model.commanding || machine.diskSaving { try await Task.sleep(nanoseconds: 10_000_000) } + XCTAssertFalse(machine.busy); XCTAssertFalse(model.commanding) + } + func screen(_ detail: VCCDebuggerSnapshot) -> String { + // Standard 32-column BASIC text cells, read without touching the clipboard. + String(bytes: detail.logicalMemory[0x400..<0x600].map { cell in + let code = cell & 0x3f + return code < 32 ? code + 64 : code + }, encoding: .ascii) ?? "" + } + func bootReady() async throws { + if machine.state == .paused { machine.resume(); try await idle() } + for _ in 0..<500 { + let value = try await detail() + if screen(value).contains("OK") { + let frame = value.machine.frames + for _ in 0..<500 { + try await Task.sleep(nanoseconds: 20_000_000) + if try await detail().machine.frames >= frame + 30 { return } + } + break + } + try await Task.sleep(nanoseconds: 20_000_000) + } + let failed = try await detail() + throw CMOCBuildError.message("Disk BASIC not ready: state=\(failed.machine.state.rawValue) frames=\(failed.machine.frames) screen=\(screen(failed))") + } + func completed() async throws { + var text = "" + for _ in 0..<1500 { + let snapshot = try await detail(); text = screen(snapshot) + if text.contains("GENERATED WORD COUNT: 5") && machine.pasteRemaining == 0 { break } + if !model.commanding && snapshot.machine.state == .paused { XCTFail("Normal launch stopped at an unrequested breakpoint"); break } + try await Task.sleep(nanoseconds: 20_000_000) + } + XCTAssertTrue(text.contains("DISK RESULT: 0"), text) + XCTAssertTrue(text.contains("GENERATED WORD COUNT: 5"), text) + XCTAssertEqual(machine.state, .running, model.message ?? model.execution) + } + do { + let template = mac.deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("examples/cmoc/HelloDisk") + try model.adopt(CMOCProject.createHelloDisk(at: root.appendingPathComponent("Hello Disk"), templateDirectory: template)) + model.build() + for _ in 0..<3000 where model.building { try await Task.sleep(nanoseconds: 10_000_000) } + XCTAssertTrue(model.buildMatchesEditor, model.log) + XCTAssertTrue(model.breakpoints.isEmpty) + XCTAssertTrue(model.resolvedBreakpointAddresses.isEmpty) + XCTAssertNotNil(model.breakpointAddress) + XCTAssertEqual(model.runToBreakpointAddresses, [try XCTUnwrap(model.breakpointAddress)]) + try await idle() + machine.selectDiskROM(diskROM); try await idle() + machine.installROM(try Data(contentsOf: rom), url: rom); try await idle() + try await bootReady() + XCTAssertTrue(machine.diskEnabled) + XCTAssertTrue(model.canLaunch, model.message ?? model.execution) + model.launchDisk(commands: ["DOS"]) + try await idle(); try await completed() + + // Reboot to a clean prompt, then prove explicit source breakpoints still work. + machine.reset(); try await idle(); try await bootReady() + model.toggleBreakpoint(13) + XCTAssertFalse(model.resolvedBreakpointAddresses.isEmpty) + model.launchDisk(commands: ["DOS"]) + try await idle() + for _ in 0..<1500 where model.currentLine != 13 { + model.refresh(); try await Task.sleep(nanoseconds: 20_000_000) + } + XCTAssertEqual(model.currentLine, 13, model.message ?? model.execution) + XCTAssertEqual(machine.state, .paused) + model.toggleBreakpoint(13); try await idle() + XCTAssertTrue(model.resolvedBreakpointAddresses.isEmpty) + machine.reset(); try await idle(); try await bootReady() + XCTAssertTrue(model.canLaunch, model.message ?? model.execution) + model.launchDisk(commands: ["DOS"]) + try await idle(); try await completed() + XCTAssertNil(model.currentLine) + + // The same default program also quickloads without a selected-line stop. + machine.reset(); try await idle(); try await bootReady() + model.launchQuickload(); try await idle(); try await completed() + XCTAssertNil(model.currentLine) + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } catch { + model.cancelBuild() + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + throw error + } + } + + @MainActor func testRealBuildMappingBecomesStaleWhenEditorChanges() async throws { + let bundled = Bundle.main.resourceURL!.appendingPathComponent("Toolchain") + let staged = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("LocalResources/ToolchainBundle") + let toolchain = FileManager.default.isExecutableFile(atPath: bundled.appendingPathComponent("bin/cmoc").path) ? bundled : staged + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path), + "This integration check requires the bundled development toolchain") + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCDevelopmentTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + let suite = "CMOCDevelopmentTests.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: folder) } + let machine = MachineModel(diskStore: .init(url: folder.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: folder.appendingPathComponent("input.json"))) + let model = CMOCDevelopmentModel(machine: machine, toolchain: toolchain) + do { + try model.adopt(CMOCProject.create(at: folder.appendingPathComponent("Project"))) + model.build() + for _ in 0..<3000 where model.building { try await Task.sleep(nanoseconds: 10_000_000) } + XCTAssertFalse(model.building) + XCTAssertNil(model.message) + XCTAssertTrue(model.buildMatchesEditor, model.log) + XCTAssertNotNil(model.breakpointAddress) + if let artifact = model.artifact { defer { try? FileManager.default.removeItem(at: artifact.directory) } + let compiled = model.source + model.source += "\n/* edit after building */\n" + XCTAssertFalse(model.buildMatchesEditor) + XCTAssertNil(model.breakpointAddress, "An old address must never masquerade as a mapping for edited source") + XCTAssertFalse(model.canRun) + model.source = compiled + XCTAssertTrue(model.buildMatchesEditor) + let romURL = staged.deletingLastPathComponent().appendingPathComponent("ROMs/coco3.rom") + if FileManager.default.fileExists(atPath: romURL.path) { + for _ in 0..<500 where machine.busy { try await Task.sleep(nanoseconds: 10_000_000) } + machine.installROM(try Data(contentsOf: romURL), url: romURL) + for _ in 0..<500 where machine.busy { try await Task.sleep(nanoseconds: 10_000_000) } + try await Task.sleep(nanoseconds: 1_500_000_000) + model.breakpointLine = 9 + XCTAssertTrue(model.canRun) + model.run() + for _ in 0..<500 where model.currentLine != 9 { + model.refresh(); try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertEqual(model.currentLine, 9, model.message ?? model.execution) + XCTAssertEqual(model.pc, model.breakpointAddress) + XCTAssertTrue(model.loadedMatchesEditor) + XCTAssertTrue(model.canStepC) + XCTAssertTrue(model.canInspectC, model.variableStatus) + model.watchExpression = "1 + 2"; model.addWatch() + XCTAssertEqual(model.watchValue("1 + 2")?.value, "3") + model.source += "\n/* stale debug source */" + XCTAssertFalse(model.canStepC) + XCTAssertFalse(model.canInspectC) + XCTAssertNil(model.watchValue("1 + 2"), "Stale sources must hide even previously captured values") + model.source = compiled + await withCheckedContinuation { continuation in + machine.debuggerWriteMemory(address: 0x4000, data: Data([0x55])) { continuation.resume() } + } + for _ in 0..<100 where model.loadedMatchesEditor { + model.refresh(); try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertFalse(model.loadedMatchesEditor, "A debugger memory edit must invalidate loaded source provenance") + XCTAssertFalse(model.canStepC); XCTAssertFalse(model.canInspectC) + XCTAssertNil(model.watchValue("1 + 2")) + XCTAssertNil(model.currentLine) + model.run() + for _ in 0..<500 where model.currentLine != 9 { + model.refresh(); try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertEqual(model.currentLine, 9) + machine.reset() + for _ in 0..<100 where model.loadedMatchesEditor { + model.refresh(); try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertFalse(model.loadedMatchesEditor, "A machine reset must detach the previous C execution session") + XCTAssertNil(model.currentLine) + } + } + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } catch { + model.cancelBuild() + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + throw error + } + } +} + +final class CMOCWorkspaceDocumentTests: XCTestCase { + @MainActor func testTabsSaveAllOutsideConflictAndRestoration() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCWorkspaceDocs-\(UUID().uuidString)") + let defaultsName = "CMOCWorkspaceDocs.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: defaultsName)! + defer { defaults.removePersistentDomain(forName: defaultsName); try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + try Data("#define ANSWER 42\n".utf8).write(to: project.directory.appendingPathComponent("shared.h")) + let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("input.json"))) + let model = CMOCDevelopmentModel(machine: machine, defaults: defaults) + try model.adopt(project) + model.source += "\n/* unsaved main */" + let main = model.source + model.openFile("shared.h"); model.source = "#define ANSWER 43\n" + model.openFile("main.c") + XCTAssertEqual(model.source, main) + XCTAssertTrue(model.unsaved) + XCTAssertTrue(model.save()) + XCTAssertEqual(try project.readText(relativePath: "shared.h"), "#define ANSWER 43\n") + model.openFile("shared.h"); model.source = "#define ANSWER 44\n" + try Data("#define ANSWER 99\n".utf8).write(to: project.directory.appendingPathComponent("shared.h")) + model.checkExternalFiles() + XCTAssertTrue(model.documents.first { $0.id == "shared.h" }!.conflict) + XCTAssertFalse(model.save()) + XCTAssertEqual(try project.readText(relativePath: "shared.h"), "#define ANSWER 99\n", "Outside edits must survive Save All") + XCTAssertEqual(model.source, "#define ANSWER 44\n", "Editor edits remain recoverable") + let restored = CMOCDevelopmentModel(machine: machine, defaults: defaults) + restored.restoreWorkspace() + XCTAssertEqual(restored.documents.map(\.id), ["main.c", "shared.h"]) + XCTAssertEqual(restored.selectedFile, "shared.h") + XCTAssertEqual(restored.source, "#define ANSWER 99\n", "Restoration reads disk without executing Make") + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + @MainActor func testSettingsGenerationProtectsCustomChangesAndKeepsBackup() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCWorkspaceSettings-\(UUID().uuidString)") + let defaultsName = "CMOCWorkspaceSettings.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: defaultsName)! + defer { defaults.removePersistentDomain(forName: defaultsName); try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + let original = try project.readText(relativePath: "Makefile") + let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("input.json"))) + let model = CMOCDevelopmentModel(machine: machine, defaults: defaults) + try model.adopt(project) + var settings = CMOCMakefileSettings(); settings.executable = "hello.bin" + var configuration = project.configuration; configuration.makefileSettings = settings; configuration.binary = "hello.bin" + let generated = try settings.generateMakefile() + let hash = CMOCProject.sha256(Data(original.utf8)) + try Data((original + "\n# outside edit\n").utf8).write(to: project.makefileURL) + XCTAssertThrowsError(try model.applyProjectSettings(configuration, makefile: generated, expectedMakefileHash: hash, expectedConfigHash: nil)) + XCTAssertFalse(FileManager.default.fileExists(atPath: project.directory.appendingPathComponent(CMOCProject.configurationFilename).path)) + try Data(original.utf8).write(to: project.makefileURL) + try model.applyProjectSettings(configuration, makefile: generated, expectedMakefileHash: hash, expectedConfigHash: nil) + XCTAssertEqual(try String(contentsOf: project.makefileURL), generated) + let backups = try FileManager.default.contentsOfDirectory(at: project.directory.appendingPathComponent(".vccplus-build/Makefile Backups"), includingPropertiesForKeys: nil) + XCTAssertEqual(backups.count, 1) + XCTAssertEqual(try String(contentsOf: backups[0]), original) + XCTAssertEqual(try CMOCProject.open(at: project.directory).configuration.binary, "hello.bin") + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + @MainActor func testClickableDiagnosticRetainsNestedFileIdentity() { + let diagnostics = CMOCDevelopmentModel.parseDiagnostics("src/one/helper.c:17: error: missing value\n/private/tmp/build/src/two/helper.c:9:4: warning: unused\nmake: failed", directory: URL(fileURLWithPath: "/private/tmp/build")) + XCTAssertEqual(diagnostics.map(\.file), ["src/one/helper.c", "src/two/helper.c"]) + XCTAssertEqual(diagnostics.map(\.line), [17, 9]) + } +} diff --git a/platforms/macos/Tests/CMOCEditingTests.swift b/platforms/macos/Tests/CMOCEditingTests.swift new file mode 100644 index 0000000..18f586d --- /dev/null +++ b/platforms/macos/Tests/CMOCEditingTests.swift @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest +import AppKit + +final class CMOCEditingTests: XCTestCase { + private func edited(_ text: String, _ range: NSRange, _ action: CMOCEditorAction) throws -> (String, NSRange) { + let edit = try XCTUnwrap(CMOCEditing.lineEdit(text, selection: range, action: action)) + return ((text as NSString).replacingCharacters(in: edit.range, with: edit.text), edit.selection) + } + func testSelectedLinesExcludeFollowingLineAndRoundTripIndent() throws { + let source = "one();\ntwo();\nthree();\n" + let result = try edited(source, NSRange(location: 2, length: 12), .indent) + XCTAssertEqual(result.0, " one();\n two();\nthree();\n") + XCTAssertEqual(try edited(result.0, result.1, .outdent).0, source) + } + func testCaretTabsCRLFAndUnicode() throws { + let source = "// 🙂\r\n\tvalue();\r\n" + let caret = (source as NSString).range(of: "value").location + 2 + let result = try edited(source, NSRange(location: caret, length: 0), .outdent) + XCTAssertEqual(result.0, "// 🙂\r\nvalue();\r\n") + XCTAssertEqual(result.1.location, caret - 1) + let indented = try edited("", NSRange(location: 0, length: 0), .indent) + XCTAssertEqual(indented.0, " "); XCTAssertEqual(indented.1.location, 4) + } + func testCommentTogglePreservesIndentBlankLinesAndFinalNewline() throws { + let source = " one();\n\n\ttwo();" + let result = try edited(source, NSRange(location: 0, length: source.utf16.count), .comment) + XCTAssertEqual(result.0, " // one();\n\n\t// two();") + XCTAssertEqual(try edited(result.0, result.1, .comment).0, source) + let mixed = "// old\nnew\n" + XCTAssertEqual(try edited(mixed, NSRange(location: 0, length: mixed.utf16.count), .comment).0, "// // old\n// new\n") + XCTAssertNil(CMOCEditing.lineEdit(" \n", selection: .init(location: 0, length: 3), action: .comment)) + } + func testBracketPairsIgnoreLiteralsCommentsAndContinuedDirectives() { + let source = "#define X { \\\n[\nvoid f() { /* ] */ puts(\"}\\\"[\"); // ( \\\n)\nvalues[2] = '('; }" + let pairs = CMOCEditing.bracketPairs(source) + let u = source as NSString + let open = u.range(of: "{ /*").location, close = u.length - 1 + XCTAssertEqual(pairs[open], close); XCTAssertEqual(pairs[close], open) + XCTAssertNil(pairs[u.range(of: "{ \\").location]) + XCTAssertEqual(pairs.count, 8) + XCTAssertTrue(CMOCEditing.bracketPairs("([)]").isEmpty) + } + func testNewlineCopiesIndentAndAddsLevelOnlyAfterCodeBrace() { + for (source, expected) in [(" if (ok) {", "\n "), (" if (ok) { ", "\n "), ("\tif (ok) {", "\n\t\t"), (" // {", "\n "), (" puts(\"{\");", "\n "), ("x\r\n y", "\r\n ")] { + XCTAssertEqual(CMOCEditing.newline(source, selection: .init(location: source.utf16.count, length: 0)), expected) + } + } + @MainActor private final class Delegate: NSObject, NSTextViewDelegate { + let undo = UndoManager() + func undoManager(for view: NSTextView) -> UndoManager? { undo } + } + @MainActor private func withEditor(_ body: (CMOCEditingTextView, UndoManager) -> Void) { + let delegate = Delegate(), editor = CMOCEditingTextView(frame: .init(x: 0, y: 0, width: 400, height: 300)) + editor.delegate = delegate; editor.isRichText = false; editor.isEditable = true; editor.allowsUndo = true + body(editor, delegate.undo) + } + @MainActor func testNativeLineCommandsUndoRedoAndReadOnly() { + for action in [CMOCEditorAction.indent, .outdent, .comment] { + withEditor { editor, undo in + let source = " first();\n second();\n" + editor.string = source; editor.setSelectedRange(.init(location: 0, length: source.utf16.count)) + editor.performSourceAction(action) + let changed = editor.string + XCTAssertNotEqual(changed, source); XCTAssertTrue(undo.canUndo) + undo.undo(); XCTAssertEqual(editor.string, source); XCTAssertFalse(undo.canUndo) + undo.redo(); XCTAssertEqual(editor.string, changed) + editor.isEditable = false; editor.performSourceAction(action); XCTAssertEqual(editor.string, changed) + } + } + } + @MainActor func testNativeReturnTabAndShiftTab() { + withEditor { editor, undo in + editor.string = "int main(void) {"; editor.setSelectedRange(.init(location: editor.string.utf16.count, length: 0)) + editor.insertNewline(nil); XCTAssertTrue(editor.string.hasSuffix("\n ")) + undo.undo(); XCTAssertEqual(editor.string, "int main(void) {") + editor.string = "one\ntwo\n"; undo.removeAllActions() + editor.setSelectedRange(.init(location: 0, length: 8)); editor.insertTab(nil) + XCTAssertEqual(editor.string, " one\n two\n") + editor.insertBacktab(nil); XCTAssertEqual(editor.string, "one\ntwo\n") + } + } + @MainActor func testMatchingNavigationDoesNotEditReadOnlyTextOrUndo() { + withEditor { editor, undo in + editor.string = "f(a[2]);"; editor.isEditable = false + editor.setSelectedRange(.init(location: 1, length: 0)); editor.performSourceAction(.match) + XCTAssertEqual(editor.selectedRange().location, 6) + XCTAssertEqual(editor.string, "f(a[2]);"); XCTAssertFalse(undo.canUndo) + editor.performSourceAction(.match); XCTAssertEqual(editor.selectedRange().location, 1) + editor.sourceEditingEnabled = false; editor.performSourceAction(.match) + XCTAssertEqual(editor.selectedRange().location, 1) + } + } +} diff --git a/platforms/macos/Tests/CMOCFloatingPointIntegrationTests.swift b/platforms/macos/Tests/CMOCFloatingPointIntegrationTests.swift new file mode 100644 index 0000000..372a018 --- /dev/null +++ b/platforms/macos/Tests/CMOCFloatingPointIntegrationTests.swift @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +/// Runs actual ROM-backed CMOC float operations before inspecting both live frames. +final class CMOCFloatingPointIntegrationTests: XCTestCase { + private struct Fixture { + let root: URL + let artifact: CMOCBuildArtifact + let metadata: CMOCVariableDebug + let rom: Data + let sources: [String: String] + func line(_ marker: String, file: String) throws -> Int { + try XCTUnwrap(sources[file]?.components(separatedBy: "\n").firstIndex { $0.contains(marker) }) + 1 + } + func address(_ marker: String, file: String) throws -> UInt16 { + try XCTUnwrap(metadata.sourceMap.addresses(forLine: line(marker, file: file), in: file).first, marker) + } + } + private func fixture() async throws -> Fixture { + let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources") + let toolchain = resources.appendingPathComponent("ToolchainBundle") + let rom = resources.appendingPathComponent("ROMs/coco3.rom") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) + && FileManager.default.fileExists(atPath: rom.path), "Local licensed CoCo ROM and staged toolchain are required") + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCFloatingPoint-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + do { + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + let sources = ["types.h": """ + struct Measurements { float x; float samples[3]; float *pointer; }; + """, "main.c": """ + #include + #include + #include "types.h" + float globalValues[6] = { 0.0f, 1.5f, -2.75f, 1.0e-20f, 1.0e20f, 0.1f }; + float globalResult; + unsigned int result; + unsigned int inspect(float input, struct Measurements *parent); + int main(void) + { + float callerValue = -6.25f; + struct Measurements measurements; + initCoCoSupport(); + measurements.x = 1.25f; + measurements.samples[0] = 0.5f; + measurements.samples[1] = -0.125f; + measurements.samples[2] = 8.0f; + measurements.pointer = &measurements.samples[1]; + result = inspect(callerValue, &measurements); /* MAIN_CALL */ + for (;;) ++result; + return 0; + } + """, "helper.c": """ + #include "types.h" + extern float globalResult; + extern unsigned int result; + unsigned int inspect(float input, struct Measurements *parent) + { + float local = input + 0.5f; + float samples[2]; + samples[0] = 0.25f; + samples[1] = -16.5f; + globalResult = parent->x * 3.0f; + result = 1; /* LEAF_STOP */ + return result; + } + """] + for (name, source) in sources { try Data(source.utf8).write(to: project.directory.appendingPathComponent(name)) } + let makefile = """ + CMOC ?= cmoc + build: main.bin + main.bin: main.o helper.o + \t"$(CMOC)" --coco --intermediate --org=2800 -o $@ main.o helper.o + main.o: main.c + \t"$(CMOC)" --coco --intermediate -O0 -fno-omit-frame-pointer -c -o $@ $< + helper.o: helper.c + \t"$(CMOC)" --coco --intermediate -O0 -fno-omit-frame-pointer -c -o $@ $< + """ + try Data(makefile.utf8).write(to: project.makefileURL) + let service = CMOCBuildService(toolchain: toolchain, buildRoot: root.appendingPathComponent("Builds")) + let artifact = try await service.build(project: project, overlays: [:]) + let map = try CMOCProjectSourceMap.parse(artifact: artifact) + let metadata = try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map) + return Fixture(root: root, artifact: artifact, metadata: metadata, rom: try Data(contentsOf: rom), sources: sources) + } catch { try? FileManager.default.removeItem(at: root); throw error } + } + @MainActor private func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { continuation in operation { continuation.resume(returning: $0) } } + } + @MainActor private func capture(_ controller: VCCMachineController) async -> VCCDebuggerSnapshot { + await withCheckedContinuation { continuation in + controller.debuggerSnapshot(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) } + } + } + @MainActor private func withStoppedProcessors(_ fixture: Fixture, + body: (VCCMachineController, VCCDebuggerSnapshot) async throws -> Void) async throws { + for use6309 in [false, true] { + let controller = VCCMachineController() + do { + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + let loaded = await command { controller.loadROM(fixture.rom, use6309: use6309, completion: $0) } + XCTAssertNil(loaded.errorMessage) + _ = await command(controller.resume) + try await Task.sleep(nanoseconds: 1_500_000_000) + _ = await command(controller.pause) + let breakpoint = try fixture.address("LEAF_STOP", file: "helper.c") + var state = await command { controller.debuggerLoadBinary(fixture.artifact.binaryData, breakpoint: breakpoint, completion: $0) } + for _ in 0..<1000 where state.state == .running { + try await Task.sleep(nanoseconds: 5_000_000) + state = await command(controller.snapshot) + } + XCTAssertNil(state.errorMessage) + XCTAssertEqual(state.state, .paused) + XCTAssertEqual(state.programCounter, breakpoint) + try await body(controller, await capture(controller)) + _ = await command(controller.shutdown) + } catch { _ = await command(controller.shutdown); throw error } + } + } + private func stack(_ fixture: Fixture, _ snapshot: VCCDebuggerSnapshot, + memory: Data? = nil, available: Data? = nil) throws -> CMOCCallStack { + CMOCCallStack.capture(metadata: fixture.metadata, pc: snapshot.machine.programCounter, + u: try XCTUnwrap(snapshot.registers["U"]?.uint16Value), s: try XCTUnwrap(snapshot.registers["S"]?.uint16Value), + memory: memory ?? snapshot.logicalMemory, available: available ?? snapshot.logicalMemoryAvailable) + } + @MainActor func testCompiledFloatingValuesAndCallerFramesOnBothProcessors() async throws { + let fixture = try await fixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + try await withStoppedProcessors(fixture) { controller, snapshot in + let originalMemory = Data(Array(snapshot.logicalMemory)) + let frames = try stack(fixture, snapshot) + XCTAssertEqual(frames.frames.map(\.functionName), ["inspect", "main"], frames.termination) + guard frames.frames.count == 2 else { return } + func evaluator(_ frame: CMOCCallStack.Frame) -> CMOCWatchEvaluator { + CMOCWatchEvaluator(metadata: fixture.metadata, + context: .init(pc: frame.pc, u: frame.u, memory: snapshot.logicalMemory, + available: snapshot.logicalMemoryAvailable), + frameLocalsAvailable: frame.localsInspectable) + } + let current = evaluator(frames.frames[0]), caller = evaluator(frames.frames[1]) + for (engine, expression, expected) in [ + (current, "input", "-6.25"), (current, "local", "-5.75"), + (current, "samples[0]", "0.25"), (current, "samples[1]", "-16.5"), + (current, "globalResult", "3.75"), (current, "parent->x", "1.25"), + (current, "*parent->pointer", "-0.125"), (caller, "callerValue", "-6.25"), + (caller, "measurements.x", "1.25"), (caller, "*measurements.pointer", "-0.125") + ] { + let value = engine.evaluate(expression) + XCTAssertNil(value.error, "\(expression): \(value.error ?? "")") + XCTAssertEqual(value.value, expected, expression) + } + let globals = current.children(of: .init(root: .variable("globalValues"))).nodes + XCTAssertEqual(globals.count, 6) + XCTAssertEqual(Array(globals.prefix(3).map(\.value)), ["0", "1.5", "-2.75"]) + XCTAssertEqual(try XCTUnwrap(Double(globals[3].value)), 1e-20, accuracy: 1e-29) + XCTAssertEqual(try XCTUnwrap(Double(globals[4].value)), 1e20, accuracy: 1e11) + XCTAssertEqual(globals[5].value, "0.099999999977", "Preserve the compiled 32-bit significand rather than rounding through host Float") + let aggregate = caller.watchTreeRoot("measurements") + XCTAssertEqual(aggregate.childCount, 3) + let member = caller.children(of: aggregate.path).nodes + XCTAssertEqual(member[0].value, "1.25") + XCTAssertEqual(caller.children(of: member[1].path).nodes.map(\.value), ["0.5", "-0.125", "8"]) + XCTAssertEqual(caller.children(of: member[2].path).nodes.first?.value, "-0.125") + XCTAssertTrue(current.visibleVariables().contains { $0.name == "local" && $0.value == "-5.75" && $0.error == nil }) + // The compiler chooses a format explicitly; the app must not guess + // from a float's name, byte count or the machine's current ROM. + let inputType = try XCTUnwrap(fixture.metadata.variables.first { $0.name == "input" }?.type) + XCTAssertEqual(inputType.floatingFormat, "coco-basic-40") + XCTAssertEqual(inputType.size, 5) + let after = await capture(controller) + XCTAssertEqual(after.machine.programCounter, snapshot.machine.programCounter) + XCTAssertEqual(after.machine.cycles, snapshot.machine.cycles) + XCTAssertEqual(after.registers, snapshot.registers) + XCTAssertEqual(snapshot.logicalMemory, originalMemory) + XCTAssertEqual(after.logicalMemory, originalMemory, "Reading floats must not execute guest math routines or touch memory") + } + } +} diff --git a/platforms/macos/Tests/CMOCFloatingPointTests.swift b/platforms/macos/Tests/CMOCFloatingPointTests.swift new file mode 100644 index 0000000..73a667c --- /dev/null +++ b/platforms/macos/Tests/CMOCFloatingPointTests.swift @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CMOCFloatingPointTests: XCTestCase { + private func evaluator(_ bytes: [UInt8], format: String? = "coco-basic-40", size: Int? = nil, + address: Int = 0x3000, unavailable: Int? = nil, stale: Bool = false) -> CMOCWatchEvaluator { + let type = CMOCVariableDebug.CType(name: "float", kind: "floating", size: size ?? bytes.count, floatingFormat: format) + let map = CMOCProjectSourceMap(entryPoint: 0x2800, binarySHA256: "", sourceHashes: [:], + instructions: [.init(sourcePath: "main.c", sourceLine: 5, address: 0x2800, bytes: [0x12], assembly: "NOP")], + objectHashes: [:], listingHashes: [:], linkMapSHA256: "") + let metadata = CMOCVariableDebug(functions: [.init(name: "main", sourcePath: "main.c", entry: 0x2800, body: 0x2800, end: 0x2820, frame: true)], + variables: [.init(name: "value", sourcePath: "main.c", line: 1, type: type, address: address, offset: nil, scope: nil, isStatic: false)], sourceMap: map) + var memory = Data(repeating: 0, count: 65536), available = Data(repeating: 1, count: 65536) + memory[0x2800] = stale ? 0x39 : 0x12 + for (offset, byte) in bytes.enumerated() where address + offset < 65536 { memory[address + offset] = byte } + if let unavailable { available[unavailable] = 0 } + return CMOCWatchEvaluator(metadata: metadata, context: .init(pc: 0x2800, u: 0x4000, memory: memory, available: available)) + } + private func ieee(_ bits: UInt32) -> CMOCWatchEvaluator { + evaluator([UInt8(bits >> 24), UInt8(truncatingIfNeeded: bits >> 16), UInt8(truncatingIfNeeded: bits >> 8), UInt8(truncatingIfNeeded: bits)], format: "ieee754-binary32-be") + } + func testBasicStoredValuesAndPrecision() throws { + let cases: [([UInt8], String)] = [ + ([0, 0, 0, 0, 0], "0"), ([0, 255, 255, 255, 255], "0"), + ([0x81, 0, 0, 0, 0], "1"), ([0x80, 0, 0, 0, 0], "0.5"), + ([0x82, 0xa0, 0, 0, 0], "-2.5"), ([0x84, 0x48, 0, 0, 0], "12.5")] + for (bytes, expected) in cases { + let engine = evaluator(bytes) + XCTAssertEqual(engine.evaluate("value").value, expected) + XCTAssertNil(engine.evaluate("value").error) + XCTAssertEqual(engine.treeNode(at: .init(root: .variable("value"))).value, expected) + } + let next = evaluator([0x81, 0, 0, 0, 1]).evaluate("value") + XCTAssertEqual(next.value, "1.0000000005", "Keep BASIC's low significand bits; do not convert through Float32") + let small = try XCTUnwrap(Double(evaluator([1, 0, 0, 0, 0]).evaluate("value").value)) + XCTAssertEqual(small, pow(2, -128), accuracy: pow(2, -128) * 1e-10) + let large = try XCTUnwrap(Double(evaluator([255, 0x7f, 255, 255, 255]).evaluate("value").value)) + XCTAssertEqual(large, pow(2, 127) - pow(2, 95), accuracy: pow(2, 127) * 1e-10) + } + func testIEEEStoredValuesSpecialsAndSubnormals() throws { + for (bits, expected): (UInt32, String) in [(0, "0"), (0x80000000, "-0"), (0x3f800000, "1"), + (0xc0200000, "-2.5"), (0x7f800000, "Infinity"), (0xff800000, "-Infinity"), + (0x7fc00001, "NaN"), (0x7f800001, "NaN"), (0xffc00001, "NaN")] { + XCTAssertEqual(ieee(bits).evaluate("value").value, expected) + XCTAssertNil(ieee(bits).evaluate("value").error) + } + XCTAssertEqual(ieee(0x3f800001).evaluate("value").value, "1.00000012") + let minimumSubnormal: Double = pow(2.0, -149.0) + let minimumNormal: Double = pow(2.0, -126.0) + let maximumSubnormal: Double = minimumNormal - minimumSubnormal + let maximumSignificand: Double = 2.0 - pow(2.0, -23.0) + let maximumFinite: Double = maximumSignificand * pow(2.0, 127.0) + let finiteCases: [(UInt32, Double)] = [ + (1, minimumSubnormal), (0x007fffff, maximumSubnormal), + (0x00800000, minimumNormal), (0x7f7fffff, maximumFinite) + ] + for (bits, expected) in finiteCases { + let actual = try XCTUnwrap(Double(ieee(bits).evaluate("value").value)) + XCTAssertEqual(actual, expected, accuracy: expected * 1e-8) + } + } + func testUnknownLegacyAndInconsistentFormatsStayUnavailable() { + for engine in [evaluator([0x81, 0, 0, 0, 0], format: nil), + evaluator([0x81, 0, 0, 0, 0], format: "unknown"), + evaluator([0x81, 0, 0, 0, 0], format: "ieee754-binary32-be"), + evaluator([0x3f, 0x80, 0, 0], format: "coco-basic-40"), + evaluator(Array(repeating: 0, count: 8), format: "unsupported")] { + XCTAssertNotNil(engine.evaluate("value").error) + XCTAssertEqual(engine.treeNode(at: .init(root: .watch("value"))).value, "Unavailable") + } + } + func testFloatInspectionKeepsMemoryAndBuildGuards() { + let bytes: [UInt8] = [0x81, 0, 0, 0, 0] + for engine in [evaluator(bytes, unavailable: 0x3004), evaluator(bytes, address: 65533), evaluator(bytes, stale: true)] { + XCTAssertNotNil(engine.evaluate("value").error) + XCTAssertNotNil(engine.treeNode(at: .init(root: .variable("value"))).error) + } + let engine = evaluator(bytes) + let before = engine.context.memory + XCTAssertEqual(engine.evaluate("value").value, "1") + XCTAssertEqual(engine.context.memory, before) + } + func testFloatingWatchArithmeticIsExplicitlyRejected() { + let engine = evaluator([0x81, 0, 0, 0, 0]) + for expression in ["value + 1", "value == 1", "-value", "!value"] { + XCTAssertTrue(engine.evaluate(expression).error?.contains("floating-point watch arithmetic") == true) + } + XCTAssertEqual(engine.evaluate("(value)").value, "1") + XCTAssertEqual(engine.evaluate("&value").value, "$3000") + } +} diff --git a/platforms/macos/Tests/CMOCImportedProjectTests.swift b/platforms/macos/Tests/CMOCImportedProjectTests.swift new file mode 100644 index 0000000..4c4f43d --- /dev/null +++ b/platforms/macos/Tests/CMOCImportedProjectTests.swift @@ -0,0 +1,235 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest +import AppKit +import SwiftUI + +/// Library source opening owns no guest execution and must review current drafts. +/// All projects, settings, recovery and tool paths are authored private fixtures. +final class CMOCImportedProjectTests: XCTestCase { + private struct Deadline: Error {} + private struct Fixture { + let root: URL + let project: CMOCProject + let imported: CMOCProject + let model: CMOCDevelopmentModel + let machine: MachineModel + let controller: VCCMachineController + let defaults: UserDefaults + var marker: URL { imported.directory.appendingPathComponent("MAKE_WAS_RUN") } + var recoveryRoot: URL { root.appendingPathComponent("Recovery") } + } + @MainActor func testImportedProjectSelectsOnlyADeclaredBuildConfiguration() async throws { + try await withFixture { fixture in + let identity = fixture.model.assistantProjectID + do { + _ = try await fixture.model.openImportedProject(at: fixture.imported.directory, + expectedProjectID: identity, preferredConfiguration: "Missing", reviewUnsaved: { XCTFail("Invalid configuration must fail before review"); return true }) + XCTFail("Missing configuration accepted") + } catch { } + XCTAssertEqual(fixture.model.project?.directory, fixture.project.directory) + let opened = try await fixture.model.openImportedProject(at: fixture.imported.directory, + expectedProjectID: identity, preferredConfiguration: "Release", reviewUnsaved: { true }) + XCTAssertTrue(opened); XCTAssertEqual(fixture.model.configurationName, "Release") + XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.marker.path)) + } + } + @MainActor private func settle(_ fixture: Fixture) async throws { + for _ in 0..<500 { + if !fixture.machine.busy && !fixture.model.building { return } + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTFail("Isolated imported-project fixture did not settle"); throw Deadline() + } + @MainActor private func step(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { done in operation { done.resume(returning: $0) } } + } + @MainActor private func snapshot(_ controller: VCCMachineController) async -> VCCDebuggerSnapshot { + await withCheckedContinuation { done in + controller.debuggerSnapshot(address: 0x8000, followPC: false, memoryAddress: 0x2000) { done.resume(returning: $0) } + } + } + @MainActor private func flush(_ model: CMOCDevelopmentModel) async { + await withCheckedContinuation { done in model.flushDraftRecovery { done.resume() } } + } + @MainActor private func withFixture(_ body: (Fixture) async throws -> Void) async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCImported-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let suite = "CMOCImported." + UUID().uuidString, defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) } + let project = try CMOCProject.create(at: root.appendingPathComponent("Existing Project")) + let imported = try CMOCProject.create(at: root.appendingPathComponent("Imported Project")) + try Data("#define PERSONAL_VALUE 1\n".utf8).write(to: project.directory.appendingPathComponent("personal.h")) + try Data("int imported_value;\nint main(void) { return 0; }\n".utf8).write(to: imported.sourceURL) + // Both Make parsing and executing a target would leave this marker. + try Data("IMPORT_SENTINEL := $(shell touch MAKE_WAS_RUN)\nbuild:\n\ttouch MAKE_WAS_RUN\n".utf8) + .write(to: imported.makefileURL) + let controller = VCCMachineController() + let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("Disks.json")), controller: controller, + displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("Input.json"))) + let model = CMOCDevelopmentModel(machine: machine, toolchain: root.appendingPathComponent("No External Tools"), + defaults: defaults, buildRoot: root.appendingPathComponent("Builds"), recoveryRoot: root.appendingPathComponent("Recovery")) + let fixture = Fixture(root: root, project: project, imported: imported, model: model, + machine: machine, controller: controller, defaults: defaults) + do { + try await settle(fixture) + try model.adopt(project) + try await body(fixture) + model.cancelBuild(); try await settle(fixture) + await flush(model) + await withCheckedContinuation { done in machine.shutdown { done.resume() } } + } catch { + model.cancelBuild() + try? await settle(fixture) + await flush(model) + await withCheckedContinuation { done in machine.shutdown { done.resume() } } + throw error + } + } + + @MainActor func testCancelPreservesCurrentDraftsNativeUndoAndRecovery() async throws { + try await withFixture { fixture in + let model = fixture.model, original = model.source + model.openFile("personal.h"); model.source = "#define PERSONAL_VALUE 42\n"; model.openFile("main.c") + let view = CSourceEditor(text: Binding(get: { model.source }, set: { model.source = $0 }), currentLine: nil) + let coordinator = view.makeCoordinator() + let editor = coordinator.makeEditor(file: "main.c", text: original) + coordinator.activeFile = "main.c" + model.assistantEditor = editor; model.assistantEditorPool = coordinator; model.assistantEditorFile = "main.c" + let undo = try XCTUnwrap(editor.undoManager) + undo.groupsByEvent = false; undo.beginUndoGrouping() + editor.insertText("\n/* personal unsaved change */\n", replacementRange: NSRange(location: original.utf16.count, length: 0)) + editor.breakUndoCoalescing(); undo.endUndoGrouping() + XCTAssertEqual(model.source, editor.string) + let dirty = model.source, identity = model.assistantProjectID + let documentTexts = model.documents.map(\.text) + var reviews = 0 + let opened = try await model.openImportedProject(at: fixture.imported.directory, expectedProjectID: identity) { + reviews += 1; return false + } + XCTAssertFalse(opened); XCTAssertEqual(reviews, 1) + XCTAssertEqual(model.project?.directory, fixture.project.directory) + XCTAssertEqual(model.assistantProjectID, identity) + XCTAssertEqual(model.documents.map(\.text), documentTexts) + XCTAssertEqual(model.source, dirty) + XCTAssertIdentical(model.assistantEditorPool, coordinator) + XCTAssertIdentical(editor.undoManager, undo); XCTAssertTrue(undo.canUndo) + XCTAssertEqual(try fixture.project.readSource(), original, "Cancel must not save over personal source") + await flush(model) + let recovery = CMOCWorkspaceRecovery(root: fixture.recoveryRoot) + let records = try recovery.scan(projectDirectory: fixture.project.directory).records + XCTAssertTrue(records.flatMap(\.drafts).contains(where: { $0.path == "main.c" && $0.text == dirty })) + XCTAssertTrue(records.flatMap(\.drafts).contains(where: { $0.path == "personal.h" && $0.text.contains("42") })) + undo.undo() + XCTAssertEqual(editor.string, original) + XCTAssertEqual(model.source, original, "The pre-import typing history remains usable") + XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.marker.path)) + } + } + + @MainActor func testStaleProjectIdentityRejectsBeforeReview() async throws { + try await withFixture { fixture in + let identity = fixture.model.assistantProjectID, before = fixture.model.source + var reviewed = false + do { + _ = try await fixture.model.openImportedProject(at: fixture.imported.directory, expectedProjectID: UUID()) { + reviewed = true; return true + } + XCTFail("A stale downloader must not replace the current C project") + } catch { XCTAssertTrue(error.localizedDescription.contains("changed during")) } + XCTAssertFalse(reviewed) + XCTAssertEqual(fixture.model.assistantProjectID, identity) + XCTAssertEqual(fixture.model.source, before) + XCTAssertEqual(fixture.model.project?.directory, fixture.project.directory) + XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.marker.path)) + } + } + + @MainActor func testProjectChangedDuringReviewCannotBeOverwrittenByImportedResult() async throws { + try await withFixture { fixture in + let other = try CMOCProject.create(at: fixture.root.appendingPathComponent("Other Project")) + var changed = false + do { + _ = try await fixture.model.openImportedProject(at: fixture.imported.directory, + expectedProjectID: fixture.model.assistantProjectID) { + do { try fixture.model.adopt(other); changed = true } catch { XCTFail(error.localizedDescription) } + return true + } + XCTFail("A review that changes projects must invalidate the import completion") + } catch { XCTAssertTrue(error.localizedDescription.contains("changed during")) } + XCTAssertTrue(changed) + XCTAssertEqual(fixture.model.project?.directory, other.directory) + XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.marker.path)) + } + } + + @MainActor func testBusyBuildAfterReviewPreventsImportedProjectSwitch() async throws { + try await withFixture { fixture in + let identity = fixture.model.assistantProjectID + do { + _ = try await fixture.model.openImportedProject(at: fixture.imported.directory, expectedProjectID: identity) { + fixture.model.build() + XCTAssertTrue(fixture.model.building) + return true + } + XCTFail("A build started during review must block the workspace switch") + } catch { XCTAssertTrue(error.localizedDescription.contains("current C operation")) } + fixture.model.cancelBuild() + XCTAssertEqual(fixture.model.project?.directory, fixture.project.directory) + XCTAssertEqual(fixture.model.assistantProjectID, identity) + XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.marker.path)) + } + } + + @MainActor func testMalformedImportFailsBeforeReviewAndKeepsDirtyProject() async throws { + try await withFixture { fixture in + fixture.model.source += "\n/* keep this draft */\n" + let dirty = fixture.model.source, identity = fixture.model.assistantProjectID + try Data("{bad configuration".utf8).write(to: fixture.imported.directory.appendingPathComponent(CMOCProject.configurationFilename)) + var reviewed = false + do { + _ = try await fixture.model.openImportedProject(at: fixture.imported.directory, expectedProjectID: identity) { + reviewed = true; return true + } + XCTFail("Malformed source project must fail") + } catch { } + XCTAssertFalse(reviewed) + XCTAssertEqual(fixture.model.project?.directory, fixture.project.directory) + XCTAssertEqual(fixture.model.source, dirty) + XCTAssertEqual(fixture.model.assistantProjectID, identity) + XCTAssertTrue(fixture.model.documents.contains(where: \.dirty)) + XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.marker.path)) + } + } + + @MainActor func testSuccessfulSourceOpenDoesNotExecuteMakeOrChangePausedGuest() async throws { + try await withFixture { fixture in + var rom = Data(repeating: 0x12, count: 32768) + // LDA #$5A; STA $2000; BRA self. This is an authored CoCo ROM fixture. + for (index, byte) in [UInt8(0x86), 0x5a, 0xb7, 0x20, 0, 0x20, 0xfe].enumerated() { rom[index] = byte } + rom[32766] = 0x80; rom[32767] = 0 + let loaded = await step { fixture.controller.loadROM(rom, use6309: false, completion: $0) } + XCTAssertNil(loaded.errorMessage) + _ = await step(fixture.controller.resume) + try await Task.sleep(nanoseconds: 40_000_000) + _ = await step(fixture.controller.pause) + let before = await snapshot(fixture.controller) + XCTAssertEqual(before.machine.state, .paused) + XCTAssertGreaterThan(before.machine.cycles, 0) + XCTAssertEqual(before.logicalMemory[0x2000], 0x5a) + let opened = try await fixture.model.openImportedProject(at: fixture.imported.directory, + expectedProjectID: fixture.model.assistantProjectID, reviewUnsaved: { true }) + XCTAssertTrue(opened) + XCTAssertEqual(fixture.model.project?.directory, fixture.imported.directory) + XCTAssertTrue(fixture.model.source.contains("imported_value")) + XCTAssertFalse(fixture.model.building); XCTAssertNil(fixture.model.artifact) + XCTAssertNil(fixture.model.launchedBuildID) + XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.marker.path), "Opening must not even evaluate Make's shell expansion") + let after = await snapshot(fixture.controller) + XCTAssertEqual(after.machine.generation, before.machine.generation) + XCTAssertEqual(after.machine.state, .paused) + XCTAssertEqual(after.machine.cycles, before.machine.cycles) + XCTAssertEqual(after.registers, before.registers) + XCTAssertEqual(after.logicalMemory, before.logicalMemory) + } + } +} diff --git a/platforms/macos/Tests/CMOCNavigationTests.swift b/platforms/macos/Tests/CMOCNavigationTests.swift new file mode 100644 index 0000000..80ed7bf --- /dev/null +++ b/platforms/macos/Tests/CMOCNavigationTests.swift @@ -0,0 +1,301 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CMOCNavigationTests: XCTestCase { + private struct Deadline: Error {} + private struct Fixture { + let root: URL + let project: CMOCProject + let model: CMOCDevelopmentModel + let machine: MachineModel + let defaults: UserDefaults + let suite: String + } + @MainActor private func waitUntil(_ description: String, _ predicate: () -> Bool) async throws { + for _ in 0..<800 { + if predicate() { return } + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTFail("Timed out waiting for " + description); throw Deadline() + } + @MainActor private func withFixture(_ body: (Fixture) async throws -> Void) async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCNavigation-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let suite = "CMOCNavigation." + UUID().uuidString, defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) } + var project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + var recipe = CMOCMakefileSettings(); recipe.sources = ["main.c", "helper.c"]; recipe.libraries = [] + recipe.includePaths = ["include"] + project.configuration.makefileSettings = recipe + try JSONEncoder().encode(project.configuration).write(to: project.directory.appendingPathComponent(CMOCProject.configurationFilename)) + try FileManager.default.createDirectory(at: project.directory.appendingPathComponent("include"), withIntermediateDirectories: true) + try Data("int helper(void);\n".utf8).write(to: project.directory.appendingPathComponent("include/api.h")) + let main = "#include \"api.h\"\nint globalValue;\nint main(void) { /* 🙂 */ return helper(); }\n" + try Data(main.utf8).write(to: project.sourceURL) + try Data("/* helper implementation */\nint helper(void) { return 42; }\n".utf8).write(to: project.directory.appendingPathComponent("helper.c")) + try Data((try recipe.generateMakefile() + "\nNAVIGATION_SENTINEL := $(shell touch navigation-must-not-run)\n").utf8).write(to: project.makefileURL) + let toolchain = root.appendingPathComponent("Toolchain"), includes = toolchain.appendingPathComponent("share/cmoc/include") + try FileManager.default.createDirectory(at: includes, withIntermediateDirectories: true) + try Data("int library_only_marker(void);\n".utf8).write(to: includes.appendingPathComponent("cmoc.h")) + let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: root.appendingPathComponent("input.json"))) + let model = CMOCDevelopmentModel(machine: machine, toolchain: toolchain, defaults: defaults, + buildRoot: root.appendingPathComponent("Builds"), recoveryRoot: root.appendingPathComponent("Recovery")) + do { + try model.adopt(project) + try await body(.init(root: root, project: project, model: model, machine: machine, defaults: defaults, suite: suite)) + await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } } + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } catch { + model.cancelBuild() + await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } } + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + throw error + } + } + @MainActor func testParameterHintsFollowCurrentDraftAndRejectDelayedResults() async throws { + try await withFixture { f in + let draft = "int sum(int left, int right);\nint main(void) { return sum(1, 2); }\n" + f.model.source = draft + f.model.refreshProjectIndex() + try await waitUntil("hint declarations") { !f.model.indexing && f.model.projectIndex?.documents["main.c"] == draft } + let caret = (draft as NSString).range(of: "2);").location + f.model.updateCursor(offset: caret) + f.model.refreshParameterHints() + try await waitUntil("second parameter") { f.model.parameterHints.first?.activeParameter == 1 } + XCTAssertEqual(f.model.parameterHints.first?.name, "sum") + XCTAssertEqual(f.model.source, draft) + let originalRequest = f.model.completionRequest + f.model.requestCompletion() + XCTAssertNotEqual(originalRequest, f.model.completionRequest) + XCTAssertEqual(f.model.source, draft, "Requesting completion must not edit the draft") + + f.model.updateCursor(offset: caret) + f.model.source = "int main(void) { return 0; }\n" + f.model.updateCursor(offset: 0) + try await Task.sleep(nanoseconds: 250_000_000) + XCTAssertTrue(f.model.parameterHints.isEmpty, "An older scan must not show a call removed from the draft") + f.model.openFile("helper.c") + f.model.refreshParameterHints() + try await Task.sleep(nanoseconds: 150_000_000) + XCTAssertTrue(f.model.parameterHints.isEmpty, "Switching documents invalidates the old call context") + + f.model.refreshProjectIndex() + try await waitUntil("reference index") { !f.model.indexing && f.model.projectIndex?.documents["@toolchain/include/cmoc.h"] != nil } + f.model.openFile("@toolchain/include/cmoc.h") + let referenceRequest = f.model.completionRequest + f.model.requestCompletion() + XCTAssertEqual(referenceRequest, f.model.completionRequest, "Read-only references cannot request an edit") + XCTAssertTrue(f.model.parameterHints.isEmpty) + } + } + @MainActor func testUnsavedSearchOutlineAndDefinitionHistoryPreserveExactCursorAndText() async throws { + try await withFixture { f in + let original = f.model.source + f.model.source += "\nint unsavedFunction(void) { return 7; } /* navigation_needle */\n" + let edited = f.model.source + f.model.refreshProjectIndex() + try await waitUntil("unsaved index") { !f.model.indexing && f.model.projectIndex?.documents["main.c"] == edited } + XCTAssertTrue(f.model.currentOutline.contains { $0.name == "unsavedFunction" && $0.isDefinition }) + XCTAssertEqual(try String(contentsOf: f.project.sourceURL, encoding: .utf8), original) + XCTAssertFalse(FileManager.default.fileExists(atPath: f.project.directory.appendingPathComponent("navigation-must-not-run").path)) + + let callOffset = (edited as NSString).range(of: "helper()", options: .backwards).location + 2 + f.model.updateCursor(offset: callOffset) + f.model.goToDefinition() + XCTAssertEqual(f.model.selectedFile, "helper.c") + XCTAssertEqual(f.model.navigationLine, 2) + XCTAssertTrue(f.model.canNavigateBack) + f.model.navigateBack() + XCTAssertEqual(f.model.selectedFile, "main.c") + XCTAssertEqual(f.model.cursorOffset, callOffset, "Back restores the actual UTF-16 caret, including text after emoji") + XCTAssertEqual(f.model.source, edited, "Navigation must preserve unsaved editor contents") + XCTAssertTrue(f.model.canNavigateForward) + f.model.navigateForward() + XCTAssertEqual(f.model.selectedFile, "helper.c") + XCTAssertEqual(f.model.navigationLine, 2) + f.model.navigateBack() + + f.model.searchQuery = "NAVIGATION_NEEDLE"; f.model.searchCaseSensitive = false + try await waitUntil("case-insensitive search") { f.model.searchMatches.contains { $0.path == "main.c" } } + let match = try XCTUnwrap(f.model.searchMatches.first { $0.path == "main.c" }) + f.model.openSearchMatch(match) + XCTAssertEqual(f.model.selectedFile, "main.c") + XCTAssertEqual(f.model.navigationColumn, match.column) + XCTAssertEqual(f.model.navigationLength, match.lengthUTF16) + XCTAssertEqual(f.model.source, edited) + f.model.searchCaseSensitive = true + try await waitUntil("case-sensitive search") { f.model.searchMatches.isEmpty } + XCTAssertNil(f.model.artifact, "Indexing and navigation do not build or load the guest") + } + } + @MainActor func testBundledHeadersAreReadOnlyAndExcludedFromProjectSearchAndOverlays() async throws { + try await withFixture { f in + f.model.refreshProjectIndex() + let path = "@toolchain/include/cmoc.h" + try await waitUntil("bundled header index") { !f.model.indexing && f.model.projectIndex?.documents[path] != nil } + let symbol = try XCTUnwrap(f.model.projectIndex?.symbols.first { $0.path == path && $0.name == "library_only_marker" }) + f.model.openSymbol(symbol) + XCTAssertEqual(f.model.selectedFile, path) + XCTAssertTrue(f.model.selectedFileIsGenerated, "Reference headers use the read-only editor path") + XCTAssertFalse(f.model.overlays.keys.contains(path), "Toolchain references must never enter a project build snapshot") + XCTAssertFalse(f.model.saveFile(path), "Reference headers cannot overwrite the bundled library") + XCTAssertTrue(f.model.documents.first { $0.id == path }?.reference == true) + f.model.checkExternalFiles() + XCTAssertFalse(f.model.documents.first { $0.id == path }?.missing == true, "Project scanning must not mistake a library header for a missing project file") + f.model.searchQuery = "library_only_marker" + try await Task.sleep(nanoseconds: 250_000_000) + XCTAssertTrue(f.model.searchMatches.isEmpty, "Find in Project excludes toolchain reference files") + f.model.openFile("main.c") + XCTAssertFalse(f.model.selectedFileIsGenerated) + XCTAssertFalse(f.model.unsaved) + } + } + @MainActor func testProjectSwitchRejectsStaleIndexAndNavigationHistory() async throws { + try await withFixture { f in + f.model.source += "\nint old_project_only;\n" + f.model.refreshProjectIndex() + let other = try CMOCProject.create(at: f.root.appendingPathComponent("OtherProject")) + try Data("int new_project_only;\nint main(void) { return 0; }\n".utf8).write(to: other.sourceURL) + try f.model.adopt(other) + f.model.refreshProjectIndex() + try await waitUntil("new project index") { !f.model.indexing && f.model.projectIndex?.documents["main.c"]?.contains("new_project_only") == true } + XCTAssertFalse(f.model.projectIndex?.symbols.contains { $0.name == "old_project_only" } == true) + XCTAssertFalse(f.model.canNavigateBack) + XCTAssertFalse(f.model.canNavigateForward) + f.model.searchQuery = "old_project_only" + try await Task.sleep(nanoseconds: 250_000_000) + XCTAssertTrue(f.model.searchMatches.isEmpty) + XCTAssertEqual(f.model.project?.directory, other.directory) + XCTAssertNil(f.model.artifact) + } + } + @MainActor func testOutdatedSearchHitDoesNotNavigateToDifferentDiskText() async throws { + try await withFixture { f in + let path = f.project.directory.appendingPathComponent("notes.txt") + try Data("before\nunique old match\nafter\n".utf8).write(to: path) + f.model.refreshProjectIndex() + try await waitUntil("text-resource index") { !f.model.indexing && f.model.projectIndex?.documents["notes.txt"] != nil } + f.model.searchQuery = "unique old match" + try await waitUntil("old text match") { f.model.searchMatches.contains { $0.path == "notes.txt" } } + let match = try XCTUnwrap(f.model.searchMatches.first { $0.path == "notes.txt" }) + try Data("completely different source\n".utf8).write(to: path) + f.model.openSearchMatch(match) + XCTAssertNotEqual(f.model.selectedFile, "notes.txt", "A stale hit must not select unrelated new disk text") + XCTAssertNotNil(f.model.message) + XCTAssertEqual(try String(contentsOf: path, encoding: .utf8), "completely different source\n") + try await waitUntil("refreshed changed source") { !f.model.indexing && f.model.projectIndex?.documents["notes.txt"] == "completely different source\n" } + f.model.openSearchMatch(match) + XCTAssertNotEqual(f.model.selectedFile, "notes.txt", "An old result also stays rejected after a replacement index has completed") + } + } + @MainActor func testReferenceNavigationKeepsSuccessfulBuildIdentity() async throws { + let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources") + let toolchain = resources.appendingPathComponent("ToolchainBundle") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path), "Staged toolchain required") + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCNavigationBuild-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let suite = "CMOCNavigationBuild." + UUID().uuidString, defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) } + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + let retired = project.directory.appendingPathComponent("retired.h") + try Data("int retired_project_symbol;\n".utf8).write(to: retired) + let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: root.appendingPathComponent("input.json"))) + let model = CMOCDevelopmentModel(machine: machine, toolchain: toolchain, defaults: defaults, + buildRoot: root.appendingPathComponent("Builds"), recoveryRoot: root.appendingPathComponent("Recovery")) + do { + try model.adopt(project) + model.build(); try await waitUntil("compiler build") { !model.building } + let artifact = try XCTUnwrap(model.artifact, model.message ?? model.log) + XCTAssertTrue(model.buildMatchesEditor) + model.refreshProjectIndex() + try await waitUntil("built index") { !model.indexing && model.projectIndex?.documents["@toolchain/include/cmoc.h"] != nil } + let symbol = try XCTUnwrap(model.projectIndex?.symbols.first { $0.path == "@toolchain/include/cmoc.h" && $0.name == "printf" }) + model.openSymbol(symbol) + XCTAssertTrue(model.selectedFileIsGenerated) + XCTAssertEqual(model.artifact?.id, artifact.id) + XCTAssertTrue(model.buildMatchesEditor, "Reading a library declaration must not make an otherwise current build stale") + model.checkExternalFiles() + XCTAssertTrue(model.buildMatchesEditor) + XCTAssertFalse(model.overlays.keys.contains { $0.hasPrefix("@toolchain/") }) + XCTAssertNil(model.launchedBuildID, "Navigation must never run a successful build") + XCTAssertNotNil(artifact.sources["retired.h"]) + try FileManager.default.removeItem(at: retired) + model.refreshProjectIndex() + try await waitUntil("index after deleted ordinary source") { !model.indexing && model.projectIndex != nil } + XCTAssertNil(model.projectIndex?.documents["retired.h"], "A deleted ordinary source must not reappear as a generated build snapshot") + XCTAssertFalse(model.projectIndex?.symbols.contains { $0.name == "retired_project_symbol" } == true) + await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } } + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } catch { + model.cancelBuild() + await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } } + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + throw error + } + } + func testIndexInputsHonorManagedFlagsAndBoundariesWithoutExecutingRecipes() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCIndexInputs-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + var project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + var recipe = CMOCMakefileSettings(); recipe.libraries = []; recipe.includePaths = ["include"] + recipe.defines = ["FEATURE=1"]; recipe.compilerOptions = ["-DOPTION=2", "-Iextra"] + recipe.generatedResources = [.init(outputs: ["generated/schema.h"], inputs: ["main.c"], command: "touch must-not-run")] + project.configuration.makefileSettings = recipe + project.configuration.configurations.append(.init(name: "Custom", makeArguments: ["CPPFLAGS=-DOTHER=1"])) + try JSONEncoder().encode(project.configuration).write(to: project.directory.appendingPathComponent(CMOCProject.configurationFilename)) + try Data(recipe.generateMakefile().utf8).write(to: project.makefileURL) + let generated = project.directory.appendingPathComponent("generated/schema.h") + try FileManager.default.createDirectory(at: generated.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("#define STALE_GENERATED 1\n".utf8).write(to: generated) + let outside = root.appendingPathComponent("outside.h") + try Data("int should_not_be_indexed;\n".utf8).write(to: outside) + try FileManager.default.createSymbolicLink(at: project.directory.appendingPathComponent("escaped.h"), withDestinationURL: outside) + let toolchain = root.appendingPathComponent("Toolchain"), headers = toolchain.appendingPathComponent("share/cmoc/include") + try FileManager.default.createDirectory(at: headers, withIntermediateDirectories: true) + try Data("int library_function(void);\n".utf8).write(to: headers.appendingPathComponent("cmoc.h")) + try Data("{\"cmoc\":\"0.1.100\"}".utf8).write(to: toolchain.appendingPathComponent("manifest.json")) + let expected = "#define CURRENT_GENERATED 1\n" + let input = try CMOCIndexInputs.load(project: project, toolchain: toolchain, configurationName: "Debug", + overlays: ["main.c": "int unsaved_input;\n"], generated: ["generated/schema.h": Data(expected.utf8)]) + XCTAssertFalse(input.configurationUncertain) + XCTAssertTrue(input.defines.contains("FEATURE=1")); XCTAssertTrue(input.defines.contains("OPTION=2")) + XCTAssertTrue(input.defines.contains("_CMOC_VERSION_=1100")); XCTAssertTrue(input.defines.contains("_COCO_BASIC_=1")) + XCTAssertTrue(input.includePaths.contains("include")); XCTAssertTrue(input.includePaths.contains("extra")) + XCTAssertEqual(input.documents["main.c"], "int unsaved_input;\n") + XCTAssertEqual(input.documents["generated/schema.h"], expected) + XCTAssertTrue(input.generatedPaths.contains("generated/schema.h")) + XCTAssertTrue(input.referencePaths.contains("@toolchain/include/cmoc.h"), "Header paths: \(input.referencePaths.sorted()); issues: \(input.issues)") + XCTAssertNil(input.documents["escaped.h"]) + XCTAssertTrue(input.issues.contains { $0.contains("Linked") }) + XCTAssertFalse(FileManager.default.fileExists(atPath: project.directory.appendingPathComponent("must-not-run").path)) + let custom = try CMOCIndexInputs.load(project: project, toolchain: toolchain, configurationName: "Custom", overlays: [:], generated: [:]) + XCTAssertTrue(custom.configurationUncertain, "Arbitrary selected Make assignments cannot be treated as compiler-verified flags") + XCTAssertFalse(custom.defines.contains("OTHER=1"), "Navigation must not execute or guess arbitrary Make variables") + let missingLibrary = try CMOCIndexInputs.load(project: project, toolchain: root.appendingPathComponent("NoToolchain"), configurationName: "Debug", overlays: [:], generated: [:]) + XCTAssertNotNil(missingLibrary.documents["main.c"], "Missing optional bundled headers must not disable project navigation") + XCTAssertTrue(missingLibrary.referencePaths.isEmpty) + XCTAssertTrue(missingLibrary.issues.contains { $0.contains("headers") && $0.contains("unavailable") }) + // These switches set compiler mode first; CMOC emits all user -D + // values after its builtins, even when the mode switch occurs later. + recipe.defines = ["_CMOC_NATIVE_FLOAT_=0"] + recipe.compilerOptions = ["--mc6839", "--native-float", "-funsigned-char", "-fsigned-char", "--no-relocate"] + project.configuration.makefileSettings = recipe + try JSONEncoder().encode(project.configuration).write(to: project.directory.appendingPathComponent(CMOCProject.configurationFilename)) + try Data(recipe.generateMakefile().utf8).write(to: project.makefileURL) + let modes = try CMOCIndexInputs.load(project: project, toolchain: toolchain, configurationName: "Debug", overlays: [:], generated: [:]) + XCTAssertFalse(modes.configurationUncertain) + XCTAssertFalse(modes.defines.contains("_CMOC_MC6839_=1"), "Only the final floating-point mode may be predefined") + XCTAssertFalse(modes.defines.contains("_CMOC_unsigned_char_=1"), "The final signed-char switch restores CMOC's default") + XCTAssertTrue(modes.defines.contains("_CMOC_NO_RELOCATE_=1")) + let branches = "#if _CMOC_NATIVE_FLOAT_\nint wrong_builtin_override;\n#else\nint correct_user_override;\n#endif\n" + let modeIndex = CMOCProjectIndex(documents: ["modes.c": branches], defines: modes.defines, + configurationUncertain: modes.configurationUncertain) + XCTAssertTrue(modeIndex.symbols.contains { $0.name == "correct_user_override" }) + XCTAssertFalse(modeIndex.symbols.contains { $0.name == "wrong_builtin_override" }) + + } + +} diff --git a/platforms/macos/Tests/CMOCOwnedCallContextTests.swift b/platforms/macos/Tests/CMOCOwnedCallContextTests.swift new file mode 100644 index 0000000..d515c3a --- /dev/null +++ b/platforms/macos/Tests/CMOCOwnedCallContextTests.swift @@ -0,0 +1,250 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CMOCOwnedCallContextTests: XCTestCase { + func testEntryExposesExactlyActualSWindowAndProvesSevenIntegerArguments() throws { + let fixture = Fixture() + let before = fixture.memory + let result = fixture.capture() + XCTAssertEqual(result["status"] as? String, "available") + let window = try XCTUnwrap(result["stack_window"] as? [String: Any]) + XCTAssertEqual(window["address"] as? Int, 0x4000) + XCTAssertEqual(window["count"] as? Int, 64) + XCTAssertEqual(window["interpretation"] as? String, "uninterpreted") + XCTAssertEqual(window["bytes"] as? [UInt8], Array(before[0x4000..<0x4040])) + let words = try XCTUnwrap(window["words_be"] as? [[String: Any]]) + XCTAssertEqual(words.count, 32) + XCTAssertEqual(words.first?["value"] as? Int, 0x280b) + XCTAssertEqual(words.last?["address"] as? Int, 0x403e) + let caller = try XCTUnwrap(result["caller"] as? [String: Any]) + XCTAssertEqual(caller["status"] as? String, "available") + XCTAssertEqual(caller["call_address"] as? Int, 0x2808) + XCTAssertEqual(caller["callee_phase"] as? String, "function_entry") + let arguments = try XCTUnwrap(result["arguments"] as? [String: Any]) + let items = try XCTUnwrap(arguments["items"] as? [[String: Any]]) + XCTAssertEqual(items.compactMap { $0["value"] as? Int64 }, Fixture.arguments.map(Int64.init)) + XCTAssertEqual(items.compactMap { $0["address"] as? Int }, stride(from: 0x4002, through: 0x400e, by: 2).map { $0 }) + XCTAssertEqual(arguments["all_recorded_parameters_available"] as? Bool, true) + XCTAssertEqual(fixture.memory, before, "Inspection has no mutable guest state.") + } + + func testBodyUsesOnlyBoundedActualUFrameAndCompilerParameterLocations() throws { + var fixture = Fixture() + fixture.pc = 0x2904; fixture.s = 0x3fee; fixture.u = 0x3ffe + fixture.word(0x3ffe, 0x6a5a) // Saved U need not itself be readable or inspected. + let result = fixture.capture() + let caller = try XCTUnwrap(result["caller"] as? [String: Any]) + XCTAssertEqual(caller["status"] as? String, "available") + XCTAssertEqual(caller["callee_phase"] as? String, "mapped_body") + let args = try XCTUnwrap(result["arguments"] as? [String: Any]) + XCTAssertEqual((args["items"] as? [[String: Any]])?.count, 7) + let window = try XCTUnwrap(result["stack_window"] as? [String: Any]) + XCTAssertEqual((window["physical_spans"] as? [[String: Any]])?.count, 2) + fixture.u = 0x6000 + XCTAssertEqual((fixture.capture()["caller"] as? [String: Any])?["status"] as? String, "unavailable") + XCTAssertEqual(fixture.capture()["status"] as? String, "available", "Raw evidence does not require a usable U frame.") + } + + func testRejectsMalformedUnavailableROMAndWrappingWindows() { + var fixture = Fixture() + fixture.memory.removeLast() + XCTAssertEqual(fixture.capture()["status"] as? String, "unavailable") + fixture = Fixture(); fixture.available.removeLast() + XCTAssertEqual(fixture.capture()["status"] as? String, "unavailable") + fixture = Fixture(); fixture.available[0x403f] = 0 + XCTAssertNil(fixture.capture()["stack_window"]) + fixture = Fixture(); fixture.pages.removeValue(forKey: 2) + XCTAssertNil(fixture.capture()["stack_window"], "Readable ROM is not RAM.") + fixture = Fixture(); fixture.pages[2] = 1024 + XCTAssertNil(fixture.capture()["stack_window"]) + fixture = Fixture(); fixture.s = 0xfdc1 + XCTAssertNil(fixture.capture()["stack_window"]) + fixture = Fixture(); fixture.s = 0xfff0 + XCTAssertNil(fixture.capture()["stack_window"]) + fixture = Fixture(); fixture.s = 0x3ff0; fixture.pages.removeValue(forKey: 1) + XCTAssertNil(fixture.capture()["stack_window"], "Both physical pages of a split window are required.") + } + + func testRejectsChangedExecutableROMPCAndUnsharedPC() { + var fixture = Fixture() + fixture.memory[0x2900] ^= 1 + XCTAssertEqual(fixture.capture()["status"] as? String, "unavailable") + fixture = Fixture(); fixture.pages.removeValue(forKey: 1) + XCTAssertEqual(fixture.capture()["status"] as? String, "unavailable") + fixture = Fixture() + XCTAssertEqual(fixture.capture(shared: ["other.c"])["status"] as? String, "unavailable") + fixture.pc = 0x5000 + XCTAssertEqual(fixture.capture()["status"] as? String, "unavailable") + } + + func testUnknownOptimizedIndirectAndInterruptFramesStayUninterpreted() { + var fixture = Fixture() + var result = fixture.capture(metadata: false) + XCTAssertEqual(result["status"] as? String, "available") + XCTAssertEqual((result["caller"] as? [String: Any])?["status"] as? String, "unavailable") + fixture.framed = false + result = fixture.capture() + XCTAssertEqual((result["arguments"] as? [String: Any])?["status"] as? String, "unavailable") + fixture = Fixture(); fixture.callBytes = [0xad, 0x84, 0x12] // JSR ,X plus unrelated NOP is not a direct call. + result = fixture.capture() + XCTAssertEqual(result["status"] as? String, "available") + XCTAssertEqual((result["caller"] as? [String: Any])?["status"] as? String, "unavailable") + fixture = Fixture(); fixture.epilogue = [0x32, 0xc4, 0x35, 0x40, 0x3b] + result = fixture.capture() + XCTAssertEqual(result["status"] as? String, "available") + XCTAssertEqual((result["caller"] as? [String: Any])?["status"] as? String, "unavailable") + } + + func testDoesNotScanOtherWordsOrDiscloseUnsharedCaller() { + var fixture = Fixture() + fixture.word(0x4000, 0x9999); fixture.word(0x4010, 0x280b) + XCTAssertEqual((fixture.capture()["caller"] as? [String: Any])?["status"] as? String, "unavailable") + fixture = Fixture(); fixture.callerPath = "private.c" + let result = fixture.capture() + XCTAssertEqual(result["status"] as? String, "available") + XCTAssertEqual((result["caller"] as? [String: Any])?["status"] as? String, "unavailable") + XCTAssertFalse(String(describing: result).contains("private.c")) + fixture = Fixture(); fixture.duplicateCall = true + XCTAssertEqual((fixture.capture()["caller"] as? [String: Any])?["status"] as? String, "unavailable", + "Ambiguous call-site evidence must not choose a caller.") + } + + func testExcludesLocalsAggregatesOutOfWindowAndMismatchedMetadata() throws { + var fixture = Fixture() + fixture.extraVariables = [ + .init(name: "local", sourcePath: "fixture.c", line: 3, type: .integer, + address: nil, offset: -2, scope: 0x2904..<0x2920, isStatic: false), + .init(name: "aggregate", sourcePath: "fixture.c", line: 3, + type: .init(name: "structure", kind: "struct", size: 4), + address: nil, offset: 30, scope: 0x2904..<0x2920, isStatic: false), + .init(name: "far", sourcePath: "fixture.c", line: 3, type: .integer, + address: nil, offset: 100, scope: 0x2904..<0x2920, isStatic: false) + ] + let args = try XCTUnwrap(fixture.capture()["arguments"] as? [String: Any]) + XCTAssertEqual((args["items"] as? [[String: Any]])?.count, 7) + XCTAssertEqual(args["all_recorded_parameters_available"] as? Bool, false) + fixture.metadataHash = "other-build" + let result = fixture.capture() + XCTAssertEqual(result["status"] as? String, "available") + XCTAssertEqual((result["arguments"] as? [String: Any])?["status"] as? String, "unavailable") + } + + func testBankMismatchRejectsEvenIdenticalLogicalBytes() { + var fixture = Fixture() + fixture.banked = true + XCTAssertEqual(fixture.capture()["status"] as? String, "available") + fixture.pages[1] = 58 + XCTAssertEqual(fixture.capture()["status"] as? String, "unavailable") + } + + func testSignedByteUsesCompilerByteOffsetAndNeverDereferencesPointers() throws { + var fixture = Fixture() + fixture.memory[0x4011] = 0x80 + fixture.extraVariables = [ + .init(name: "byteArgument", sourcePath: "fixture.c", line: 3, + type: .init(name: "signed char", kind: "integer", size: 1, signed: true), + address: nil, offset: 19, scope: 0x2904..<0x2920, isStatic: false), + .init(name: "pointerArgument", sourcePath: "fixture.c", line: 3, + type: .init(name: "int *", kind: "pointer", size: 2), + address: nil, offset: 20, scope: 0x2904..<0x2920, isStatic: false) + ] + let args = try XCTUnwrap(fixture.capture()["arguments"] as? [String: Any]) + let items = try XCTUnwrap(args["items"] as? [[String: Any]]) + XCTAssertEqual(items.last?["name"] as? String, "byteArgument") + XCTAssertEqual(items.last?["address"] as? Int, 0x4011) + XCTAssertEqual(items.last?["value"] as? Int64, -128) + XCTAssertEqual(items.count, 8) + XCTAssertEqual(args["all_recorded_parameters_available"] as? Bool, false) + } + + func testOverlappingParameterLocationsAreNotInterpreted() throws { + var fixture = Fixture() + fixture.extraVariables = [ + .init(name: "alias", sourcePath: "fixture.c", line: 3, type: .integer, + address: nil, offset: 4, scope: 0x2904..<0x2920, isStatic: false) + ] + let args = try XCTUnwrap(fixture.capture()["arguments"] as? [String: Any]) + let items = try XCTUnwrap(args["items"] as? [[String: Any]]) + XCTAssertEqual(items.count, 6) + XCTAssertFalse(items.contains { ($0["name"] as? String) == "arg0" || ($0["name"] as? String) == "alias" }) + XCTAssertEqual(args["all_recorded_parameters_available"] as? Bool, false) + } + + private struct Fixture { + static let arguments: [UInt16] = [0x0102, 0x2030, 0x7f80, 0xa0b0, 0xc0d0, 0xdead, 0xbeef] + var memory = Data(repeating: 0, count: 65536) + var available = Data(repeating: 1, count: 65536) + var pages = [1: 57, 2: 12] + var pc: UInt16 = 0x2900, s: UInt16 = 0x4000, u: UInt16 = 0x6a5a + var framed = true, banked = false, duplicateCall = false + var callBytes: [UInt8] = [0x17, 0x00, 0xf5] + var epilogue: [UInt8] = [0x32, 0xc4, 0x35, 0xc0] + var callerPath = "fixture.c", metadataHash = "fixture" + var extraVariables: [CMOCVariableDebug.Variable] = [] + + init() { + word(0x4000, 0x280b) + for (index, value) in Self.arguments.enumerated() { word(0x4002 + index * 2, value) } + } + mutating func word(_ address: Int, _ value: UInt16) { + memory[address] = UInt8(value >> 8); memory[address + 1] = UInt8(value & 255) + } + func capture(metadata useMetadata: Bool = true, shared: Set = ["fixture.c"]) -> [String: Any] { + let module: String? = banked ? "resident" : nil + var instructions: [CMOCProjectSourceMap.Instruction] = [] + for entry in [0x2800, 0x2900] { + let path = entry == 0x2800 ? callerPath : "fixture.c" + let rows: [(Int, [UInt8])] = [(0, [0x34, 0x40]), (2, [0x33, 0xe4]), (4, [0x12]), + (0x20, Array(epilogue.prefix(2))), (0x22, Array(epilogue.dropFirst(2)))] + for (offset, bytes) in rows { + instructions.append(.init(sourcePath: path, sourceLine: 3, address: UInt16(entry + offset), + bytes: bytes, assembly: "authored", moduleID: module)) + } + } + instructions.append(.init(sourcePath: callerPath, sourceLine: 2, address: 0x2808, + bytes: callBytes, assembly: "authored direct call", moduleID: module)) + if duplicateCall, let call = instructions.last { instructions.append(call) } + var live = memory + // Fixture code is prepared independently of capture's immutable snapshot. + // A caller's deliberate mutation at entry must remain visible to the guard. + var code = Data(repeating: 0x12, count: 0x125) + for instruction in instructions { + let begin = Int(instruction.address) + code.replaceSubrange((begin - 0x2800)..<(begin - 0x2800 + instruction.bytes.count), with: instruction.bytes) + } + for offset in 0.. (line: Int, column: Int, offset: Int) { + let text = source as NSString; var start = 0, found = NSRange(location: NSNotFound, length: 0) + for _ in 0...occurrence { found = text.range(of: needle, range: NSRange(location: start, length: text.length - start)); if found.location == NSNotFound { XCTFail("Missing fixture token \(needle)"); return (1,1,0) }; start = NSMaxRange(found) } + let before = text.substring(to: found.location) + return (before.components(separatedBy: "\n").count, found.location - text.lineRange(for: NSRange(location: found.location, length: 0)).location + 1, found.location) + } + func testDeclarationsIgnoreCommentsStringsAndCMOCAssembly() { + let source = """ + /* void invented(void) {} */ + const char *message = "int fake;"; + typedef unsigned int Count; + typedef int (*Handler)(int code); + static Count total; + int (*callback)(int); + int compute(int amount) { + Count local = amount; + asm { bogus int assembly_symbol } + // int comment; + return local; + } + """ + let index = CMOCProjectIndex(documents: ["main.c": source]) + XCTAssertEqual(Set(index.outline(path: "main.c").map(\.name)), ["message", "Count", "Handler", "total", "callback", "compute"]) + XCTAssertEqual(index.symbols.first { $0.name == "callback" }?.kind, .variable) + XCTAssertEqual(index.symbols.first { $0.name == "Handler" }?.kind, .type) + XCTAssertEqual(index.symbols.first { $0.name == "amount" }?.kind, .parameter) + XCTAssertEqual(index.symbols.first { $0.name == "local" }?.scope, "compute") + XCTAssertFalse(index.symbols.contains { ["invented", "fake", "bogus", "assembly_symbol", "comment"].contains($0.name) }) + XCTAssertNil(index.token(atUTF16Offset: location("fake", in: source).offset, in: "main.c")) + XCTAssertNil(index.token(atUTF16Offset: location("comment", in: source).offset, in: "main.c")) + } + func testPrototypeNavigatesToExternalDefinitionAndDuplicateDefinitionsStayVisible() { + let source = "#include \"api.h\"\nint main(void) { return calculate(2); }" + let index = CMOCProjectIndex(documents: ["main.c": source, "api.h": "int calculate(int value);", "compute.c": "int calculate(int value) { return value; }"]) + let here = location("calculate", in: source) + let result = index.definitions(named: "calculate", from: "main.c", line: here.line, column: here.column) + XCTAssertEqual(result.map(\.path), ["compute.c"]) + XCTAssertTrue(result[0].isDefinition) + XCTAssertFalse(index.symbols.first { $0.path == "api.h" }!.isDefinition) + let duplicate = CMOCProjectIndex(documents: ["main.c": source, "a.c": "int calculate(int v) { return v; }", "b.c": "int calculate(int v) { return v+1; }"]) + XCTAssertEqual(duplicate.definitions(named: "calculate", from: "main.c", line: here.line, column: here.column).count, 2) + } + func testLocalAndNestedBlockShadowingStayInsideTheirScope() { + let source = """ + int value; + int main(int value) { + value++; + { int value; value++; } + value++; + } + int other(void) { return value; } + """ + let index = CMOCProjectIndex(documents: ["main.c": source]) + let inner = location("value++", in: source, occurrence: 1) + let outer = location("value++", in: source, occurrence: 2) + let other = location("return value", in: source) + XCTAssertEqual(index.definitions(named: "value", from: "main.c", line: inner.line, column: inner.column).first?.line, 4) + XCTAssertEqual(index.definitions(named: "value", from: "main.c", line: outer.line, column: outer.column).first?.kind, .parameter) + XCTAssertEqual(index.definitions(named: "value", from: "main.c", line: other.line, column: other.column + 7).first?.line, 1) + } + func testStaticDefinitionsNeverCrossTranslationUnits() { + let index = CMOCProjectIndex(documents: ["a.c": "static int helper(void) { return 1; }\nint a(void) { return helper(); }", "b.c": "static int helper(void) { return 2; }\nint b(void) { return helper(); }", "c.c": "int c(void) { return helper(); }"]) + XCTAssertEqual(index.definitions(named: "helper", from: "a.c", line: 2, column: 22).map(\.path), ["a.c"]) + XCTAssertTrue(index.definitions(named: "helper", from: "c.c", line: 1, column: 22).isEmpty) + } + func testLiteralIncludesResolveConfiguredAndBundledHeaderPaths() { + let index = CMOCProjectIndex(documents: [ + "src/main.c": "#include \"feature.h\"\n#include \nint main(void) { return printFeature(); }", + "include/feature.h": "#include \"detail.h\"\nint printFeature(void);", + "include/detail.h": "typedef unsigned int Count;", + "@toolchain/include/cmoc.h": "int printf(const char *format, ...);", + "unrelated/feature.h": "int printFeature(int unrelated);" + ], includePaths: ["include", "@toolchain/include"]) + XCTAssertEqual(index.definitions(named: "printFeature", from: "src/main.c", line: 3, column: 25).map(\.path), ["include/feature.h"]) + XCTAssertEqual(index.definitions(named: "Count", from: "src/main.c", line: 3, column: 1).map(\.path), ["include/detail.h"]) + XCTAssertEqual(index.definitions(named: "printf", from: "src/main.c", line: 3, column: 1).map(\.path), ["@toolchain/include/cmoc.h"]) + } + func testPlanetAtlasResolvesCompatibilityConversionsInDefinitionAndCompletion() throws { + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + func read(_ path: String) throws -> String { try String(contentsOf: root.appendingPathComponent(path), encoding: .utf8) } + let source = try read("examples/cmoc/manual/atlas.c") + var documents = ["main.c": source, "inc/decbfile.h": try read("third_party/cmoc-libraries/decbfile/decbfile.h")] + for name in ["cmoc", "coco", "stdarg"] { + documents["inc/\(name).h"] = try read("third_party/cmoc/src/stdlib/\(name).h") + } + for name in ["stddef", "stdio", "stdlib", "errno"] { + documents["compat/\(name).h"] = try read("sdk/cmoc/compat/include/\(name).h") + } + let here = location("strtoul(", in: source) + let index = CMOCProjectIndex(documents: documents, includePaths: ["compat", "inc"]) + for name in ["strtol", "strtoul"] { + XCTAssertEqual(index.definitions(named: name, from: "main.c", line: here.line, column: here.column).map(\.path), ["compat/stdlib.h"]) + let candidates = index.completionSymbols(from: "main.c", offset: here.offset, prefix: name) + XCTAssertEqual(candidates.filter { $0.name == name }.map(\.kind), [.function]) + } + } + + func testExplicitUndefFollowsOrderedIncludesAndPreservesConditionalAlternatives() { + let source = """ + #include "original.h" + int before(void) { return convert(1); } + #include "replacement.h" + int after(void) { return convert(2); } + #include "original.h" + int redefined(void) { return convert(3); } + """ + let docs = ["main.c": source, "original.h": "#define convert(n) old(n)", + "replacement.h": "#undef convert\nint convert(int n);"] + func lookup(_ candidate: String, documents: [String: String] = [:]) -> [CMOCProjectIndex.Symbol] { + let index = CMOCProjectIndex(documents: docs.merging(documents) { _, updated in updated }) + let here = location(candidate, in: source) + return index.definitions(named: "convert", from: "main.c", line: here.line, column: here.column) + } + XCTAssertEqual(lookup("convert(1)").map(\.kind), [.macro]) + XCTAssertEqual(lookup("convert(2)").map(\.kind), [.function]) + XCTAssertEqual(lookup("convert(3)").map(\.kind), [.macro], "An unguarded header may restore the macro") + let maybe = ["replacement.h": "#if UNKNOWN_MODE(9)\n#undef convert\nint convert(int n);\n#endif"] + let uncertain = lookup("convert(2)", documents: maybe) + XCTAssertEqual(uncertain.map(\.kind), [.function, .macro]) + XCTAssertTrue(uncertain.allSatisfy(\.conditional)) + } + + func testKnownInactiveBranchesAreExcludedAndUnknownBranchesRemainMarked() { + let source = """ + #if 0 + int definitely_off; + #endif + #if ENABLE + int enabled; + #else + int disabled; + #endif + #if UNKNOWN_COMPLEX(2) + int maybe_one; + #else + int maybe_two; + #endif + """ + let index = CMOCProjectIndex(documents: ["main.c": source], defines: ["ENABLE=1"]) + XCTAssertEqual(Set(index.symbols.map(\.name)), ["enabled", "maybe_one", "maybe_two"]) + XCTAssertFalse(index.symbols.first { $0.name == "enabled" }!.conditional) + XCTAssertTrue(index.symbols.filter { $0.name.hasPrefix("maybe") }.allSatisfy(\.conditional)) + let custom = CMOCProjectIndex(documents: ["main.c": "#ifdef CUSTOM_FLAG\nint option;\n#endif"], configurationUncertain: true) + XCTAssertTrue(custom.symbols[0].conditional) + XCTAssertFalse(custom.issues.isEmpty) + } + func testIncludedMacroStateIsConservativeAndMultilineMacrosDoNotCreateFunctions() { + let source = """ + #include + #ifdef HEADER_FLAG + int conditional; + #endif + #define REPEAT REPEAT + 1 + #define BODY(x) \\ + int not_a_function(int y) { return y; } + int real; + """ + let index = CMOCProjectIndex(documents: ["main.c": source]) + XCTAssertTrue(index.symbols.first { $0.name == "conditional" }!.conditional) + XCTAssertFalse(index.symbols.contains { $0.name == "not_a_function" }) + let macro = index.symbols.first { $0.name == "REPEAT" }! + XCTAssertEqual(macro.column, 9) + XCTAssertEqual(macro.kind, .macro) + } + func testMemberAccessDoesNotPretendSameNamedGlobalIsItsDefinition() { + let source = "struct Record { int value; };\nint value;\nint main(void) { struct Record record; return record.value; }" + let index = CMOCProjectIndex(documents: ["main.c": source]) + let here = location("record.value", in: source) + let matches = index.definitions(named: "value", from: "main.c", line: here.line, column: here.column + 7) + XCTAssertEqual(matches.count, 1); XCTAssertEqual(matches[0].kind, .member); XCTAssertTrue(matches[0].conditional) + XCTAssertEqual(index.definitions(named: "value", from: "main.c", line: here.line, column: here.column + 12).first?.kind, .member, "Caret at the end of a member must keep its member context") + } + func testSearchUsesUTF16CoordinatesLiteralMatchingAndExplicitLimits() { + let source = "// 😀 Token token\nconst char *s = \"TOKEN\";\n" + let index = CMOCProjectIndex(documents: ["main.c": source, "@toolchain/include/api.h": "token", "README.md": "token"]) + let results = index.search(query: "token", caseSensitive: false, paths: ["main.c"]) + XCTAssertEqual(results.matches.count, 3); XCTAssertFalse(results.truncated) + XCTAssertEqual(results.matches[0].column, 7) + XCTAssertEqual((source as NSString).substring(with: NSRange(location: results.matches[0].offsetUTF16, length: results.matches[0].lengthUTF16)), "Token") + XCTAssertEqual(index.search(query: "Token", caseSensitive: true).matches.count, 1) + XCTAssertTrue(index.search(query: "token", limit: 2).truncated) + XCTAssertEqual(index.search(query: ".*").matches.count, 0, "Search is literal, not a regular expression") + } + func testQuotedIncludesTakeLocalPrecedenceAndAngleIncludesUseSearchPaths() { + let index = CMOCProjectIndex(documents: ["main.c": "#include \"api.h\"\n#include \nint main(void) { return 0; }", "api.h": "int localAPI(void);", "inc/api.h": "int wrongAPI(void);", "system.h": "int wrongSystem(void);", "inc/system.h": "int configuredSystem(void);"], includePaths: ["inc"]) + XCTAssertEqual(index.definitions(named: "localAPI", from: "main.c", line: 3, column: 1).first?.path, "api.h") + XCTAssertFalse(index.definitions(named: "localAPI", from: "main.c", line: 3, column: 1).first!.conditional) + XCTAssertTrue(index.definitions(named: "wrongAPI", from: "main.c", line: 3, column: 1).first!.conditional) + XCTAssertFalse(index.definitions(named: "configuredSystem", from: "main.c", line: 3, column: 1).first!.conditional) + XCTAssertTrue(index.definitions(named: "wrongSystem", from: "main.c", line: 3, column: 1).first!.conditional) + } + func testContinuedCommentsAndStringsDoNotInventDeclarations() { + let source = "// continued \\\nint notCode;\nconst char *text = \"continued \\\n#define NOT_MACRO 1\";\nint actual;" + let index = CMOCProjectIndex(documents: ["main.c": source]) + XCTAssertEqual(Set(index.outline(path: "main.c").map(\.name)), ["text", "actual"]) + } + func testCMOCAssemblyFunctionsAndForLoopLocalsAreRecognizedWithoutLeaking() { + let source = "asm byte readButtons(void) { ldb #$00; rts; }\nvoid asm output(byte value) { stb $FF20; }\nint i;\nvoid loop(void) { for (int i = 0; i < 2; ++i) { i++; } i++; }" + let index = CMOCProjectIndex(documents: ["main.c": source]) + XCTAssertEqual(index.symbols.filter { $0.kind == .function && $0.isDefinition }.map(\.name), ["readButtons", "output", "loop"]) + let inside = location("i++", in: source) + let outside = location("i++", in: source, occurrence: 1) + XCTAssertEqual(index.definitions(named: "i", from: "main.c", line: inside.line, column: inside.column).first?.scope, "loop") + XCTAssertNil(index.definitions(named: "i", from: "main.c", line: outside.line, column: outside.column).first?.scope) + XCTAssertFalse(index.symbols.contains { ["ldb", "rts", "stb"].contains($0.name) }) + } + func testConditionalInitializersAndFunctionReturningPointerKeepTheirNames() { + let index = CMOCProjectIndex(documents: ["main.c": "int flag; int selected = flag ? 1 : 2; struct Bits { unsigned bit:1; }; int (*factory(void))(int) { return 0; }"]) + XCTAssertEqual(index.symbols.first { $0.name == "selected" }?.kind, .variable) + XCTAssertEqual(index.symbols.first { $0.name == "bit" }?.kind, .member) + XCTAssertEqual(index.symbols.first { $0.name == "factory" }?.kind, .function) + XCTAssertTrue(index.symbols.first { $0.name == "factory" }!.isDefinition) + } + func testOversizedInputsAreReportedAndDoNotHideAcceptedDocuments() { + let index = CMOCProjectIndex(documents: ["good.c": "int good;", "large.c": String(repeating: "x", count: CMOCProjectIndex.maximumFileBytes + 1)]) + XCTAssertEqual(Set(index.documents.keys), ["good.c"]) + XCTAssertEqual(index.symbols.map(\.name), ["good"]) + XCTAssertTrue(index.issues.contains { $0.contains("large.c") }) + } + func testAggregateTypedefEnumAndMalformedInputRemainBounded() { + let index = CMOCProjectIndex(documents: ["types.h": "typedef struct { int x; } Point;\nenum Color { RED = 1, GREEN, BLUE };\nstruct Named { int y; };", "broken.c": "void incomplete( { int ignored;", "deep.c": String(repeating: "{", count: 80) + "int too_deep;" + String(repeating: "}", count: 80)]) + XCTAssertEqual(Set(index.outline(path: "types.h").map(\.name)), ["Point", "Color", "RED", "GREEN", "BLUE", "Named"]) + XCTAssertTrue(index.outline(path: "broken.c").isEmpty) + XCTAssertTrue(index.symbols.filter { $0.path == "deep.c" }.isEmpty) + } +} diff --git a/platforms/macos/Tests/CMOCProjectInputTests.swift b/platforms/macos/Tests/CMOCProjectInputTests.swift new file mode 100644 index 0000000..35c09d1 --- /dev/null +++ b/platforms/macos/Tests/CMOCProjectInputTests.swift @@ -0,0 +1,133 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest +import Foundation + +final class CMOCProjectInputTests: XCTestCase { + private func fixture() throws -> URL { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCInputs-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try write("int main(void) { return 0; }\n", "main.c", at: root) + try write("all:\n\t@true\n", "Makefile", at: root) + return root + } + private func write(_ value: String, _ path: String, at root: URL) throws { + let url = root.appendingPathComponent(path) + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(value.utf8).write(to: url) + } + func testNestedHeadersAndExplicitGeneratedInputsShareOneManifest() throws { + let root = try fixture(); defer { try? FileManager.default.removeItem(at: root) } + try write("#define VALUE 7\n", "include/game/detail/value.h", at: root) + try write("#define GENERATED 9\n", ".build/value.h", at: root) + try write("incidental sibling", ".build/receipt.json", at: root) + try write("incidental nested sibling", ".build/screens/picture.png", at: root) + try write("payload", "out/keep.dat", at: root) + try write("generated output", "out/capture.json", at: root) + var config = CMOCProjectConfiguration() + config.generatedInputs = [".build/value.h"] + config.resourceInputs = ["out/keep.dat"] + config.outputDirectories = ["out"] + let project = CMOCProject(directory: root, configuration: config) + let manifest = try CMOCProjectInputManifest.capture(project: project) + XCTAssertTrue(manifest.sharedPaths.contains("include/game/detail/value.h")) + XCTAssertEqual(manifest.files[".build/value.h"], Data("#define GENERATED 9\n".utf8)) + XCTAssertNil(manifest.files[".build/receipt.json"]) + XCTAssertNil(manifest.files[".build/screens/picture.png"]) + XCTAssertNotNil(manifest.files["out/keep.dat"]) + XCTAssertNil(manifest.files["out/capture.json"]) + XCTAssertEqual(manifest.entries.first { $0.path == ".build/value.h" }?.role, "generated_input") + let scope = try MCPCMOCProject(project: project, files: manifest.sharedPaths, customMake: true) + XCTAssertTrue(scope.paths.contains("include/game/detail/value.h")) + XCTAssertEqual(Set(try project.fileEntries().map(\.relativePath)), Set(manifest.files.keys)) + try write("new evidence", ".build/receipt.json", at: root) + try write("more evidence", ".build/extra.json", at: root) + XCTAssertEqual(try CMOCProjectInputManifest.capture(project: project), manifest, + "An explicit exception must not re-include excluded siblings") + } + func testEvidenceGrowthAndTimestampChangesDoNotChangeIdentity() throws { + let root = try fixture(); defer { try? FileManager.default.removeItem(at: root) } + let project = CMOCProject(directory: root) + let original = try CMOCProjectInputManifest.capture(project: project) + try write("receipt", "evidence/run.json", at: root) + try write("log", "captures/session.log", at: root) + try write("receipt", "trial-receipt.json", at: root) + try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSince1970: 1)], ofItemAtPath: root.appendingPathComponent("main.c").path) + let touched = try CMOCProjectInputManifest.capture(project: project) + XCTAssertEqual(original, touched) + XCTAssertTrue(touched.changes(from: original).isEmpty) + XCTAssertNil(touched.files["evidence/run.json"]) + XCTAssertTrue(touched.entries.contains { $0.path == "evidence" && !$0.included && !$0.affectsRevision }) + try write("int main(void) { return 1; }\n", "main.c", at: root) + try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSince1970: 1)], ofItemAtPath: root.appendingPathComponent("main.c").path) + let edited = try CMOCProjectInputManifest.capture(project: project) + XCTAssertNotEqual(edited, touched) + XCTAssertEqual(edited.changes(from: touched).map(\.path), ["main.c"]) + XCTAssertFalse(try XCTUnwrap(edited.changes(from: touched).first).requiresReview) + } + func testNewScopeAndRecipeChangesRequireReviewButContentEditsDoNot() throws { + let root = try fixture(); defer { try? FileManager.default.removeItem(at: root) } + let project = CMOCProject(directory: root) + let before = try CMOCProjectInputManifest.capture(project: project) + try write("#define NEW 1\n", "include/new.h", at: root) + var after = try CMOCProjectInputManifest.capture(project: project) + XCTAssertTrue(try XCTUnwrap(after.changes(from: before).first).requiresReview) + let shared = after + try write("#define NEW 2\n", "include/new.h", at: root) + after = try CMOCProjectInputManifest.capture(project: project) + XCTAssertFalse(try XCTUnwrap(after.changes(from: shared).first).requiresReview) + let edited = after + try write("all:\n\t@echo changed\n", "Makefile", at: root) + after = try CMOCProjectInputManifest.capture(project: project) + XCTAssertTrue(try XCTUnwrap(after.changes(from: edited).first).requiresReview) + XCTAssertFalse(after.entries.contains { $0.path.hasPrefix(root.path) }) + } + func testSymlinkInputsAreRejectedEvenWhenExplicit() throws { + let root = try fixture(); defer { try? FileManager.default.removeItem(at: root) } + try FileManager.default.createSymbolicLink(atPath: root.appendingPathComponent("linked.h").path, withDestinationPath: "/etc/hosts") + var config = CMOCProjectConfiguration(); config.generatedInputs = ["linked.h"] + XCTAssertThrowsError(try CMOCProjectInputManifest.capture(project: CMOCProject(directory: root, configuration: config))) + } + func testRestrictedRecipeDoesNotAcquireUnsharedMakeResources() throws { + let root = try fixture(); defer { try? FileManager.default.removeItem(at: root) } + try write("private project notes", "README.md", at: root) + let project = CMOCProject(directory: root) + let before = try CMOCProjectInputManifest.capture(project: project).restricting(to: ["main.c"]) + try write("changed notes", "README.md", at: root) + try write("all:\n\t@echo changed personal recipe\n", "Makefile", at: root) + let after = try CMOCProjectInputManifest.capture(project: project).restricting(to: ["main.c"]) + XCTAssertEqual(before, after) + XCTAssertEqual(after.sharedPaths, ["main.c"]) + XCTAssertNil(after.files["Makefile"]) + XCTAssertNil(after.entries.first { $0.path == "README.md" }?.sha256) + } + func testUnapprovedSupportRootIsNotReadOrHashedBeforeNativeApproval() throws { + let root = try fixture(); defer { try? FileManager.default.removeItem(at: root) } + let name = "VCCSupport-" + UUID().uuidString + let sibling = root.deletingLastPathComponent().appendingPathComponent(name) + try FileManager.default.createDirectory(at: sibling, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: sibling) } + try write("authored private fixture", "unapproved.txt", at: sibling) + try FileManager.default.createSymbolicLink(atPath: sibling.appendingPathComponent("link").path, withDestinationPath: "/etc/hosts") + var config = CMOCProjectConfiguration(); config.buildSupportDirectories = ["../" + name] + let project = CMOCProject(directory: root, configuration: config) + let pending = try CMOCProjectInputManifest.capture(project: project, approvedSupportDirectories: []) + XCTAssertTrue(pending.support.files.isEmpty) + let row = try XCTUnwrap(pending.entries.first { $0.role == "pending_support_root" }) + XCTAssertEqual(row.path, "../" + name); XCTAssertNil(row.sha256) + XCTAssertFalse(pending.entries.contains { $0.path.hasSuffix("unapproved.txt") }) + try write("changed outside the approved scope", "unapproved.txt", at: sibling) + XCTAssertEqual(try CMOCProjectInputManifest.capture(project: project, approvedSupportDirectories: []), pending) + XCTAssertThrowsError(try CMOCProjectInputManifest.capture(project: project), "Only approval may enumerate the root and discover its unsafe member") + try FileManager.default.removeItem(at: sibling.appendingPathComponent("link")) + XCTAssertNotNil(try CMOCProjectInputManifest.capture(project: project).support.files["../" + name + "/unapproved.txt"]) + } + func testHardVersionControlExclusionsAreCaseInsensitiveAndOutputLinksRefused() throws { + let root = try fixture(); defer { try? FileManager.default.removeItem(at: root) } + try write("must not be shared", ".HG/store/data.c", at: root) + try write("must not be shared", ".GIT/config", at: root) + let before = try CMOCProjectInputManifest.capture(project: CMOCProject(directory: root)) + XCTAssertFalse(before.files.keys.contains { $0.lowercased().hasPrefix(".hg/") || $0.lowercased().hasPrefix(".git/") }) + try FileManager.default.createSymbolicLink(atPath: root.appendingPathComponent("captures").path, withDestinationPath: "/etc") + XCTAssertThrowsError(try CMOCProjectInputManifest.capture(project: CMOCProject(directory: root))) + } +} diff --git a/platforms/macos/Tests/CMOCSourceDebugTests.swift b/platforms/macos/Tests/CMOCSourceDebugTests.swift new file mode 100644 index 0000000..73ebc6d --- /dev/null +++ b/platforms/macos/Tests/CMOCSourceDebugTests.swift @@ -0,0 +1,306 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +/// End-to-end qualification: actual compiler output and an executing CoCo, +/// rather than handcrafted addresses or a second implementation of the mapper. +final class CMOCSourceDebugTests: XCTestCase { + private struct Fixture { + let root: URL + let artifact: CMOCBuildArtifact + let map: CMOCProjectSourceMap + let rom: Data + let sources: [String: String] + func line(_ marker: String, file: String = "main.c") throws -> Int { + try XCTUnwrap(sources[file]?.components(separatedBy: "\n").firstIndex { $0.contains(marker) }) + 1 + } + func address(_ marker: String, file: String = "main.c") throws -> UInt16 { + try XCTUnwrap(map.addresses(forLine: line(marker, file: file), in: file).first, marker) + } + } + private func fixture() async throws -> Fixture { + let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources") + let toolchain = resources.appendingPathComponent("ToolchainBundle") + let rom = resources.appendingPathComponent("ROMs/coco3.rom") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) + && FileManager.default.fileExists(atPath: rom.path), "Local licensed CoCo ROM and staged toolchain are required") + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCSourceDebug-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + do { + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + let sources = ["main.c": """ + #include + #include + #include "shared.h" + unsigned int result; + unsigned int progress; + unsigned int values[3] = {11, 22, 33}; + struct Pair pair = {4, 45}; + unsigned int *pointer = &values[1]; + int signedValue = -1234; + unsigned char *ioPointer = (unsigned char *)0xFF00; + int main(void) + { + unsigned int mainLocal = 7; + initCoCoSupport(); + result = transform(mainLocal); /* CALL_TRANSFORM */ + progress = result; /* AFTER_TRANSFORM */ + result = recurse(3); /* CALL_RECURSE */ + progress = result; /* AFTER_RECURSE */ + for (;;) ++progress; + return 0; + } + """, "helper.c": """ + #include "shared.h" + unsigned int transform(unsigned int value) + { + unsigned int local = value + 5; + { + unsigned int value = 99; + result = value; /* SHADOW_VALUE */ + } + result = local; /* OUTER_VALUE */ + return local * 2; /* RETURN_TRANSFORM */ + } + unsigned int recurse(unsigned int n) + { + unsigned int local = n + 10; + if (n == 0) return local; /* RECURSION_BASE */ + return recurse(n - 1) + local; /* RECURSION_CALL */ + } + """, "shared.h": """ + struct Pair { unsigned int left; unsigned int right; }; + extern unsigned int result; + unsigned int transform(unsigned int value); + unsigned int recurse(unsigned int n); + """] + for (name, source) in sources { try Data(source.utf8).write(to: project.directory.appendingPathComponent(name)) } + let makefile = """ + CMOC ?= cmoc + .PHONY: build clean + build: main.bin + main.bin: main.o helper.o + \t"$(CMOC)" --coco --intermediate --org=2800 -o $@ main.o helper.o + %.o: %.c shared.h + \t"$(CMOC)" --coco --intermediate -O0 -fno-omit-frame-pointer -c -o $@ $< + clean: + \trm -f *.o *.bin *.s *.lst *.map *.link + """ + try Data(makefile.utf8).write(to: project.makefileURL) + let artifact = try await CMOCBuildService(toolchain: toolchain, buildRoot: root.appendingPathComponent("Builds")) + .build(project: project, overlays: [:]) + let map = try CMOCProjectSourceMap.parse(artifact: artifact) + XCTAssertEqual(Set(map.sourcePaths), Set(["main.c", "helper.c"])) + return Fixture(root: root, artifact: artifact, map: map, rom: try Data(contentsOf: rom), sources: sources) + } catch { try? FileManager.default.removeItem(at: root); throw error } + } + @MainActor private func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { continuation in operation { continuation.resume(returning: $0) } } + } + @MainActor private func capture(_ controller: VCCMachineController) async -> VCCDebuggerSnapshot { + await withCheckedContinuation { continuation in + controller.debuggerSnapshot(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) } + } + } + @MainActor private func waitForStop(_ controller: VCCMachineController) async throws -> VCCDebuggerSnapshot { + var state = await command(controller.snapshot) + for _ in 0..<1000 where state.state == .running { + try await Task.sleep(nanoseconds: 5_000_000) + state = await command(controller.snapshot) + } + XCTAssertEqual(state.state, .paused, state.errorMessage ?? "Execution did not stop") + XCTAssertNil(state.errorMessage) + return await capture(controller) + } + @MainActor private func runTo(_ fixture: Fixture, controller: VCCMachineController, marker: String, file: String = "main.c") async throws -> VCCDebuggerSnapshot { + let address = try fixture.address(marker, file: file) + let result = await command { controller.debuggerLoadBinary(fixture.artifact.binaryData, breakpoint: address, completion: $0) } + XCTAssertNil(result.errorMessage) + let stopped = try await waitForStop(controller) + XCTAssertEqual(stopped.machine.programCounter, address) + return stopped + } + @MainActor private func startSourceStep(_ mode: Int, fixture: Fixture, controller: VCCMachineController, + snapshot: VCCDebuggerSnapshot) async -> VCCMachineSnapshot { + var identities: [CMOCProjectSourceMap.Location: UInt32] = [:] + let ids = fixture.map.instructions.map { instruction -> NSNumber in + let location = CMOCProjectSourceMap.Location(path: instruction.sourcePath, line: instruction.sourceLine) + if identities[location] == nil { identities[location] = UInt32(identities.count + 1) } + return NSNumber(value: identities[location]!) + } + return await command { + controller.debuggerStepSource(mode: mode, + addresses: fixture.map.instructions.map { NSNumber(value: $0.address) }, locations: ids, + bytes: fixture.map.instructions.map { Data($0.bytes) }, + generation: snapshot.machine.generation, programRevision: snapshot.machine.debuggerProgramRevision, + mappingFingerprint: snapshot.machine.debuggerMappingFingerprint, + programCounter: snapshot.machine.programCounter, completion: $0) + } + } + @MainActor private func sourceStep(_ mode: Int, fixture: Fixture, controller: VCCMachineController) async throws -> VCCDebuggerSnapshot { + let result = await startSourceStep(mode, fixture: fixture, controller: controller, snapshot: await capture(controller)) + XCTAssertNil(result.errorMessage) + return try await waitForStop(controller) + } + @MainActor private func withProcessors(_ fixture: Fixture, + body: (VCCMachineController) async throws -> Void) async throws { + for use6309 in [false, true] { + let controller = VCCMachineController() + do { + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + let loaded = await command { controller.loadROM(fixture.rom, use6309: use6309, completion: $0) } + XCTAssertNil(loaded.errorMessage) + _ = await command(controller.resume) + try await Task.sleep(nanoseconds: 1_500_000_000) + _ = await command(controller.pause) + try await body(controller) + _ = await command(controller.shutdown) + } catch { _ = await command(controller.shutdown); throw error } + } + } + @MainActor func testRealMultiFileStepIntoOverOutAndRecursiveFramesOnBothCPUs() async throws { + let fixture = try await fixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let metadata = try CMOCVariableDebug.parse(artifact: fixture.artifact, verifiedMap: fixture.map) + try await withProcessors(fixture) { controller in + let original = try await runTo(fixture, controller: controller, marker: "CALL_TRANSFORM") + let over = try await sourceStep(1, fixture: fixture, controller: controller) + XCTAssertEqual(fixture.map.location(at: over.machine.programCounter), + .init(path: "main.c", line: try fixture.line("AFTER_TRANSFORM"))) + XCTAssertEqual(over.machine.generation, original.machine.generation) + XCTAssertEqual(over.machine.debuggerProgramRevision, original.machine.debuggerProgramRevision) + XCTAssertEqual(over.breakpoints, original.breakpoints, "Temporary step targets must not replace permanent breakpoints") + assertValue("result", "24", in: try evaluator(metadata, over)) + + _ = try await runTo(fixture, controller: controller, marker: "CALL_TRANSFORM") + let into = try await sourceStep(0, fixture: fixture, controller: controller) + XCTAssertEqual(fixture.map.location(at: into.machine.programCounter)?.path, "helper.c", "Into must enter the other translation unit") + let out = try await sourceStep(2, fixture: fixture, controller: controller) + XCTAssertEqual(fixture.map.location(at: out.machine.programCounter)?.path, "main.c", "Out must return to the caller") + + _ = try await runTo(fixture, controller: controller, marker: "CALL_RECURSE") + var recursive = try await sourceStep(0, fixture: fixture, controller: controller) + let callLine = try fixture.line("RECURSION_CALL", file: "helper.c") + for _ in 0..<12 where fixture.map.location(at: recursive.machine.programCounter)?.line != callLine { + recursive = try await sourceStep(0, fixture: fixture, controller: controller) + } + XCTAssertEqual(fixture.map.location(at: recursive.machine.programCounter), .init(path: "helper.c", line: callLine)) + let outerU = recursive.registers["U"]?.uint16Value + var nested = try await sourceStep(0, fixture: fixture, controller: controller) + for _ in 0..<12 where fixture.map.location(at: nested.machine.programCounter)?.line != callLine { + nested = try await sourceStep(0, fixture: fixture, controller: controller) + } + XCTAssertEqual(fixture.map.location(at: nested.machine.programCounter), .init(path: "helper.c", line: callLine)) + XCTAssertNotEqual(nested.registers["U"]?.uint16Value, outerU, "Recursion must establish a distinct live frame") + let returned = try await sourceStep(2, fixture: fixture, controller: controller) + XCTAssertEqual(returned.registers["U"]?.uint16Value, outerU, "Out must leave exactly one recursive invocation") + XCTAssertEqual(fixture.map.location(at: returned.machine.programCounter)?.path, "helper.c") + + _ = try await runTo(fixture, controller: controller, marker: "CALL_TRANSFORM") + let calleePoint = try fixture.address("SHADOW_VALUE", file: "helper.c") + _ = await command { controller.debuggerConfigureBreakpoints([NSNumber(value: calleePoint)], disabled: [0x7001], completion: $0) } + let userStop = try await sourceStep(1, fixture: fixture, controller: controller) + XCTAssertEqual(userStop.machine.programCounter, calleePoint, "Step Over must still honor an explicit breakpoint inside the call") + XCTAssertEqual(userStop.breakpoints, [NSNumber(value: calleePoint)]) + XCTAssertEqual(userStop.disabledBreakpoints, [0x7001]) + } + } + @MainActor func testSourceStepRejectsEditedMemoryAndStalePausedPCWithoutExecuting() async throws { + let fixture = try await fixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + try await withProcessors(fixture) { controller in + var previous = try await runTo(fixture, controller: controller, marker: "CALL_TRANSFORM") + _ = await command { controller.debuggerWriteMemory(address: 0x7000, data: Data([0x55]), completion: $0) } + var before = await capture(controller) + var rejected = await startSourceStep(0, fixture: fixture, controller: controller, snapshot: previous) + XCTAssertNotNil(rejected.errorMessage, "An explicit memory edit invalidates the captured build connection") + XCTAssertEqual(rejected.state, .paused) + XCTAssertEqual(rejected.cycles, before.machine.cycles) + XCTAssertEqual(rejected.programCounter, before.machine.programCounter) + + previous = try await runTo(fixture, controller: controller, marker: "CALL_TRANSFORM") + _ = await command(controller.debuggerStep) + before = await capture(controller) + rejected = await startSourceStep(1, fixture: fixture, controller: controller, snapshot: previous) + XCTAssertNotNil(rejected.errorMessage, "The worker must check expected PC at the command boundary") + XCTAssertEqual(rejected.state, .paused) + XCTAssertEqual(rejected.cycles, before.machine.cycles) + XCTAssertEqual(rejected.programCounter, before.machine.programCounter) + let after = await capture(controller) + XCTAssertEqual(after.breakpoints, before.breakpoints) + XCTAssertEqual(after.disabledBreakpoints, before.disabledBreakpoints) + } + } + private func evaluator(_ metadata: CMOCVariableDebug, _ snapshot: VCCDebuggerSnapshot) throws -> CMOCWatchEvaluator { + CMOCWatchEvaluator(metadata: metadata, context: .init(pc: snapshot.machine.programCounter, + u: try XCTUnwrap(snapshot.registers["U"]?.uint16Value), + memory: snapshot.logicalMemory, available: snapshot.logicalMemoryAvailable)) + } + private func assertValue(_ expression: String, _ expected: String, in evaluator: CMOCWatchEvaluator, + file: StaticString = #filePath, line: UInt = #line) { + let result = evaluator.evaluate(expression) + XCTAssertNil(result.error, "\(expression): \(result.error ?? "")", file: file, line: line) + XCTAssertEqual(result.value, expected, expression, file: file, line: line) + } + @MainActor func testLiveCompilerVariablesShadowingArraysPointersAndReadOnlyWatchesOnBothCPUs() async throws { + let fixture = try await fixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let metadata = try CMOCVariableDebug.parse(artifact: fixture.artifact, verifiedMap: fixture.map) + XCTAssertTrue(metadata.functions.contains { $0.name == "transform" && $0.frame }) + try await withProcessors(fixture) { controller in + let nested = try await runTo(fixture, controller: controller, marker: "SHADOW_VALUE", file: "helper.c") + let inner = try evaluator(metadata, nested) + assertValue("value", "99", in: inner) + assertValue("local", "12", in: inner) + assertValue("result", "0", in: inner) + assertValue("signedValue", "-1234", in: inner) + assertValue("values[1]", "22", in: inner) + assertValue("*pointer", "22", in: inner) + assertValue("pointer[1]", "33", in: inner) + assertValue("pair.right", "45", in: inner) + assertValue("values[1] + local * 2", "46", in: inner) + XCTAssertEqual(inner.visibleVariables().filter { $0.name == "value" }.count, 1, "Only the innermost shadow is visible") + for expression in ["values[3]", "*ioPointer", "value = 5", "transform(1)", "++local", "1 / 0", "missing"] { + XCTAssertNotNil(inner.evaluate(expression).error, expression) + } + let afterInspection = await capture(controller) + XCTAssertEqual(afterInspection.logicalMemory, nested.logicalMemory, "Watch evaluation cannot write guest memory or read I/O for side effects") + XCTAssertEqual(afterInspection.machine.cycles, nested.machine.cycles) + + let outer = try await sourceStep(0, fixture: fixture, controller: controller) + XCTAssertEqual(fixture.map.location(at: outer.machine.programCounter), + .init(path: "helper.c", line: try fixture.line("OUTER_VALUE", file: "helper.c"))) + let outerValues = try evaluator(metadata, outer) + assertValue("value", "7", in: outerValues) + assertValue("local", "12", in: outerValues) + assertValue("result", "99", in: outerValues) + let returned = try await sourceStep(2, fixture: fixture, controller: controller) + let caller = try evaluator(metadata, returned) + assertValue("mainLocal", "7", in: caller) + XCTAssertNotNil(caller.evaluate("local").error, "A callee's stack local is unavailable after return") + + _ = try await runTo(fixture, controller: controller, marker: "CALL_RECURSE") + var recursive = try await sourceStep(0, fixture: fixture, controller: controller) + let callLine = try fixture.line("RECURSION_CALL", file: "helper.c") + for _ in 0..<12 where fixture.map.location(at: recursive.machine.programCounter)?.line != callLine { + recursive = try await sourceStep(0, fixture: fixture, controller: controller) + } + assertValue("n", "3", in: try evaluator(metadata, recursive)) + assertValue("local", "13", in: try evaluator(metadata, recursive)) + var child = try await sourceStep(0, fixture: fixture, controller: controller) + for _ in 0..<12 where fixture.map.location(at: child.machine.programCounter)?.line != callLine { + child = try await sourceStep(0, fixture: fixture, controller: controller) + } + assertValue("n", "2", in: try evaluator(metadata, child)) + assertValue("local", "12", in: try evaluator(metadata, child)) + let parent = try await sourceStep(2, fixture: fixture, controller: controller) + assertValue("n", "3", in: try evaluator(metadata, parent)) + assertValue("local", "13", in: try evaluator(metadata, parent)) + + let code = try XCTUnwrap(fixture.map.instructions.first) + _ = await command { controller.debuggerWriteMemory(address: code.address, data: Data([code.bytes[0] ^ 1]), completion: $0) } + let changed = await capture(controller) + XCTAssertNotNil(try evaluator(metadata, changed).evaluate("result").error, + "Even apparently valid data must not be reported against changed executable bytes") + } + } +} diff --git a/platforms/macos/Tests/CMOCSourceMapTests.swift b/platforms/macos/Tests/CMOCSourceMapTests.swift new file mode 100644 index 0000000..e954b0c --- /dev/null +++ b/platforms/macos/Tests/CMOCSourceMapTests.swift @@ -0,0 +1,1056 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CMOCSourceMapTests: XCTestCase { + /// Explicit opt-in diagnostic for any retained custom project's immutable + /// build result. No project Makefile is executed and no emulator is loaded. + func testExplicitlySuppliedBankedBuildEvidence() throws { + guard let path = ProcessInfo.processInfo.environment["VCC_TEST_BANKED_ARTIFACT"] else { + throw XCTSkip("Supply a retained banked artifact directory for project qualification.") + } + let directory = URL(fileURLWithPath: path).resolvingSymlinksInPath() + let project = try CMOCProject.open(at: directory) + let files = try CMOCProject.files(in: directory) + let sources = files.filter { CMOCProject.isSource($0.key) && String(data: $0.value, encoding: .utf8) != nil && !$0.value.contains(0) } + let settings = project.configuration + let entry = try XCTUnwrap(sources[settings.entrySource]) + let binaryPath = try XCTUnwrap(settings.binary) + let binary = try XCTUnwrap(files[binaryPath]) + // Compiler source markers retain the original isolated working folder. + // Recover it from a full, retained metadata record rather than assuming + // it is the current output folder or a historical machine path. + var compilationDirectory: URL? + for (name, data) in sources where name.hasSuffix(".s") { + guard let text = String(data: data, encoding: .utf8) else { continue } + for row in text.components(separatedBy: .newlines) { + guard let marker = row.range(of: "* VCCDBG1 "), + let record = try? JSONSerialization.jsonObject(with: Data(row[marker.upperBound...].utf8)) as? [String: Any], + let location = record["location"] as? String, let colon = location.lastIndex(of: ":") else { continue } + let sourcePath = String(location[.. CMOCSourceMap { + try CMOCSourceMap.parse(source: source, sourceName: sourceName, listing: listing, + object: object, objectName: "main.o", linkMap: map, binary: binary) + } + } + private func word(_ n: Int) -> [UInt8] { [UInt8(truncatingIfNeeded: n >> 8), UInt8(truncatingIfNeeded: n)] } + private func cString(_ text: String) -> [UInt8] { Array(text.utf8) + [0] } + private func object(_ sections: [Section]) -> Data { + var result = cString("LWOBJ16") + for section in sections { + result += cString(section.name) + result += section.bssLength == nil ? [0] : [1, 0] + for (name, offset) in section.locals { result += cString(name) + word(offset) } + result += [0] + for (name, offset) in section.exports { result += cString(name) + word(offset) } + result += [0] // export terminator + for (offset, expression) in section.relocations { result += expression + [0] + word(offset) } + result += [0] + word(section.bssLength ?? section.bytes.count) + if section.bssLength == nil { result += section.bytes } + } + return Data(result + [0]) + } + private func binary(_ blocks: [(Int, [UInt8])], entry: Int = 0x2800) -> Data { + var result: [UInt8] = [] + for (address, bytes) in blocks { result += [0] + word(bytes.count) + word(address) + bytes } + return Data(result + [255, 0, 0] + word(entry)) + } + private func row(_ assembly: String, offset: Int? = nil, bytes: [UInt8] = []) -> String { + (offset.map { String(format: "%04X", $0) } ?? " ") + " " + + bytes.map { String(format: "%02X", $0) }.joined().padding(toLength: 16, withPad: " ", startingAt: 0) + + " ( main.s):00123 " + assembly + } + private func fixture() -> Fixture { + // main.o code is at $4200, not the first 'code' section ($2800). + // rodata appears first in the object but after code in final memory. + let relativePrint: [UInt8] = [2] + cString("_print") + [5, 4, 2, 1] + word(3) + [4, 2] + let localString: [UInt8] = [3] + cString("message") + let object = object([ + Section(name: "rodata", bytes: [72, 73, 0], locals: [("message", 0)]), + Section(name: "code", bytes: [0x17, 0, 0, 0x8e, 0, 0, 0x4f, 0x5f, 0x39], + relocations: [(1, relativePrint), (4, localString)]), + Section(name: "bss", bytes: [], bssLength: 4) + ]) + let listing = [row("SECTION rodata"), row("FCB 72,73,0", offset: 0, bytes: [72,73,0]), row("ENDSECTION"), + row("SECTION code"), row("* Line main.c:2: function call: print()"), + row("LBSR _print", offset: 0, bytes: [0x17, 0, 0]), + row("LDX #message", offset: 3, bytes: [0x8e, 0, 0]), + row("* Line main.c:3: return with value"), row("CLRA", offset: 6, bytes: [0x4f]), + row("CLRB", offset: 7, bytes: [0x5f]), row("RTS", offset: 8, bytes: [0x39]), row("ENDSECTION")] + return Fixture(listing: Data(listing.joined(separator: "\n").utf8), object: object, + map: Data(""" + Section: code (crt.o) load at 2800, length 0001 + Section: code (main.o) load at 4200, length 0009 + Section: bss (main.o) load at 4400, length 0004 + Section: rodata (main.o) load at 4300, length 0003 + Symbol: _print (crt.o) = 2800 + """.utf8), + binary: binary([(0x2800, [0x39]), (0x4200, [0x17, 0xe5, 0xfd, 0x8e, 0x43, 0, 0x4f, 0x5f, 0x39]), (0x4300, [72,73,0])])) + } + + func testObjectAndSectionAwareMappingUsesFinalRelocatedBytes() throws { + let result = try fixture().parse() + XCTAssertEqual(result.executableLines, [2, 3]) + XCTAssertEqual(result.addresses(forLine: 2), [0x4200, 0x4203]) + XCTAssertEqual(result.addresses(forLine: 3), [0x4206, 0x4207, 0x4208]) + XCTAssertEqual(result.instructions[0].bytes, [0x17, 0xe5, 0xfd]) + XCTAssertEqual(result.instructions[1].bytes, [0x8e, 0x43, 0x00]) + XCTAssertEqual(result.line(at: 0x4200), 2) + XCTAssertNil(result.line(at: 0x4201), "An operand byte is never a source breakpoint") + XCTAssertNil(result.line(at: 0x2800), "Runtime objects never acquire the user's source location") + XCTAssertNil(result.line(at: 0x4300), "Read-only data is not executable C") + XCTAssertEqual(result.entryPoint, 0x2800) + } + + func testBankedManifestVerifiesRelocatedImagesAndKeepsOverlappingPCsDistinct() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let source = Data("void first(void) {}\nvoid second(void) {}\n".utf8) + let object = object([ + Section(name: "first", bytes: [0x8e, 0, 0, 0x12], relocations: [(1, [2] + cString("_target"))]), + Section(name: "second", bytes: [0x39]) + ]) + let listing = Data([ + row("SECTION first"), row("* Line main.c:1"), row("LDX #_target", offset: 0, bytes: [0x8e, 0, 0]), row("ENDSECTION"), + row("SECTION second"), row("* Line main.c:2"), row("RTS", offset: 0, bytes: [0x39]), row("ENDSECTION") + ].joined(separator: "\n").utf8) + let map = Data("Section: first (main.o) load at 4000, length 0004\nSection: second (main.o) load at 4000, length 0001\nSymbol: _target (runtime.o) = 1234\n".utf8) + let packed = binary([(0x0e00, [0x12])], entry: 0x0e00) + var files = ["game.bin": packed, "game.map": map, "main.o": object, "main.lst": listing, + "first.raw": Data([0x8e, 0x12, 0x34, 0x12, 0]), "second.raw": Data([0x39])] + func manifest(secondPage: Int = 5) throws -> Data { + let value: [String: Any] = [ + "version": 1, "entryPoint": 0x0e00, + "binary": ["path": "game.bin", "sha256": CMOCSourceMap.sha256(packed)], + "linkMap": ["path": "game.map", "sha256": CMOCSourceMap.sha256(map)], + "sources": ["main.c": CMOCSourceMap.sha256(source)], + "artifacts": files.filter { $0.key != "game.bin" && $0.key != "game.map" }.mapValues(CMOCSourceMap.sha256), + "modules": [ + ["id": "first", "sections": ["first"], "codeSections": ["first"], "image": ["path": "first.raw", "logicalAddress": 0x4000], "pages": [["logicalPage": 2, "physicalPage": 4]]], + ["id": "second", "sections": ["second"], "codeSections": ["second"], "image": ["path": "second.raw", "logicalAddress": 0x4000], "pages": [["logicalPage": 2, "physicalPage": secondPage]]] + ] + ] + return try JSONSerialization.data(withJSONObject: value) + } + func layout(_ data: Data) throws -> CMOCBankedDebugLayout { + for (path, data) in files { try data.write(to: directory.appendingPathComponent(path)) } + return try CMOCBankedDebugLayout.parse(data: data, directory: directory, sources: ["main.c": source], + binary: packed, binaryPath: "game.bin", allowedOutputs: Array(files.keys)) + } + let verified = try layout(manifest()) + XCTAssertEqual(verified.modules[0].codeGuards, [.init(address: 0x4000, bytes: [0x8e, 0x12, 0x34, 0x12])]) + let units = [CMOCProjectSourceMap.TranslationUnit(sourcePath: "main.c", sourceName: "main.c", objectName: "main.o", listing: listing, object: object)] + let result = try CMOCProjectSourceMap.parse(sources: ["main.c": source], compilationDirectory: directory, + units: units, linkMap: map, binary: packed, bankedLayout: verified) + XCTAssertEqual(result.instructions.count, 2) + XCTAssertEqual(Set(result.instructions.compactMap(\.moduleID)), ["first", "second"]) + XCTAssertEqual(Set(result.instructions.compactMap(\.physicalAddress)), [UInt32(4 * 8192), UInt32(5 * 8192)]) + XCTAssertNil(result.location(at: 0x4000), "An unselected overlay PC must remain ambiguous") + XCTAssertEqual(result.projected(physicalPages: [2: 4]).location(at: 0x4000)?.line, 1) + XCTAssertEqual(result.projected(physicalPages: [2: 5]).location(at: 0x4000)?.line, 2) + XCTAssertTrue(result.projected(physicalPages: [2: 6]).instructions.isEmpty) + let activeMap = result.projected(physicalPages: [2: 4]) + var memory = Data(repeating: 0, count: 65536), available = Data(repeating: 1, count: 65536) + memory.replaceSubrange(0x4000..<0x4004, with: [0x8e,0x12,0x34,0x12]); memory[0x5001] = 7 + XCTAssertTrue(activeMap.verifiesRuntime(memory: memory, available: available)) + XCTAssertFalse(result.verifiesRuntime(memory: memory, available: available), "Banked runtime checks require an explicit physical projection") + let metadata = CMOCVariableDebug(functions: [.init(name: "first", sourcePath: "main.c", entry: 0x4000, + body: 0x4000, end: 0x4004, frame: false, moduleID: "first")], variables: [ + .init(name: "score", sourcePath: "main.c", line: 1, type: .integer, address: 0x5000, + offset: nil, scope: nil, isStatic: false, moduleID: "first")], sourceMap: activeMap) + func watch(_ data: Data) -> CMOCWatchEvaluator.Value { + CMOCWatchEvaluator(metadata: metadata, context: .init(pc: 0x4000, u: 0x6000, memory: data, available: available)).evaluate("score") + } + XCTAssertEqual(watch(memory).value, "7") + memory[0x4003] = 0x39 // Assembly-only tail, outside the sole C instruction. + XCTAssertFalse(activeMap.verifiesRuntime(memory: memory, available: available)) + XCTAssertNotNil(watch(memory).error, "A matching C opcode cannot conceal changed unmapped assembly") + let stack = CMOCCallStack.capture(metadata: metadata, pc: 0x4000, u: 0x6000, s: 0x6000, memory: memory, available: available) + XCTAssertTrue(stack.frames.isEmpty); XCTAssertTrue(stack.termination.contains("Executable bytes changed")) + memory[0x4003] = 0x12; available[0x4003] = 0 + XCTAssertFalse(activeMap.verifiesRuntime(memory: memory, available: available), "Unavailable assembly bytes cannot establish source identity") + let extended = try layout(manifest(secondPage: 300)) + var extendedPages = Array(repeating: 0, count: 8); extendedPages[2] = 300 + XCTAssertTrue(extended.modules[1].isMapped(physicalPages: extendedPages)) + XCTAssertEqual(extended.modules[1].physicalAddress(0x4000), UInt32(300 * 8192), + "8 MiB RAM pages must retain identity above the 8-bit page range") + XCTAssertThrowsError(try layout(manifest(secondPage: 1024)), "Pages outside the largest supported RAM capacity are rejected") + let emptySections = self.object([ + Section(name: "first", bytes: [0x39], locals: [("_first", 0)]), + Section(name: "bss", bytes: [], bssLength: 0), Section(name: "data", bytes: []) + ]) + XCTAssertEqual(try CMOCSourceMap.resolvedObjectSymbolModules(object: emptySections, layout: verified), ["_first": "first"], + "Empty default sections without debug symbols must not suppress all metadata") + for missingBSS in [Section(name: "bss", bytes: [], bssLength: 2), + Section(name: "bss", bytes: [], locals: [("_end", 0)], bssLength: 0)] { + XCTAssertThrowsError(try CMOCSourceMap.resolvedObjectSymbolModules( + object: self.object([missingBSS]), layout: verified), + "Real storage and debug labels still require explicit module ownership") + } + let validManifest = try manifest() + func changed(_ mutation: (inout [String: Any]) -> Void) throws -> Data { + var json = try XCTUnwrap(JSONSerialization.jsonObject(with: validManifest) as? [String: Any]) + mutation(&json) + return try JSONSerialization.data(withJSONObject: json) + } + func bssManifest(address: Int, extraPage: Int? = nil) throws -> Data { + let bssMap = Data((String(data: map, encoding: .utf8)! + String(format: "Section: bss (main.o) load at %04X, length 0001\n", address)).utf8) + files["game.map"] = bssMap + return try changed { value in + value["linkMap"] = ["path": "game.map", "sha256": CMOCSourceMap.sha256(bssMap)] + var modules = value["modules"] as! [[String: Any]] + modules[0]["sections"] = ["first", "bss"] + if let extraPage { modules[0]["pages"] = [["logicalPage": 2, "physicalPage": 4], ["logicalPage": 3, "physicalPage": extraPage]] } + value["modules"] = modules + } + } + XCTAssertNoThrow(try layout(bssManifest(address: 0x4004)), "An image's zero padding may cover its own BSS") + XCTAssertThrowsError(try layout(bssManifest(address: 0x6000, extraPage: 5)), "BSS must not alias another module's physical image") + files["game.map"] = map + XCTAssertThrowsError(try layout(changed { $0["sources"] = ["main.c": String(repeating: "0", count: 64)] })) + XCTAssertThrowsError(try layout(changed { $0["binary"] = ["path": "game.bin", "sha256": String(repeating: "0", count: 64)] })) + XCTAssertThrowsError(try layout(changed { $0["artifacts"] = ["../outside.o": CMOCSourceMap.sha256(object)] })) + XCTAssertThrowsError(try layout(changed { $0["disk"] = ["path": "unrelated.dsk", "sha256": CMOCSourceMap.sha256(packed)] })) + XCTAssertThrowsError(try layout(changed { $0["version"] = 2 })) + XCTAssertThrowsError(try layout(Data(repeating: 32, count: 1024 * 1024 + 1))) + try FileManager.default.removeItem(at: directory.appendingPathComponent("second.raw")) + try FileManager.default.createSymbolicLink(at: directory.appendingPathComponent("second.raw"), withDestinationURL: directory.appendingPathComponent("first.raw")) + XCTAssertThrowsError(try CMOCBankedDebugLayout.parse(data: validManifest, directory: directory, sources: ["main.c": source], + binary: packed, binaryPath: "game.bin", allowedOutputs: Array(files.keys))) + try FileManager.default.removeItem(at: directory.appendingPathComponent("second.raw")) + XCTAssertThrowsError(try layout(manifest(secondPage: 4)), "Logical overlap requires different physical banks") + files["first.raw"] = Data([0x8e, 0x12, 0x35, 0x12, 0]) + let stale = try layout(manifest()) // A new hash alone cannot bless a wrong relocation operand. + XCTAssertThrowsError(try CMOCProjectSourceMap.parse(sources: ["main.c": source], compilationDirectory: directory, + units: units, linkMap: map, binary: packed, bankedLayout: stale)) + } + func testPureBSSModuleNeedsNoInventedImageAndKeepsVerifiedGlobalPlacement() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCPureBSS-" + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let source = Data("int pilot;\nvoid main(void) {}\n".utf8) + let code = Section(name: "code", bytes: [0x12], locals: [("_main", 0), ("body", 0), ("end", 1)]) + let bss = Section(name: "bss", bytes: [], locals: [("_pilot", 0)], bssLength: 2) + var currentObject = object([code, bss]) + let records: [[String: Any]] = [ + ["kind": "function", "name": "main", "location": "main.c:2", "symbol": "_main", "begin": "body", "end": "end", "frame": false], + ["kind": "variable", "name": "pilot", "location": "main.c:1", "symbol": "_pilot", "begin": "", "end": "", "static": false, + "type": ["name": "int", "kind": "integer", "size": 2, "signed": true]] + ] + let listing = try Data(([ + row("SECTION code"), row("* Line main.c:2"), row("NOP", offset: 0, bytes: [0x12]), row("ENDSECTION") + ] + records.map { row("* VCCDBG1 " + String(decoding: try JSONSerialization.data(withJSONObject: $0), as: UTF8.self)) }).joined(separator: "\n").utf8) + let map = Data("Section: code (main.o) load at 4000, length 0001\nSection: bss (main.o) load at 8000, length 0002\nSymbol: _main (main.o) = 4000\nSymbol: body (main.o) = 4000\nSymbol: end (main.o) = 4001\nSymbol: _pilot (main.o) = 8000\n".utf8) + let packed = binary([(0x0e00, [0x12])], entry: 0x0e00) + let image = Data([0x12]) + let defaultModules: [[String: Any]] = [ + ["id": "resident", "sections": ["code"], "codeSections": ["code"], "image": ["path": "code.raw", "logicalAddress": 0x4000], + "pages": [["logicalPage": 2, "physicalPage": 4]]], + ["id": "state", "sections": ["bss"], "codeSections": [], "pages": [["logicalPage": 4, "physicalPage": 10]]] + ] + func layout(modules: [[String: Any]]? = nil) throws -> CMOCBankedDebugLayout { + let files = ["game.bin": packed, "game.map": map, "main.o": currentObject, "main.lst": listing, "code.raw": image] + for (name, data) in files { try data.write(to: directory.appendingPathComponent(name)) } + let manifest: [String: Any] = [ + "version": 1, "entryPoint": 0x0e00, + "binary": ["path": "game.bin", "sha256": CMOCSourceMap.sha256(packed)], + "linkMap": ["path": "game.map", "sha256": CMOCSourceMap.sha256(map)], + "sources": ["main.c": CMOCSourceMap.sha256(source)], + "artifacts": files.filter { !["game.bin", "game.map"].contains($0.key) }.mapValues(CMOCSourceMap.sha256), + "modules": modules ?? defaultModules + ] + return try CMOCBankedDebugLayout.parse(data: JSONSerialization.data(withJSONObject: manifest), directory: directory, + sources: ["main.c": source], binary: packed, binaryPath: "game.bin", allowedOutputs: Array(files.keys)) + } + func sourceMap(_ layout: CMOCBankedDebugLayout) throws -> CMOCProjectSourceMap { + try CMOCProjectSourceMap.parse(sources: ["main.c": source], compilationDirectory: directory, + units: [.init(sourcePath: "main.c", sourceName: "main.c", objectName: "main.o", listing: listing, object: currentObject)], + linkMap: map, binary: packed, bankedLayout: layout) + } + let verified = try layout() + let state = try XCTUnwrap(verified.module(id: "state")) + XCTAssertTrue(state.bytes.isEmpty) + XCTAssertTrue(state.codeGuards.isEmpty) + XCTAssertEqual(state.logicalAddress, 0x8000) + XCTAssertEqual(state.physicalAddress(0x8001), UInt32(10 * 8192 + 1)) + let mapped = try sourceMap(verified) + let artifact = CMOCBuildArtifact(id: UUID(), directory: directory, source: String(decoding: source, as: UTF8.self), + sourceData: source, sourceSHA256: CMOCSourceMap.sha256(source), binaryData: packed, buildLog: "", binaryRelativePath: "game.bin") + let metadata = try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: mapped) + var memory = Data(repeating: 0, count: 65536) + let available = Data(repeating: 1, count: 65536) + memory[0x4000] = 0x12; memory[0x8000] = 0x12; memory[0x8001] = 0x34 + let projected = metadata.projected(physicalPages: [2: 4, 4: 10], memory: memory, available: available) + XCTAssertEqual(projected.variables.map(\.name), ["pilot"]) + let evaluator = CMOCWatchEvaluator(metadata: projected, context: .init(pc: 0x4000, u: 0x7000, memory: memory, available: available)) + XCTAssertEqual(evaluator.evaluate("pilot").value, "4660") + XCTAssertTrue(metadata.projected(physicalPages: [2: 4, 4: 11], memory: memory, available: available).variables.isEmpty, + "Uninitialized storage still requires its exact physical bank") + + var missingCodeImage = defaultModules + missingCodeImage[0].removeValue(forKey: "image") + XCTAssertThrowsError(try layout(modules: missingCodeImage)) { error in + XCTAssertTrue(error.localizedDescription.contains("codeSections require a module image")) + } + var overflowingOffset = defaultModules + overflowingOffset[0]["image"] = ["path": "code.raw", "logicalAddress": 0x4000, "offset": Int.min] + XCTAssertThrowsError(try layout(modules: overflowingOffset), "Validate offsets before computing an inferred image length") + var alias = defaultModules + alias[1]["pages"] = [["logicalPage": 4, "physicalPage": 4]] + XCTAssertThrowsError(try layout(modules: alias), "Pure BSS must not alias another module's physical code") + var missingPage = defaultModules + missingPage[1]["pages"] = [["logicalPage": 5, "physicalPage": 10]] + XCTAssertThrowsError(try layout(modules: missingPage), "Omitting the real storage page cannot invent BSS identity") + + currentObject = object([code, Section(name: "bss", bytes: [0, 7], locals: [("_pilot", 0)])]) + let undeclaredInitializedImage = try layout() + XCTAssertThrowsError(try sourceMap(undeclaredInitializedImage), + "An initialized object section cannot borrow the no-image BSS declaration") { error in + XCTAssertTrue(error.localizedDescription.contains("bytes do not match")) + } + } + + private func sourceOnlySymbols(aliasCollision: Bool = false, duplicateName: Bool = false, + forgedMapAddress: Bool = false) throws -> CMOCProjectSourceMap { + let source = Data("/* Assembly-backed build without compiler type comments. */\n".utf8) + let residentBytes: [UInt8] = [0x12, 0x12, 0x39], overlayBytes: [UInt8] = [0x86, 9, 0x39] + var residentNames = [("_sample", 0), ("resident_after", 1), ("L0001", 1), (".vcc.debug.L0003", 1), + ("L0002", 2), ("_code_end", 3), ("_missing_map", 0), + ("funcend_sample", 1), ("funcsize_sample", 2), ("funcsize_main", 1), + ("funcend_explicit_asm", 1), ("funcsize_explicit_asm", 2)] + if aliasCollision { residentNames.append(("sample", 1)) } + if duplicateName { residentNames.append(("_shared", 0)) } + var overlayNames = [("_other", 0)] + if duplicateName { overlayNames.append(("_shared", 0)) } + let resident = object([ + Section(name: "resident", bytes: residentBytes, locals: residentNames, + exports: [("L0002", 2), ("funcend_explicit_asm", 1), ("funcsize_explicit_asm", 2)]), + Section(name: "bss", bytes: [], locals: [("_counter", 0)], bssLength: 2), + Section(name: "rodata", bytes: [5, 7], locals: [("_data_entry", 0)]) + ]) + let overlay = object([Section(name: "overlay", bytes: overlayBytes, locals: overlayNames)]) + var mapRows = ["Section: resident (resident.o) load at 4000, length 0003", + "Section: bss (resident.o) load at 6000, length 0002", + "Section: rodata (resident.o) load at 6002, length 0002", + "Section: overlay (overlay.o) load at 4000, length 0003"] + for (name, offset) in residentNames where name != "_missing_map" { + let address = forgedMapAddress && name == "_sample" ? 0x4001 : 0x4000 + offset + mapRows.append(String(format: "Symbol: %@ (resident.o) = %04X", name, address)) + } + for (name, offset) in overlayNames { mapRows.append(String(format: "Symbol: %@ (overlay.o) = %04X", name, 0x4000 + offset)) } + mapRows += ["Symbol: _counter (resident.o) = 6000", "Symbol: _data_entry (resident.o) = 6002", "Symbol: _forged (resident.o) = 4000"] + let mapData = Data(mapRows.joined(separator: "\n").utf8) + let packed = binary([(0x0e00, [0x12])], entry: 0x0e00) + let layout = CMOCBankedDebugLayout(entryPoint: 0x0e00, binarySHA256: CMOCSourceMap.sha256(packed), linkMap: mapData, + sourceHashes: ["main.c": CMOCSourceMap.sha256(source)], + artifactHashes: ["resident.o": CMOCSourceMap.sha256(resident), "overlay.o": CMOCSourceMap.sha256(overlay)], modules: [ + .init(id: "resident", sections: ["resident"], codeSections: ["resident"], logicalAddress: 0x4000, + bytes: residentBytes, pages: [.init(logicalPage: 2, physicalPage: 4)], codeGuards: [.init(address: 0x4000, bytes: residentBytes)]), + .init(id: "overlay", sections: ["overlay"], codeSections: ["overlay"], logicalAddress: 0x4000, + bytes: overlayBytes, pages: [.init(logicalPage: 2, physicalPage: 5)], codeGuards: [.init(address: 0x4000, bytes: overlayBytes)]), + .init(id: "state", sections: ["bss", "rodata"], codeSections: [], logicalAddress: 0x6002, + bytes: [5, 7], pages: [.init(logicalPage: 3, physicalPage: 6)], codeGuards: []) + ]) + return try CMOCProjectSourceMap.parse(sources: ["main.c": source], compilationDirectory: FileManager.default.temporaryDirectory, + units: [.init(sourcePath: "main.c", sourceName: "main.c", objectName: "resident.o", listing: Data(), object: resident), + .init(sourcePath: "main.c", sourceName: "main.c", objectName: "overlay.o", listing: Data(), object: overlay)], + linkMap: mapData, binary: packed, bankedLayout: layout) + } + + func testSourceOnlyExecutableSymbolsDoNotRequireOrInventTypedMetadata() throws { + let map = try sourceOnlySymbols() + XCTAssertTrue(map.instructions.isEmpty, "Executable symbols do not create C source locations") + let sample = try XCTUnwrap(map.executableSymbol(named: "sample")) + XCTAssertEqual(sample.name, "_sample") + XCTAssertEqual(sample.address, 0x4000); XCTAssertEqual(sample.moduleID, "resident") + XCTAssertEqual(sample.objectPath, "resident.o"); XCTAssertEqual(sample.sectionName, "resident") + XCTAssertEqual(sample.physicalAddress, UInt32(4 * 8192)) + XCTAssertTrue(sample.sourcePaths.isEmpty, "An assembler object without C markers does not acquire a fabricated source declaration") + XCTAssertEqual(map.executableSymbol(named: "_sample"), sample) + XCTAssertTrue(map.executableSymbolNames.contains("sample")) + XCTAssertTrue(map.executableSymbolNames.contains("L0002"), "Explicitly exported assembly labels remain selectable") + XCTAssertNotNil(map.executableSymbol(named: "funcend_explicit_asm")) + XCTAssertNotNil(map.executableSymbol(named: "funcsize_explicit_asm")) + for unavailable in ["_counter", "counter", "_data_entry", "_code_end", "_forged", "_missing_map", "L0001", ".vcc.debug.L0003", + "funcend_sample", "funcsize_sample", "funcsize_main"] { + XCTAssertNil(map.executableSymbol(named: unavailable), unavailable) + } + let source = Data("/* Assembly-backed build without compiler type comments. */\n".utf8) + let artifact = CMOCBuildArtifact(id: UUID(), directory: FileManager.default.temporaryDirectory, + source: String(decoding: source, as: UTF8.self), sourceData: source, sourceSHA256: CMOCSourceMap.sha256(source), + binaryData: binary([(0x0e00, [0x12])], entry: 0x0e00), buildLog: "") + XCTAssertThrowsError(try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map), + "Unavailable VCCDBG1 types must not erase the separately verified executable map") + var memory = Data(repeating: 0, count: 65536), available = Data(repeating: 1, count: 65536) + memory.replaceSubrange(0x4000..<0x4003, with: [0x12, 0x12, 0x39]) + XCTAssertNil(map.executableLocation(at: 0x4000, memory: memory, available: available), "An unprojected PC is not a runtime claim") + let active = map.projected(physicalPages: [2: 4, 3: 6], memory: memory, available: available) + XCTAssertEqual(active.executableSymbol(named: "sample"), sample) + XCTAssertNil(active.executableSymbol(named: "other")) + let location = try XCTUnwrap(active.executableLocation(at: 0x4001, memory: memory, available: available)) + XCTAssertEqual(location.moduleID, "resident"); XCTAssertEqual(location.physicalAddress, UInt32(4 * 8192 + 1)) + XCTAssertEqual(location.codeRange, 0x4000..<0x4003) + XCTAssertNil(active.instruction(at: 0x4001)); XCTAssertNil(active.location(at: 0x4001)) + XCTAssertEqual(active.executableCodeRanges, [0x4000..<0x4003]) + XCTAssertNil(active.executableLocation(at: 0x6000, memory: memory, available: available), "BSS is not executable") + XCTAssertNil(active.executableLocation(at: 0xfe00, memory: memory, available: available)) + let wrong = map.projected(physicalPages: [2: 7, 3: 6], memory: memory, available: available) + XCTAssertTrue(wrong.executableSymbols.isEmpty) + XCTAssertNil(wrong.executableLocation(at: 0x4001, memory: memory, available: available)) + memory[0x4002] = 0x12 + XCTAssertNil(active.executableLocation(at: 0x4000, memory: memory, available: available), "A changed assembly tail invalidates a previously selected module") + XCTAssertTrue(map.projected(physicalPages: [2: 4, 3: 6], memory: memory, available: available).executableSymbols.isEmpty) + memory[0x4002] = 0x39; available[0x4002] = 0 + XCTAssertNil(active.executableLocation(at: 0x4000, memory: memory, available: available)) + } + + func testPublicSymbolCatalogUsesEncodedJSONBudgetWithoutTruncatingPrivateSelection() throws { + var map = try sourceOnlySymbols() + let original = try XCTUnwrap(map.executableSymbol(named: "sample")) + map.executableSymbols = (0..<200).map { index in + .init(name: "entry_" + String(index) + String(repeating: "x", count: 1000), objectPath: original.objectPath, + sectionName: original.sectionName, address: original.address, moduleID: original.moduleID, + physicalAddress: original.physicalAddress) + } + let names = map.executableSymbolNames + let publicNames = CMOCSourceMap.boundedJSONCatalog(names) + XCTAssertEqual(publicNames.total, 200); XCTAssertTrue(publicNames.truncated) + XCTAssertGreaterThan(publicNames.items.count, 0) + XCTAssertLessThanOrEqual(try JSONSerialization.data(withJSONObject: publicNames.items).count, 32 * 1024) + let last = try XCTUnwrap(names.last) + XCTAssertFalse(publicNames.items.contains(last)) + XCTAssertNotNil(map.executableSymbol(named: last), "Wire limits must never silently remove private verified selectors") + + // Quoting, backslashes and control characters must count as encoded + // bytes, including when advertising dictionaries at a shared PC. + let rows = (0..<100).map { ["name": String($0) + String(repeating: "\"\\\n", count: 30), "object_path": "obj/main.o"] } + let bounded = CMOCSourceMap.boundedJSONCatalog(rows, maximumBytes: 2048) + XCTAssertEqual(bounded.total, rows.count); XCTAssertTrue(bounded.truncated) + XCTAssertLessThanOrEqual(try JSONSerialization.data(withJSONObject: bounded.items).count, 2048) + XCTAssertEqual(bounded.items, Array(rows.prefix(bounded.items.count))) + let tiny = CMOCSourceMap.boundedJSONCatalog(["oversized"], maximumBytes: 2) + XCTAssertTrue(tiny.items.isEmpty); XCTAssertTrue(tiny.truncated) + let complete = CMOCSourceMap.boundedJSONCatalog(["one", "two"], maximumBytes: 100) + XCTAssertFalse(complete.truncated); XCTAssertEqual(complete.total, 2) + } + + func testSourceOnlyMemoryAndStopRequireKnownSharedContributingSources() throws { + var map = try sourceOnlySymbols() + var memory = Data(repeating: 0, count: 65536) + let available = Data(repeating: 1, count: 65536) + memory.replaceSubrange(0x4000..<0x4003, with: [0x12, 0x12, 0x39]) + let unknown = map.projected(physicalPages: [2: 4, 3: 6], memory: memory, available: available) + XCTAssertTrue(unknown.executableCodeRanges(sharedPaths: ["main.c"]).isEmpty) + XCTAssertNil(unknown.executableLocation(at: 0x4001, memory: memory, available: available, sharedPaths: ["main.c"]), + "An unknown source association must not become shared executable memory") + let sampleIndex = try XCTUnwrap(map.executableSymbols.firstIndex(where: { $0.name == "_sample" })) + map.executableSymbols[sampleIndex].sourcePaths = ["main.c"] + let active = map.projected(physicalPages: [2: 4, 3: 6], memory: memory, available: available) + XCTAssertEqual(active.sharedExecutableModuleIDs(paths: ["main.c"]), ["resident"]) + XCTAssertEqual(active.executableCodeRanges(sharedPaths: ["main.c"]), [0x4000..<0x4003]) + XCTAssertNotNil(active.executableLocation(at: 0x4001, memory: memory, available: available, sharedPaths: ["main.c"])) + XCTAssertTrue(active.executableCodeRanges(sharedPaths: ["unshared.c"]).isEmpty) + XCTAssertNil(active.executableLocation(at: 0x4001, memory: memory, available: available, sharedPaths: ["unshared.c"])) + memory.replaceSubrange(0x4000..<0x4003, with: [0x86, 9, 0x39]) + let overlay = map.projected(physicalPages: [2: 5, 3: 6], memory: memory, available: available) + XCTAssertTrue(overlay.executableCodeRanges(sharedPaths: ["main.c"]).isEmpty, + "Resident source evidence does not grant an overlapping unknown overlay") + XCTAssertNil(overlay.executableLocation(at: 0x4001, memory: memory, available: available, sharedPaths: ["main.c"])) + } + + func testSourceOnlySymbolAliasesAmbiguityAndMapAddressMustBeHonest() throws { + let aliases = try sourceOnlySymbols(aliasCollision: true) + XCTAssertNil(aliases.executableSymbol(named: "sample"), "A raw name and another symbol's C alias cannot select an arbitrary address") + XCTAssertFalse(aliases.executableSymbolNames.contains("sample")) + XCTAssertNotNil(aliases.executableSymbol(named: "_sample")) + let duplicate = try sourceOnlySymbols(duplicateName: true) + XCTAssertNil(duplicate.executableSymbol(named: "shared")); XCTAssertNil(duplicate.executableSymbol(named: "_shared")) + var memory = Data(repeating: 0, count: 65536) + memory.replaceSubrange(0x4000..<0x4003, with: [0x12, 0x12, 0x39]) + let active = duplicate.projected(physicalPages: [2: 4, 3: 6], memory: memory, available: Data(repeating: 1, count: 65536)) + XCTAssertEqual(active.executableSymbol(named: "shared")?.moduleID, "resident") + XCTAssertNil(try sourceOnlySymbols(forgedMapAddress: true).executableSymbol(named: "sample"), "An object symbol must agree with its own map record") + let flat = CMOCProjectSourceMap(entryPoint: 0x4000, binarySHA256: "", sourceHashes: [:], + instructions: [.init(sourcePath: "main.c", sourceLine: 1, address: 0x4000, bytes: [0x12], assembly: "NOP")], + objectHashes: [:], listingHashes: [:], linkMapSHA256: "") + XCTAssertTrue(flat.executableSymbolNames.isEmpty) + XCTAssertNil(flat.executableLocation(at: 0x4000, memory: memory, available: Data(repeating: 1, count: 65536))) + XCTAssertEqual(flat.instruction(at: 0x4000)?.sourceLine, 1, "Ordinary flat C stops retain their prior behavior") + } + + func testRuntimeBankProjectionWaitsForCompleteModuleInstallation() { + let first = CMOCBankedDebugLayout.Module(id: "first", sections: ["first"], codeSections: ["first"], + logicalAddress: 0x4000, bytes: [0x12,0x12], pages: [.init(logicalPage: 2, physicalPage: 4)], + codeGuards: [.init(address: 0x4000, bytes: [0x12,0x12])]) + let pending = CMOCBankedDebugLayout.Module(id: "pending", sections: ["pending"], codeSections: ["pending"], + logicalAddress: 0x6000, bytes: [0x39], pages: [.init(logicalPage: 3, physicalPage: 6)], + codeGuards: [.init(address: 0x6000, bytes: [0x39])]) + let data = CMOCBankedDebugLayout.Module(id: "data", sections: ["bss"], codeSections: [], + logicalAddress: 0x5000, bytes: [0], pages: [.init(logicalPage: 2, physicalPage: 4)], codeGuards: []) + let layout = CMOCBankedDebugLayout(entryPoint: 0x4000, binarySHA256: "", linkMap: Data(), + sourceHashes: [:], artifactHashes: [:], modules: [first,pending,data]) + let map = CMOCProjectSourceMap(entryPoint: 0x4000, binarySHA256: "", sourceHashes: [:], instructions: [ + .init(sourcePath: "first.c", sourceLine: 1, address: 0x4000, bytes: [0x12], assembly: "NOP", moduleID: "first"), + .init(sourcePath: "pending.c", sourceLine: 1, address: 0x6000, bytes: [0x39], assembly: "RTS", moduleID: "pending") + ], objectHashes: [:], listingHashes: [:], linkMapSHA256: "", bankedLayout: layout) + let metadata = CMOCVariableDebug(functions: [], variables: [ + .init(name: "score", sourcePath: "first.c", line: 1, type: .integer, address: 0x5000, offset: nil, + scope: nil, isStatic: false, moduleID: "data"), + .init(name: "pendingLocal", sourcePath: "pending.c", line: 1, type: .integer, address: nil, offset: -2, + scope: 0x6000..<0x6001, isStatic: false, moduleID: "pending", scopeModuleID: "pending") + ], sourceMap: map) + var memory = Data(repeating: 0, count: 65536) + let available = Data(repeating: 1, count: 65536), pages = [2: 4, 3: 6] + memory[0x4000] = 0x12; memory[0x4001] = 0x12 + let active = map.projected(physicalPages: pages, memory: memory, available: available) + XCTAssertEqual(active.activeModuleIDs, Set(["first","data"])) + XCTAssertEqual(active.location(at: 0x4000)?.path, "first.c"); XCTAssertNil(active.location(at: 0x6000)) + XCTAssertTrue(active.verifiesRuntime(memory: memory, available: available), "A mapped but not installed overlay must not block a valid current module") + XCTAssertEqual(metadata.projected(physicalPages: pages, memory: memory, available: available).variables.map(\.name), ["score"], + "Mapped data remains inspectable while not-yet-installed code contributes no locals") + memory[0x6000] = 0x39 + XCTAssertEqual(map.projected(physicalPages: pages, memory: memory, available: available).location(at: 0x6000)?.path, "pending.c") + memory[0x4001] = 0x39 + let changed = map.projected(physicalPages: pages, memory: memory, available: available) + XCTAssertNil(changed.location(at: 0x4000), "Changing an unmapped assembly tail removes the current module's C claim") + XCTAssertEqual(changed.location(at: 0x6000)?.path, "pending.c", "Other complete installed modules retain their identity") + } + func testStaleExecutableAndRelocationOperandsAreRejected() { + for byteIndex in [11, 12, 15, 25] { // opcode, relocated call, relocated data, literal data + var input = fixture() + input.binary[byteIndex] ^= 1 + XCTAssertThrowsError(try input.parse()) + } + } + func testListingMustMatchOriginalObjectBeforeRelocation() { + var input = fixture() + input.listing = Data(String(decoding: input.listing, as: UTF8.self).replacingOccurrences(of: "170000", with: "170001").utf8) + XCTAssertThrowsError(try input.parse()) + } + func testMissingAndAmbiguousObjectsAndSectionsAreRejected() { + let replacements = [ + ("(main.o)", "(missing.o)"), + ("Section: bss (main.o)", "Section: bss (other/main.o)"), + ("load at 4200, length 0009", "load at 4200, length 0008"), + ("Section: bss (main.o)", "Section: code (main.o)") + ] + for (before, after) in replacements { + var input = fixture() + input.map = Data(String(decoding: input.map, as: UTF8.self).replacingOccurrences(of: before, with: after).utf8) + XCTAssertThrowsError(try input.parse(), before) + } + } + func testUnresolvedAndAmbiguousExternalSymbolsAreRejected() { + var input = fixture() + input.map = Data(String(decoding: input.map, as: UTF8.self).replacingOccurrences(of: "Symbol: _print", with: "Symbol: _other").utf8) + XCTAssertThrowsError(try input.parse()) + input = fixture() + input.map.append(Data("\nSymbol: _print (other.o) = 2800\n".utf8)) + XCTAssertThrowsError(try input.parse(), "Even duplicate symbols with equal values are ambiguous") + } + func testOnlyExactSourceIdentityAndValidLinesAreMapped() throws { + for replacement in ["other/main.c:2", "main.c:999"] { + var input = fixture() + input.listing = Data(String(decoding: input.listing, as: UTF8.self).replacingOccurrences(of: "main.c:2", with: replacement).replacingOccurrences(of: "main.c:3", with: replacement).utf8) + XCTAssertThrowsError(try input.parse()) + } + var input = fixture() + input.listing = Data(String(decoding: input.listing, as: UTF8.self).replacingOccurrences(of: "main.c:", with: "./main.c:").utf8) + XCTAssertEqual(try input.parse().addresses(forLine: 2), [0x4200, 0x4203]) + } + func testEquatesAndIncludedHeaderLinesDoNotBecomeInstructions() throws { + var input = fixture() + let addition = row("local EQU 0", bytes: [0, 0]) + "\n" + row("* Line cmoc.h:2: inline helper") + "\n" + let text = String(decoding: input.listing, as: UTF8.self) + .replacingOccurrences(of: row("LDX #message", offset: 3, bytes: [0x8e,0,0]), with: addition + row("LDX #message", offset: 3, bytes: [0x8e,0,0])) + input.listing = Data(text.utf8) + XCTAssertEqual(try input.parse().addresses(forLine: 2), [0x4200]) + } + func testAbsoluteSnapshotIdentityAndInlineAssemblyFailClosed() throws { + var input = fixture() + XCTAssertEqual(try input.parse(sourceName: "/build/main.c").executableLines, [2,3]) + input.listing = Data(String(decoding: input.listing, as: UTF8.self).replacingOccurrences(of: "main.c:", with: "/build/main.c:").utf8) + XCTAssertEqual(try input.parse(sourceName: "/build/main.c").executableLines, [2,3]) + XCTAssertThrowsError(try input.parse(sourceName: "/other/main.c")) + input = fixture() + input.listing = Data(String(decoding: input.listing, as: UTF8.self).replacingOccurrences(of: "function call: print()", with: "inline assembly").utf8) + XCTAssertEqual(try input.parse().executableLines, [3], "Inline assembler may contain arbitrary data and has no C breakpoint in this prototype") + } + func testProvenanceRejectsEditedSourceOrExecutable() throws { + let input = fixture(), mapping = try input.parse() + XCTAssertTrue(mapping.matches(source: input.source, binary: input.binary)) + XCTAssertFalse(mapping.matches(source: input.source + Data("\n".utf8), binary: input.binary)) + XCTAssertFalse(mapping.matches(source: input.source, binary: input.binary + Data([0]))) + XCTAssertEqual(mapping.provenance.objectSHA256, CMOCSourceMap.sha256(input.object)) + XCTAssertEqual(mapping.provenance.listingSHA256, CMOCSourceMap.sha256(input.listing)) + XCTAssertEqual(mapping.provenance.linkMapSHA256, CMOCSourceMap.sha256(input.map)) + } + func testByteRelocationAndMalformedExpressions() throws { + var input = fixture() + input.object = object([Section(name: "code", bytes: [0x86, 0, 0x39], + relocations: [(1, [255, 1, 1, 0, 65])])]) + input.map = Data("Section: code (main.o) load at 2800, length 0003".utf8) + input.binary = binary([(0x2800, [0x86, 65, 0x39])]) + input.listing = Data([row("SECTION code"), row("* Line main.c:2: assignment"), + row("LDA #65", offset: 0, bytes: [0x86, 0]), + row("RTS", offset: 2, bytes: [0x39]), row("ENDSECTION")].joined(separator: "\n").utf8) + XCTAssertEqual(try input.parse().instructions[0].bytes, [0x86, 65]) + for expression: [UInt8] in [[4, 1], [1, 0, 1, 1, 0, 0, 4, 4], [3] + cString("missing"), [99]] { + input.object = object([Section(name: "code", bytes: [0x86, 0, 0x39], relocations: [(1, expression)])]) + XCTAssertThrowsError(try input.parse()) + } + } + func testMalformedTruncatedAndOverlappingArtifactsAreRejected() { + var input = fixture() + input.object.removeLast(3) + XCTAssertThrowsError(try input.parse()) + input = fixture(); input.binary.removeLast() + XCTAssertThrowsError(try input.parse()) + input = fixture(); input.binary = binary([(0x2800, [0x39]), (0x2800, [0x39])]) + XCTAssertThrowsError(try input.parse()) + input = fixture(); input.listing = Data([0xff]) + XCTAssertThrowsError(try input.parse()) + } + private func projectFixture() -> (sources: [String: Data], units: [CMOCProjectSourceMap.TranslationUnit], map: Data, binary: Data) { + let source = Data("int work(void) {\n return 7;\n}\n".utf8) + let header = Data("static int helper(void) {\n return 8;\n}\n".utf8) + let paths = ["left/main.c", "right/main.c"] + let instructions: [[UInt8]] = [[0x4f, 0x5f, 0x39], [0x4f, 0x5c, 0x39]] + let units = paths.enumerated().map { index, path in + let code = instructions[index] + let listing = [row("SECTION code"), row("* Line /build/" + path + ":2: return"), + row("CLRA", offset: 0, bytes: [code[0]]), row("CLRB", offset: 1, bytes: [code[1]]), + row("* Line include/common.h:2: return"), row("RTS", offset: 2, bytes: [code[2]]), row("ENDSECTION")] + return CMOCProjectSourceMap.TranslationUnit(sourcePath: path, sourceName: "/build/" + path, + objectName: "obj/" + path.replacingOccurrences(of: ".c", with: ".o"), + listing: Data(listing.joined(separator: "\n").utf8), object: object([Section(name: "code", bytes: code)])) + } + return ([paths[0]: source, paths[1]: source, "include/common.h": header], units, + Data("Section: code (obj/left/main.o) load at 2800, length 0003\nSection: code (obj/right/main.o) load at 2900, length 0003".utf8), + binary([(0x2800, instructions[0]), (0x2900, instructions[1])])) + } + func testProjectMapsDuplicateBasenamesAndHeaderInstructionsByExactIdentity() throws { + let fixture = projectFixture() + let map = try CMOCProjectSourceMap.parse(sources: fixture.sources, compilationDirectory: URL(fileURLWithPath: "/build"), + units: fixture.units, linkMap: fixture.map, binary: fixture.binary) + XCTAssertEqual(map.sourcePaths, ["include/common.h", "left/main.c", "right/main.c"]) + XCTAssertEqual(map.addresses(file: "left/main.c", line: 2), [0x2800, 0x2801]) + XCTAssertEqual(map.addresses(file: "right/main.c", line: 2), [0x2900, 0x2901]) + XCTAssertEqual(map.addresses(file: "include/common.h", line: 2), [0x2802, 0x2902]) + XCTAssertEqual(map.location(at: 0x2900), .init(path: "right/main.c", line: 2)) + XCTAssertEqual(map.instruction(at: 0x2901)?.bytes, [0x5c]) + XCTAssertTrue(map.matches(sources: fixture.sources, binary: fixture.binary)) + var stale = fixture.sources; stale["include/common.h"]!.append(Data("\n".utf8)) + XCTAssertFalse(map.matches(sources: stale, binary: fixture.binary), "Header edits detach source provenance too") + XCTAssertEqual(map.map(forFile: "left/main.c")?.executableLines, [2]) + } + func testProjectRejectsWrongObjectIdentityDespiteMatchingBasename() { + let fixture = projectFixture(), unit = fixture.units[0] + let wrong = CMOCProjectSourceMap.TranslationUnit(sourcePath: unit.sourcePath, sourceName: unit.sourceName, + objectName: "obj/wrong/main.o", listing: unit.listing, object: unit.object) + XCTAssertThrowsError(try CMOCProjectSourceMap.parse(sources: fixture.sources, compilationDirectory: URL(fileURLWithPath: "/build"), + units: [wrong], linkMap: fixture.map, binary: fixture.binary)) + } + func testProjectDoesNotGuessNestedSourcesFromBareBasenames() throws { + let fixture = projectFixture() + let units = fixture.units.map { unit in + CMOCProjectSourceMap.TranslationUnit(sourcePath: unit.sourcePath, sourceName: unit.sourceName, + objectName: unit.objectName, listing: Data(String(decoding: unit.listing, as: UTF8.self) + .replacingOccurrences(of: "/build/" + unit.sourcePath, with: "main.c").utf8), object: unit.object) + } + let map = try CMOCProjectSourceMap.parse(sources: fixture.sources, compilationDirectory: URL(fileURLWithPath: "/build"), + units: units, linkMap: fixture.map, binary: fixture.binary) + XCTAssertEqual(map.sourcePaths, ["include/common.h"], "Ambiguous bare nested filenames never claim executable lines") + } + func testProjectRejectsStaleSecondObjectAndUnsafeSourcePaths() { + let fixture = projectFixture(); var bytes = fixture.binary; bytes[15] ^= 1 + XCTAssertThrowsError(try CMOCProjectSourceMap.parse(sources: fixture.sources, compilationDirectory: URL(fileURLWithPath: "/build"), + units: fixture.units, linkMap: fixture.map, binary: bytes)) + var sources = fixture.sources; sources["../elsewhere.c"] = Data("int x;".utf8) + XCTAssertThrowsError(try CMOCProjectSourceMap.parse(sources: sources, compilationDirectory: URL(fileURLWithPath: "/build"), + units: fixture.units, linkMap: fixture.map, binary: fixture.binary)) + } + func testArtifactDiscoveryHandlesGeneratedSourceAndDifferentObjectDirectories() throws { + let fixture = projectFixture(), root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + var paths: [String] = [] + for unit in fixture.units { + let objectURL = root.appendingPathComponent(unit.objectName) + try FileManager.default.createDirectory(at: objectURL.deletingLastPathComponent(), withIntermediateDirectories: true) + try unit.object.write(to: objectURL) + let listingPath = String(unit.objectName.dropLast(2)) + ".lst" + try unit.listing.write(to: root.appendingPathComponent(listingPath)); paths += [unit.objectName, listingPath] + } + try fixture.map.write(to: root.appendingPathComponent("program.map")) + try fixture.binary.write(to: root.appendingPathComponent("program.bin")) + let data = fixture.sources["left/main.c"]! + let artifact = CMOCBuildArtifact(id: UUID(), directory: root, source: String(decoding: data, as: UTF8.self), sourceData: data, + sourceSHA256: CMOCSourceMap.sha256(data), binaryData: fixture.binary, buildLog: "", + sources: fixture.sources, compilationDirectory: URL(fileURLWithPath: "/build"), entrySourcePath: "left/main.c", + binaryRelativePath: "program.bin", outputPaths: paths) + let map = try CMOCProjectSourceMap.parse(artifact: artifact) + XCTAssertEqual(map.instructions.count, 6) + XCTAssertEqual(map.location(at: 0x2901)?.path, "right/main.c") + XCTAssertEqual(map.flatCodeGuards.map(\.address), [0x2800, 0x2900]) + let receipt = CMOCPublicDebugEvidence.fields(artifact: artifact, sharedPaths: ["left/main.c"]) + XCTAssertEqual(receipt["status"] as? String, "source_only", "Ordinary custom builds expose verified map evidence without a bank manifest") + XCTAssertEqual(receipt["banked"] as? Bool, false) + XCTAssertEqual(receipt["owned_stop_evidence"] as? String, "verified_flat_code") + let stops = try XCTUnwrap(receipt["c_line_stops"] as? [[String: Any]]) + XCTAssertFalse(stops.isEmpty) + XCTAssertTrue(stops.allSatisfy { $0["path"] as? String == "left/main.c" }) + XCTAssertEqual(receipt["reason_code"] as? String, "typed_metadata_unavailable") + var changed = fixture.binary; changed[5] ^= 1 + try changed.write(to: root.appendingPathComponent("program.bin")) + let mismatch = CMOCPublicDebugEvidence.fields(artifact: artifact, sharedPaths: Set(fixture.sources.keys)) + XCTAssertEqual(mismatch["status"] as? String, "unavailable") + XCTAssertTrue((mismatch["reason"] as? String ?? "").contains("retained executable bytes differ")) + try fixture.binary.write(to: root.appendingPathComponent("program.bin")) + try Data("Section: code (wrong.o) load at 2800, length 0003".utf8).write(to: root.appendingPathComponent("program.map")) + XCTAssertEqual(CMOCPublicDebugEvidence.fields(artifact: artifact, sharedPaths: Set(fixture.sources.keys))["status"] as? String, "unavailable") + } + +} + +/// Real-toolchain checks are optional only when licensed local ROMs/tool staging +/// are absent. The sources and disks here are authored test inputs, never games. +final class CMOCMultiFileExecutionTests: XCTestCase { + @MainActor private func command(_ body: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { continuation in body { continuation.resume(returning: $0) } } + } + @MainActor private func stop(_ controller: VCCMachineController, timeout: TimeInterval = 15) async -> VCCMachineSnapshot { + let deadline = Date().addingTimeInterval(timeout) + var snapshot = await command(controller.snapshot) + while snapshot.state == .running && Date() < deadline { + try? await Task.sleep(nanoseconds: 20_000_000) + snapshot = await command(controller.snapshot) + } + XCTAssertNil(snapshot.errorMessage) + XCTAssertEqual(snapshot.state, .paused, "Expected a verified source breakpoint before the deadline") + return snapshot + } + @MainActor private func boot(_ controller: VCCMachineController) async throws { + _ = await command(controller.resume) + let deadline = Date().addingTimeInterval(10) + while Date() < deadline { + let text: String? = await withCheckedContinuation { continuation in + controller.copyScreenText { text, _ in continuation.resume(returning: text) } + } + if text?.contains("OK") == true { + // The ROM prints OK before finishing keyboard initialization. + // Wait for guest frames, not a guessed host sleep, before typing. + let visible = await command(controller.snapshot) + while Date() < deadline { + let ready = await command(controller.snapshot) + if ready.frames >= visible.frames + 18 { return } + try await Task.sleep(nanoseconds: 20_000_000) + } + } + try await Task.sleep(nanoseconds: 40_000_000) + } + XCTFail("Disk BASIC did not reach its prompt") + throw CMOCBuildError.message("Disk BASIC boot timed out") + } + @MainActor func testHelloDiskDOSAndLOADMRunTheSameProgramOnBothCPUs() async throws { + let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + let resources = mac.appendingPathComponent("LocalResources") + let runtime = resources.appendingPathComponent("ToolchainBundle") + let romURL = resources.appendingPathComponent("ROMs/coco3.rom"), diskROMURL = resources.appendingPathComponent("ROMs/disk11.rom") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: runtime.appendingPathComponent("bin/cmoc").path) && FileManager.default.fileExists(atPath: romURL.path) && FileManager.default.fileExists(atPath: diskROMURL.path), "Stage local tools and ROMs") + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCHelloDOS-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let template = mac.deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("examples/cmoc/HelloDisk") + let project = try CMOCProject.createHelloDisk(at: root.appendingPathComponent("Hello Disk"), templateDirectory: template) + let build = try await CMOCBuildService(toolchain: runtime, buildRoot: root.appendingPathComponent("Builds")).build(project: project, overlays: [:], action: .disk) + let map = try CMOCProjectSourceMap.parse(artifact: build) + let point = try XCTUnwrap(map.instructions.first { $0.sourcePath == "main.c" && $0.sourceLine == 13 }) + let disk = try Data(contentsOf: XCTUnwrap(build.diskURL)) + let rom = try Data(contentsOf: romURL), diskROM = try Data(contentsOf: diskROMURL) + for cpu in [false, true] { + for text in ["DOS", "LOADM\"HELLO\":EXEC"] { + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command { controller.loadDiskROM(diskROM, name: "Disk BASIC", completion: $0) } + _ = await command { controller.configureCartridges([2,0,0,0,2], roms: Array(repeating: Data(), count: 5), names: Array(repeating: "", count: 5), multiPak: true, physicalSlot: 4, completion: $0) } + _ = await command { controller.mountDisk(disk, drive: 0, name: "HELLO.dsk", readOnly: true, completion: $0) } + _ = await command { controller.loadROM(rom, use6309: cpu, completion: $0) } + try await boot(controller) + let before = await command(controller.pause) + let armed = await command { controller.debuggerArmDevelopmentBreakpoints([NSNumber(value: point.address)], guardAddresses: map.instructions.map { NSNumber(value: $0.address) }, guardBytes: map.instructions.map { Data($0.bytes) }, completion: $0) } + XCTAssertNil(armed.errorMessage); XCTAssertFalse(armed.debuggerDevelopmentAttached) + _ = await command(controller.resume) + let paste = try CocoPaste(text + "\n", mode: .text) + _ = await command { controller.pasteChords(paste.chords.map { NSNumber(value: $0) }, completion: $0) } + let stopped = await stop(controller) + XCTAssertEqual(stopped.programCounter, point.address, "\(text), 6309=\(cpu)") + XCTAssertTrue(stopped.debuggerDevelopmentAttached) + XCTAssertEqual(stopped.generation, before.generation) + XCTAssertEqual(stopped.debuggerProgramRevision, before.debuggerProgramRevision) + XCTAssertGreaterThan(stopped.disks[0].readEvents, before.disks[0].readEvents) + _ = await command(controller.resume) + var screen = "" + for _ in 0..<200 { + screen = await withCheckedContinuation { continuation in controller.copyScreenText { value, _ in continuation.resume(returning: value ?? "") } } + if screen.contains("GENERATED WORD COUNT: 5") { break } + try await Task.sleep(nanoseconds: 20_000_000) + } + XCTAssertTrue(screen.contains("DISK RESULT: 0"), screen) + XCTAssertTrue(screen.contains("GENERATED WORD COUNT: 5"), screen) + let after = await command(controller.pause) + XCTAssertFalse(after.disks[0].dirty) + let exported: Data? = await withCheckedContinuation { continuation in controller.exportDisk(inDrive: 0) { data, _, _ in continuation.resume(returning: data) } } + XCTAssertEqual(exported, disk, "Boot and reading must preserve every disk byte") + _ = await command(controller.shutdown) + } + } + } + + @MainActor func testMultiFileQuickloadAndDiskBootStopAtVerifiedSourceOnBothCPUs() async throws { + let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + let resources = mac.appendingPathComponent("LocalResources"), toolchain = resources.appendingPathComponent("ToolchainBundle") + let romURL = resources.appendingPathComponent("ROMs/coco3.rom"), diskROMURL = resources.appendingPathComponent("ROMs/disk11.rom") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) && + FileManager.default.fileExists(atPath: romURL.path) && FileManager.default.fileExists(atPath: diskROMURL.path), + "The staged standalone tools and licensed local ROMs are required") + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCMultiFileExecution-" + UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let projectRoot = folder.appendingPathComponent("Project") + _ = try CMOCProject.create(at: projectRoot) + try FileManager.default.createDirectory(at: projectRoot.appendingPathComponent("src"), withIntermediateDirectories: true) + let main = """ + #include + #include "src/helper.h" + int main(void) + { + unsigned answer = calculate(); + printf("MULTI FILE RESULT %u\\n", answer); + return 0; + } + """ + let helper = """ + #include "helper.h" + unsigned testResult; + unsigned calculate(void) + { + testResult = 40; + testResult += 2; + return testResult; + } + """ + try Data(main.utf8).write(to: projectRoot.appendingPathComponent("main.c")) + try Data(helper.utf8).write(to: projectRoot.appendingPathComponent("src/helper.c")) + try Data("unsigned calculate(void);\n".utf8).write(to: projectRoot.appendingPathComponent("src/helper.h")) + var settings = CMOCMakefileSettings() + settings.sources = ["main.c", "src/helper.c"]; settings.diskImage = "program.dsk"; settings.diskBootMode = .program + try Data(settings.generateMakefile().utf8).write(to: projectRoot.appendingPathComponent("Makefile")) + var configuration = CMOCProjectConfiguration() + configuration.diskTarget = "disk"; configuration.diskImage = "program.dsk"; configuration.jobs = 2 + try JSONEncoder().encode(configuration).write(to: projectRoot.appendingPathComponent(CMOCProject.configurationFilename)) + let project = try CMOCProject.open(at: projectRoot) + let build = try await CMOCBuildService(toolchain: toolchain, buildRoot: folder.appendingPathComponent("Builds")) + .build(project: project, overlays: [:], action: .disk) + let mapping = try CMOCProjectSourceMap.parse(artifact: build) + let first = try XCTUnwrap(mapping.instructions.first { $0.sourcePath == "src/helper.c" && $0.sourceLine == 6 }) + let second = try XCTUnwrap(mapping.instructions.first { $0.sourcePath == "main.c" && $0.sourceLine == 6 }) + let symbol = try XCTUnwrap(String(contentsOf: build.mapURL, encoding: .utf8).components(separatedBy: .newlines) + .first { $0.hasPrefix("Symbol: _testResult (obj/src/helper.o) = ") }) + let resultAddress = try XCTUnwrap(UInt16(try XCTUnwrap(symbol.split(separator: " ").last), radix: 16)) + let disk = try Data(contentsOf: XCTUnwrap(build.diskURL)) + XCTAssertEqual(disk.count, 35 * 18 * 256) + let rom = try Data(contentsOf: romURL), diskROM = try Data(contentsOf: diskROMURL) + for use6309 in [false, true] { + for launchCommand in ["", "LOADM\"MAIN\":EXEC", "DOS"] { + let diskLaunch = !launchCommand.isEmpty + let controller = VCCMachineController() + do { + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + let diskConfigured = await command { controller.loadDiskROM(diskROM, name: "Test disk ROM", completion: $0) } + XCTAssertNil(diskConfigured.errorMessage) + let layout = await command { controller.configureCartridges([2,0,0,0,2], roms: Array(repeating: Data(), count: 5), + names: Array(repeating: "", count: 5), multiPak: true, physicalSlot: 4, completion: $0) } + XCTAssertNil(layout.errorMessage) + let mounted = await command { controller.mountDisk(disk, drive: 0, name: "program.dsk", readOnly: true, completion: $0) } + XCTAssertNil(mounted.errorMessage) + let loaded = await command { controller.loadROM(rom, use6309: use6309, completion: $0) } + XCTAssertNil(loaded.errorMessage) + try await boot(controller) + let before = await command(controller.pause) + let points = [NSNumber(value: first.address), NSNumber(value: second.address)] + if diskLaunch { + let armed = await command { controller.debuggerArmDevelopmentBreakpoints(points, + guardAddresses: mapping.instructions.map { NSNumber(value: $0.address) }, + guardBytes: mapping.instructions.map { Data($0.bytes) }, completion: $0) } + XCTAssertNil(armed.errorMessage); XCTAssertFalse(armed.debuggerDevelopmentAttached) + XCTAssertEqual(armed.programCounter, before.programCounter, "Arming disk debugging must not quickload or change PC") + _ = await command(controller.resume) + let paste = try CocoPaste(launchCommand + "\n", mode: .text) + let typed = await command { controller.pasteChords(paste.chords.map { NSNumber(value: $0) }, completion: $0) } + XCTAssertNil(typed.errorMessage) + } else { + let loaded = await command { controller.debuggerLoadBinary(build.binaryData, breakpoints: points, completion: $0) } + XCTAssertNil(loaded.errorMessage) + } + let stopped = await stop(controller) + if stopped.state != .paused { + let screen: String? = await withCheckedContinuation { continuation in + controller.copyScreenText { text, _ in continuation.resume(returning: text) } + } + print("CMOC FAILED LAUNCH cpu6309=\(use6309) disk=\(diskLaunch) remaining=\(stopped.pasteRemaining) screen=\(screen ?? "unavailable")") + throw CMOCBuildError.message("Source breakpoint not reached") + } + XCTAssertEqual(stopped.programCounter, first.address) + XCTAssertEqual(mapping.location(at: stopped.programCounter), .init(path: "src/helper.c", line: 6)) + XCTAssertTrue(stopped.debuggerDevelopmentAttached) + XCTAssertEqual(stopped.generation, before.generation) + if diskLaunch { + XCTAssertEqual(stopped.debuggerProgramRevision, before.debuggerProgramRevision, "Disk loading is guest execution, not host quickload") + XCTAssertGreaterThan(stopped.disks[0].readEvents, before.disks[0].readEvents) + } + let detail: VCCDebuggerSnapshot = await withCheckedContinuation { continuation in + controller.debuggerSnapshot(address: first.address, followPC: true, memoryAddress: resultAddress) { continuation.resume(returning: $0) } + } + XCTAssertEqual(detail.instructions.first?.bytes, Data(first.bytes)) + XCTAssertEqual(detail.memory.prefix(2), Data([0,40]), "The helper executes until immediately before the selected C statement") + _ = await command(controller.resume) + let next = await stop(controller) + XCTAssertEqual(next.programCounter, second.address) + XCTAssertEqual(mapping.location(at: next.programCounter), .init(path: "main.c", line: 6)) + let secondDetail: VCCDebuggerSnapshot = await withCheckedContinuation { continuation in + controller.debuggerSnapshot(address: second.address, followPC: true, memoryAddress: resultAddress) { continuation.resume(returning: $0) } + } + XCTAssertEqual(secondDetail.memory.prefix(2), Data([0,42])) + XCTAssertEqual(secondDetail.instructions.first?.bytes, Data(second.bytes)) + XCTAssertFalse(next.disks[0].dirty) + _ = await command(controller.shutdown) + } catch { + _ = await command(controller.shutdown) + throw error + } + } + } + } +} + +final class CMOCLiveBreakpointModelTests: XCTestCase { + @MainActor private func waitUntil(_ condition: () -> Bool, timeout: TimeInterval = 10, action: () -> Void = {}) async throws { + let deadline = Date().addingTimeInterval(timeout) + while !condition(), Date() < deadline { + action(); try await Task.sleep(nanoseconds: 20_000_000) + } + XCTAssertTrue(condition(), "Model operation did not finish before its deadline") + } + @MainActor private func detail(_ machine: MachineModel) async -> VCCDebuggerSnapshot? { + await withCheckedContinuation { continuation in + machine.readDebugger(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) } + } + } + @MainActor func testPausedLiveToggleKeepsInstructionUpdatesAndRejectsUnobservedMemoryEdits() async throws { + let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources") + let toolchain = resources.appendingPathComponent("ToolchainBundle"), romURL = resources.appendingPathComponent("ROMs/coco3.rom") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) && + FileManager.default.fileExists(atPath: romURL.path), "Staged tools and a licensed local CoCo ROM are required") + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCLiveBreakpoints-" + UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + let suite = "CMOCLiveBreakpoints." + UUID().uuidString + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: folder) } + let machine = MachineModel(diskStore: .init(url: folder.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: folder.appendingPathComponent("input.json"))) + let model = CMOCDevelopmentModel(machine: machine, toolchain: toolchain, defaults: defaults) + do { + try model.adopt(CMOCProject.create(at: folder.appendingPathComponent("Project"))) + model.build(); try await waitUntil({ !model.building }, timeout: 30) + XCTAssertNil(model.message); XCTAssertTrue(model.buildMatchesEditor, model.log) + try await waitUntil({ !machine.busy }) + machine.installROM(try Data(contentsOf: romURL), url: romURL) + try await waitUntil({ !machine.busy }) + try await Task.sleep(nanoseconds: 1_500_000_000) + await withCheckedContinuation { continuation in machine.debuggerConfigureBreakpoints([0x4500], disabled: []) { continuation.resume() } } + let lines = model.source.components(separatedBy: "\n") + let startLine = try XCTUnwrap(lines.firstIndex { $0.contains("width(40)") }) + 1 + let menuLine = try XCTUnwrap(lines.firstIndex { $0.contains("What planet do you live on?") }) + 1 + model.breakpointLine = startLine; model.run() + try await waitUntil({ model.currentLine == startLine && !model.commanding }, action: { model.refresh() }) + XCTAssertTrue(model.loadedMatchesEditor) + let before = try XCTUnwrap(model.pc) + // Add a later point while paused at an earlier source statement. + // Conditional guards have not hit again; stepping must still update. + model.toggleBreakpoint(menuLine) + try await waitUntil({ !model.commanding }) + XCTAssertEqual(machine.state, .paused) + model.stepInstruction() + try await waitUntil({ model.pc != before && !model.commanding }, action: { model.refresh() }) + XCTAssertTrue(model.loadedMatchesEditor) + let stepped = try XCTUnwrap(model.pc) + XCTAssertEqual(model.currentLine, model.projectMapping?.location(at: stepped)?.line) + XCTAssertEqual(model.currentFile, model.projectMapping?.location(at: stepped)?.path) + model.toggleBreakpoint(menuLine) // Remove the final explicit point. + try await waitUntil({ !model.commanding }) + model.stepInstruction() + try await waitUntil({ model.pc != stepped && !model.commanding }, action: { model.refresh() }) + XCTAssertTrue(model.loadedMatchesEditor, "Removing points must not discard an already verified code connection") + let clearedDetail = await detail(machine) + let cleared = try XCTUnwrap(clearedDetail) + XCTAssertEqual(cleared.breakpoints, [0x4500], "Only the development feature's breakpoints are removed") + + // Modify RAM without letting model.refresh observe the changed epoch. + // A live toggle must inspect a new snapshot before rearming, rather + // than blessing the new revision using its old source connection. + await withCheckedContinuation { continuation in + machine.debuggerWriteMemory(address: 0x4000, data: Data([0x55])) { continuation.resume() } + } + model.toggleBreakpoint(menuLine) + try await waitUntil({ !model.commanding }) + XCTAssertFalse(model.loadedMatchesEditor) + XCTAssertNil(model.currentLine); XCTAssertNil(model.currentFile) + XCTAssertEqual(machine.state, .paused) + let changedDetail = await detail(machine) + let changed = try XCTUnwrap(changedDetail) + XCTAssertEqual(changed.breakpoints, [0x4500]) + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } catch { + model.cancelBuild() + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + throw error + } + } +} diff --git a/platforms/macos/Tests/CMOCVariableDebugTests.swift b/platforms/macos/Tests/CMOCVariableDebugTests.swift new file mode 100644 index 0000000..d2b26bf --- /dev/null +++ b/platforms/macos/Tests/CMOCVariableDebugTests.swift @@ -0,0 +1,494 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CMOCVariableDebugTests: XCTestCase { + private let word = CMOCVariableDebug.CType(name: "int", kind: "integer", size: 2, signed: true) + private func fixture(frame: Bool = true, changedCode: Bool = false, io: Bool = false) -> CMOCWatchEvaluator { + let sourceMap = CMOCProjectSourceMap(entryPoint: 0x2800, binarySHA256: "", sourceHashes: [:], + instructions: [.init(sourcePath: "main.c", sourceLine: 5, address: 0x2800, bytes: [0x12], assembly: "NOP")], + objectHashes: [:], listingHashes: [:], linkMapSHA256: "") + let pointer = CMOCVariableDebug.CType(name: "int *", kind: "pointer", size: 2, element: word) + let array = CMOCVariableDebug.CType(name: "int[3]", kind: "array", size: 6, count: 3, element: word) + let variables: [CMOCVariableDebug.Variable] = [ + .init(name: "global", sourcePath: "main.c", line: 1, type: word, address: 0x3000, offset: nil, scope: nil, isStatic: false), + .init(name: "local", sourcePath: "main.c", line: 2, type: word, address: nil, offset: -2, scope: 0x2800..<0x2820, isStatic: false), + .init(name: "pointer", sourcePath: "main.c", line: 1, type: pointer, address: 0x3002, offset: nil, scope: nil, isStatic: false), + .init(name: "array", sourcePath: "main.c", line: 1, type: array, address: 0x3010, offset: nil, scope: nil, isStatic: false) + ] + let metadata = CMOCVariableDebug(functions: [.init(name: "main", sourcePath: "main.c", entry: 0x2800, body: 0x2800, end: 0x2820, frame: frame)], + variables: variables, sourceMap: sourceMap) + var memory = Data(repeating: 0, count: 65536), available = Data(repeating: 1, count: 65536) + memory[0x2800] = changedCode ? 0x39 : 0x12 + memory[0x3000] = 0xff; memory[0x3001] = 0xf9 // -7, big endian + memory[0x3002] = io ? 0xff : 0x30; memory[0x3003] = io ? 0 : 0x12 + memory[0x3ffe] = 0; memory[0x3fff] = 42 + for i in 0..<3 { memory[0x3011 + 2*i] = UInt8(11 * (i+1)) } + for i in 0xff00..<0x10000 { available[i] = 0 } + return CMOCWatchEvaluator(metadata: metadata, context: .init(pc: 0x2800, u: 0x4000, memory: memory, available: available)) + } + func testSignedBigEndianLocalsArrayAndPointerReads() { + let evaluator = fixture() + XCTAssertEqual(evaluator.evaluate("global").value, "-7") + XCTAssertEqual(evaluator.evaluate("local").value, "42") + XCTAssertEqual(evaluator.evaluate("array").value, "[11, 22, 33]") + XCTAssertEqual(evaluator.evaluate("array[1]").value, "22") + XCTAssertEqual(evaluator.evaluate("*pointer").value, "22") + XCTAssertEqual(evaluator.evaluate("*(pointer + 1)").value, "33") + XCTAssertEqual(evaluator.evaluate("&array[2]").value, "$3014") + XCTAssertEqual(evaluator.visibleVariables().count, 4) + } + func testFlatEntriesAndPublicGlobalsUseCompleteVerifiedCodeAndSharedStorage() throws { + let code = Array(repeating: UInt8(0x12), count: 8) + let map = CMOCProjectSourceMap(entryPoint: 0x2800, binarySHA256: "binary", sourceHashes: [:], + instructions: [.init(sourcePath: "main.c", sourceLine: 3, address: 0x2802, bytes: [0x12], assembly: "NOP")], + objectHashes: [:], listingHashes: [:], linkMapSHA256: "map", + flatCodeGuards: [.init(address: 0x2800, bytes: code)]) + let function = CMOCVariableDebug.Function(name: "main", sourcePath: "main.c", entry: 0x2800, + body: 0x2802, end: 0x2808, frame: false, sourceLine: 2) + let unavailable = CMOCVariableDebug.Function(name: "outside", sourcePath: "main.c", entry: 0x2800, + body: 0x2800, end: 0x2809, frame: false) + let metadata = CMOCVariableDebug(functions: [function, unavailable], variables: [ + .init(name: "known", sourcePath: "main.c", line: 1, type: word, address: 0x3000, + offset: nil, scope: nil, isStatic: false), + .init(name: "hidden", sourcePath: "private.c", line: 1, type: word, address: 0x3002, + offset: nil, scope: nil, isStatic: false), + .init(name: "unknown", sourcePath: "main.c", line: 1, type: word, address: 0x6000, + offset: nil, scope: nil, isStatic: false) + ], sourceMap: map) + XCTAssertEqual(metadata.functionEntryNames, ["main"]) + XCTAssertEqual(metadata.breakpointInstruction(named: "main")?.address, 0x2802) + XCTAssertEqual(metadata.entryFunction(containing: 0x2800)?.name, "main") + let receipt = CMOCPublicDebugEvidence.fields(map: map, metadata: metadata, variableError: nil, sharedPaths: ["main.c"]) + XCTAssertEqual(receipt["function_entries"] as? [String], ["main"]) + XCTAssertEqual((receipt["globals"] as? [[String: Any]])?.count, 2) + var memory = Data(repeating: 0, count: 65536), available = Data(repeating: 1, count: 65536) + memory.replaceSubrange(0x2800..<0x2808, with: code) + memory[0x3000] = 0; memory[0x3001] = 42 + for i in 0xff00..<0x10000 { available[i] = 0 } + let context = CMOCWatchEvaluator.Context(pc: 0x2800, u: 0x4000, memory: memory, available: available) + let values = CMOCPublicDebugEvidence.globals(metadata: metadata, sharedPaths: ["main.c"], context: context, + permittedRanges: [0x2800..<0x2808, 0x3000..<0x3002], physicalPages: [1: 57]) + XCTAssertEqual(values.total, 2) + let known = try XCTUnwrap(values.items.first { $0["name"] as? String == "known" }) + XCTAssertEqual(known["value"] as? String, "42") + XCTAssertEqual(known["physical_address"] as? Int, 57 * 8192 + 0x1000) + XCTAssertEqual(values.items.first { $0["name"] as? String == "unknown" }?["status"] as? String, "unavailable") + XCTAssertFalse(values.items.contains { $0["name"] as? String == "hidden" }) + memory[0x2800] = 0x39 // Unmapped prologue byte, outside the lone C statement. + XCTAssertFalse(map.verifiesRuntime(memory: memory, available: available)) + let stale = CMOCPublicDebugEvidence.globals(metadata: metadata, sharedPaths: ["main.c"], + context: .init(pc: 0x2800, u: 0x4000, memory: memory, available: available), + permittedRanges: [0x3000..<0x3002], physicalPages: [1: 57]) + XCTAssertEqual(stale.items.first { $0["name"] as? String == "known" }?["status"] as? String, "unavailable") + } + func testBankedMetadataProjectionHidesWrongBankGlobalsAndLexicalScopes() { + let layout = CMOCBankedDebugLayout(entryPoint: 0x4000, binarySHA256: "", linkMap: Data(), sourceHashes: [:], artifactHashes: [:], modules: [ + .init(id: "resident", sections: ["code", "bss"], codeSections: ["code"], logicalAddress: 0x2800, bytes: [0x12], pages: [.init(logicalPage: 1, physicalPage: 0x39)], codeGuards: [.init(address: 0x2800, bytes: [0x12])]), + .init(id: "overlay", sections: ["overlay"], codeSections: ["overlay"], logicalAddress: 0x4000, bytes: [0x12], pages: [.init(logicalPage: 2, physicalPage: 0x20)], codeGuards: [.init(address: 0x4000, bytes: [0x12])]) + ]) + let map = CMOCProjectSourceMap(entryPoint: 0x2800, binarySHA256: "", sourceHashes: [:], instructions: [], objectHashes: [:], listingHashes: [:], linkMapSHA256: "", bankedLayout: layout) + let metadata = CMOCVariableDebug(functions: [ + .init(name: "resident", sourcePath: "main.c", entry: 0x2800, body: 0x2800, end: 0x2801, frame: true, moduleID: "resident"), + .init(name: "overlay", sourcePath: "overlay.c", entry: 0x4000, body: 0x4000, end: 0x4001, frame: true, moduleID: "overlay") + ], variables: [ + .init(name: "global", sourcePath: "main.c", line: 1, type: word, address: 0x3000, offset: nil, scope: nil, isStatic: false, moduleID: "resident"), + .init(name: "overlayGlobal", sourcePath: "overlay.c", line: 1, type: word, address: 0x4100, offset: nil, scope: nil, isStatic: false, moduleID: "overlay"), + .init(name: "staticLocal", sourcePath: "overlay.c", line: 1, type: word, address: 0x3002, offset: nil, scope: 0x4000..<0x4001, isStatic: true, moduleID: "resident", scopeModuleID: "overlay") + ], sourceMap: map) + let wrong = metadata.projected(physicalPages: [1: 0x39, 2: 0x21]) + XCTAssertEqual(wrong.variables.map(\.name), ["global"]) + XCTAssertEqual(wrong.functions.map(\.name), ["resident"]) + XCTAssertEqual(metadata.projected(physicalPages: [1: 0x39, 2: 0x20]).variables.count, 3) + XCTAssertTrue(metadata.projected(physicalPages: [1: 0x38, 2: 0x21]).variables.isEmpty) + } + func testBreakpointFunctionCatalogRequiresUniqueMappedBodyInItsModule() { + let map = CMOCProjectSourceMap(entryPoint: 0x4000, binarySHA256: "", sourceHashes: [:], instructions: [ + .init(sourcePath: "main.c", sourceLine: 1, address: 0x4001, bytes: [0x12], assembly: "NOP", moduleID: "resident"), + .init(sourcePath: "main.c", sourceLine: 2, address: 0x4004, bytes: [0x12], assembly: "NOP", moduleID: "resident"), + .init(sourcePath: "main.c", sourceLine: 2, address: 0x4002, bytes: [0x12], assembly: "NOP", moduleID: "resident"), + .init(sourcePath: "main.c", sourceLine: 3, address: 0x4008, bytes: [0x12], assembly: "NOP", moduleID: "resident"), + .init(sourcePath: "overlay.c", sourceLine: 1, address: 0x5000, bytes: [0x12], assembly: "NOP", moduleID: "overlay") + ], objectHashes: [:], listingHashes: [:], linkMapSHA256: "") + let main = CMOCVariableDebug.Function(name: "main", sourcePath: "main.c", entry: 0x4000, body: 0x4002, + end: 0x4008, frame: false, moduleID: "resident") + let assembly = CMOCVariableDebug.Function(name: "raw", sourcePath: "main.c", entry: 0x5000, body: 0x5000, + end: 0x5002, frame: false, moduleID: "resident") + let metadata = CMOCVariableDebug(functions: [assembly, main], variables: [], sourceMap: map) + XCTAssertEqual(metadata.breakpointInstruction(named: "main")?.address, 0x4002) + XCTAssertEqual(metadata.breakpointInstruction(named: "main")?.moduleID, "resident") + XCTAssertNil(metadata.breakpointInstruction(named: "raw"), "An instruction at the same address in another module is not a valid body") + XCTAssertNil(metadata.breakpointInstruction(named: "missing")) + XCTAssertEqual(metadata.breakpointFunctionNames, ["main"]) + let duplicate = CMOCVariableDebug(functions: [main, main], variables: [], sourceMap: map) + XCTAssertNil(duplicate.breakpointInstruction(named: "main")) + XCTAssertTrue(duplicate.breakpointFunctionNames.isEmpty) + } + + func testFunctionEntryStopsRequireExecutableBankedRangesAndUnambiguousActivePC() { + let executable = CMOCBankedDebugLayout.Module(id: "assembly", sections: ["code"], codeSections: ["code"], + logicalAddress: 0x4000, bytes: Array(repeating: 0x12, count: 8), pages: [.init(logicalPage: 2, physicalPage: 4)], + codeGuards: [.init(address: 0x4000, bytes: [0x12, 0x12]), .init(address: 0x4002, bytes: Array(repeating: 0x12, count: 6))]) + let bss = CMOCBankedDebugLayout.Module(id: "state", sections: ["bss"], codeSections: [], logicalAddress: 0x6000, + bytes: [], pages: [.init(logicalPage: 3, physicalPage: 5)], codeGuards: []) + let function = CMOCVariableDebug.Function(name: "raw", sourcePath: "main.c", entry: 0x4000, body: 0x4002, + end: 0x4008, frame: false, moduleID: "assembly", sourceLine: 12) + let invalid = [ + CMOCVariableDebug.Function(name: "data", sourcePath: "main.c", entry: 0x6000, body: 0x6000, end: 0x6002, frame: false, moduleID: "state"), + .init(name: "gap", sourcePath: "main.c", entry: 0x4000, body: 0x4000, end: 0x4009, frame: false, moduleID: "assembly"), + .init(name: "io", sourcePath: "main.c", entry: 0xfdff, body: 0xfdff, end: 0xfe01, frame: false, moduleID: "assembly"), + .init(name: "empty", sourcePath: "main.c", entry: 0x4000, body: 0x4000, end: 0x4000, frame: false, moduleID: "assembly"), + .init(name: "negative", sourcePath: "main.c", entry: -1, body: 0, end: 1, frame: false, moduleID: "assembly"), + .init(name: "unknown", sourcePath: "main.c", entry: 0x4000, body: 0x4000, end: 0x4001, frame: false, moduleID: "absent") + ] + func metadata(_ functions: [CMOCVariableDebug.Function], executable override: CMOCBankedDebugLayout.Module? = nil) -> CMOCVariableDebug { + let layout = CMOCBankedDebugLayout(entryPoint: 0x4000, binarySHA256: "", linkMap: Data(), sourceHashes: [:], + artifactHashes: [:], modules: [override ?? executable, bss]) + let map = CMOCProjectSourceMap(entryPoint: 0x4000, binarySHA256: "", sourceHashes: [:], instructions: [], + objectHashes: [:], listingHashes: [:], linkMapSHA256: "", bankedLayout: layout) + return CMOCVariableDebug(functions: functions, variables: [ + .init(name: "fileState", sourcePath: "main.c", line: 1, type: word, address: 0x6000, + offset: nil, scope: nil, isStatic: true, moduleID: "state"), + .init(name: "otherState", sourcePath: "other.c", line: 1, type: word, address: 0x6002, + offset: nil, scope: nil, isStatic: true, moduleID: "state"), + .init(name: "local", sourcePath: "main.c", line: 12, type: word, address: nil, + offset: -2, scope: 0x4000..<0x4008, isStatic: false, moduleID: "assembly", scopeModuleID: "assembly") + ], sourceMap: map) + } + let complete = metadata([function] + invalid) + XCTAssertEqual(complete.entryFunction(named: "raw")?.entry, 0x4000) + XCTAssertEqual(complete.entryFunction(named: "raw")?.sourceLine, 12) + XCTAssertEqual(complete.functionEntryNames, ["raw"]) + XCTAssertNil(complete.breakpointInstruction(named: "raw"), "An entry stop is not an invented C statement") + XCTAssertNil(complete.entryFunction(containing: 0x4000), "A live function claim requires a physical projection") + var memory = Data(repeating: 0, count: 65536) + memory.replaceSubrange(0x4000..<0x4008, with: repeatElement(UInt8(0x12), count: 8)) + let available = Data(repeating: 1, count: 65536) + let active = complete.projected(physicalPages: [2: 4, 3: 5], memory: memory, available: available) + XCTAssertEqual(active.entryFunction(containing: 0x4000)?.name, "raw", "Prologue bytes precede the C body but belong to the executable function") + XCTAssertEqual(active.entryFunction(containing: 0x4007)?.name, "raw") + XCTAssertNil(active.entryFunction(containing: 0x4008)) + let entryWatch = CMOCWatchEvaluator(metadata: active, + context: .init(pc: 0x4000, u: 0x7000, memory: memory, available: available), frameLocalsAvailable: false) + XCTAssertEqual(entryWatch.evaluate("fileState").value, "0", "A verified prologue retains file-static global scope") + XCTAssertNotNil(entryWatch.evaluate("otherState").error) + XCTAssertNotNil(entryWatch.evaluate("local").error, "A function entry does not establish stack-local storage") + let wrong = complete.projected(physicalPages: [2: 6, 3: 5], memory: memory, available: available) + XCTAssertNil(wrong.entryFunction(named: "raw")); XCTAssertNil(wrong.entryFunction(containing: 0x4000)) + XCTAssertTrue(wrong.functionEntryNames.isEmpty) + let overlap = CMOCVariableDebug.Function(name: "overlap", sourcePath: "main.c", entry: 0x4002, body: 0x4002, + end: 0x4004, frame: false, moduleID: "assembly", sourceLine: 18) + let overlapping = metadata([function, overlap]).projected(physicalPages: [2: 4], memory: memory, available: available) + XCTAssertNil(overlapping.entryFunction(containing: 0x4002), "Overlapping records cannot choose an arbitrary function") + XCTAssertEqual(overlapping.entryFunction(containing: 0x4000)?.name, "raw") + let duplicate = metadata([function, function]).projected(physicalPages: [2: 4], memory: memory, available: available) + XCTAssertNil(duplicate.entryFunction(named: "raw")); XCTAssertNil(duplicate.entryFunction(containing: 0x4000)) + XCTAssertTrue(duplicate.functionEntryNames.isEmpty) + let missingPage = CMOCBankedDebugLayout.Module(id: executable.id, sections: executable.sections, codeSections: executable.codeSections, + logicalAddress: executable.logicalAddress, bytes: executable.bytes, pages: [.init(logicalPage: 3, physicalPage: 4)], codeGuards: executable.codeGuards) + XCTAssertNil(metadata([function], executable: missingPage).entryFunction(named: "raw")) + let invalidPage = CMOCBankedDebugLayout.Module(id: executable.id, sections: executable.sections, codeSections: executable.codeSections, + logicalAddress: executable.logicalAddress, bytes: executable.bytes, pages: [.init(logicalPage: 2, physicalPage: -1)], codeGuards: executable.codeGuards) + XCTAssertNil(metadata([function], executable: invalidPage).entryFunction(named: "raw")) + } + + func testReadOnlyExpressionsAndCheckedWideArithmetic() { + let evaluator = fixture() + XCTAssertEqual(evaluator.evaluate("(local + global) * 2").value, "70") + XCTAssertEqual(evaluator.evaluate("32767 + 1").typeName, "watch integer (64-bit)") + XCTAssertEqual(evaluator.evaluate("32767 + 1").value, "32768") + XCTAssertEqual(evaluator.evaluate("0 && (1 / 0)").value, "0") + XCTAssertEqual(evaluator.evaluate("1 || missing").value, "1") + for expression in ["++local", "--local", "local++", "global=3", "main()", "1/0", "array[3]", "array[-1]", "1 << 40", "9223372036854775807+1", "9223372036854775807 << 1"] { + XCTAssertNotNil(evaluator.evaluate(expression).error, expression) + } + } + func testUnavailableIOStaleCodeAndMissingFramesFailExplicitly() { + XCTAssertNotNil(fixture(io: true).evaluate("*pointer").error) + XCTAssertNotNil(fixture(changedCode: true).evaluate("global").error) + XCTAssertNotNil(fixture(frame: false).evaluate("local").error) + XCTAssertNil(fixture(frame: false).evaluate("global").error) + let empty = CMOCWatchEvaluator(metadata: fixture().metadata, context: .init(pc: 0x2800, u: 0, memory: Data(), available: Data())) + XCTAssertNotNil(empty.evaluate("1").error) + XCTAssertNotNil(fixture().evaluate(String(repeating: "(", count: 40) + "1" + String(repeating: ")", count: 40)).error) + } + private func parse(_ type: [String: Any], mutateListing: Bool = false, tamperSymbol: Bool = false) throws -> CMOCVariableDebug { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("VCCVariableMetadata-" + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let source = Data("int main(void) { return 0; }\n".utf8), binary = Data([1,2,3]) + func c(_ value: String) -> [UInt8] { Array(value.utf8) + [0] } + let code = c("code") + [0] + c("_main") + [0,0] + c("body") + [0,0] + c("end") + [0,32] + [0,0,0,0,32] + Array(repeating: UInt8(0x12), count: 32) + let bss = c("bss") + [1,0] + c("_data") + [0,0] + [0,0,0,0,2] + let object = Data(c("LWOBJ16") + code + bss + [0]) + let records: [[String: Any]] = [ + ["kind":"function", "name":"main", "location":"main.c:1", "symbol":"_main", "begin":"body", "end":"end", "frame":true], + ["kind":"variable", "name":"data", "location":"main.c:1", "symbol":"_data", "begin":"", "end":"", "static":false, "type":type] + ] + let listing = try Data(records.map { "* VCCDBG1 " + String(decoding: try JSONSerialization.data(withJSONObject: $0), as: UTF8.self) }.joined(separator: "\n").utf8) + let map = Data(("Section: code (main.o) load at 2800, length 0020\nSection: bss (main.o) load at 3000, length 0002\nSymbol: _main (main.o) = 2800\nSymbol: body (main.o) = 2800\nSymbol: end (main.o) = 2820\nSymbol: _data (main.o) = " + (tamperSymbol ? "3001" : "3000") + "\n").utf8) + try listing.write(to: directory.appendingPathComponent("main.lst")); try object.write(to: directory.appendingPathComponent("main.o")); try map.write(to: directory.appendingPathComponent("main.map")) + let artifact = CMOCBuildArtifact(id: UUID(), directory: directory, source: "main.c", sourceData: source, + sourceSHA256: CMOCSourceMap.sha256(source), binaryData: binary, buildLog: "") + let verified = CMOCProjectSourceMap(entryPoint: 0x2800, binarySHA256: CMOCSourceMap.sha256(binary), sourceHashes: ["main.c":CMOCSourceMap.sha256(source)], + instructions: [], objectHashes: ["main.o":CMOCSourceMap.sha256(object)], listingHashes: ["main.o":CMOCSourceMap.sha256(listing)], linkMapSHA256: CMOCSourceMap.sha256(map)) + if mutateListing { try Data((String(decoding: listing, as: UTF8.self) + "\n").utf8).write(to: directory.appendingPathComponent("main.lst")) } + return try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: verified) + } + func testMetadataBindsToArtifactsAndRejectsOverflowingTypeLayouts() throws { + let integer: [String: Any] = ["name":"int", "kind":"integer", "size":2, "signed":true] + XCTAssertEqual(try parse(integer).variables[0].address, 0x3000) + XCTAssertThrowsError(try parse(integer, mutateListing: true)) + XCTAssertThrowsError(try parse(integer, tamperSymbol: true), "A forged unused map symbol must fail even when its hash agrees") + XCTAssertThrowsError(try parse(["name":"bad", "kind":"array", "size":2, "count":65535, + "element":["name":"bad", "kind":"integer", "size":Int.max, "signed":true]])) + XCTAssertThrowsError(try parse(["name":"bad", "kind":"aggregate", "size":2, + "members":[["name":"x", "offset":Int.max, "type":integer]]])) + var nested = integer + for _ in 0..<30 { nested = ["name":"pointer", "kind":"pointer", "size":2, "element":nested] } + XCTAssertThrowsError(try parse(nested)) + } + func testFloatingMetadataRequiresExplicitEncodingAndConsistentStorage() throws { + func floating(_ size: Int, _ format: String? = nil) -> [String: Any] { + var type: [String: Any] = ["name": "float", "kind": "floating", "size": size] + if let format { type["floatingFormat"] = format } + return type + } + XCTAssertNil(try parse(floating(5)).variables[0].type.floatingFormat) + XCTAssertEqual(try parse(floating(5, "coco-basic-40")).variables[0].type.floatingFormat, "coco-basic-40") + XCTAssertEqual(try parse(floating(4, "ieee754-binary32-be")).variables[0].type.floatingFormat, "ieee754-binary32-be") + XCTAssertEqual(try parse(floating(8, "unsupported")).variables[0].type.floatingFormat, "unsupported") + XCTAssertEqual(try parse(floating(5, "future-format")).variables[0].type.floatingFormat, "future-format") + XCTAssertThrowsError(try parse(floating(4, "coco-basic-40"))) + XCTAssertThrowsError(try parse(floating(5, "ieee754-binary32-be"))) + XCTAssertThrowsError(try parse(floating(5, String(repeating: "x", count: 129)))) + } + func testCompilerTagsActualFloatingFormatsIncludingNestedTypes() throws { + let runtime = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("LocalResources/ToolchainBundle") + let compiler = runtime.appendingPathComponent("bin/cmoc") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: compiler.path), "Staged compiler required") + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCFloatFormats-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let source = """ + float positive = 1.5f; + float negative = -2.25f; + double alias = 3.5f; + struct Values { float item; float samples[2]; } values; + int main(void) { float local = 0.5f; return local > 0; } + """ + for (mode, flags, format, size, positive, negative) in [ + ("basic", [String](), "coco-basic-40", 5, "$81,$40,$00,$00,$00", "$82,$90,$00,$00,$00"), + ("native", ["--native-float"], "coco-basic-40", 5, "$81,$40,$00,$00,$00", "$82,$90,$00,$00,$00"), + ("mc6839", ["--mc6839"], "ieee754-binary32-be", 4, "$3F,$C0,$00,$00", "$C0,$10,$00,$00") + ] { + let directory = root.appendingPathComponent(mode) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try Data(source.utf8).write(to: directory.appendingPathComponent("probe.c")) + let process = Process(), output = Pipe() + process.executableURL = compiler; process.currentDirectoryURL = directory + process.arguments = flags + ["-O0", "-fno-omit-frame-pointer", "--intermediate", "-c", "probe.c"] + process.standardOutput = output; process.standardError = output + try process.run() + let log = String(decoding: output.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + process.waitUntilExit() + XCTAssertEqual(process.terminationStatus, 0, log) + let assembly = try String(contentsOf: directory.appendingPathComponent("probe.s"), encoding: .utf8) + var types: [String: CMOCVariableDebug.CType] = [:] + for line in assembly.components(separatedBy: .newlines) { + guard let marker = line.range(of: "* VCCDBG1 ") else { continue } + let payload = Data(line[marker.upperBound...].utf8) + let record = try XCTUnwrap(JSONSerialization.jsonObject(with: payload) as? [String: Any]) + guard let name = record["name"] as? String, let rawType = record["type"] else { continue } + types[name] = try JSONDecoder().decode(CMOCVariableDebug.CType.self, + from: JSONSerialization.data(withJSONObject: rawType)) + } + for name in ["positive", "negative", "local", "alias"] { + let type = try XCTUnwrap(types[name], name) + XCTAssertEqual(type.kind, "floating"); XCTAssertEqual(type.floatingFormat, format) + XCTAssertEqual(type.size, size) + } + // CMOC 0.1.100 lowers source-level double to float, rather than + // providing an independent 64-bit target type. + XCTAssertEqual(types["alias"]?.name, "float") + XCTAssertEqual(types["values"]?.members?[0].type.floatingFormat, format) + XCTAssertEqual(types["values"]?.members?[1].type.element?.floatingFormat, format) + XCTAssertTrue(assembly.contains(positive)); XCTAssertTrue(assembly.contains(negative)) + } + } + func testMetadataPathsDoNotDependOnLiveIncrementalWorkspaceLifetime() async throws { + let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources") + let toolchain = resources.appendingPathComponent("ToolchainBundle") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path), "Staged compiler required") + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCMetadataLive-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + let main = "#include \n#include \nunsigned int score = 5;\nunsigned int transform(unsigned int);\nint main(void) { unsigned int round = 2; initCoCoSupport(); score = transform(round); return score; }\n" + let helper = "extern unsigned int score;\nunsigned int transform(unsigned int value) { unsigned int local = value + 5; score = local; return local * 2; }\n" + try Data(main.utf8).write(to: project.sourceURL) + try Data(helper.utf8).write(to: project.directory.appendingPathComponent("helper.c")) + let makefile = "CMOC ?= cmoc\nbuild: main.bin\nmain.bin: main.o helper.o\n\t$(CMOC) --intermediate -o $@ $^\n%.o: %.c\n\t$(CMOC) -O0 -fno-omit-frame-pointer --intermediate -c -o $@ $<\n" + try Data(makefile.utf8).write(to: project.makefileURL) + let service = CMOCBuildService(toolchain: toolchain, buildRoot: root.appendingPathComponent("Builds")) + let artifact = try await service.build(project: project, overlays: [:]) + try withExtendedLifetime(service) { + XCTAssertTrue(FileManager.default.fileExists(atPath: artifact.compilationDirectory.appendingPathComponent("helper.c").path)) + let map = try CMOCProjectSourceMap.parse(artifact: artifact) + let metadata = try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map) + XCTAssertEqual(Set(metadata.functions.map(\.name)), ["main", "transform"]) + XCTAssertTrue(metadata.variables.contains { $0.name == "local" && $0.sourcePath == "helper.c" }) + // A later incremental build may remove a source. Frozen debug + // artifacts remain valid even when the original physical path goes away. + try FileManager.default.removeItem(at: artifact.compilationDirectory.appendingPathComponent("helper.c")) + XCTAssertEqual(try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map).variables.count, metadata.variables.count) + } + } + + func testLongCompilerTypeRecordsUseOnlyVerifiedMatchingAssembly() async throws { + let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("LocalResources") + let toolchain = resources.appendingPathComponent("ToolchainBundle") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path), "Staged compiler required") + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCLongMetadata-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + let members = (0..<80).map { "unsigned char member\($0);" }.joined(separator: "\n") + let source = "struct Pilot {\n" + members + "\n};\nstruct Pilot pilot;\nstatic asm unsigned raw_probe(void) { asm { ldd #7 } }\nint main(void) { pilot.member79 = raw_probe(); return pilot.member79; }\n" + try Data(source.utf8).write(to: project.sourceURL) + let service = CMOCBuildService(toolchain: toolchain, buildRoot: root.appendingPathComponent("Builds")) + let artifact = try await service.build(project: project, overlays: [:]) + let map = try CMOCProjectSourceMap.parse(artifact: artifact) + let assemblyPath = "main.s", listingPath = "main.lst" + let original = try XCTUnwrap(artifact.sources[assemblyPath], "Compiler assembly must be part of the frozen build source set") + let assembly = String(decoding: original, as: UTF8.self) + let listing = try String(contentsOf: artifact.fileURL(listingPath), encoding: .utf8) + func records(_ text: String) -> [String] { + text.components(separatedBy: .newlines).compactMap { row in + row.range(of: "* VCCDBG1 ").map { String(row[$0.upperBound...]) } + } + } + XCTAssertTrue(records(assembly).contains { $0.utf8.count > 2048 }) + XCTAssertTrue(records(listing).contains { $0.utf8.count == 2038 }, "The real assembler truncates long comment rows at 2,048 input bytes") + let metadata = try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map) + let pilot = try XCTUnwrap(metadata.variables.first { $0.name == "pilot" }) + XCTAssertEqual(pilot.type.size, 80) + XCTAssertEqual(pilot.type.members?.count, 80) + XCTAssertEqual(pilot.type.members?.last?.name, "member79") + XCTAssertTrue(metadata.functions.contains { $0.name == "raw_probe" }, "Pure assembly still has honest compiler function metadata") + XCTAssertNil(metadata.breakpointInstruction(named: "raw_probe")) + XCTAssertFalse(metadata.breakpointFunctionNames.contains("raw_probe")) + XCTAssertNotNil(metadata.breakpointInstruction(named: "main")) + XCTAssertTrue(metadata.breakpointFunctionNames.contains("main")) + let mainFunction = try XCTUnwrap(metadata.functions.first { $0.name == "main" }) + let duplicate = CMOCVariableDebug(functions: metadata.functions + [mainFunction], variables: metadata.variables, sourceMap: map) + XCTAssertNil(duplicate.breakpointInstruction(named: "main")) + XCTAssertFalse(duplicate.breakpointFunctionNames.contains("main")) + XCTAssertNotNil(metadata.entryFunction(named: "raw_probe"), "Complete verified flat executable guards establish honest entry provenance") + var declarationOnly = map; declarationOnly.flatCodeGuards = [] + let unguarded = CMOCVariableDebug(functions: metadata.functions, variables: metadata.variables, sourceMap: declarationOnly) + XCTAssertNil(unguarded.entryFunction(named: "raw_probe"), "Compiler symbols alone do not establish executable entry provenance") + + // Reuse the real compiler result to qualify assembly entries against + // executable guards derived from the independently verified image. + var binaryBytes: [Int: UInt8] = [:], cursor = 0 + while cursor + 5 <= artifact.binaryData.count { + let type = artifact.binaryData[cursor] + let length = Int(artifact.binaryData[cursor + 1]) * 256 + Int(artifact.binaryData[cursor + 2]) + let address = Int(artifact.binaryData[cursor + 3]) * 256 + Int(artifact.binaryData[cursor + 4]) + cursor += 5 + if type == 255 { break } + guard type == 0, cursor + length <= artifact.binaryData.count else { return XCTFail("Unexpected compiler DECB result") } + for offset in 0.. CMOCBankedDebugLayout.CodeGuard in + XCTAssertGreaterThan(function.end, function.entry) + let code = try (function.entry.. (CMOCBuildArtifact, CMOCProjectSourceMap) { + let copy = CMOCBuildArtifact(id: artifact.id, directory: artifact.directory, source: artifact.source, + sourceData: artifact.sourceData, sourceSHA256: artifact.sourceSHA256, binaryData: artifact.binaryData, + buildLog: artifact.buildLog, sources: sources, fileHashes: artifact.fileHashes, + compilationDirectory: artifact.compilationDirectory, entrySourcePath: artifact.entrySourcePath, + binaryRelativePath: artifact.binaryRelativePath, diskRelativePath: artifact.diskRelativePath, + outputPaths: artifact.outputPaths, configurationName: artifact.configurationName, action: artifact.action) + let verified = CMOCProjectSourceMap(entryPoint: map.entryPoint, binarySHA256: map.binarySHA256, + sourceHashes: sources.mapValues(CMOCSourceMap.sha256), instructions: map.instructions, + objectHashes: map.objectHashes, listingHashes: map.listingHashes, linkMapSHA256: map.linkMapSHA256) + return (copy, verified) + } + // A stale immutable source set is rejected before assembly recovery. + var forged = artifact.sources + forged[assemblyPath] = Data((assembly + "\n").utf8) + XCTAssertThrowsError(try CMOCVariableDebug.parse(artifact: evidence(forged).0, verifiedMap: map)) + + // Matching hashes alone are insufficient: records must still correspond + // to the independently verified listing in count and order. + var rows = assembly.components(separatedBy: .newlines) + let positions = rows.indices.filter { rows[$0].contains("* VCCDBG1 ") } + let first = try XCTUnwrap(positions.first), second = try XCTUnwrap(positions.dropFirst().first) + rows.swapAt(first, second) + let reordered = Data(rows.joined(separator: "\n").utf8) + forged[assemblyPath] = reordered + try reordered.write(to: artifact.fileURL(assemblyPath)) + var candidate = evidence(forged) + XCTAssertThrowsError(try CMOCVariableDebug.parse(artifact: candidate.0, verifiedMap: candidate.1)) { error in + XCTAssertTrue(error.localizedDescription.contains("differs from the verified listing")) + } + rows.remove(at: first) + let removed = Data(rows.joined(separator: "\n").utf8) + forged[assemblyPath] = removed + try removed.write(to: artifact.fileURL(assemblyPath)) + candidate = evidence(forged) + XCTAssertThrowsError(try CMOCVariableDebug.parse(artifact: candidate.0, verifiedMap: candidate.1)) { error in + XCTAssertTrue(error.localizedDescription.contains("record count differs")) + } + try original.write(to: artifact.fileURL(assemblyPath)) + var unhashed = artifact.sources + unhashed.removeValue(forKey: assemblyPath) + candidate = evidence(unhashed) + XCTAssertThrowsError(try CMOCVariableDebug.parse(artifact: candidate.0, verifiedMap: candidate.1)) { error in + XCTAssertTrue(error.localizedDescription.contains("invalid or truncated JSON")) + XCTAssertTrue(error.localizedDescription.contains(listingPath)) + } + } + +} diff --git a/platforms/macos/Tests/CMOCVariableTreeIntegrationTests.swift b/platforms/macos/Tests/CMOCVariableTreeIntegrationTests.swift new file mode 100644 index 0000000..91baf58 --- /dev/null +++ b/platforms/macos/Tests/CMOCVariableTreeIntegrationTests.swift @@ -0,0 +1,210 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +/// Qualifies expandable values against real CMOC output and current/caller frames. +final class CMOCVariableTreeIntegrationTests: XCTestCase { + private struct Fixture { + let root: URL + let artifact: CMOCBuildArtifact + let metadata: CMOCVariableDebug + let rom: Data + let sources: [String: String] + func line(_ marker: String, file: String) throws -> Int { + try XCTUnwrap(sources[file]?.components(separatedBy: "\n").firstIndex { $0.contains(marker) }) + 1 + } + func address(_ marker: String, file: String) throws -> UInt16 { + try XCTUnwrap(metadata.sourceMap.addresses(forLine: line(marker, file: file), in: file).first, marker) + } + } + private func fixture() async throws -> Fixture { + let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources") + let toolchain = resources.appendingPathComponent("ToolchainBundle") + let rom = resources.appendingPathComponent("ROMs/coco3.rom") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) + && FileManager.default.fileExists(atPath: rom.path), "Local licensed CoCo ROM and staged toolchain are required") + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCVariableTree-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + do { + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + let sources = ["types.h": """ + struct Point { int x; int y; }; + struct Bag { struct Point point; unsigned int samples[40]; struct Point *pointer; }; + """, "main.c": """ + #include + #include + #include "types.h" + unsigned int result; + unsigned int inspect(struct Bag *parent); + int main(void) + { + struct Bag bag; + unsigned int i; + initCoCoSupport(); + bag.point.x = -7; + bag.point.y = 11; + bag.pointer = &bag.point; + for (i = 0; i < 40; ++i) bag.samples[i] = 100 + i; + result = inspect(&bag); /* MAIN_CALL */ + for (;;) ++result; + return 0; + } + """, "helper.c": """ + #include "types.h" + extern unsigned int result; + struct Point *nullPoint = 0; + unsigned char *ioPointer = (unsigned char *)0xFF00; + unsigned int inspect(struct Bag *parent) + { + struct Bag local; + unsigned int i; + local.point.x = -17; + local.point.y = 21; + local.pointer = &local.point; + for (i = 0; i < 40; ++i) local.samples[i] = 200 + i; + result = local.samples[39]; /* LEAF_STOP */ + return result + parent->samples[39]; + } + """] + for (name, source) in sources { try Data(source.utf8).write(to: project.directory.appendingPathComponent(name)) } + let makefile = """ + CMOC ?= cmoc + build: main.bin + main.bin: main.o helper.o + \t"$(CMOC)" --coco --intermediate --org=2800 -o $@ main.o helper.o + main.o: main.c + \t"$(CMOC)" --coco --intermediate -O0 -fno-omit-frame-pointer -c -o $@ $< + helper.o: helper.c + \t"$(CMOC)" --coco --intermediate -O0 -fno-omit-frame-pointer -c -o $@ $< + """ + try Data(makefile.utf8).write(to: project.makefileURL) + let service = CMOCBuildService(toolchain: toolchain, buildRoot: root.appendingPathComponent("Builds")) + let artifact = try await service.build(project: project, overlays: [:]) + let map = try CMOCProjectSourceMap.parse(artifact: artifact) + let metadata = try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map) + return Fixture(root: root, artifact: artifact, metadata: metadata, rom: try Data(contentsOf: rom), sources: sources) + } catch { try? FileManager.default.removeItem(at: root); throw error } + } + @MainActor private func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { continuation in operation { continuation.resume(returning: $0) } } + } + @MainActor private func capture(_ controller: VCCMachineController) async -> VCCDebuggerSnapshot { + await withCheckedContinuation { continuation in + controller.debuggerSnapshot(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) } + } + } + @MainActor private func withStoppedProcessors(_ fixture: Fixture, + body: (VCCMachineController, VCCDebuggerSnapshot) async throws -> Void) async throws { + for use6309 in [false, true] { + let controller = VCCMachineController() + do { + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + let loaded = await command { controller.loadROM(fixture.rom, use6309: use6309, completion: $0) } + XCTAssertNil(loaded.errorMessage) + _ = await command(controller.resume) + try await Task.sleep(nanoseconds: 1_500_000_000) + _ = await command(controller.pause) + let breakpoint = try fixture.address("LEAF_STOP", file: "helper.c") + var state = await command { controller.debuggerLoadBinary(fixture.artifact.binaryData, breakpoint: breakpoint, completion: $0) } + for _ in 0..<1000 where state.state == .running { + try await Task.sleep(nanoseconds: 5_000_000) + state = await command(controller.snapshot) + } + XCTAssertNil(state.errorMessage) + XCTAssertEqual(state.state, .paused) + XCTAssertEqual(state.programCounter, breakpoint) + try await body(controller, await capture(controller)) + _ = await command(controller.shutdown) + } catch { _ = await command(controller.shutdown); throw error } + } + } + private func stack(_ fixture: Fixture, _ snapshot: VCCDebuggerSnapshot, + memory: Data? = nil, available: Data? = nil) throws -> CMOCCallStack { + CMOCCallStack.capture(metadata: fixture.metadata, pc: snapshot.machine.programCounter, + u: try XCTUnwrap(snapshot.registers["U"]?.uint16Value), s: try XCTUnwrap(snapshot.registers["S"]?.uint16Value), + memory: memory ?? snapshot.logicalMemory, available: available ?? snapshot.logicalMemoryAvailable) + } + private typealias TreePath = CMOCWatchEvaluator.TreePath + private func variable(_ name: String, _ components: [CMOCWatchEvaluator.Component] = []) -> TreePath { + TreePath(root: .variable(name), components: components) + } + @MainActor func testCompiledAggregatePagesAndPointersUseSelectedFrameWithoutGuestSideEffects() async throws { + let fixture = try await fixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + try await withStoppedProcessors(fixture) { controller, snapshot in + let originalMemory = Data(Array(snapshot.logicalMemory)) + let frames = try stack(fixture, snapshot) + XCTAssertEqual(frames.frames.map(\.functionName), ["inspect", "main"], frames.termination) + guard frames.frames.count == 2 else { return } + func evaluator(_ frame: CMOCCallStack.Frame, memory: Data? = nil, + available: Data? = nil) -> CMOCWatchEvaluator { + CMOCWatchEvaluator(metadata: fixture.metadata, + context: .init(pc: frame.pc, u: frame.u, memory: memory ?? snapshot.logicalMemory, + available: available ?? snapshot.logicalMemoryAvailable), + frameLocalsAvailable: frame.localsInspectable) + } + let current = evaluator(frames.frames[0]), caller = evaluator(frames.frames[1]) + let local = variable("local") + let roots = current.variableTreeRoots() + let localRoot = try XCTUnwrap(roots.first { $0.path == local }) + XCTAssertNil(localRoot.error) + XCTAssertEqual(localRoot.childCount, 3) + XCTAssertEqual(current.children(of: local).nodes.count, 3) + XCTAssertNil(current.children(of: local).error) + for (engine, root, start, x, y) in [(current, "local", 200, "-17", "21"), + (caller, "bag", 100, "-7", "11")] { + let samples = variable(root, [.member("samples")]) + let first = engine.children(of: samples) + XCTAssertNil(first.error) + XCTAssertEqual(first.totalCount, 40) + XCTAssertEqual(first.nodes.count, 32) + XCTAssertEqual(first.nextOffset, 32) + XCTAssertEqual(first.nodes.map(\.value), (0..<32).map { String(start + $0) }) + let second = engine.children(of: samples, offset: 32) + XCTAssertNil(second.error) + XCTAssertEqual(second.nodes.count, 8) + XCTAssertNil(second.nextOffset) + XCTAssertEqual(second.nodes.map(\.value), (32..<40).map { String(start + $0) }) + XCTAssertEqual(Set((first.nodes + second.nodes).map(\.path)).count, 40, + "Array children must keep distinct typed paths across pages") + XCTAssertEqual(engine.treeNode(at: variable(root, [.member("point"), .member("x")])).value, x) + XCTAssertEqual(engine.treeNode(at: variable(root, [.member("point"), .member("y")])).value, y) + let pointer = variable(root, [.member("pointer")]) + XCTAssertEqual(engine.treeNode(at: pointer).childCount, 1) + XCTAssertEqual(engine.children(of: pointer).nodes.count, 1) + XCTAssertEqual(engine.treeNode(at: variable(root, [.member("pointer"), .pointee, .member("x")])).value, x) + } + // The leaf's pointer argument refers to the caller's real aggregate. + let parentSamples = variable("parent", [.pointee, .member("samples")]) + XCTAssertEqual(current.children(of: parentSamples, offset: 32).nodes.map(\.value), + (132..<140).map(String.init)) + let watch = current.watchTreeRoot("parent->point") + XCTAssertNil(watch.error) + XCTAssertEqual(watch.childCount, 2) + XCTAssertEqual(current.children(of: watch.path).nodes.map(\.value), ["-7", "11"]) + // Pointer expansion is explicit and never invokes memory-mapped I/O. + for name in ["nullPoint", "ioPointer"] { + let root = current.treeNode(at: variable(name)) + XCTAssertNil(root.error, "Reading a pointer value is different from dereferencing it") + let page = current.children(of: variable(name)) + XCTAssertTrue(page.error != nil || page.nodes.contains { $0.error != nil }, + "Unsafe pointees need an explicit explanation") + } + // Reusing a typed path must still revalidate the current snapshot. + // Force independent storage: mutating a directly bridged NSData + // value can also mutate the test snapshot's backing bytes. + var altered = Data(Array(originalMemory)) + let instruction = try XCTUnwrap(fixture.metadata.sourceMap.instructions.first) + altered[Int(instruction.address)] ^= 1 + let stale = evaluator(frames.frames[0], memory: altered) + XCTAssertNotNil(stale.treeNode(at: variable("local", [.member("samples"), .index(39)])).error) + XCTAssertNotNil(stale.children(of: local).error) + let after = await capture(controller) + XCTAssertEqual(after.machine.programCounter, snapshot.machine.programCounter) + XCTAssertEqual(after.machine.cycles, snapshot.machine.cycles) + XCTAssertEqual(after.registers, snapshot.registers) + XCTAssertEqual(snapshot.logicalMemory, originalMemory, "Inspection must not mutate its captured snapshot") + XCTAssertEqual(after.logicalMemory, originalMemory, + "Expanding current/caller values and pointer errors must not execute guest code or touch memory") + } + } +} diff --git a/platforms/macos/Tests/CMOCVariableTreeTests.swift b/platforms/macos/Tests/CMOCVariableTreeTests.swift new file mode 100644 index 0000000..445a029 --- /dev/null +++ b/platforms/macos/Tests/CMOCVariableTreeTests.swift @@ -0,0 +1,151 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CMOCVariableTreeTests: XCTestCase { + private struct Fixture { + let metadata: CMOCVariableDebug + var memory: Data + var available: Data + func evaluator(u: UInt16 = 0x4000, locals: Bool = true) -> CMOCWatchEvaluator { + CMOCWatchEvaluator(metadata: metadata, context: .init(pc: 0x2800, u: u, memory: memory, available: available), frameLocalsAvailable: locals) + } + mutating func word(_ address: Int, _ value: UInt16) { + memory[address] = UInt8(value >> 8); memory[address + 1] = UInt8(value & 255) + } + } + private func fixture() -> Fixture { + let word = CMOCVariableDebug.CType.integer + let array = CMOCVariableDebug.CType(name: "int[40]", kind: "array", size: 80, count: 40, element: word) + let small = CMOCVariableDebug.CType(name: "int[3]", kind: "array", size: 6, count: 3, element: word) + let float = CMOCVariableDebug.CType(name: "float", kind: "floating", size: 5) + let bag = CMOCVariableDebug.CType(name: "struct Bag", kind: "aggregate", size: 13, members: [ + .init(name: "number", offset: 0, type: word), .init(name: "unsupported", offset: 2, type: float), + .init(name: "items", offset: 7, type: small) + ]) + let union = CMOCVariableDebug.CType(name: "union Word", kind: "aggregate", size: 2, members: [ + .init(name: "first", offset: 0, type: word), .init(name: "second", offset: 0, type: word) + ]) + let pointer = CMOCVariableDebug.CType(name: "int *", kind: "pointer", size: 2, element: word) + let terminal = CMOCVariableDebug.CType(name: "struct Node", kind: "aggregate", size: 4, members: []) + let next = CMOCVariableDebug.CType(name: "struct Node *", kind: "pointer", size: 2, element: terminal) + let node = CMOCVariableDebug.CType(name: "struct Node", kind: "aggregate", size: 4, members: [ + .init(name: "value", offset: 0, type: word), .init(name: "next", offset: 2, type: next) + ]) + var deep = word + for _ in 0..<14 { deep = .init(name: "int[]", kind: "array", size: 2, count: 1, element: deep) } + let wide = CMOCVariableDebug.CType(name: "struct Wide", kind: "aggregate", size: 80, + members: (0..<40).map { .init(name: "field\($0)", offset: $0 * 2, type: word) }) + let entries: [(String, CMOCVariableDebug.CType, Int)] = [ + ("array", array, 0x3000), ("bag", bag, 0x3100), ("union", union, 0x3120), + ("pointer", pointer, 0x3200), ("null", pointer, 0x3202), ("io", pointer, 0x3204), + ("node", node, 0x3300), ("deep", deep, 0x3400), ("wide", wide, 0x3500) + ] + let map = CMOCProjectSourceMap(entryPoint: 0x2800, binarySHA256: "", sourceHashes: [:], + instructions: [.init(sourcePath: "main.c", sourceLine: 5, address: 0x2800, bytes: [0x12], assembly: "NOP")], + objectHashes: [:], listingHashes: [:], linkMapSHA256: "") + let variables = entries.map { CMOCVariableDebug.Variable(name: $0.0, sourcePath: "main.c", line: 1, type: $0.1, + address: $0.2, offset: nil, scope: nil, isStatic: false) } + [ + .init(name: "local", sourcePath: "main.c", line: 2, type: small, address: nil, offset: -6, scope: 0x2800..<0x2820, isStatic: false) + ] + let metadata = CMOCVariableDebug(functions: [.init(name: "main", sourcePath: "main.c", entry: 0x2800, body: 0x2800, end: 0x2820, frame: true)], variables: variables, sourceMap: map) + var result = Fixture(metadata: metadata, memory: Data(repeating: 0, count: 65536), available: Data(repeating: 1, count: 65536)) + result.memory[0x2800] = 0x12 + for i in 0..<40 { result.word(0x3000 + 2*i, UInt16(i)); result.word(0x3500 + 2*i, UInt16(100 + i)) } + result.word(0x3100, 7); result.word(0x3107, 11); result.word(0x3109, 22); result.word(0x310b, 33) + result.word(0x3120, 456); result.word(0x3200, 0x3109); result.word(0x3204, 0xff00) + result.word(0x3300, 8); result.word(0x3302, 0x3300) + result.word(0x3ffa, 9); result.word(0x40fa, 19) + for i in 0xff00..<65536 { result.available[i] = 0 } + return result + } + private func path(_ name: String, _ components: [CMOCWatchEvaluator.Component] = []) -> CMOCWatchEvaluator.TreePath { + .init(root: .variable(name), components: components) + } + func testArrayAndMemberPagesRespectDeclaredBoundsAndStableTypedIdentity() { + let evaluator = fixture().evaluator() + let root = evaluator.treeNode(at: path("array")) + XCTAssertEqual(root.childCount, 40) + XCTAssertEqual(root.value, "[40 elements]") + let first = evaluator.children(of: root.path) + XCTAssertEqual(first.nodes.count, 32); XCTAssertEqual(first.nextOffset, 32) + XCTAssertEqual(first.nodes.first?.name, "[0]"); XCTAssertEqual(first.nodes.last?.value, "31") + let last = evaluator.children(of: root.path, offset: 32) + XCTAssertEqual(last.nodes.count, 8); XCTAssertNil(last.nextOffset); XCTAssertEqual(last.nodes.last?.value, "39") + XCTAssertNotNil(evaluator.children(of: root.path, offset: -1).error) + XCTAssertNotNil(evaluator.children(of: root.path, offset: 41).error) + XCTAssertNotNil(evaluator.treeNode(at: path("array", [.index(40)])).error) + XCTAssertNotNil(evaluator.treeNode(at: path("pointer", [.index(0)])).error, "Pointers must not imply array bounds") + XCTAssertNotEqual(root.id, evaluator.watchTreeRoot("array").id) + let members = evaluator.children(of: path("wide"), offset: 32) + XCTAssertEqual(members.nodes.map(\.name), (32..<40).map { "field\($0)" }) + XCTAssertEqual(members.nodes.last?.value, "139") + } + func testUnsupportedAggregateChildrenDoNotHideSiblingsOrNestedArraysAndUnions() { + let evaluator = fixture().evaluator() + XCTAssertNil(evaluator.treeNode(at: path("bag")).error) + let members = evaluator.children(of: path("bag")).nodes + XCTAssertEqual(members.count, 3); XCTAssertEqual(members[0].value, "7") + XCTAssertNotNil(members[1].error); XCTAssertEqual(members[1].typeName, "float"); XCTAssertEqual(members[2].childCount, 3) + XCTAssertEqual(evaluator.children(of: members[2].path).nodes.map(\.value), ["11", "22", "33"]) + XCTAssertEqual(evaluator.children(of: path("union")).nodes.map(\.value), ["456", "456"]) + let watch = evaluator.watchTreeRoot("(bag)") + XCTAssertEqual(evaluator.children(of: watch.path).nodes[0].value, "7") + } + func testPointerExpansionIsExplicitAndNullIOAndCyclesFailAtTheirOwnChild() { + let evaluator = fixture().evaluator() + XCTAssertEqual(evaluator.treeNode(at: path("pointer")).value, "$3109") + XCTAssertEqual(evaluator.children(of: path("pointer")).nodes.first?.value, "22") + for name in ["null", "io"] { + XCTAssertNil(evaluator.treeNode(at: path(name)).error) + let child = evaluator.children(of: path(name)).nodes.first + XCTAssertEqual(child?.name, "Pointee"); XCTAssertNotNil(child?.error); XCTAssertEqual(child?.childCount, 0) + } + let child = evaluator.children(of: path("node", [.member("next")])).nodes.first + XCTAssertTrue(child?.error?.contains("cycle") == true) + XCTAssertEqual(evaluator.treeNode(at: path("node", [.member("value")])).value, "8") + } + func testDepthLimitAndUnavailableSiblingAreBounded() { + var fixture = fixture(); fixture.available[0x3100] = 0 + let evaluator = fixture.evaluator() + let members = evaluator.children(of: path("bag")).nodes + XCTAssertNotNil(members[0].error) + XCTAssertNil(members[2].error) + XCTAssertEqual(evaluator.children(of: members[2].path).nodes[1].value, "22") + let deep = path("deep", Array(repeating: .index(0), count: 12)) + XCTAssertEqual(evaluator.treeNode(at: deep).childCount, 0) + XCTAssertNotNil(evaluator.treeNode(at: deep).error) + XCTAssertNotNil(evaluator.children(of: deep).error) + XCTAssertNotNil(evaluator.treeNode(at: deep.appending(.index(0))).error) + } + func testPathsResolveAgainForSelectedFramesStaleCodeAndLocalAvailability() { + var fixture = fixture() + let local = path("local", [.index(0)]) + XCTAssertEqual(fixture.evaluator().treeNode(at: local).value, "9") + XCTAssertEqual(fixture.evaluator(u: 0x4100).treeNode(at: local).value, "19") + var gated = fixture.evaluator() + XCTAssertEqual(gated.treeNode(at: local).value, "9") + gated.frameLocalsAvailable = false + XCTAssertNotNil(gated.treeNode(at: local).error, "Cached code verification must not cache local availability") + XCTAssertNotNil(gated.children(of: path("local")).error) + XCTAssertNil(gated.treeNode(at: path("array", [.index(0)])).error) + fixture.memory[0x2800] = 0x39 + let stale = fixture.evaluator() + XCTAssertNotNil(stale.children(of: path("array")).error) + XCTAssertNotNil(stale.treeNode(at: local).error) + XCTAssertNotNil(stale.watchTreeRoot("1 + 2").error) + } + func testCachedVerificationOwnsFoundationSnapshotBuffers() { + let fixture = fixture() + let memory = NSMutableData(data: fixture.memory), availability = NSMutableData(data: fixture.available) + let evaluator = CMOCWatchEvaluator(metadata: fixture.metadata, + context: .init(pc: 0x2800, u: 0x4000, memory: Data(referencing: memory), available: Data(referencing: availability))) + XCTAssertEqual(evaluator.treeNode(at: path("array", [.index(1)])).value, "1") + memory.mutableBytes.assumingMemoryBound(to: UInt8.self)[0x2800] = 0x39 + memory.mutableBytes.assumingMemoryBound(to: UInt8.self)[0x3003] = 99 + availability.mutableBytes.assumingMemoryBound(to: UInt8.self)[0x3002] = 0 + XCTAssertEqual(evaluator.context.memory[0x2800], 0x12) + XCTAssertEqual(evaluator.context.available[0x3002], 1) + XCTAssertEqual(evaluator.treeNode(at: path("array", [.index(1)])).value, "1") + } + +} diff --git a/platforms/macos/Tests/CMOCWorkflowHardeningTests.swift b/platforms/macos/Tests/CMOCWorkflowHardeningTests.swift new file mode 100644 index 0000000..a052e18 --- /dev/null +++ b/platforms/macos/Tests/CMOCWorkflowHardeningTests.swift @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CMOCWorkflowHardeningTests: XCTestCase { + private var resources: URL { + URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("LocalResources") + } + @MainActor private func waitForBuild(_ model: CMOCDevelopmentModel) async throws { + for _ in 0..<3000 where model.building { try await Task.sleep(nanoseconds: 10_000_000) } + XCTAssertFalse(model.building, "Build should finish or cancel within the test deadline") + } + @MainActor private func snapshot(_ machine: MachineModel) async throws -> VCCDebuggerSnapshot { + let value: VCCDebuggerSnapshot? = await withCheckedContinuation { continuation in + machine.readDebugger(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) } + } + return try XCTUnwrap(value) + } + @MainActor func testFailedCancelledAndCleanBuildsKeepLastRunnableAndLoadedIdentity() async throws { + let toolchain = resources.appendingPathComponent("ToolchainBundle") + let rom = resources.appendingPathComponent("ROMs/coco3.rom") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path) + && FileManager.default.fileExists(atPath: rom.path), "Staged toolchain and local CoCo ROM required") + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCWorkflow-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let suite = "CMOCWorkflow.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) } + let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: root.appendingPathComponent("input.json"))) + let model = CMOCDevelopmentModel(machine: machine, toolchain: toolchain, defaults: defaults, + buildRoot: root.appendingPathComponent("Builds"), recoveryRoot: root.appendingPathComponent("Recovery")) + do { + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + try model.adopt(project) + let source = model.source + model.build(); try await waitForBuild(model) + let successful = try XCTUnwrap(model.artifact, model.message ?? model.log) + XCTAssertTrue(successful.hasBinary) + for _ in 0..<500 where machine.busy { try await Task.sleep(nanoseconds: 10_000_000) } + machine.installROM(try Data(contentsOf: rom), url: rom) + for _ in 0..<500 where machine.busy { try await Task.sleep(nanoseconds: 10_000_000) } + try await Task.sleep(nanoseconds: 1_500_000_000) + model.breakpointLine = 9 + model.run() + for _ in 0..<500 where model.currentLine != 9 { + model.refresh(); try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertEqual(model.currentLine, 9, model.message ?? model.execution) + XCTAssertEqual(model.launchedBuildID, successful.id) + let before = try await snapshot(machine) + let beforeMemory = Data(Array(before.logicalMemory)) + + model.source += "\n#error intentional_failed_build\n" + model.build(); try await waitForBuild(model) + XCTAssertEqual(model.artifact?.id, successful.id, "A failed attempt must not erase the last runnable result") + XCTAssertEqual(model.launchedBuildID, successful.id, "Building does not replace the guest program") + XCTAssertTrue(model.latestBuildAttempt.localizedCaseInsensitiveContains("failed")) + XCTAssertFalse(model.buildMatchesEditor) + XCTAssertFalse(model.canInspectC, "The changed source cannot inspect the old loaded program") + XCTAssertTrue(FileManager.default.fileExists(atPath: successful.directory.path)) + + model.source = source + model.build(.clean); try await waitForBuild(model) + XCTAssertEqual(model.artifact?.id, successful.id, "Clean has no new runnable result") + XCTAssertEqual(model.launchedBuildID, successful.id) + XCTAssertTrue(FileManager.default.fileExists(atPath: successful.binaryURL.path), "Clean affects its work cache, not a frozen successful result") + + model.openFile("Makefile") + let makefile = model.source + model.source += "\nslow:\n\tsleep 5\n" + model.build(.custom, target: "slow") + try await Task.sleep(nanoseconds: 150_000_000) + model.cancelBuild(); try await waitForBuild(model) + XCTAssertEqual(model.artifact?.id, successful.id) + XCTAssertEqual(model.launchedBuildID, successful.id) + XCTAssertTrue(model.latestBuildAttempt.localizedCaseInsensitiveContains("cancel")) + + model.source = makefile + model.build(); try await waitForBuild(model) + XCTAssertNotEqual(model.artifact?.id, successful.id, "A new successful build becomes the runnable result") + XCTAssertTrue(model.buildMatchesEditor) + XCTAssertEqual(model.launchedBuildID, successful.id, "Compiling a new result does not load it into the guest") + model.refresh(); try await Task.sleep(nanoseconds: 100_000_000) + XCTAssertFalse(model.canInspectC, "New source mappings cannot attach themselves to the old program") + let other = try CMOCProject.create(at: root.appendingPathComponent("OtherProject")) + try model.adopt(other) + XCTAssertNil(model.artifact, "A different project does not inherit a foreign runnable result") + XCTAssertEqual(model.launchedBuildID, successful.id, "Switching editors does not replace the guest program") + XCTAssertFalse(model.canInspectC) + let after = try await snapshot(machine) + XCTAssertEqual(after.machine.programCounter, before.machine.programCounter) + XCTAssertEqual(after.machine.cycles, before.machine.cycles) + XCTAssertEqual(after.registers, before.registers) + XCTAssertEqual(after.logicalMemory, beforeMemory, "Build, Clean and Cancel must leave the paused guest untouched") + await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } } + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } catch { + model.cancelBuild() + await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } } + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + throw error + } + } + @MainActor func testMissingOpenFilesPreserveTextAndInvalidateBuildWithoutRecreatingFiles() async throws { + let toolchain = resources.appendingPathComponent("ToolchainBundle") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path), "Staged toolchain required") + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCMissingFiles-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let suite = "CMOCMissingFiles.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) } + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + let cleanURL = project.directory.appendingPathComponent("clean.h"), dirtyURL = project.directory.appendingPathComponent("dirty.h") + try Data("#define CLEAN 1\n".utf8).write(to: cleanURL) + try Data("#define DIRTY 2\n".utf8).write(to: dirtyURL) + let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: root.appendingPathComponent("input.json"))) + let model = CMOCDevelopmentModel(machine: machine, toolchain: toolchain, defaults: defaults, + buildRoot: root.appendingPathComponent("Builds"), recoveryRoot: root.appendingPathComponent("Recovery")) + do { + try model.adopt(project) + model.openFile("clean.h"); model.openFile("dirty.h") + model.build(); try await waitForBuild(model) + XCTAssertTrue(model.buildMatchesEditor, model.message ?? model.log) + model.source = "#define DIRTY 3\n" + try FileManager.default.removeItem(at: cleanURL); try FileManager.default.removeItem(at: dirtyURL) + model.checkExternalFiles() + XCTAssertEqual(model.documents.first { $0.id == "clean.h" }?.text, "#define CLEAN 1\n") + XCTAssertEqual(model.documents.first { $0.id == "dirty.h" }?.text, "#define DIRTY 3\n") + XCTAssertTrue(model.documents.first { $0.id == "clean.h" }?.missing == true) + XCTAssertTrue(model.documents.first { $0.id == "dirty.h" }?.missing == true) + XCTAssertFalse(model.buildMatchesEditor) + XCTAssertFalse(model.saveFile("dirty.h"), "Recreating a missing source needs an explicit recovery action") + XCTAssertFalse(FileManager.default.fileExists(atPath: dirtyURL.path)) + model.openFile("clean.h") + XCTAssertEqual(model.source, "#define CLEAN 1\n", "Missing open files must remain available for recovery") + await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } } + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } catch { + model.cancelBuild() + await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } } + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + throw error + } + } + @MainActor func testReopeningInterruptedBuildReportsIncompleteAttemptWithoutBuildingOrLaunching() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCInterrupted-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let suite = "CMOCInterrupted.\(UUID().uuidString)", defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) } + let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) + let marker = project.directory.appendingPathComponent("BUILD_WAS_RUN") + try Data("build:\n\ttouch BUILD_WAS_RUN\n".utf8).write(to: project.directory.appendingPathComponent("Makefile")) + let key = "CMOCBuildAttempt." + CMOCProject.sha256(Data(project.directory.resolvingSymlinksInPath().path.utf8)) + defaults.set("In progress", forKey: key) + defaults.set(project.directory.path, forKey: "CMOCWorkspace.directory") + let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: root.appendingPathComponent("input.json"))) + let model = CMOCDevelopmentModel(machine: machine, defaults: defaults, + buildRoot: root.appendingPathComponent("Builds"), recoveryRoot: root.appendingPathComponent("Recovery")) + do { + for _ in 0..<500 where machine.busy { try await Task.sleep(nanoseconds: 10_000_000) } + let before = try await snapshot(machine) + model.restoreWorkspace() + XCTAssertEqual(model.project?.directory, project.directory) + XCTAssertTrue(model.latestBuildAttempt.contains("did not report completion")) + XCTAssertFalse(model.building) + XCTAssertNil(model.artifact) + XCTAssertNil(model.launchedBuildID) + XCTAssertFalse(model.canRun) + XCTAssertFalse(FileManager.default.fileExists(atPath: marker.path), "Reopening a project must never execute its Makefile") + let after = try await snapshot(machine) + XCTAssertEqual(after.machine.generation, before.machine.generation) + XCTAssertEqual(after.machine.debuggerProgramRevision, before.machine.debuggerProgramRevision) + XCTAssertEqual(after.machine.programCounter, before.machine.programCounter) + XCTAssertEqual(after.machine.cycles, before.machine.cycles) + await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } } + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } catch { + await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } } + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + throw error + } + } +} diff --git a/platforms/macos/Tests/CMOCWorkspaceRecoveryTests.swift b/platforms/macos/Tests/CMOCWorkspaceRecoveryTests.swift new file mode 100644 index 0000000..b56856a --- /dev/null +++ b/platforms/macos/Tests/CMOCWorkspaceRecoveryTests.swift @@ -0,0 +1,230 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest +import Darwin + +final class CMOCWorkspaceRecoveryTests: XCTestCase { + private struct Fixture { + let root: URL + var project: URL { root.appendingPathComponent("Project") } + var store: URL { root.appendingPathComponent("Recovery") } + func recovery(session: UUID = UUID(), pid: Int32 = Int32.max) -> CMOCWorkspaceRecovery { + CMOCWorkspaceRecovery(root: store, sessionID: session, processID: pid) + } + var projectFolder: URL { store.appendingPathComponent(CMOCProject.sha256(Data(project.resolvingSymlinksInPath().path.utf8))) } + func remove() { try? FileManager.default.removeItem(at: root) } + } + private func fixture() throws -> Fixture { + let fixture = Fixture(root: FileManager.default.temporaryDirectory.appendingPathComponent("CRecovery-" + UUID().uuidString)) + try FileManager.default.createDirectory(at: fixture.project, withIntermediateDirectories: true) + return fixture + } + private func draft(_ path: String = "main.c", text: String = "int changed;", saved: String = "int original;") -> CMOCWorkspaceRecovery.Draft { + .init(path: path, text: text, savedText: saved, savedHash: CMOCProject.sha256(Data(saved.utf8))) + } + func testRecoveryRetainsDraftAndOriginalIdentityWithoutWritingProject() throws { + let f = try fixture(); defer { f.remove() } + let file = f.project.appendingPathComponent("main.c") + try Data("int original;".utf8).write(to: file) + let owner = f.recovery() + try owner.save(projectDirectory: f.project, drafts: [draft(), draft("sub/header.h")]) + XCTAssertEqual(try String(contentsOf: file, encoding: .utf8), "int original;") + XCTAssertFalse(FileManager.default.fileExists(atPath: f.project.appendingPathComponent("sub/header.h").path)) + let reopened = f.recovery() + let record = try XCTUnwrap(reopened.records(projectDirectory: f.project).first) + XCTAssertFalse(record.isFromRunningSession) + XCTAssertEqual(record.drafts, [draft(), draft("sub/header.h")]) + // A missing source does not make its unsaved recovery copy disappear. + try FileManager.default.removeItem(at: file) + XCTAssertEqual(try reopened.records(projectDirectory: f.project).first?.drafts[0].text, "int changed;") + try reopened.save(projectDirectory: f.project, drafts: record.drafts) + try reopened.discard(record) + XCTAssertEqual(try reopened.records(projectDirectory: f.project).count, 1) + XCTAssertFalse(FileManager.default.fileExists(atPath: file.path)) + } + func testConcurrentSessionsKeepSeparateCopiesAndRejectLiveDiscard() throws { + let f = try fixture(); defer { f.remove() } + let first = f.recovery(pid: getpid()), second = f.recovery() + try first.save(projectDirectory: f.project, drafts: [draft(text: "first session")]) + try second.save(projectDirectory: f.project, drafts: [draft(text: "second session")]) + let scan = try second.scan(projectDirectory: f.project) + XCTAssertEqual(scan.records.count, 2) + let live = try XCTUnwrap(scan.records.first { $0.id == first.sessionID }) + XCTAssertTrue(live.isFromRunningSession) + XCTAssertThrowsError(try second.discard(live)) + try second.save(projectDirectory: f.project, drafts: []) + let left = try second.records(projectDirectory: f.project) + XCTAssertEqual(left.count, 1); XCTAssertEqual(left[0].drafts[0].text, "first session") + XCTAssertFalse(try first.records(projectDirectory: f.project)[0].isFromRunningSession) + } + func testInvalidDraftsKeepPreviousRecoveryCopy() throws { + let f = try fixture(); defer { f.remove() } + let store = f.recovery() + try store.save(projectDirectory: f.project, drafts: [draft()]) + for drafts in [[draft("../escape.c")], [draft("/absolute.c")], [draft("main.c"), draft("MAIN.C")], + [draft(text: String(repeating: "x", count: CMOCProject.maximumSourceBytes + 1))], + [CMOCWorkspaceRecovery.Draft(path: "main.c", text: "new", savedText: "old", savedHash: "wrong")], + (0...CMOCWorkspaceRecovery.maximumDrafts).map { draft("file\($0).c") }] { + XCTAssertThrowsError(try store.save(projectDirectory: f.project, drafts: drafts)) + XCTAssertEqual(try store.records(projectDirectory: f.project)[0].drafts, [draft()]) + } + } + func testDamagedRecordIsReportedWithoutHidingHealthySession() throws { + let f = try fixture(); defer { f.remove() } + let store = f.recovery() + try store.save(projectDirectory: f.project, drafts: [draft()]) + let broken = f.projectFolder.appendingPathComponent(UUID().uuidString + ".json") + try Data("{truncated".utf8).write(to: broken) + let scan = try store.scan(projectDirectory: f.project) + XCTAssertEqual(scan.records.count, 1) + XCTAssertEqual(scan.issues.count, 1) + XCTAssertTrue(scan.issues[0].contains("damaged")) + XCTAssertThrowsError(try store.records(projectDirectory: f.project)) + XCTAssertTrue(FileManager.default.fileExists(atPath: broken.path)) + } + func testChangedRecordCannotBeDiscardedUsingAnOlderSelection() throws { + let f = try fixture(); defer { f.remove() } + let owner = f.recovery(), reader = f.recovery() + try owner.save(projectDirectory: f.project, drafts: [draft(text: "first")]) + let first = try XCTUnwrap(reader.records(projectDirectory: f.project).first) + try owner.save(projectDirectory: f.project, drafts: [draft(text: "newer")]) + XCTAssertThrowsError(try reader.discard(first)) + XCTAssertEqual(try reader.records(projectDirectory: f.project)[0].drafts[0].text, "newer") + let other = CMOCWorkspaceRecovery(root: f.root.appendingPathComponent("OtherRecovery")) + XCTAssertThrowsError(try other.discard(first)) + } + func testRecoveryRefusesLinkedRootsFoldersAndRecords() throws { + let f = try fixture(); defer { f.remove() } + let external = f.root.appendingPathComponent("External") + try FileManager.default.createDirectory(at: external, withIntermediateDirectories: true) + let linkedRoot = f.root.appendingPathComponent("LinkedRecovery") + try FileManager.default.createSymbolicLink(at: linkedRoot, withDestinationURL: external) + XCTAssertThrowsError(try CMOCWorkspaceRecovery(root: linkedRoot).save(projectDirectory: f.project, drafts: [draft()])) + let store = f.recovery() + try store.save(projectDirectory: f.project, drafts: [draft()]) + let record = try XCTUnwrap(store.records(projectDirectory: f.project).first) + let recordURL = f.projectFolder.appendingPathComponent(record.id.uuidString + ".json") + let canary = external.appendingPathComponent("canary") + try Data("unchanged".utf8).write(to: canary) + try FileManager.default.removeItem(at: recordURL) + try FileManager.default.createSymbolicLink(at: recordURL, withDestinationURL: canary) + XCTAssertEqual(try store.scan(projectDirectory: f.project).issues.count, 1) + XCTAssertThrowsError(try store.save(projectDirectory: f.project, drafts: [])) + XCTAssertThrowsError(try store.discard(record)) + XCTAssertEqual(try String(contentsOf: canary, encoding: .utf8), "unchanged") + try FileManager.default.removeItem(at: f.projectFolder) + try FileManager.default.createSymbolicLink(at: f.projectFolder, withDestinationURL: external) + XCTAssertThrowsError(try store.scan(projectDirectory: f.project)) + XCTAssertThrowsError(try store.save(projectDirectory: f.project, drafts: [draft()])) + XCTAssertEqual(try String(contentsOf: canary, encoding: .utf8), "unchanged") + } + @MainActor private func waitForRecovery(_ model: CMOCDevelopmentModel) async throws { + for _ in 0..<500 where model.recoveryBusy { try await Task.sleep(nanoseconds: 10_000_000) } + XCTAssertFalse(model.recoveryBusy) + } + @MainActor private func flush(_ model: CMOCDevelopmentModel) async { + await withCheckedContinuation { continuation in model.flushDraftRecovery { continuation.resume() } } + } + @MainActor private func model(_ f: Fixture, defaults: UserDefaults) -> (MachineModel, CMOCDevelopmentModel) { + let machine = MachineModel(diskStore: .init(url: f.root.appendingPathComponent("disks.json")), displayDefaults: defaults, + inputStore: .init(url: f.root.appendingPathComponent("input.json"))) + return (machine, CMOCDevelopmentModel(machine: machine, defaults: defaults, + buildRoot: f.root.appendingPathComponent("Builds"), recoveryRoot: f.store)) + } + private func populateProject(_ f: Fixture) throws -> CMOCProject { + try Data(CMOCProject.starterSource.utf8).write(to: f.project.appendingPathComponent("main.c")) + try Data(CMOCProject.starterMakefile.utf8).write(to: f.project.appendingPathComponent("Makefile")) + return try CMOCProject.open(at: f.project) + } + @MainActor func testModelRestoresConflictingAndMissingDraftsWithoutOverwritingSources() async throws { + let f = try fixture(); defer { f.remove() } + let suite = "CRecoveryModel." + UUID().uuidString, defaults: UserDefaults + defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let project = try populateProject(f) + let original = try project.readText(relativePath: "main.c") + let old = f.recovery() + try old.save(projectDirectory: f.project, drafts: [draft(text: original + "\n/* recovered */", saved: original), draft("missing.h")]) + try Data((original + "\n/* outside edit */").utf8).write(to: project.sourceURL) + let (machine, model) = model(f, defaults: defaults) + try model.adopt(project); try await waitForRecovery(model) + let selected = try XCTUnwrap(model.recoveryRecords.first) + model.restoreRecovery(selected); try await waitForRecovery(model); await flush(model) + let main = try XCTUnwrap(model.documents.first { $0.id == "main.c" }) + XCTAssertTrue(main.conflict); XCTAssertFalse(main.missing) + XCTAssertTrue(main.text.contains("recovered")); XCTAssertEqual(main.savedText, original) + let missing = try XCTUnwrap(model.documents.first { $0.id == "missing.h" }) + XCTAssertTrue(missing.missing); XCTAssertTrue(missing.conflict) + XCTAssertFalse(model.save(), "Recovery must not authorize overwriting externally changed source") + XCTAssertEqual(try project.readText(relativePath: "main.c"), original + "\n/* outside edit */") + XCTAssertFalse(FileManager.default.fileExists(atPath: f.project.appendingPathComponent("missing.h").path)) + let durable = try f.recovery().records(projectDirectory: f.project) + XCTAssertEqual(durable.count, 1) + XCTAssertNotEqual(durable[0].id, old.sessionID, "The adopted copy must replace the prior session only after it is durable") + XCTAssertEqual(durable[0].drafts.count, 2) + XCTAssertTrue(durable[0].drafts.first { $0.path == "main.c" }!.text.contains("recovered")) + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + @MainActor func testModelKeepsPriorCopyWhenDurableAdoptionCannotBeWritten() async throws { + let f = try fixture(); defer { f.remove() } + let suite = "CRecoveryModel." + UUID().uuidString, defaults: UserDefaults + defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let project = try populateProject(f), old = f.recovery() + let original = try project.readText(relativePath: "main.c") + try old.save(projectDirectory: f.project, drafts: [draft(text: "recovered source", saved: original)]) + let (machine, model) = model(f, defaults: defaults) + try model.adopt(project); try await waitForRecovery(model) + let selected = try XCTUnwrap(model.recoveryRecords.first) + let kept = f.root.appendingPathComponent("RecoveryKept") + try FileManager.default.moveItem(at: f.store, to: kept) + try Data("not a directory".utf8).write(to: f.store) + model.restoreRecovery(selected); try await waitForRecovery(model) + XCTAssertEqual(model.source, "recovered source", "A failed recovery write must not erase the in-memory draft") + XCTAssertTrue(model.message?.contains("real directory") == true) + let priorFile = kept.appendingPathComponent(f.projectFolder.lastPathComponent).appendingPathComponent(old.sessionID.uuidString + ".json") + XCTAssertTrue(FileManager.default.fileExists(atPath: priorFile.path), "Failed adoption must leave the old durable copy intact") + XCTAssertEqual(try project.readText(relativePath: "main.c"), original) + try FileManager.default.removeItem(at: f.store) + try FileManager.default.moveItem(at: kept, to: f.store) + await flush(model) + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + @MainActor func testMissingProjectStillOffersItsDraftsForExport() async throws { + let f = try fixture(); defer { f.remove() } + let suite = "CRecoveryModel." + UUID().uuidString, defaults: UserDefaults + defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let old = f.recovery() + try old.save(projectDirectory: f.project, drafts: [draft()]) + defaults.set(f.project.path, forKey: "CMOCWorkspace.directory") + try FileManager.default.removeItem(at: f.project) + let (machine, model) = model(f, defaults: defaults) + model.restoreWorkspace(); try await waitForRecovery(model) + XCTAssertNil(model.project) + let record = try XCTUnwrap(model.recoveryRecords.first) + XCTAssertEqual(record.drafts, [draft()], "Export has the full draft text even when the project cannot open") + model.restoreRecovery(record) + XCTAssertTrue(model.message?.contains("export") == true) + XCTAssertEqual(try old.records(projectDirectory: f.project).count, 1) + XCTAssertFalse(FileManager.default.fileExists(atPath: f.project.path)) + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + + func testScanBoundsRetainedSessionsWithoutDeletingUnreviewedCopies() throws { + let f = try fixture(); defer { f.remove() } + for _ in 0...CMOCWorkspaceRecovery.maximumScanRecords { + try f.recovery().save(projectDirectory: f.project, drafts: [draft()]) + } + let reader = f.recovery() + let first = try reader.scan(projectDirectory: f.project) + XCTAssertEqual(first.records.count, CMOCWorkspaceRecovery.maximumScanRecords) + XCTAssertEqual(first.issues.count, 1) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: f.projectFolder.path).count, CMOCWorkspaceRecovery.maximumScanRecords + 1) + try reader.discard(first.records[0]) + let next = try reader.scan(projectDirectory: f.project) + XCTAssertEqual(next.records.count, CMOCWorkspaceRecovery.maximumScanRecords) + XCTAssertTrue(next.issues.isEmpty) + XCTAssertFalse(Set(first.records.map(\.id)).isSuperset(of: Set(next.records.map(\.id))), "The remaining record becomes reviewable after explicit cleanup") + } + +} diff --git a/platforms/macos/Tests/CartridgePersistenceTests.swift b/platforms/macos/Tests/CartridgePersistenceTests.swift new file mode 100644 index 0000000..5a9bc97 --- /dev/null +++ b/platforms/macos/Tests/CartridgePersistenceTests.swift @@ -0,0 +1,391 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CartridgePersistenceTests: XCTestCase { + @MainActor func testSpeechSoundTwoROMSelectionProfilesMoveAndRecovery() async throws { + let f = try Fixture(); defer { f.remove() } + let pic = f.folder.appendingPathComponent("pic.bin"), speech = f.folder.appendingPathComponent("speech.bin") + var firmware = Data(repeating: 0, count: 4096) + firmware[0] = 0xb3; firmware[1] = 0xe0; firmware[2] = 0xfd; firmware[4094] = 0xf0 + try firmware.write(to: pic); try Data(repeating: 0, count: 2048).write(to: speech) + try await withModel(f.store) { model in + model.setMultiPak(true); try await settled(model) + model.assignCartridge(.speechSound, slot: 2); try await settled(model) + XCTAssertNotNil(model.cartridgeRestoreErrors[2]) + model.selectSpeechROM(speech, slot: 2, speech: false); try await settled(model) + XCTAssertNotNil(model.fileError); XCTAssertNil(model.cartridgeAssignments.slots[2].url) + model.selectSpeechROM(pic, slot: 2, speech: false); try await settled(model) + XCTAssertEqual(model.cartridgeAssignments.slots[2].url, pic) + XCTAssertNotNil(model.cartridgeRestoreErrors[2]) + model.selectSpeechROM(speech, slot: 2, speech: true); try await settled(model) + XCTAssertTrue(model.cartridgeRestoreErrors.isEmpty) + model.assignCartridge(.speechSound, slot: 1); try await settled(model) + XCTAssertEqual(model.cartridgeAssignments.slots[2].kind, .empty) + XCTAssertEqual(model.cartridgeAssignments.slots[1].speechROMURL, speech) + var profile = ConfigurationProfile(name: "Speech") + profile.media = try f.store.load() + let exported = f.folder.appendingPathComponent("speech.vccprofile") + try ProfileStore.write(profile, to: exported) + let imported = try ProfileStore.read(exported), prepared = try PreparedProfile.read(imported) + XCTAssertEqual(prepared.cartridges[1].count, 6144) + XCTAssertEqual(prepared.request().kinds[1], 6) + XCTAssertTrue(imported.references.contains { $0.key == .speechROM(1) }) + let duplicate = profile.media.cartridges!.slots[1] + profile.media.cartridges?.slots[2] = duplicate + XCTAssertThrowsError(try profile.validate()) + } + try FileManager.default.removeItem(at: speech) + try await withModel(f.store) { model in + XCTAssertEqual(model.cartridgeAssignments.slots[1].kind, .speechSound) + XCTAssertNotNil(model.cartridgeRestoreErrors[1]) + var profile = ConfigurationProfile(name: "Missing speech"); profile.media = try f.store.load() + XCTAssertThrowsError(try PreparedProfile.read(profile)) + try Data(repeating: 0, count: 2048).write(to: speech) + model.retryRememberedCartridges(); try await settled(model) + XCTAssertTrue(model.cartridgeRestoreErrors.isEmpty) + XCTAssertEqual(model.cartridgeNames[1], "Speech/Sound Cartridge") + } + } + + @MainActor func testOrchestraOptionalROMProfilesMovesAndMissingFileRecovery() async throws { + let f = try Fixture(); defer { f.remove() } + try await withModel(f.store) { model in + model.setMultiPak(true); try await settled(model) + model.assignCartridge(.orchestra90, slot: 1); try await settled(model) + XCTAssertEqual(model.cartridgeNames[1], "Orchestra-90"); XCTAssertFalse(model.hardware.custom) + XCTAssertEqual(model.hardware.values["slot1"], "orchestra") + XCTAssertNil(model.cartridgeAssignments.slots[1].url) + model.selectCartridgeROM(f.second, slot: 1, kind: .orchestra90); try await settled(model) + XCTAssertNotNil(model.fileError); XCTAssertNil(model.cartridgeAssignments.slots[1].url) + model.selectCartridgeROM(f.rom, slot: 1, kind: .orchestra90); try await settled(model) + XCTAssertNil(model.fileError) + model.assignCartridge(.orchestra90, slot: 2); try await settled(model) + XCTAssertEqual(model.cartridgeAssignments.slots[1].kind, .empty) + XCTAssertEqual(model.cartridgeAssignments.slots[2].url, f.rom) + var profile = ConfigurationProfile(name: "Orchestra") + profile.media = try f.store.load() + let url = f.folder.appendingPathComponent("orchestra.vccprofile") + try ProfileStore.write(profile, to: url) + let restored = try ProfileStore.read(url) + XCTAssertEqual(restored, profile) + let prepared = try PreparedProfile.read(restored).request() + XCTAssertEqual(prepared.kinds[2], 5); XCTAssertEqual(prepared.cartridgeROMs[2].count, 8192) + XCTAssertTrue(ProfileGuidance(restored).coverage.contains("Multi-Pak")) + profile.media.cartridges?.slots[1].kind = .orchestra90 + XCTAssertThrowsError(try profile.validate()) + } + try FileManager.default.removeItem(at: f.rom) + try await withModel(f.store) { model in + XCTAssertNotNil(model.cartridgeRestoreErrors[2]) + XCTAssertEqual(model.cartridgeNames[2], "Orchestra-90", "Missing program ROM leaves sound hardware available") + var profile = ConfigurationProfile(name: "Missing"); profile.media = try f.store.load() + XCTAssertThrowsError(try PreparedProfile.read(profile), "Profile loading must not silently omit a selected ROM") + try Data(repeating: 0x12, count: 8192).write(to: f.rom) + model.retryRememberedCartridges(); try await settled(model) + XCTAssertTrue(model.cartridgeRestoreErrors.isEmpty) + model.setMultiPak(false); try await settled(model) + model.assignCartridge(.orchestra90, slot: 0); try await settled(model) + XCTAssertNil(model.cartridgeAssignments.slots[0].url) + model.setMultiPak(true); try await settled(model) + XCTAssertEqual(model.cartridgeAssignments.slots[2].url, f.rom) + model.assignCartridge(.orchestra90, slot: 2); try await settled(model) // Remove ROM only. + XCTAssertNil(model.cartridgeAssignments.slots[2].url) + } + try await withModel(f.store) { model in + XCTAssertEqual(model.cartridgeAssignments.slots[2].kind, .orchestra90) + XCTAssertNil(model.cartridgeAssignments.slots[2].url) + XCTAssertTrue(model.cartridgeRestoreErrors.isEmpty) + } + } + @MainActor func testOrchestraBridgePlaysThroughNativeAudioAndRejectsInvalidLayouts() async throws { + @MainActor func step(_ action: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { done in action { done.resume(returning: $0) } } + } + let c = VCCMachineController() + _ = await step { c.setAudioEnabled(true, volume: 0, completion: $0) } + _ = await step { c.loadDiagnostic(use6309: false, completion: $0) } + let empty = Array(repeating: Data(), count: 5), names = Array(repeating: "", count: 5) + var state = await step { c.configureCartridges([0,5,0,0,0], roms: empty, names: names, multiPak: true, physicalSlot: 4, completion: $0) } + XCTAssertNil(state.errorMessage); XCTAssertEqual(state.cartridgeNames[1], "Orchestra-90") + state = await step { c.configureCartridges([0,5,5,0,0], roms: empty, names: names, multiPak: true, physicalSlot: 4, completion: $0) } + XCTAssertNotNil(state.errorMessage); XCTAssertEqual(state.cartridgeKinds[2], 0) + var bad = empty; bad[1] = Data(repeating: 0, count: 8193) + state = await step { c.configureCartridges([0,5,0,0,0], roms: bad, names: names, multiPak: true, physicalSlot: 4, completion: $0) } + XCTAssertNotNil(state.errorMessage) + let code: [UInt8] = [0x86,0x40,0xb7,0xff,0x7b,0x8e,1,0,0x30,0x1f,0x26,0xfc,0x88,0x80,0x20,0xf2] + let binary = Data([0,0,UInt8(code.count),0x30,0] + code + [0xff,0,0,0x30,0]) + _ = await step { c.quickLoadBinary(binary, completion: $0) } + for _ in 0..<300 { + state = await step(c.snapshot) + if state.audioConsumed > 4410 || state.errorMessage != nil { break } + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertNil(state.errorMessage); XCTAssertGreaterThan(state.audioConsumed, 4410) + XCTAssertGreaterThan(state.audioSignalSamples, 4410) + let starts = state.audioStarts, generation = state.generation + let muted = await step { c.setAudioEnabled(true, volume: 0, completion: $0) } + XCTAssertEqual(muted.audioStarts, starts); XCTAssertEqual(muted.generation, generation) + let paused = await step(c.pause) + try await Task.sleep(nanoseconds: 100_000_000) + state = await step(c.snapshot) + XCTAssertEqual(state.frames, paused.frames); XCTAssertEqual(state.audioConsumed, paused.audioConsumed) + _ = await step(c.shutdown) + } + + @MainActor func testRamDiskAssignmentProfilesAndConventionalFallback() async throws { + let f = try Fixture(); defer { f.remove() } + try await withModel(f.store) { model in + model.setMultiPak(true); try await settled(model) + model.assignCartridge(.ramDisk, slot: 1); try await settled(model) + XCTAssertEqual(model.cartridgeNames[1], "RAM disk (512 KB)") + XCTAssertTrue(model.hardware.custom) + XCTAssertEqual(model.hardware.values["slot1"], "empty", "Never show a RAM disk as a hard-disk controller") + model.assignCartridge(.ramDisk, slot: 2); try await settled(model) + XCTAssertEqual(model.cartridgeAssignments.slots[1].kind, .empty) + var profile = ConfigurationProfile(name: "RAM disk setup") + profile.media = try f.store.load() + let url = f.folder.appendingPathComponent("ram.vccprofile") + try ProfileStore.write(profile, to: url) + let restored = try ProfileStore.read(url) + XCTAssertEqual(restored.media.cartridges?.slots[2].kind, .ramDisk) + XCTAssertTrue(ProfileGuidance(restored).coverage.contains("conventional")) + let prepared = try PreparedProfile.read(restored) + XCTAssertEqual(prepared.request().kinds[2], 4) + var invalid = restored + invalid.media.cartridges?.slots[3].kind = .ramDisk + XCTAssertThrowsError(try invalid.validate()) + } + try await withModel(f.store) { model in + XCTAssertEqual(model.cartridgeNames[2], "RAM disk (512 KB)") + XCTAssertTrue(model.hardware.custom) + model.assignCartridge(.empty, slot: 2); try await settled(model) + XCTAssertFalse(model.hardware.custom) + } + } + + @MainActor func testRamDiskBridgeRetainsAcrossLayoutChangesButClearsOnDetachAndProfile() async throws { + @MainActor func step(_ action: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { done in action { done.resume(returning: $0) } } + } + for cpu in [false, true] { + let controller = VCCMachineController() + _ = await step { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await step { controller.loadDiagnostic(use6309: cpu, completion: $0) } + func layout(_ kinds: [NSNumber], mpi: Bool = true, slot: Int = 4) async { + let state = await step { controller.configureCartridges(kinds, + roms: Array(repeating: Data(), count: 5), names: Array(repeating: "", count: 5), + multiPak: mpi, physicalSlot: slot, completion: $0) } + XCTAssertNil(state.errorMessage) + } + func run(write: UInt8? = nil, expect: UInt8) async throws { + var code: [UInt8] = [0x86,0x30,0xb7,0xff,0x7f] // CTS4, SCS1; ignored in single mode. + if let write { code += [0x86,write,0xb7,0xff,0x43] } + // Compare the device value, then park at distinct success/failure PCs. + code += [0xb6,0xff,0x43,0x81,expect,0x26,2,0x20,0xfe,0x20,0xfe] + let binary = Data([0,0,UInt8(code.count),0x30,0] + code + [0xff,0,0,0x30,0]) + let expectedPC = 0x3000 + code.count - 4 + var state = await step { controller.quickLoadBinary(binary, completion: $0) } + XCTAssertNil(state.errorMessage) + for _ in 0..<100 { + state = await step(controller.snapshot) + if state.programCounter == expectedPC || state.programCounter == expectedPC + 2 { break } + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertEqual(Int(state.programCounter), expectedPC, "Guest observed unexpected RAM disk contents") + _ = await step(controller.pause) + } + await layout([0,4,0,0,0]); try await run(write: 0xa5, expect: 0xa5) + _ = await step(controller.reset); try await run(expect: 0xa5) + _ = await step(controller.softReset); try await run(expect: 0xa5) + await layout([4,4,0,0,0], mpi: false); try await run(expect: 0xa5) + await layout([4,0,0,0,0], mpi: false); try await run(expect: 0xa5) + await layout([0,0,0,0,0], mpi: false) + await layout([4,0,0,0,0], mpi: false); try await run(expect: 0) + try await run(write: 0x67, expect: 0x67) + let profile = VCCMachineProfile(); profile.sound = false; profile.use6309 = cpu; profile.kinds = [4,0,0,0,0] + var rom = Data(repeating: 0x12, count: 32768) + rom[0] = 0x20; rom[1] = 0xfe; rom[32766] = 0x80; rom[32767] = 0 + profile.systemROM = rom + let applied: Bool = await withCheckedContinuation { done in + controller.applyProfile(profile) { ok, state in XCTAssertNil(state.errorMessage); done.resume(returning: ok) } + } + XCTAssertTrue(applied); try await run(expect: 0) + _ = await step(controller.shutdown) + } + } + private struct Fixture { + let folder: URL, rom: URL, second: URL, diskROM: URL, disk: URL, store: DiskAssignmentStore + init() throws { + folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + rom = folder.appendingPathComponent("Cart é.ROM"); second = folder.appendingPathComponent("Second.ccc") + diskROM = folder.appendingPathComponent("disk.rom"); disk = folder.appendingPathComponent("disk.DSK") + store = DiskAssignmentStore(url: folder.appendingPathComponent("settings.json")) + try Data(repeating: 0x12, count: 8192).write(to: rom) + try Data(repeating: 0x34, count: 16384).write(to: second) + try Data(repeating: 0, count: 8192).write(to: diskROM) + try Data(repeating: 0, count: 161280).write(to: disk) + } + func remove() { try? FileManager.default.removeItem(at: folder) } + } + @MainActor private func settled(_ model: MachineModel) async throws { + for _ in 0..<1000 { + if !model.busy && !model.diskSaving { return } + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTFail("Cartridge operation timed out"); throw NSError(domain: "TestTimeout", code: 1) + } + @MainActor private func withModel(_ store: DiskAssignmentStore, _ body: (MachineModel) async throws -> Void) async throws { + let model = MachineModel(diskStore: store) + do { try await settled(model); try await body(model) } + catch { + await withCheckedContinuation { c in model.shutdown { c.resume() } }; throw error + } + await withCheckedContinuation { c in model.shutdown { c.resume() } } + } + func testCartridgeFileAndSettingsValidation() throws { + let f = try Fixture(); defer { f.remove() } + XCTAssertEqual(try DiskFiles.readCartridgeROM(f.rom).count, 8192) + for bytes in [Data(), Data(repeating: 0, count: 262145), Data([0x4d,0x5a,0,0])] { + try bytes.write(to: f.second); XCTAssertThrowsError(try DiskFiles.readCartridgeROM(f.second)) + } + XCTAssertThrowsError(try DiskFiles.readCartridgeROM(f.disk)) + var s = DiskAssignments(); s.cartridges = CartridgeAssignments() + s.cartridges?.slots[1] = .init(kind: .rom, url: f.rom) + try f.store.save(s); XCTAssertEqual(try f.store.load(), s) + var invalid = s; invalid.cartridges?.physicalSlot = 0; XCTAssertThrowsError(try f.store.save(invalid)) + invalid = s; invalid.cartridges?.slots.removeLast(); XCTAssertThrowsError(try f.store.save(invalid)) + invalid = s; invalid.cartridges?.slots[1].url = nil; XCTAssertThrowsError(try f.store.save(invalid)) + invalid = s; invalid.cartridges?.slots[2].kind = .floppy; invalid.cartridges?.slots[3].kind = .floppy + XCTAssertThrowsError(try f.store.save(invalid)); XCTAssertEqual(try f.store.load(), s) + } + @MainActor func testModesSlotsAndDiskAssignmentsSurviveRelaunch() async throws { + let f = try Fixture(); defer { f.remove() } + var old = DiskAssignments(); old.rom = f.diskROM + old.drives[0] = .init(url: f.disk, writeProtected: true, temporary: true) + try f.store.save(old) + try await withModel(f.store) { model in + XCTAssertTrue(model.diskConnected); XCTAssertEqual(model.cartridgeAssignments.slots[0].kind, .floppy) + model.setMultiPak(true); try await settled(model) + XCTAssertEqual(model.cartridgeAssignments.slots[4].kind, .floppy) + XCTAssertTrue(model.diskConnected); XCTAssertTrue(model.disks[0].mounted) + model.selectCartridgeROM(f.rom, slot: 1); try await settled(model) + model.selectCartridgeROM(f.second, slot: 2); try await settled(model) + model.selectPhysicalSlot(2); try await settled(model) + XCTAssertEqual(model.romSlot, 2); XCTAssertEqual(model.ioSlot, 2) + model.setMultiPak(false); try await settled(model) + XCTAssertTrue(model.diskConnected); XCTAssertEqual(model.romSlot, 0) + model.selectCartridgeROM(f.second, slot: 0); try await settled(model) + XCTAssertFalse(model.diskConnected); XCTAssertTrue(model.disks[0].mounted) + XCTAssertTrue(model.disks[0].writeProtected); XCTAssertTrue(model.diskTemporary[0]) + } + try await withModel(f.store) { model in + XCTAssertFalse(model.cartridgeAssignments.multiPak); XCTAssertEqual(model.cartridgeNames[0], f.second.lastPathComponent) + XCTAssertEqual(model.cartridgeNames[1], f.rom.lastPathComponent) + XCTAssertFalse(model.diskConnected); XCTAssertTrue(model.disks[0].mounted) + model.setMultiPak(true); try await settled(model) + XCTAssertTrue(model.diskConnected); XCTAssertEqual(model.romSlot, 2) + model.assignCartridge(.floppy, slot: 3); try await settled(model) + XCTAssertEqual(model.cartridgeAssignments.slots[4].kind, .empty) + XCTAssertEqual(model.cartridgeAssignments.slots[3].kind, .floppy) + model.assignCartridge(.empty, slot: 1); try await settled(model) + } + try await withModel(f.store) { model in + XCTAssertTrue(model.cartridgeAssignments.multiPak) + XCTAssertTrue(model.cartridgeNames[1].isEmpty); XCTAssertEqual(model.cartridgeNames[2], f.second.lastPathComponent) + XCTAssertEqual(model.cartridgeNames[3], "Floppy controller"); XCTAssertTrue(model.disks[0].mounted) + } + } + @MainActor func testUnavailableROMRetryPreservesOtherSlotsAndSettings() async throws { + let f = try Fixture(); defer { f.remove() } + var settings = DiskAssignments(); var layout = CartridgeAssignments() + layout.multiPak = true; layout.mpiConfigured = true + layout.slots[1] = .init(kind: .rom, url: f.rom); layout.slots[2] = .init(kind: .rom, url: f.second) + settings.cartridges = layout; try f.store.save(settings) + let saved = try Data(contentsOf: f.store.url); try FileManager.default.removeItem(at: f.rom) + try await withModel(f.store) { model in + XCTAssertNotNil(model.cartridgeRestoreErrors[1]); XCTAssertTrue(model.cartridgeNames[1].isEmpty) + XCTAssertEqual(model.cartridgeNames[2], f.second.lastPathComponent) + XCTAssertEqual(try Data(contentsOf: f.store.url), saved) + try Data(repeating: 0x12, count: 8192).write(to: f.rom) + // A working slot's original file may disappear; retry must retain its owned bytes. + try FileManager.default.removeItem(at: f.second) + model.retryRememberedCartridges(); try await settled(model) + XCTAssertTrue(model.cartridgeRestoreErrors.isEmpty) + XCTAssertEqual(model.cartridgeNames[1], f.rom.lastPathComponent) + XCTAssertEqual(model.cartridgeNames[2], f.second.lastPathComponent) + try Data().write(to: f.rom) + model.selectCartridgeROM(f.rom, slot: 2); try await settled(model) + XCTAssertNotNil(model.fileError); XCTAssertEqual(model.cartridgeNames[2], f.second.lastPathComponent) + XCTAssertEqual(try Data(contentsOf: f.store.url), saved) + } + } + @MainActor func testFirstMPIActivationKeepsMissingROMRecoverable() async throws { + let f = try Fixture(); defer { f.remove() } + var settings = DiskAssignments(); var layout = CartridgeAssignments() + layout.slots[0] = .init(kind: .rom, url: f.rom); settings.cartridges = layout + try f.store.save(settings); try FileManager.default.removeItem(at: f.rom) + try await withModel(f.store) { model in + model.setMultiPak(true); try await settled(model) + XCTAssertNotNil(model.cartridgeRestoreErrors[4]) + model.setMultiPak(false); try await settled(model) + model.assignCartridge(.empty, slot: 0); try await settled(model) + XCTAssertNil(model.cartridgeRestoreErrors[0]); XCTAssertNotNil(model.cartridgeRestoreErrors[4]) + model.setMultiPak(true); try await settled(model) + try Data(repeating: 0x12, count: 8192).write(to: f.rom) + model.retryRememberedCartridges(); try await settled(model) + XCTAssertTrue(model.cartridgeRestoreErrors.isEmpty); XCTAssertEqual(model.cartridgeNames[4], f.rom.lastPathComponent) + } + } + @MainActor func testDirtyDisksRemainAvailableWhenDisconnected() async throws { + let f = try Fixture(); defer { f.remove() } + var settings = DiskAssignments(); settings.rom = f.diskROM; try f.store.save(settings) + try await withModel(f.store) { model in + model.createDisk(0); try await settled(model) + XCTAssertTrue(model.disks[0].dirty) + model.selectCartridgeROM(f.rom, slot: 0); try await settled(model) + XCTAssertFalse(model.diskConnected); XCTAssertTrue(model.disks[0].dirty) + model.setMultiPak(true); try await settled(model) + model.assignCartridge(.floppy, slot: 1); try await settled(model) + XCTAssertTrue(model.diskConnected); XCTAssertTrue(model.disks[0].dirty) + await withCheckedContinuation { c in model.prepareToQuit { c.resume() } } + XCTAssertTrue(model.unsavedMedia) + model.exportDisk(0, to: f.disk); try await settled(model) + XCTAssertFalse(model.disks[0].dirty); XCTAssertTrue(model.diskConnected) + } + } + @MainActor func testBridgeRejectsInvalidAndBusyLayoutsWithoutReplacingSlots() async throws { + let controller = VCCMachineController() + func step(_ action: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { c in action { c.resume(returning: $0) } } + } + let diskROM = Data(repeating: 0, count: 8192) + _ = await step { controller.loadDiskROM(diskROM, name: "disk", completion: $0) } + _ = await step { controller.mountDisk(Data(repeating: 0, count: 161280), drive: 0, name: "test", readOnly: false, completion: $0) } + let empty = Array(repeating: Data(), count: 5), names = Array(repeating: "", count: 5) + var snapshot = await step { controller.configureCartridges([0,2,0,0,2], roms: empty, names: names, multiPak: true, physicalSlot: 4, completion: $0) } + XCTAssertNotNil(snapshot.errorMessage); XCTAssertFalse(snapshot.multiPakEnabled); XCTAssertTrue(snapshot.disks[0].mounted) + snapshot = await step { controller.configureCartridges([2,0,0,0,2], roms: empty, names: names, multiPak: true, physicalSlot: 4, completion: $0) } + XCTAssertNil(snapshot.errorMessage); XCTAssertTrue(snapshot.multiPakEnabled) + // Start a write command and leave its data transfer incomplete. + var system = Data(repeating: 0, count: 32768) + let code: [UInt8] = [0x86,0x29,0xb7,0xff,0x40,0x86,1,0xb7,0xff,0x4a,0x86,0xa0,0xb7,0xff,0x48,0x20,0xfe] + system.replaceSubrange(0.. +#include "../../../src/devices/RomCartridge.h" +#include "../../../src/devices/RamDiskDevice.h" +#include "../../../src/devices/Orchestra90Device.h" +#include "../../../src/devices/SpeechSoundDevice.h" +#include "../../../src/devices/FD502/Fd502Device.h" +#include "../../../src/core/MachineSession.h" +#include "../../../src/core/tcc1014mmu.h" +#include "../../../src/core/mc6821.h" +using namespace VCC::Devices; +namespace { +struct Host : DeviceHost { + unsigned nmis = 0; bool line = false; + void cartridgeNmi() override { ++nmis; } + void cartridgeLine(bool value) override { line = value; } +}; +struct Probe : CartridgeDevice { + unsigned ticks = 0, writes = 0, resets = 0; + std::uint8_t value; bool line; std::uint16_t sample; + Probe(unsigned value, bool line = false, unsigned sample = 0) : value(value), line(line), sample(sample) {} + void reset() override { ++resets; } + void horizontalSync(DeviceHost& host) override { ++ticks; host.cartridgeNmi(); } + std::uint8_t readMemory(std::uint16_t) const override { return value; } + std::uint8_t readPort(std::uint8_t, DeviceHost&) override { return value; } + void writePort(std::uint8_t, std::uint8_t, DeviceHost&) override { ++writes; } + bool cartLine() const override { return line; } + std::uint16_t audio() const override { return sample; } +}; +} +@interface CartridgeTests : XCTestCase +@end +@implementation CartridgeTests +- (void)testSpeechSoundROMValidationBusIsolationAndAudioClock { + Host host; SpeechSoundDevice missing; + XCTAssertFalse(missing.ready()); XCTAssertFalse(missing.cartLine()); + missing.advanceAudio(); XCTAssertEqual(missing.audioTicks(),0u); XCTAssertEqual(missing.audio(),0); + bool rejected=false; + try { SpeechSoundDevice bad(std::vector(4096)); } catch(const std::invalid_argument&) { rejected=true; } + XCTAssertTrue(rejected); + std::vector rom(6144,0);rom[0]=0xb3;rom[1]=0xe0;rom[2]=0xfd;rom[4094]=0xf0; + auto device=std::make_shared(rom), inactive=std::make_shared(rom); + XCTAssertTrue(device->ready()); XCTAssertFalse(device->cartLine()); + XCTAssertEqual(device->readMemory(0xc000),0xff); + for(unsigned p=0;p<256;++p) if(p!=0x7d && p!=0x7e) XCTAssertEqual(device->readPort(p,host),0); + CartridgeBus bus;bus.connect(&host);bus.configure({inactive,nullptr,device,nullptr,nullptr},true,4); + bus.writePort(0x7e,65);XCTAssertEqual(device->diagnostics().CommandCount(),1u); + XCTAssertEqual(inactive->diagnostics().CommandCount(),0u);XCTAssertEqual(bus.readPort(0x7e)&128,0); + for(unsigned i=0;i<500;++i){bus.horizontalSync();bus.audio();} + XCTAssertEqual(device->audioTicks(),0u,"Scanlines and snapshot reads must not advance audio"); + for(unsigned i=0;i<44100;++i)bus.advanceAudio(); + XCTAssertEqual(device->audioTicks(),44100u);XCTAssertEqual(inactive->audioTicks(),0u); + XCTAssertEqual(device->diagnostics().CpuIllegalCount(),0u); + bus.writePort(0x7d,0);XCTAssertNotEqual(bus.readPort(0x7e)&128,0); + bus.configure({inactive,nullptr,device,nullptr,nullptr},false,4);bus.advanceAudio(); + XCTAssertEqual(inactive->audioTicks(),1u);XCTAssertEqual(device->audioTicks(),0u); + const auto created = makeDevice(DeviceKind::SpeechSound,rom); + XCTAssertNotEqual(created.get(),nullptr); +} +- (void)testSpeechSoundAdvancesAtSampleRateOnBothGuestProcessors { + using namespace VCC::Mac; + std::vector rom(6144,0);rom[0]=0xb3;rom[1]=0xe0;rom[2]=0xfd;rom[4094]=0xf0; + for(auto cpu:{Processor::MC6809,Processor::HD6309}) { + MachineSession session;auto device=std::make_shared(rom); + session.cartridges().configure({nullptr,device,nullptr,nullptr,nullptr},true,4); + session.loadDiagnostic(cpu);session.resume(); + std::uint64_t samples=0; + for(unsigned i=0;i<60;++i){session.advance();samples+=session.takeAudio().size();} + XCTAssertEqual(device->audioTicks(),samples);XCTAssertGreaterThan(samples,44000u);XCTAssertLessThan(samples,45000u); + session.pause();auto ticks=device->audioTicks();session.advance();XCTAssertEqual(device->audioTicks(),ticks); + session.softReset();XCTAssertEqual(device->audioTicks(),0u); + session.resume();session.advance();XCTAssertGreaterThan(device->audioTicks(),0u); + session.reset();XCTAssertEqual(device->audioTicks(),0u); + } +} + +- (void)testOrchestraRegistersROMResetAndBroadcastRouting { + Host host; Orchestra90Device bare; + XCTAssertFalse(bare.cartLine()); XCTAssertEqual(bare.readMemory(0xc000), 0xff); + XCTAssertEqual(bare.audio(), 0); + bare.writePort(0x7a, 0x23, host); bare.writePort(0x7b, 0xc1, host); + bare.writePort(0x40, 0xff, host); bare.reset(); + XCTAssertEqual(bare.audio(), 0x23c1); + for (unsigned p = 0; p < 256; ++p) XCTAssertEqual(bare.readPort(p, host), 0); + std::vector rom(8192, 0x12); rom[0]=0x43; rom[8191]=0x78; + auto sound = std::make_shared(rom); + XCTAssertTrue(sound->cartLine()); XCTAssertEqual(sound->readMemory(0xc000), 0x43); + XCTAssertEqual(sound->readMemory(0xffff), 0x78); XCTAssertEqual(sound->readMemory(0xe000), 0x43); + bool rejected = false; + try { Orchestra90Device invalid(std::vector(8193)); } catch (const std::invalid_argument&) { rejected = true; } + XCTAssertTrue(rejected); + auto idle = std::make_shared(0x55, false, 0x8080); + auto inactive = std::make_shared(); + CartridgeBus bus; bus.connect(&host); bus.configure({inactive,sound,nullptr,nullptr,idle},true,4); + XCTAssertFalse(host.line); XCTAssertEqual(bus.readMemory(0xc000), 0x55); + bus.writePort(0x7a, 0x21); bus.writePort(0x7b, 0xd3); + XCTAssertEqual(bus.audio(), 0x21d3); XCTAssertEqual(inactive->audio(), 0); + bus.writePort(0x7f, 0x03); // CTS1, SCS4; sound ports are broadcast regardless. + XCTAssertTrue(host.line); XCTAssertEqual(bus.readMemory(0xc000), 0x43); + bus.writePort(0x7a, 0x00); bus.writePort(0x7b, 0xff); + XCTAssertEqual(bus.audio(), 0x00ff, @"Right channel must not carry into left"); + bus.reset(); XCTAssertEqual(sound->audio(), 0x00ff); + bus.configure({inactive,sound,nullptr,nullptr,idle}, false, 4); + XCTAssertEqual(bus.audio(), 0); bus.writePort(0x7a, 0x40); + XCTAssertEqual(bus.audio(), 0x4000); XCTAssertEqual(sound->audio(), 0x00ff); + XCTAssertEqual(makeDevice(DeviceKind::Orchestra90, rom)->readMemory(0xe000), 0x43); +} +- (void)testGuestOrchestraStereoReachesPCMOnBothProcessors { + using namespace VCC::Mac; + for (auto cpu : {Processor::MC6809, Processor::HD6309}) { + MachineSession session; auto sound = std::make_shared(); + session.cartridges().configure({nullptr,sound,nullptr,nullptr,nullptr}, true, 4); + session.loadDiagnostic(cpu); + // Authored guest toggles exactly one DAC; the other must stay silent. + for (auto port : {0x7b, 0x7a}) { + session.cartridges().writePort(0x7a, 0); session.cartridges().writePort(0x7b, 0); + std::vector code{0x86,0x40,0xb7,0xff,std::uint8_t(port), + 0x8e,0x01,0x00,0x30,0x1f,0x26,0xfc,0x88,0x80,0x20,0xf2}; + std::vector binary{0,0,std::uint8_t(code.size()),0x30,0}; + binary.insert(binary.end(),code.begin(),code.end()); binary.insert(binary.end(),{0xff,0,0,0x30,0}); + session.quickLoad(binary); session.advance(); session.takeAudio(); + session.advance(); auto samples = session.takeAudio(); + XCTAssertGreaterThan(samples.size(), 700u); + bool low = false, high = false; + for (const auto sample : samples) { + auto active = port == 0x7a ? sample.left : sample.right; + auto silent = port == 0x7a ? sample.right : sample.left; + XCTAssertEqual(silent, 0.0f); XCTAssertTrue(active == .25f || active == .75f); + low |= active == .25f; high |= active == .75f; + } + XCTAssertTrue(low && high); + AudioBuffer buffer; buffer.gain = .5f; buffer.write(samples.data(), samples.size()); + std::vector left(samples.size()), right(samples.size()); + buffer.read(left.data(),right.data(),samples.size()); + XCTAssertEqual(left[0], samples[0].left * .5f); XCTAssertEqual(right[0], samples[0].right * .5f); + buffer.gain = 0; buffer.write(samples.data(), samples.size()); buffer.read(left.data(),right.data(),samples.size()); + XCTAssertTrue(std::all_of(left.begin(),left.end(),[](float v){return v==0;})); + XCTAssertTrue(std::all_of(right.begin(),right.end(),[](float v){return v==0;})); + session.pause(); session.advance(); XCTAssertTrue(session.takeAudio().empty()); + const auto latched = sound->audio(); session.softReset(); XCTAssertEqual(sound->audio(),latched); + session.reset(); XCTAssertEqual(sound->audio(),latched); + } + } +} + +- (void)testRamDiskRegistersIsolationAndResetMatchLegacy { + Host host; RamDiskDevice first, second; + for (unsigned bank = 0; bank < 8; ++bank) { + first.writePort(0x40, 0xff, host); first.writePort(0x41, 0xff, host); + first.writePort(0x42, bank, host); first.writePort(0x43, 0xa0 + bank, host); + } + for (unsigned bank = 0; bank < 8; ++bank) { + first.writePort(0x42, bank | 0xf8, host); + XCTAssertEqual(first.readPort(0x43, host), 0xa0 + bank); + XCTAssertEqual(first.readPort(0x43, host), 0xa0 + bank, @"Read must not advance the address"); + XCTAssertEqual(first.readPort(0x40, host), 0); + } + first.reset(); + XCTAssertEqual(first.readPort(0x43, host), 0xa7, @"Reset retains the data and all address latches"); + XCTAssertEqual(second.readPort(0x43, host), 0); + XCTAssertEqual(first.readMemory(0xc000), 0); XCTAssertFalse(first.cartLine()); + XCTAssertEqual(first.audio(), 0); first.horizontalSync(host); XCTAssertEqual(host.nmis, 0u); + auto fresh = makeDevice(DeviceKind::RamDisk, {}); + XCTAssertEqual(fresh->readPort(0x43, host), 0); +} +- (void)testGuestRAMDiskWritesAndReadsOnBothCPUsWithIndependentROMRouting { + for (auto cpu : {VCC::Mac::Processor::MC6809, VCC::Mac::Processor::HD6309}) { + VCC::Mac::MachineSession session; + auto ram = std::make_shared(); + auto rom = std::make_shared(std::vector(8192, 0x67)); + session.cartridges().configure({nullptr,ram,nullptr,nullptr,rom}, true, 4); + std::vector system(32768); + // Keep CTS on ROM slot 4, route SCS to RAM disk slot 1; access its last byte. + const std::uint8_t code[]{0x86,0x30,0xb7,0xff,0x7f, + 0x86,0xff,0xb7,0xff,0x40,0xb7,0xff,0x41, + 0x86,0xff,0xb7,0xff,0x42,0x86,0xa5,0xb7,0xff,0x43, + 0xb6,0xff,0x43,0xb7,2,0,0xb6,0xc0,0,0xb7,2,1,0x20,0xfe}; + std::copy(std::begin(code),std::end(code),system.begin()); system[32766]=0x80; + session.load(system,cpu); session.resume(); session.advance(); session.pause(); + XCTAssertEqual(MemRead8(0x200), 0xa5); XCTAssertEqual(MemRead8(0x201), 0x67); + session.softReset(); session.cartridges().writePort(0x7f,0x30); + XCTAssertEqual(session.cartridges().readPort(0x43), 0xa5); + session.reset(); session.cartridges().writePort(0x7f,0x30); + XCTAssertEqual(session.cartridges().readPort(0x43), 0xa5); + session.cartridges().writePort(0x7f,0x33); + session.cartridges().writePort(0x43,0x77); // Other SCS slot cannot write RAM disk. + session.cartridges().writePort(0x7f,0x30); + XCTAssertEqual(session.cartridges().readPort(0x43), 0xa5); + } +} +- (void)testRawROMMappingBankingAndValidation { + Host host; std::vector bytes(262144); + for (unsigned i = 0; i < bytes.size(); ++i) bytes[i] = i / 16384; + RomCartridge rom(bytes); + XCTAssertEqual(rom.readMemory(0xc000), 1); XCTAssertEqual(rom.readMemory(0), 0); + rom.writePort(0x40, 0xff, host); + XCTAssertEqual(rom.readMemory(0), 15); XCTAssertEqual(rom.readMemory(0x4000), 0); + rom.reset(); XCTAssertEqual(rom.readMemory(0), 0); XCTAssertTrue(rom.cartLine()); + RomCartridge small({1,2,3}); XCTAssertEqual(small.readMemory(4), 2); + bool empty = false, large = false; + try { RomCartridge bad({}); } catch (const std::invalid_argument&) { empty = true; } + try { RomCartridge bad(std::vector(262145)); } catch (const std::invalid_argument&) { large = true; } + XCTAssertTrue(empty && large); +} +- (void)testMultiPakIndependentRoutingTicksInterruptsAndAudio { + Host host; CartridgeBus bus; bus.connect(&host); + auto single = std::make_shared(9); + auto first = std::make_shared(1, true, 0x8080); + auto last = std::make_shared(4, false, 0x8080); + CartridgeBus::Slots slots{single,first,nullptr,nullptr,last}; + bus.configure(slots, true, 4); + XCTAssertEqual(bus.readPort(0x7f), 0x33); XCTAssertFalse(host.line); + bus.writePort(0x7f, 0xc3); // masked CTS=slot1, SCS=slot4 + XCTAssertEqual(bus.readPort(0x7f), 3); XCTAssertTrue(host.line); + XCTAssertEqual(bus.readMemory(0), 1); XCTAssertEqual(bus.readPort(0x48), 4); + bus.writePort(0x40, 7); XCTAssertEqual(first->writes, 0u); XCTAssertEqual(last->writes, 1u); + bus.writePort(0x60, 8); XCTAssertEqual(first->writes, 1u); XCTAssertEqual(last->writes, 2u); + XCTAssertEqual(bus.readPort(0x60), 1); XCTAssertEqual(bus.audio(), 0x8080); + bus.horizontalSync(); XCTAssertEqual(host.nmis, 2u); + XCTAssertEqual(first->ticks, 1u); XCTAssertEqual(last->ticks, 1u); XCTAssertEqual(single->ticks, 0u); + bus.writePort(0x7f, 0x11); XCTAssertEqual(bus.readMemory(0), 0xff); XCTAssertFalse(host.line); + bus.reset(); XCTAssertEqual(bus.readPort(0x7f), 0x33); + bus.configure(slots, false, 4); XCTAssertEqual(bus.readMemory(0), 9); + bus.writePort(0x7f, 0x11); XCTAssertEqual(bus.romSlot(), 0u); XCTAssertEqual(single->writes, 1u); + bus.horizontalSync(); XCTAssertEqual(single->ticks, 1u); XCTAssertEqual(first->ticks, 1u); + bus.configure(slots, true, 1); XCTAssertTrue(host.line); XCTAssertEqual(bus.readPort(0x7f), 0); + slots[2] = first; bool rejected = false; + try { bus.configure(slots, true, 2); } catch (const std::invalid_argument&) { rejected = true; } + XCTAssertTrue(rejected); XCTAssertEqual(bus.readPort(0x7f), 0); +} +- (void)testSelectedROMDrivesPIACartridgeSignal { + VCC::Mac::MachineSession session; + auto rom = std::make_shared(std::vector(8192, 0x12)); + CartridgeBus::Slots slots{nullptr,rom,nullptr,nullptr,nullptr}; + session.cartridges().configure(slots, true, 1); + session.loadDiagnostic(); + SetCartAutoStart(1); irq_fs(0); + XCTAssertTrue(pia1_read(0x23) & 0x80); + session.cartridges().writePort(0x7f, 0x33); + PiaReset(); irq_fs(0); XCTAssertFalse(pia1_read(0x23) & 0x80); + session.cartridges().writePort(0x7f, 0x03); + irq_fs(0); XCTAssertTrue(pia1_read(0x23) & 0x80); + session.cartridges().configure(slots, false, 1); + PiaReset(); irq_fs(0); XCTAssertFalse(pia1_read(0x23) & 0x80); +} +- (void)testGuestSelectsROMAndDiskSlotsOnBothCPUs { + for (auto cpu : {VCC::Mac::Processor::MC6809, VCC::Mac::Processor::HD6309}) { + VCC::Mac::MachineSession session; + auto disk = std::make_shared(std::vector(8192, 0x44)); + auto rom = std::make_shared(std::vector(8192, 0x67)); + session.cartridges().configure({nullptr,rom,nullptr,nullptr,disk}, true, 4); + std::vector system(32768); + // LDA #$03; STA $FF7F; LDA $C000; STA $0200; + // LDA $FF7F; STA $0201; loop. ROM and disk selection differ. + const std::uint8_t code[]{0x86,3,0xb7,0xff,0x7f,0xb6,0xc0,0,0xb7,2,0, + 0xb6,0xff,0x7f,0xb7,2,1,0x20,0xfe}; + std::copy(std::begin(code),std::end(code),system.begin()); system[32766]=0x80; + session.load(system,cpu); session.resume(); session.advance(); + XCTAssertEqual(MemRead8(0x200), 0x67); XCTAssertEqual(MemRead8(0x201), 3); + XCTAssertEqual(session.cartridges().ioSlot(), 4u); + session.softReset(); XCTAssertEqual(session.cartridges().readPort(0x7f), 0x33); + session.pause(); session.cartridges().configure({rom,nullptr,nullptr,nullptr,disk}, false, 4); + XCTAssertEqual(session.cartridges().readMemory(0), 0x67); + } +} +@end diff --git a/platforms/macos/Tests/CompanionLibraryTests.swift b/platforms/macos/Tests/CompanionLibraryTests.swift new file mode 100644 index 0000000..abf784b --- /dev/null +++ b/platforms/macos/Tests/CompanionLibraryTests.swift @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CompanionLibraryTests: XCTestCase { + private static func release(_ id: String, media: String = "disk") -> SoftwareLibraryRelease { + .init(id: id, titleID: "title", name: id, category: "Disks/Games", mediaType: media, + contentRole: "software", sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Example.zip")!, + modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, + packageSHA256: String(repeating: "a", count: 64), byteSize: 256, languageStatus: "unknown", + metadata: .object(["title": .string("Authored Example"), "optional": .null, "enabled": .bool(false), "count": .number(2)]), + setup: .init(status: "manual-setup", command: nil, instructions: "Follow the authored instructions.", + configuration: .object([:]), selectedMembers: .array([]), reasons: [], validation: .object([:])), + assets: [], downloadURLs: []) + } + private static var catalog: SoftwareLibraryCatalog { + .init(titles: [.init(id: "title", name: "Authored Example", identityStatus: "reviewed", + releases: [release("disk"), release("tape", media: "cassette")]), + .init(id: "cart-title", name: "Cartridge only", identityStatus: "reviewed", + releases: [release("cart", media: "cartridge")])], + metadata: ["schema_version": "1", "archive_attribution": "Color Computer Archive"]) + } + func testWireRoundTripKeepsMetadataAndDiskFilterRemovesAlternateEditions() throws { + let bytes = try JSONEncoder().encode(Self.catalog) + let restored = try JSONDecoder().decode(SoftwareLibraryCatalog.self, from: bytes) + XCTAssertEqual(restored.titles.count, 2) + XCTAssertEqual(restored.releases.first?.metadata, Self.catalog.releases.first?.metadata) + XCTAssertEqual(restored.companionDisksOnly.titles.map(\.id), ["title"]) + XCTAssertEqual(restored.companionDisksOnly.releases.map(\.id), ["disk"]) + let request = CompanionLibraryRequest(operation: .setFavorite, titleID: "title", enabled: false) + XCTAssertEqual(try JSONDecoder().decode(CompanionLibraryRequest.self, + from: JSONEncoder().encode(request)).enabled, false) + } + @MainActor + func testCompanionStatePersistsMutationsThroughAuthority() async throws { + let service = FakeLibrary(catalog: Self.catalog) + let state = SoftwareLibraryState(companion: service) + state.toggleFavorite("title") + state.selectRelease("disk", for: "title") + await state.flush() + let requests = await service.requests + XCTAssertEqual(requests.map(\.operation), [.setFavorite, .setPreferredRelease]) + XCTAssertTrue(state.isFavorite("title")) + XCTAssertEqual(state.preferredReleaseID(for: "title"), "disk") + XCTAssertNil(state.saveError) + XCTAssertFalse(FileManager.default.fileExists(atPath: state.directory.appendingPathComponent("Unused.json").path)) + } + @MainActor + func testClearingFiltersAndChangingEditionCannotExposeTapeOrCartridge() async throws { + let service = FakeLibrary(catalog: Self.catalog) + let model = SoftwareLibraryModel(companion: service) { _ in XCTFail("Browsing must not insert media.") } + XCTAssertEqual(model.query.scope, .all, "Disk software without artwork must be visible on first opening.") + await model.load() + model.clearFilters() + for _ in 0..<100 where model.filtering { try await Task.sleep(nanoseconds: 20_000_000) } + XCTAssertEqual(model.rows.map(\.id), ["title"]) + XCTAssertEqual(model.catalog?.releases.map(\.id), ["disk"]) + XCTAssertEqual(model.selectedRow?.title.releases.map(\.id), ["disk"]) + model.chooseRelease("tape") + XCTAssertEqual(model.selectedRelease?.id, "disk") + XCTAssertEqual(model.launchLabel(Self.release("disk"), installed: true), "Insert Disk…") + await model.shutdown() + } + func testAuthorityDiskMemberGateRejectsOtherMediaAndEscapes() { + XCTAssertTrue(CompanionLibraryAuthority.diskMember("disks/hello.DSK")) + XCTAssertTrue(CompanionLibraryAuthority.diskMember("boot.os9")) + for member in ["../hello.dsk", "/hello.dsk", "dir/../hello.dsk", "dir//hello.dsk", "dir\\hello.dsk", "disk:hello.dsk", "cart.ccc", "tape.cas", "graphic.png", "disk.dsk\n"] { + XCTAssertFalse(CompanionLibraryAuthority.diskMember(member), member) + } + } + + private actor FakeLibrary: CompanionLibraryAccess { + let catalog: SoftwareLibraryCatalog + var favorites = Set() + var preferred: [String: String] = [:] + private(set) var requests: [CompanionLibraryRequest] = [] + init(catalog: SoftwareLibraryCatalog) { self.catalog = catalog } + func libraryRequest(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse { + requests.append(request) + switch request.operation { + case .setFavorite: + if request.enabled == true { favorites.insert(request.titleID!) } + else { favorites.remove(request.titleID!) } + case .setPreferredRelease: preferred[request.titleID!] = request.releaseID! + case .snapshot: break + default: throw CompanionLibraryFailure(message: "Unexpected operation in authored test.") + } + // Deliberately return unfiltered metadata: the client enforces disks-only too. + return .init(snapshot: .init(catalog: catalog, favorites: favorites, preferredReleaseIDs: preferred, installations: [])) + } + } +} diff --git a/platforms/macos/Tests/CompanionStartupTests.swift b/platforms/macos/Tests/CompanionStartupTests.swift new file mode 100644 index 0000000..028a947 --- /dev/null +++ b/platforms/macos/Tests/CompanionStartupTests.swift @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class CompanionStartupTests: XCTestCase { + @MainActor + func testBackgroundCompanionDoesNotRestoreMediaOrCreateRememberedStartupFiles() async throws { + let fixture = try StartupTests.Fixture() + defer { fixture.remove() } + let suite = "VCCCompanionStartup-" + UUID().uuidString + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let model = MachineModel(diskStore: fixture.disks, displayDefaults: defaults, + inputStore: .init(url: fixture.support.appendingPathComponent("Input.json")), + startupStore: fixture.startup, restoreMediaOnLaunch: false) + // Give accidental queued startup work a chance to run. The assertion is + // against real authored media/state, not an internal implementation flag. + try await Task.sleep(nanoseconds: 100_000_000) + XCTAssertEqual(model.state, .empty) + XCTAssertFalse(model.busy) + XCTAssertTrue(model.disks.allSatisfy { !$0.mounted }) + XCTAssertTrue(model.hardDisks.allSatisfy { !$0.mounted }) + XCTAssertNil(model.systemROMURL) + XCTAssertFalse(model.tapeMounted) + XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.support.path)) + await withCheckedContinuation { continuation in model.shutdown { continuation.resume() } } + XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.support.path), + "Quitting a service-only session must not save an empty startup configuration") + } + + @MainActor + func testExplicitForegroundRestoreUsesOriginalStartupOnce() async throws { + let fixture = try StartupTests.Fixture() + defer { fixture.remove() } + let suite = "VCCCompanionForeground-" + UUID().uuidString + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let model = MachineModel(diskStore: fixture.disks, displayDefaults: defaults, + inputStore: .init(url: fixture.support.appendingPathComponent("Input.json")), + startupStore: fixture.startup, restoreMediaOnLaunch: false) + model.restoreDeferredCompanionMachine() + for _ in 0..<1000 { + if !model.busy && !model.diskSaving { break } + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertFalse(model.busy) + XCTAssertNotNil(model.systemROMURL) + XCTAssertTrue(model.disks[0].mounted) + let assignments = try Data(contentsOf: fixture.disks.url) + let diskName = model.disks[0].name + model.restoreDeferredCompanionMachine() + try await Task.sleep(nanoseconds: 100_000_000) + XCTAssertEqual(model.disks[0].name, diskName) + XCTAssertEqual(try Data(contentsOf: fixture.disks.url), assignments) + await withCheckedContinuation { continuation in model.shutdown { continuation.resume() } } + } +} diff --git a/platforms/macos/Tests/ControllerTests.mm b/platforms/macos/Tests/ControllerTests.mm new file mode 100644 index 0000000..c0f6128 --- /dev/null +++ b/platforms/macos/Tests/ControllerTests.mm @@ -0,0 +1,619 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import +#import "../Bridge/VCCMachineController.h" +#include +#include +#include +#include + +@interface ControllerTests : XCTestCase +@end +@implementation ControllerTests +- (void)waitForPrinterFrames:(VCCMachineController*)controller after:(uint64_t)frame attempts:(NSUInteger)attempts completion:(VCCMachineCompletion)completion { + [controller snapshotWithCompletion:^(VCCMachineSnapshot* current) { + if (current.frames >= frame + 3 || current.errorMessage || attempts == 0) { completion(current); return; } + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ + [self waitForPrinterFrames:controller after:frame attempts:attempts - 1 completion:completion]; + }); + }]; +} +- (void)testJoystickInputSnapshotsAreImmutableAndReleaseOnPause { + for (BOOL use6309 : {NO, YES}) { + auto c = [VCCMachineController new]; + auto initial = [self diskCommand:^(VCCMachineCompletion done) { [c loadDiagnosticWith6309:use6309 completion:done]; }]; + XCTAssertEqual(initial.joystickInputs.count, 2u); + XCTAssertEqual(initial.joystickInputs[0].x, 8191u); + [self diskCommand:^(VCCMachineCompletion done) { [c resumeWithCompletion:done]; }]; + [c setJoystick:0 x:0 y:16383 buttons:3 mode:0]; + [c setJoystick:1 x:16383 y:0 buttons:2 mode:2]; + [c setKeyboardMask:2]; + auto held = [self diskCommand:^(VCCMachineCompletion done) { [c snapshotWithCompletion:done]; }]; + XCTAssertEqual(held.joystickInputs[0].x, 0u); XCTAssertEqual(held.joystickInputs[0].y, 16383u); + XCTAssertEqual(held.joystickInputs[0].buttons, 3u); XCTAssertTrue(held.keyboardInputHeld); + XCTAssertEqual(held.joystickInputs[1].x, 16383u); XCTAssertEqual(held.joystickInputs[1].y, 0u); + XCTAssertEqual(held.joystickInputs[1].buttons, 2u); XCTAssertEqual(held.joystickInputs[1].mode, 2u); + auto paused = [self diskCommand:^(VCCMachineCompletion done) { [c pauseWithCompletion:done]; }]; + for (VCCJoystickInputSnapshot *port in paused.joystickInputs) { + XCTAssertEqual(port.x, 8191u); XCTAssertEqual(port.y, 8191u); XCTAssertEqual(port.buttons, 0u); + } + // Previously published observations remain immutable when live input changes. + XCTAssertEqual(held.joystickInputs[0].x, 0u); XCTAssertEqual(held.joystickInputs[0].buttons, 3u); + XCTAssertTrue(held.keyboardInputHeld); XCTAssertFalse(paused.keyboardInputHeld); + XCTAssertEqual(paused.generation, held.generation); + [c setJoystick:0 x:16383 y:0 buttons:1 mode:0]; + auto ignored = [self diskCommand:^(VCCMachineCompletion done) { [c snapshotWithCompletion:done]; }]; + XCTAssertEqual(ignored.joystickInputs[0].x, 8191u); XCTAssertEqual(ignored.joystickInputs[0].buttons, 0u); + XCTAssertEqual(ignored.frames, paused.frames); XCTAssertEqual(ignored.cycles, paused.cycles); + XCTAssertFalse(ignored.keyboardInputHeld); + [self diskCommand:^(VCCMachineCompletion done) { [c shutdownWithCompletion:done]; }]; + } +} +- (void)testDriveWireOptInPreservesRunningMachine { + auto controller = [VCCMachineController new]; + auto initial = [self diskCommand:^(VCCMachineCompletion done) { [controller loadDiagnosticWithCompletion:done]; }]; + XCTAssertFalse(initial.driveWireEnabled); + auto running = [self diskCommand:^(VCCMachineCompletion done) { [controller resumeWithCompletion:done]; }]; + for (BOOL enabled : {YES, NO}) { + auto updated = [self diskCommand:^(VCCMachineCompletion done) { + [controller setDriveWireEnabled:enabled completion:done]; + }]; + XCTAssertNil(updated.errorMessage); + XCTAssertEqual(updated.driveWireEnabled, enabled); + XCTAssertEqual(updated.state, VCCMachineStateRunning); + XCTAssertEqual(updated.generation, running.generation); + } + [self diskCommand:^(VCCMachineCompletion done) { [controller shutdownWithCompletion:done]; }]; +} +- (void)testMacShellGrantEndsOnResetOrNetworkingOff { + auto c = [VCCMachineController new]; + [self diskCommand:^(VCCMachineCompletion done) { [c loadDiagnosticWithCompletion:done]; }]; + auto denied = [self diskCommand:^(VCCMachineCompletion done) { [c startMacShellWithCompletion:done]; }]; + XCTAssertNotNil(denied.errorMessage); + [self diskCommand:^(VCCMachineCompletion done) { [c setDriveWireEnabled:YES completion:done]; }]; + for (bool reset : {true, false}) { + auto armed = [self diskCommand:^(VCCMachineCompletion done) { [c startMacShellWithCompletion:done]; }]; + XCTAssertEqualObjects(armed.macShellStatus, @"ready"); + XCTAssertEqual(armed.macShellRequestID, 0u); + auto ended = [self diskCommand:^(VCCMachineCompletion done) { + if (reset) [c softResetWithCompletion:done]; else [c setDriveWireEnabled:NO completion:done]; + }]; + XCTAssertEqualObjects(ended.macShellStatus, @"idle"); + auto stale = [self diskCommand:^(VCCMachineCompletion done) { [c decideMacShellRequest:42 allow:YES completion:done]; }]; + XCTAssertNotNil(stale.errorMessage); + XCTAssertEqualObjects(stale.macShellStatus, @"idle"); + } + [self diskCommand:^(VCCMachineCompletion done) { [c shutdownWithCompletion:done]; }]; +} +- (void)testPrinterControlsKeepRunningAudioClock { + auto c = [VCCMachineController new]; + [self diskCommand:^(VCCMachineCompletion done) { [c loadDiagnosticWithCompletion:done]; }]; + [self diskCommand:^(VCCMachineCompletion done) { [c setAudioEnabled:YES volume:0 completion:done]; }]; + [self diskCommand:^(VCCMachineCompletion done) { [c resumeWithCompletion:done]; }]; + auto first = [self diskCommand:^(VCCMachineCompletion done) { [self waitForAudio:c attempts:250 completion:done]; }]; + XCTAssertNil(first.errorMessage); XCTAssertGreaterThan(first.audioStarts, 0u); + XCTAssertTrue(first.audioEnabled); XCTAssertEqual(first.state, VCCMachineStateRunning); + for (unsigned i = 0; i < 6; ++i) { + auto before = [self diskCommand:^(VCCMachineCompletion done) { [c snapshotWithCompletion:done]; }]; + auto changed = [self diskCommand:^(VCCMachineCompletion done) { + if (i % 3 == 2) [c clearPrinterOutputWithCompletion:done]; + else [c setPrinterEnabled:i % 3 == 0 completion:done]; + }]; + XCTAssertNil(changed.errorMessage); XCTAssertEqual(changed.state, VCCMachineStateRunning); + XCTAssertEqual(changed.generation, first.generation); XCTAssertEqual(changed.audioStarts, first.audioStarts); + auto later = [self diskCommand:^(VCCMachineCompletion done) { + [self waitForPrinterFrames:c after:changed.frames attempts:250 completion:done]; + }]; + XCTAssertNil(later.errorMessage); XCTAssertEqual(later.state, VCCMachineStateRunning); + XCTAssertGreaterThan(later.frames, changed.frames); XCTAssertGreaterThan(later.cycles, before.cycles); + XCTAssertEqual(later.generation, first.generation); XCTAssertEqual(later.audioStarts, first.audioStarts); + XCTAssertGreaterThan(later.audioConsumed, before.audioConsumed); XCTAssertTrue(later.audioEnabled); + } + [self diskCommand:^(VCCMachineCompletion done) { [c shutdownWithCompletion:done]; }]; + auto rejected = [self diskCommand:^(VCCMachineCompletion done) { [c setPrinterEnabled:YES completion:done]; }]; + XCTAssertNotNil(rejected.errorMessage); XCTAssertEqual(rejected.state, VCCMachineStateClosed); + rejected = [self diskCommand:^(VCCMachineCompletion done) { [c clearPrinterOutputWithCompletion:done]; }]; + XCTAssertNotNil(rejected.errorMessage); XCTAssertEqual(rejected.state, VCCMachineStateClosed); +} +- (void)testPrinterBridgeCapturesGuestAndPreservesSession { + auto done = [self expectationWithDescription:@"Printer output is immutable and independent of machine lifetime"]; + auto controller = [VCCMachineController new]; + std::vector rom(0x8000, 0x12); + std::vector code{0x86,0x04,0xb7,0xff,0x21}; + auto sample = [&](unsigned bit) { code.insert(code.end(), {0x86,uint8_t(bit << 1),0xb7,0xff,0x20}); }; + const uint8_t message[] = {'P','R','I','N','T',0x0d}; + for (auto byte : message) { + sample(1); sample(0); + for (unsigned bit = 0; bit < 8; ++bit) sample((byte >> bit) & 1); + sample(1); + } + code.insert(code.end(), {0x20,0xfe}); std::copy(code.begin(), code.end(), rom.begin()); + rom[0x7ffe] = 0x80; rom[0x7fff] = 0; + NSData* expected = [NSData dataWithBytes:message length:sizeof(message)]; + [controller loadROM:[NSData dataWithBytes:rom.data() length:rom.size()] use6309:NO completion:^(VCCMachineSnapshot* loaded) { + XCTAssertFalse(loaded.printerEnabled); XCTAssertEqual(loaded.printerByteCount, 0u); + }]; + [controller setPrinterEnabled:YES completion:^(VCCMachineSnapshot* enabled) { + XCTAssertTrue(enabled.printerEnabled); XCTAssertEqual(enabled.state, VCCMachineStatePaused); + }]; + [controller resumeWithCompletion:^(VCCMachineSnapshot* running) { + [self waitForFrame:controller attempts:200 completion:^(VCCMachineSnapshot* frame) { + [controller pauseWithCompletion:^(VCCMachineSnapshot* paused) { + XCTAssertEqual(paused.printerByteCount, sizeof(message)); XCTAssertEqual(paused.printerDroppedBytes, 0u); + [controller printerOutputWithCompletion:^(VCCPrinterOutput* output, VCCMachineSnapshot* read) { + XCTAssertTrue([NSThread isMainThread]); XCTAssertEqualObjects(output.bytes, expected); + XCTAssertEqual(output.revision, read.printerRevision); XCTAssertTrue(output.enabled); + XCTAssertEqual(output.capacity, 1024u * 1024u); + XCTAssertEqual(read.generation, paused.generation); XCTAssertEqual(read.cycles, paused.cycles); + XCTAssertEqual(read.audioStarts, paused.audioStarts); + [controller clearPrinterOutputWithCompletion:^(VCCMachineSnapshot* cleared) { + XCTAssertEqual(cleared.printerByteCount, 0u); XCTAssertTrue(cleared.printerEnabled); + XCTAssertGreaterThan(cleared.printerRevision, read.printerRevision); + XCTAssertEqual(cleared.generation, paused.generation); XCTAssertEqual(cleared.cycles, paused.cycles); + XCTAssertEqualObjects(output.bytes, expected); + [controller setPrinterEnabled:NO completion:^(VCCMachineSnapshot* stopped) { + XCTAssertFalse(stopped.printerEnabled); + [done fulfill]; + }]; + }]; + }]; + }]; + }]; + }]; + [self waitForExpectations:@[done] timeout:10]; + [self diskCommand:^(VCCMachineCompletion completion) { [controller shutdownWithCompletion:completion]; }]; +} +- (void)waitForFrame:(VCCMachineController *)controller attempts:(NSUInteger)attempts completion:(VCCMachineCompletion)completion { + [controller snapshotWithCompletion:^(VCCMachineSnapshot *snapshot) { + if (snapshot.frames > 0 || snapshot.errorMessage || attempts == 0) { completion(snapshot); return; } + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ + [self waitForFrame:controller attempts:attempts - 1 completion:completion]; + }); + }]; +} +- (void)testControllerExecutionAndShutdown { + auto done = [self expectationWithDescription:@"Ordered lifecycle and immutable frame delivery"]; + auto controller = [VCCMachineController new]; + [controller loadDiagnosticWithCompletion:^(VCCMachineSnapshot *loaded) { + XCTAssertTrue([NSThread isMainThread]); XCTAssertEqual(loaded.state, VCCMachineStatePaused); + XCTAssertNil(loaded.errorMessage); + [controller resumeWithCompletion:^(VCCMachineSnapshot *running) { + XCTAssertEqual(running.state, VCCMachineStateRunning); + [self waitForFrame:controller attempts:200 completion:^(VCCMachineSnapshot *rendered) { + XCTAssertGreaterThan(rendered.frames, 0u); XCTAssertNil(rendered.errorMessage); + XCTAssertEqual(rendered.pixels.length, 640u * 480u * 4u); + NSData *saved = rendered.pixels; + [controller pauseWithCompletion:^(VCCMachineSnapshot *paused) { + XCTAssertEqual(paused.state, VCCMachineStatePaused); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 50 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ + [controller snapshotWithCompletion:^(VCCMachineSnapshot *still) { + XCTAssertEqual(still.frames, paused.frames); XCTAssertEqual(still.cycles, paused.cycles); + [controller resetWithCompletion:^(VCCMachineSnapshot *reset) { + XCTAssertEqual(reset.state, VCCMachineStatePaused); XCTAssertEqual(reset.frames, 0u); + XCTAssertNil(reset.pixels); XCTAssertGreaterThan(reset.generation, paused.generation); + [controller shutdownWithCompletion:^(VCCMachineSnapshot *closed) { + XCTAssertEqual(closed.state, VCCMachineStateClosed); XCTAssertNil(closed.pixels); + const uint32_t *pixels = static_cast(saved.bytes); + if (saved.length == 640 * 480 * 4) XCTAssertEqual(pixels[50 * 640], 0xff0000u); + [controller resumeWithCompletion:^(VCCMachineSnapshot *rejected) { + XCTAssertEqual(rejected.state, VCCMachineStateClosed); + XCTAssertNotNil(rejected.errorMessage); [done fulfill]; + }]; + }]; + }]; + }]; + }); + }]; + }]; + }]; + }]; + [self waitForExpectations:@[done] timeout:10]; +} +- (void)testQueuedCommandsAndInvalidInput { + auto done = [self expectationWithDescription:@"FIFO commands"]; + auto controller = [VCCMachineController new]; + NSMutableArray *order = [NSMutableArray new]; + [controller loadDiagnosticWithCompletion:^(VCCMachineSnapshot *s) { XCTAssertNil(s.errorMessage); [order addObject:@"load"]; }]; + [controller resumeWithCompletion:^(VCCMachineSnapshot *s) { XCTAssertEqual(s.state, VCCMachineStateRunning); [order addObject:@"run"]; }]; + [controller pauseWithCompletion:^(VCCMachineSnapshot *s) { XCTAssertEqual(s.state, VCCMachineStatePaused); [order addObject:@"pause"]; }]; + [controller loadROM:[NSData data] use6309:NO completion:^(VCCMachineSnapshot *s) { + XCTAssertNotNil(s.errorMessage); XCTAssertEqual(s.state, VCCMachineStatePaused); [order addObject:@"invalid"]; + }]; + [controller shutdownWithCompletion:^(VCCMachineSnapshot *s) { + XCTAssertEqualObjects(order, (@[@"load", @"run", @"pause", @"invalid"])); + XCTAssertEqual(s.state, VCCMachineStateClosed); [done fulfill]; + }]; + [self waitForExpectations:@[done] timeout:5]; +} +- (void)testControllerDeallocationReleasesOwnership { + auto loaded = [self expectationWithDescription:@"Load first"]; + __block VCCMachineController *first = [VCCMachineController new]; + [first loadDiagnosticWithCompletion:^(VCCMachineSnapshot *s) { XCTAssertNil(s.errorMessage); [loaded fulfill]; }]; + [self waitForExpectations:@[loaded] timeout:5]; + first = nil; // No explicit shutdown; destructor must drain/release the machine. + auto done = [self expectationWithDescription:@"Load replacement"]; + auto next = [VCCMachineController new]; + [next loadDiagnosticWithCompletion:^(VCCMachineSnapshot *s) { + XCTAssertNil(s.errorMessage); XCTAssertEqual(s.state, VCCMachineStatePaused); + [next shutdownWithCompletion:^(VCCMachineSnapshot *closed) { [done fulfill]; }]; + }]; + [self waitForExpectations:@[done] timeout:5]; +} +- (void)verifySoftResetWith6309:(BOOL)use6309 { + auto done = [self expectationWithDescription:@"Soft reset through serialized bridge"]; + auto controller = [VCCMachineController new]; + __block uint64_t generation = 0; + [controller softResetWithCompletion:^(VCCMachineSnapshot *s) { + XCTAssertEqual(s.state, VCCMachineStateEmpty); XCTAssertNotNil(s.errorMessage); + }]; + [controller loadDiagnosticWith6309:use6309 completion:^(VCCMachineSnapshot *s) { + XCTAssertNil(s.errorMessage); generation = s.generation; + }]; + [controller resumeWithCompletion:^(VCCMachineSnapshot *s) { XCTAssertEqual(s.state, VCCMachineStateRunning); }]; + [controller softResetWithCompletion:^(VCCMachineSnapshot *s) { + XCTAssertEqual(s.state, VCCMachineStateRunning); XCTAssertNil(s.errorMessage); + XCTAssertEqual(s.frames, 0u); XCTAssertEqual(s.cycles, 0u); XCTAssertNil(s.pixels); + XCTAssertEqual(s.programCounter, 0x8000); XCTAssertGreaterThan(s.generation, generation); + generation = s.generation; + }]; + [controller pauseWithCompletion:^(VCCMachineSnapshot *s) { XCTAssertEqual(s.state, VCCMachineStatePaused); }]; + [controller softResetWithCompletion:^(VCCMachineSnapshot *s) { + XCTAssertEqual(s.state, VCCMachineStatePaused); XCTAssertEqual(s.cycles, 0u); + XCTAssertGreaterThan(s.generation, generation); XCTAssertNil(s.errorMessage); + }]; + [controller resumeWithCompletion:^(VCCMachineSnapshot *s) { + [self waitForFrame:controller attempts:200 completion:^(VCCMachineSnapshot *frame) { + XCTAssertGreaterThan(frame.frames, 0u); XCTAssertNil(frame.errorMessage); + [controller shutdownWithCompletion:^(VCCMachineSnapshot *closed) { [done fulfill]; }]; + }]; + }]; + [self waitForExpectations:@[done] timeout:10]; +} +- (void)test6809SoftReset { [self verifySoftResetWith6309:NO]; } +- (void)test6309SoftReset { [self verifySoftResetWith6309:YES]; } +- (void)testCassetteBridgeTransportAndExport { + auto done=[self expectationWithDescription:@"Cassette copy and transport"]; + auto controller=[VCCMachineController new]; + const uint8_t bytes[]={0x55,0x3c,0xa5}; + NSData *source=[NSData dataWithBytes:bytes length:3]; + [controller mountTape:source wav:NO completion:^(VCCMachineSnapshot *s) { + XCTAssertTrue(s.tapeMounted); XCTAssertEqual(s.tapeLength,3u); XCTAssertNil(s.errorMessage); + }]; + [controller setTapeFast:YES completion:^(VCCMachineSnapshot *s) { XCTAssertTrue(s.tapeFast); }]; + [controller tapeAction:1 completion:^(VCCMachineSnapshot *s) { XCTAssertEqual(s.tapeMode,1); }]; + [controller tapeAction:2 completion:^(VCCMachineSnapshot *s) { XCTAssertEqual(s.tapeMode,0); XCTAssertEqual(s.tapePosition,0u); }]; + [controller mountTape:source wav:YES completion:^(VCCMachineSnapshot *s) { + XCTAssertNotNil(s.errorMessage); XCTAssertEqual(s.tapeLength,3u); + }]; + [controller exportTapeWithCompletion:^(NSData *data,VCCMachineSnapshot *s) { + XCTAssertEqualObjects(data,source); XCTAssertNil(s.errorMessage); + [controller discardTapeWithCompletion:^(VCCMachineSnapshot *discarded) { + XCTAssertFalse(discarded.tapeMounted); XCTAssertFalse(discarded.tapeDirty); + [controller shutdownWithCompletion:^(VCCMachineSnapshot *closed) { [done fulfill]; }]; + }]; + }]; + [self waitForExpectations:@[done] timeout:5]; +} +- (void)waitForAudio:(VCCMachineController*)controller attempts:(NSUInteger)attempts completion:(VCCMachineCompletion)completion { + [controller snapshotWithCompletion:^(VCCMachineSnapshot *s) { + if(s.audioConsumed>=4410 || s.errorMessage || attempts==0) { completion(s); return; } + dispatch_after(dispatch_time(DISPATCH_TIME_NOW,20*NSEC_PER_MSEC),dispatch_get_main_queue(),^{ + [self waitForAudio:controller attempts:attempts-1 completion:completion]; + }); + }]; +} +- (void)testVolumeChangesKeepAudioClockRunning { + auto c = [VCCMachineController new]; + [self diskCommand:^(VCCMachineCompletion done) { [c setAudioEnabled:YES volume:0 completion:done]; }]; + [self diskCommand:^(VCCMachineCompletion done) { [c loadDiagnosticWithCompletion:done]; }]; + [self diskCommand:^(VCCMachineCompletion done) { [c resumeWithCompletion:done]; }]; + auto first = [self diskCommand:^(VCCMachineCompletion done) { [self waitForAudio:c attempts:250 completion:done]; }]; + XCTAssertNil(first.errorMessage); XCTAssertGreaterThan(first.audioStarts, 0u); + for (unsigned i = 0; i < 20; ++i) { + auto changed = [self diskCommand:^(VCCMachineCompletion done) { [c setAudioEnabled:YES volume:i % 2 ? 0 : 0.25 completion:done]; }]; + XCTAssertNil(changed.errorMessage); XCTAssertEqual(changed.audioStarts, first.audioStarts); + XCTAssertGreaterThanOrEqual(changed.audioConsumed, first.audioConsumed); + } + auto changedDisplay = [self diskCommand:^(VCCMachineCompletion done) { [c setVideoOutput:1 completion:done]; }]; + XCTAssertEqual(changedDisplay.videoOutput, 1); XCTAssertNil(changedDisplay.errorMessage); + XCTAssertEqual(changedDisplay.audioStarts, first.audioStarts); + XCTAssertEqual(changedDisplay.generation, first.generation); + auto liveSettings = [self diskCommand:^(VCCMachineCompletion done) { + [c configureMachineWith6309:NO ram:1 overclock:3 frameInterval:4 fastForward:NO completion:done]; + }]; + XCTAssertNil(liveSettings.errorMessage); XCTAssertEqual(liveSettings.state, VCCMachineStateRunning); + XCTAssertEqual(liveSettings.audioStarts, first.audioStarts); XCTAssertEqual(liveSettings.generation, first.generation); + auto off = [self diskCommand:^(VCCMachineCompletion done) { [c setAudioEnabled:NO volume:0 completion:done]; }]; + auto delay = [self expectationWithDescription:@"Silent pacing continues"]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 200*NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ [delay fulfill]; }); + [self waitForExpectations:@[delay] timeout:5]; + auto silent = [self diskCommand:^(VCCMachineCompletion done) { [c snapshotWithCompletion:done]; }]; + XCTAssertGreaterThan(silent.frames, off.frames); XCTAssertLessThan(silent.frames - off.frames, 30u); + XCTAssertEqual(silent.audioConsumed, off.audioConsumed); + [self diskCommand:^(VCCMachineCompletion done) { [c setAudioEnabled:YES volume:0 completion:done]; }]; + auto resumed = [self expectationWithDescription:@"Output restarts"]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 200*NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ [resumed fulfill]; }); + [self waitForExpectations:@[resumed] timeout:5]; + auto on = [self diskCommand:^(VCCMachineCompletion done) { [c snapshotWithCompletion:done]; }]; + XCTAssertNil(on.errorMessage); XCTAssertTrue(on.audioEnabled); + XCTAssertEqual(on.audioStarts, first.audioStarts + 1); XCTAssertGreaterThan(on.audioConsumed, silent.audioConsumed); + [self diskCommand:^(VCCMachineCompletion done) { [c shutdownWithCompletion:done]; }]; +} +- (void)testNativeAudioPauseAndRestart { + auto done=[self expectationWithDescription:@"Silent native output lifecycle"]; + auto controller=[VCCMachineController new]; + [controller setAudioEnabled:YES volume:0 completion:^(VCCMachineSnapshot *s) { XCTAssertTrue(s.audioEnabled); }]; + [controller loadDiagnosticWithCompletion:^(VCCMachineSnapshot *s) { XCTAssertNil(s.errorMessage); }]; + [controller resumeWithCompletion:^(VCCMachineSnapshot *s) { + [self waitForAudio:controller attempts:250 completion:^(VCCMachineSnapshot *playing) { + XCTAssertGreaterThanOrEqual(playing.audioConsumed,4410u, + @"Audio error: %@; starts: %llu; enabled: %@", playing.errorMessage, + (unsigned long long)playing.audioStarts, playing.audioEnabled ? @"yes" : @"no"); + [controller pauseWithCompletion:^(VCCMachineSnapshot *paused) { + XCTAssertNil(paused.errorMessage); XCTAssertTrue(paused.audioEnabled); XCTAssertGreaterThan(paused.frames,3u); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW,100*NSEC_PER_MSEC),dispatch_get_main_queue(),^{ + [controller snapshotWithCompletion:^(VCCMachineSnapshot *still) { + XCTAssertEqual(still.frames,paused.frames); XCTAssertEqual(still.audioUnderruns,paused.audioUnderruns); + [controller resumeWithCompletion:^(VCCMachineSnapshot *s) { + dispatch_after(dispatch_time(DISPATCH_TIME_NOW,200*NSEC_PER_MSEC),dispatch_get_main_queue(),^{ + [controller snapshotWithCompletion:^(VCCMachineSnapshot *running) { + XCTAssertNil(running.errorMessage); XCTAssertGreaterThan(running.frames,paused.frames); + [controller shutdownWithCompletion:^(VCCMachineSnapshot *closed) { [done fulfill]; }]; + }]; + }); + }]; + }]; + }); + }]; + }]; + }]; + [self waitForExpectations:@[done] timeout:10]; +} + +- (VCCMachineSnapshot*)diskCommand:(void (^)(VCCMachineCompletion))operation { + auto done = [self expectationWithDescription:@"Disk command completion"]; + __block VCCMachineSnapshot *result = nil; + operation(^(VCCMachineSnapshot *snapshot) { result = snapshot; [done fulfill]; }); + [self waitForExpectations:@[done] timeout:10]; + return result; +} +- (VCCDebugGraphicsCapture*)graphics:(VCCMachineController*)controller current:(BOOL)current physical:(BOOL)physical address:(uint32_t)address mode:(NSInteger)mode { + auto done = [self expectationWithDescription:@"Graphics capture on main queue"]; + __block VCCDebugGraphicsCapture *result; + [controller debuggerGraphicsCurrentPage:current address:address physical:physical mode:mode alternatePalette:NO completion:^(VCCDebugGraphicsCapture *capture) { + XCTAssertTrue(NSThread.isMainThread); + result = capture; + [done fulfill]; + }]; + [self waitForExpectations:@[done] timeout:10]; + return result; +} +- (void)testGraphicsPreviewCapturesImmutablePixelsAndByteLocations { + auto c = [VCCMachineController new]; + auto initial = [self diskCommand:^(VCCMachineCompletion done) { [c loadDiagnosticWithCompletion:done]; }]; + auto current = [self graphics:c current:YES physical:NO address:0 mode:0]; + XCTAssertNil(current.errorMessage); XCTAssertTrue(current.physical); + XCTAssertEqual(current.machine.cycles, initial.cycles); + XCTAssertEqual(current.machine.programCounter, initial.programCounter); + XCTAssertEqual(current.machine.generation, initial.generation); + auto writeByte = [&](uint16_t address, uint8_t value) { + auto s = [self diskCommand:^(VCCMachineCompletion done) { + [c debuggerWriteMemoryAtAddress:address data:[NSData dataWithBytes:&value length:1] completion:done]; + }]; + XCTAssertNil(s.errorMessage); + }; + writeByte(0x4001, 0xa0); + auto before = [self graphics:c current:NO physical:NO address:0x4000 mode:5]; + XCTAssertNil(before.errorMessage); XCTAssertFalse(before.physical); + XCTAssertEqual(before.width, 256); XCTAssertEqual(before.height, 192); + XCTAssertEqual(before.rgba.length, 256u * 192u * 4u); + XCTAssertNil([before pixelAtX:-1 y:0]); XCTAssertNil([before pixelAtX:0 y:192]); + auto high = [before pixelAtX:8 y:0]; + XCTAssertEqual(high.address, 0x4001u); XCTAssertEqual(high.value, 0xa0); + XCTAssertEqual(high.mask, 0x80); XCTAssertTrue(high.available); XCTAssertNil(high.attributeAddress); + XCTAssertEqual([before pixelAtX:10 y:0].mask, 0x20); + XCTAssertEqual([before pixelAtX:8 y:1].address, 0x4021u); + writeByte(0x4001, 0x40); + auto after = [self graphics:c current:NO physical:NO address:0x4000 mode:5]; + XCTAssertTrue([after hasSameLayoutAs:before]); + XCTAssertEqual([before pixelAtX:8 y:0].value, 0xa0); XCTAssertEqual([after pixelAtX:8 y:0].value, 0x40); + auto ram = [self graphics:c current:NO physical:YES address:0x4000 mode:5]; + XCTAssertNil(ram.errorMessage); XCTAssertFalse([after hasSameLayoutAs:ram]); + [self diskCommand:^(VCCMachineCompletion done) { [c resumeWithCompletion:done]; }]; + auto live = [self graphics:c current:YES physical:NO address:0 mode:0]; + XCTAssertNil(live.errorMessage); XCTAssertEqual(live.machine.state, VCCMachineStateRunning); + XCTAssertEqual(live.machine.generation, initial.generation); + [self diskCommand:^(VCCMachineCompletion done) { [c shutdownWithCompletion:done]; }]; +} +- (void)testGraphicsPreviewRejectsOverflowAndMarksUnavailableMappedIO { + auto c = [VCCMachineController new]; + auto empty = [self graphics:c current:YES physical:NO address:0 mode:0]; + XCTAssertNotNil(empty.errorMessage); XCTAssertNil([empty pixelAtX:0 y:0]); + auto initial = [self diskCommand:^(VCCMachineCompletion done) { [c loadDiagnosticWithCompletion:done]; }]; + for (BOOL physical : {NO, YES}) { + auto invalid = [self graphics:c current:NO physical:physical address:UINT32_MAX mode:5]; + XCTAssertNotNil(invalid.errorMessage); XCTAssertEqual(invalid.rgba.length, 0u); + XCTAssertNil(invalid.machine.errorMessage); + XCTAssertEqual(invalid.machine.cycles, initial.cycles); + } + auto invalidMode = [self graphics:c current:NO physical:YES address:0 mode:10]; + XCTAssertNotNil(invalidMode.errorMessage); + // A 128 × 96 one-bit page is 1536 bytes; this base puts $FF00 at y=80. + auto io = [self graphics:c current:NO physical:NO address:0xfa00 mode:1]; + XCTAssertNil(io.errorMessage); XCTAssertEqual(io.height, 96); + XCTAssertEqual([io pixelAtX:0 y:80].address, 0xff00u); XCTAssertFalse([io pixelAtX:0 y:80].available); + XCTAssertTrue([io pixelAtX:0 y:79].available); + XCTAssertEqual(io.machine.cycles, initial.cycles); + [self diskCommand:^(VCCMachineCompletion done) { [c shutdownWithCompletion:done]; }]; +} +- (void)testDiskBridgeLifecycleAndProtection { + auto c = [VCCMachineController new]; + NSData *rom = [NSMutableData dataWithLength:8192]; + auto s = [self diskCommand:^(VCCMachineCompletion done) { [c loadDiagnosticWithCompletion:done]; }]; + XCTAssertEqual(s.disks.count, 4u); XCTAssertFalse(s.diskEnabled); + s = [self diskCommand:^(VCCMachineCompletion done) { [c loadDiskROM:[NSData data] name:@"bad" completion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertFalse(s.diskEnabled); + s = [self diskCommand:^(VCCMachineCompletion done) { [c loadDiskROM:rom name:@"authored.rom" completion:done]; }]; + XCTAssertNil(s.errorMessage); XCTAssertTrue(s.diskEnabled); XCTAssertEqual(s.state, VCCMachineStatePaused); + for (NSInteger drive = 0; drive < 4; ++drive) { + s = [self diskCommand:^(VCCMachineCompletion done) { [c createDiskInDrive:drive completion:done]; }]; + XCTAssertNil(s.errorMessage); XCTAssertTrue(s.disks[drive].mounted); XCTAssertTrue(s.disks[drive].dirty); + XCTAssertEqual(s.disks[drive].byteCount, 161280u); + } + VCCMachineSnapshot *immutable = s; + s = [self diskCommand:^(VCCMachineCompletion done) { [c disableDisksWithCompletion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertTrue(s.diskEnabled); + s = [self diskCommand:^(VCCMachineCompletion done) { [c ejectDiskInDrive:0 discard:NO completion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertTrue(s.disks[0].dirty); + __block NSData *exported = nil; __block uint64_t token = 0; + s = [self diskCommand:^(VCCMachineCompletion done) { + [c exportDiskInDrive:0 completion:^(NSData *data, uint64_t value, VCCMachineSnapshot *snapshot) { + exported = data; token = value; done(snapshot); + }]; + }]; + XCTAssertEqual(exported.length, 161280u); XCTAssertTrue(s.disks[0].dirty); XCTAssertEqual(s.state,VCCMachineStatePaused); + s = [self diskCommand:^(VCCMachineCompletion done) { [c markDiskSavedInDrive:0 token:token+1 name:@"wrong.dsk" completion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertTrue(s.disks[0].dirty); + s = [self diskCommand:^(VCCMachineCompletion done) { [c markDiskSavedInDrive:0 token:token name:@"Disk é.DSK" completion:done]; }]; + XCTAssertNil(s.errorMessage); XCTAssertFalse(s.disks[0].dirty); XCTAssertEqualObjects(s.disks[0].name,@"Disk é.DSK"); + XCTAssertTrue(immutable.disks[0].dirty, @"Published drive snapshots must not mutate"); + s = [self diskCommand:^(VCCMachineCompletion done) { [c mountDisk:[NSData data] drive:0 name:@"broken.dsk" readOnly:NO completion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertEqualObjects(s.disks[0].name,@"Disk é.DSK"); + s = [self diskCommand:^(VCCMachineCompletion done) { [c setDiskWriteProtected:YES drive:0 completion:done]; }]; + XCTAssertNil(s.errorMessage); XCTAssertTrue(s.disks[0].writeProtected); + s = [self diskCommand:^(VCCMachineCompletion done) { [c setDiskWriteProtected:NO drive:0 completion:done]; }]; + XCTAssertFalse(s.disks[0].writeProtected); + s = [self diskCommand:^(VCCMachineCompletion done) { [c mountDisk:exported drive:0 name:@"read-only.dsk" readOnly:YES completion:done]; }]; + XCTAssertNil(s.errorMessage); XCTAssertTrue(s.disks[0].sourceReadOnly); XCTAssertTrue(s.disks[0].writeProtected); + s = [self diskCommand:^(VCCMachineCompletion done) { [c setDiskWriteProtected:NO drive:0 completion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertTrue(s.disks[0].writeProtected); + s = [self diskCommand:^(VCCMachineCompletion done) { [c loadDiskROM:rom name:@"replacement.rom" completion:done]; }]; + XCTAssertNil(s.errorMessage); XCTAssertEqualObjects(s.diskROMName,@"replacement.rom"); + XCTAssertTrue(s.disks[0].mounted); XCTAssertTrue(s.disks[1].dirty); + s = [self diskCommand:^(VCCMachineCompletion done) { [c loadDiskROM:[NSData data] name:@"invalid" completion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertEqualObjects(s.diskROMName,@"replacement.rom"); + for (NSInteger drive : {-1,4}) { + s = [self diskCommand:^(VCCMachineCompletion done) { [c createDiskInDrive:drive completion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertEqual(s.disks.count,4u); + } + for (NSInteger drive = 0; drive < 4; ++drive) { + s = [self diskCommand:^(VCCMachineCompletion done) { [c ejectDiskInDrive:drive discard:YES completion:done]; }]; + XCTAssertNil(s.errorMessage); XCTAssertFalse(s.disks[drive].mounted); + } + s = [self diskCommand:^(VCCMachineCompletion done) { [c disableDisksWithCompletion:done]; }]; + XCTAssertNil(s.errorMessage); XCTAssertFalse(s.diskEnabled); XCTAssertEqual(s.state,VCCMachineStatePaused); + [self diskCommand:^(VCCMachineCompletion done) { [c shutdownWithCompletion:done]; }]; +} +- (void)testVDKExtendedHeaderProtectionAndFailedDiskReplacement { + auto c = [VCCMachineController new]; + [self diskCommand:^(VCCMachineCompletion done) { [c loadDiagnosticWithCompletion:done]; }]; + [self diskCommand:^(VCCMachineCompletion done) { + [c loadDiskROM:[NSMutableData dataWithLength:8192] name:@"authored.rom" completion:done]; + }]; + auto vdk = [NSMutableData dataWithLength:256 + 18 * 256]; + const uint8_t header[] = {'d','k',0,1,0x10,0x10,0,0,1,1,1,0}; + memcpy(vdk.mutableBytes, header, sizeof(header)); + auto s = [self diskCommand:^(VCCMachineCompletion done) { [c mountDisk:vdk drive:2 name:@"Archive.DSK" readOnly:NO completion:done]; }]; + XCTAssertNil(s.errorMessage); XCTAssertEqualObjects(s.disks[2].floppyExtension, @"vdk"); + XCTAssertTrue(s.disks[2].formatWriteProtected); XCTAssertTrue(s.disks[2].writeProtected); + XCTAssertFalse(s.disks[2].sourceReadOnly); + s = [self diskCommand:^(VCCMachineCompletion done) { [c setDiskWriteProtected:NO drive:2 completion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertTrue(s.disks[2].writeProtected); + s = [self diskCommand:^(VCCMachineCompletion done) { [c mountDisk:vdk drive:2 name:@"Wrong.dmk" readOnly:NO completion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertEqualObjects(s.disks[2].name, @"Archive.DSK"); + [self diskCommand:^(VCCMachineCompletion done) { + [c exportDiskInDrive:2 completion:^(NSData *data, uint64_t token, VCCMachineSnapshot *snapshot) { + XCTAssertEqualObjects(data, vdk); done(snapshot); + }]; + }]; + [self diskCommand:^(VCCMachineCompletion done) { [c shutdownWithCompletion:done]; }]; +} +- (void)testCreateFloppyImageInSelectedFormat { + auto c = [VCCMachineController new]; + [self diskCommand:^(VCCMachineCompletion done) { + [c loadDiskROM:[NSMutableData dataWithLength:8192] name:@"authored.rom" completion:done]; + }]; + NSInteger drive = 0; + for (VCCFloppyFormat format : {VCCFloppyFormatStandard, VCCFloppyFormatTrackDMK, VCCFloppyFormatSectorVDK}) { + auto s = [self diskCommand:^(VCCMachineCompletion done) { [c createDiskInDrive:drive format:format completion:done]; }]; + XCTAssertNil(s.errorMessage); XCTAssertTrue(s.disks[drive].dirty); + XCTAssertEqualObjects(s.disks[drive].floppyExtension, (@[@"dsk", @"dmk", @"vdk"])[drive]); + XCTAssertEqual(s.disks[drive].tracks, 35u); + ++drive; + } + [self diskCommand:^(VCCMachineCompletion done) { [c shutdownWithCompletion:done]; }]; +} +- (NSData*)diskWriterROM { + auto rom = [NSMutableData dataWithLength:32768]; + // Authored 6809/6309 program: write 256 bytes to sector 1, trigger deferred + // commit with one final data-register access, then loop. No disk ROM needed. + const uint8_t program[] = { + 0x86,0x29,0xb7,0xff,0x40, 0x86,1,0xb7,0xff,0x4a, + 0x86,0xa0,0xb7,0xff,0x48, 0x8e,1,0, 0x86,0x5a, + 0xb7,0xff,0x4b,0x30,0x1f,0x26,0xf9,0xb7,0xff,0x4b,0x20,0xfe + }; + memcpy(rom.mutableBytes, program, sizeof(program)); + auto* bytes = static_cast(rom.mutableBytes); bytes[32766] = 0x80; + return rom; +} +- (void)testDiskExportRejectsNewWritesAndReplacement { + for (BOOL use6309 : {NO,YES}) { + auto c = [VCCMachineController new]; + [self diskCommand:^(VCCMachineCompletion done) { [c loadDiskROM:[NSMutableData dataWithLength:8192] name:@"authored" completion:done]; }]; + [self diskCommand:^(VCCMachineCompletion done) { [c createDiskInDrive:0 completion:done]; }]; + [self diskCommand:^(VCCMachineCompletion done) { [c loadROM:[self diskWriterROM] use6309:use6309 completion:done]; }]; + __block uint64_t token = 0; __block NSData *before = nil; + [self diskCommand:^(VCCMachineCompletion done) { + [c exportDiskInDrive:0 completion:^(NSData *data,uint64_t value,VCCMachineSnapshot *s) { token=value; before=data; done(s); }]; + }]; + [self diskCommand:^(VCCMachineCompletion done) { [c resumeWithCompletion:done]; }]; + [self diskCommand:^(VCCMachineCompletion done) { [self waitForFrame:c attempts:200 completion:done]; }]; + auto s = [self diskCommand:^(VCCMachineCompletion done) { [c pauseWithCompletion:done]; }]; + XCTAssertFalse(s.diskBusy); XCTAssertTrue(s.disks[0].dirty); + s = [self diskCommand:^(VCCMachineCompletion done) { [c markDiskSavedInDrive:0 token:token name:@"stale.dsk" completion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertTrue(s.disks[0].dirty); + __block NSData *after = nil; + [self diskCommand:^(VCCMachineCompletion done) { + [c exportDiskInDrive:0 completion:^(NSData *data,uint64_t value,VCCMachineSnapshot *s) { token=value; after=data; done(s); }]; + }]; + XCTAssertNotEqualObjects(before,after); XCTAssertEqual(static_cast(after.bytes)[0],0x5a); + [self diskCommand:^(VCCMachineCompletion done) { [c ejectDiskInDrive:0 discard:YES completion:done]; }]; + [self diskCommand:^(VCCMachineCompletion done) { [c mountDisk:after drive:0 name:@"replacement.dsk" readOnly:NO completion:done]; }]; + s = [self diskCommand:^(VCCMachineCompletion done) { [c markDiskSavedInDrive:0 token:token name:@"wrong.dsk" completion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertEqualObjects(s.disks[0].name,@"replacement.dsk"); + [self diskCommand:^(VCCMachineCompletion done) { [c shutdownWithCompletion:done]; }]; + } +} +- (void)testDiskBusyControllerRejectsMediaChanges { + auto c = [VCCMachineController new]; + [self diskCommand:^(VCCMachineCompletion done) { [c loadDiskROM:[NSMutableData dataWithLength:8192] name:@"authored" completion:done]; }]; + [self diskCommand:^(VCCMachineCompletion done) { [c createDiskInDrive:0 completion:done]; }]; + auto rom = [NSMutableData dataWithLength:32768]; + const uint8_t program[] = {0x86,1,0xb7,0xff,0x40,0x86,0x10,0xb7,0xff,0x48,0x20,0xfe}; // motor off, pending seek + memcpy(rom.mutableBytes,program,sizeof(program)); static_cast(rom.mutableBytes)[32766]=0x80; + [self diskCommand:^(VCCMachineCompletion done) { [c loadROM:rom use6309:NO completion:done]; }]; + [self diskCommand:^(VCCMachineCompletion done) { [c resumeWithCompletion:done]; }]; + auto s = [self diskCommand:^(VCCMachineCompletion done) { [self waitForFrame:c attempts:200 completion:done]; }]; + XCTAssertTrue(s.diskBusy); + const auto generation = s.generation; + s = [self diskCommand:^(VCCMachineCompletion done) { + [c configureMachineWith6309:YES ram:0 overclock:1 frameInterval:1 fastForward:YES completion:done]; + }]; + XCTAssertNotNil(s.errorMessage); XCTAssertTrue(s.diskBusy); XCTAssertFalse(s.fastForward); + XCTAssertFalse(s.use6309); XCTAssertEqual(s.ramConfiguration, 1u); XCTAssertEqual(s.generation, generation); + s = [self diskCommand:^(VCCMachineCompletion done) { [c pauseForDiskChangeWithCompletion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertTrue(s.diskBusy); + s = [self diskCommand:^(VCCMachineCompletion done) { [c ejectDiskInDrive:0 discard:YES completion:done]; }]; + XCTAssertNotNil(s.errorMessage); XCTAssertTrue(s.disks[0].mounted); + [self diskCommand:^(VCCMachineCompletion done) { [c pauseWithCompletion:done]; }]; + s = [self diskCommand:^(VCCMachineCompletion done) { [c softResetWithCompletion:done]; }]; + XCTAssertFalse(s.diskBusy); XCTAssertTrue(s.disks[0].dirty); + s = [self diskCommand:^(VCCMachineCompletion done) { + [c configureMachineWith6309:YES ram:0 overclock:1 frameInterval:1 fastForward:NO completion:done]; + }]; + XCTAssertNil(s.errorMessage); XCTAssertTrue(s.use6309); XCTAssertEqual(s.ramConfiguration, 0u); + XCTAssertTrue(s.disks[0].mounted); XCTAssertTrue(s.disks[0].dirty); XCTAssertTrue(s.diskConnected); + s = [self diskCommand:^(VCCMachineCompletion done) { [c ejectDiskInDrive:0 discard:YES completion:done]; }]; + XCTAssertNil(s.errorMessage); XCTAssertFalse(s.disks[0].mounted); + [self diskCommand:^(VCCMachineCompletion done) { [c shutdownWithCompletion:done]; }]; +} +@end diff --git a/platforms/macos/Tests/CoreTests.mm b/platforms/macos/Tests/CoreTests.mm new file mode 100644 index 0000000..8f975fc --- /dev/null +++ b/platforms/macos/Tests/CoreTests.mm @@ -0,0 +1,217 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import +#include "../../../tests/core/CoreChecks.h" +#include +#include "../../../src/core/PrinterCapture.h" +#include "../../../src/core/MachineSession.h" +#include "../../../src/core/CpuMemory.h" +#include +#include + +@interface CoreTests : XCTestCase +@end +@implementation CoreTests +- (void)testBASICProgramTokens { + try { CheckBasicProgramTokens(); } catch (const std::exception& e) { XCTFail(@"%s", e.what()); } +} +- (void)testBASICProgramValidation { + try { CheckBasicProgramValidation(); } catch (const std::exception& e) { XCTFail(@"%s", e.what()); } +} +- (void)testOptionalLocalBASICPrinterOutput { + // Opt-in local integration only. The public test suite contains no ROM data + // or machine-specific path; set VCC_PRINTER_ROM to a supplied CoCo 3 ROM. + const char* path = std::getenv("VCC_PRINTER_ROM"); + XCTSkipIf(path == nullptr || *path == '\0', @"Set VCC_PRINTER_ROM to run the optional local BASIC printer check"); + NSData* source = [NSData dataWithContentsOfFile:[NSString stringWithUTF8String:path]]; + XCTAssertEqual(source.length, 32768u, "VCC_PRINTER_ROM must name a readable 32 KiB CoCo 3 ROM"); + if (source.length != 32768) return; + const auto* begin = static_cast(source.bytes); + std::vector rom(begin, begin + source.length); + auto chord = [](char c) -> uint64_t { + if (c >= 'A' && c <= 'Z') return uint64_t{1} << (c - '@'); + if (c >= '0' && c <= '9') return uint64_t{1} << (32 + c - '0'); + if (c == '"') return (uint64_t{1} << 34) | (uint64_t{1} << 55); + if (c == '#') return (uint64_t{1} << 35) | (uint64_t{1} << 55); + if (c == '-') return uint64_t{1} << 45; + if (c == ',') return uint64_t{1} << 44; + if (c == ' ') return uint64_t{1} << 31; + if (c == '\r') return uint64_t{1} << 48; + return 0; + }; + using namespace VCC::Mac; + for (auto cpu : {Processor::MC6809, Processor::HD6309}) { + MachineSession machine; machine.load(rom, cpu); machine.resume(); + auto frames = [&](unsigned n) { while (n--) machine.advance(); }; + auto type = [&](const std::string& text) { + for (char c : text) { machine.setKeyboard(chord(c)); frames(4); machine.setKeyboard(0); frames(4); } + }; + frames(300); + XCTAssertNotEqual(machine.copyScreenText().find("OK"), std::string::npos); + machine.printer().setEnabled(true); + type("PRINT #-2,\"HELLO FROM PRINTER\"\r"); frames(300); + auto text7 = [&] { + std::string result; + for (uint8_t byte : machine.printer().bytes()) result += char(byte & 0x7f); + return result; + }; + XCTAssertEqual(text7(), std::string("HELLO FROM PRINTER\r"), "BASIC PRINT #-2 reaches the serial capture exactly"); + const auto printed = machine.printer().bytes(); + std::size_t high = 0; + for (uint8_t byte : printed) if (byte & 0x80) ++high; + std::printf("BASIC printer %s: PRINT captured %zu bytes, %zu high-bit bytes; raw hex:", + cpu == Processor::MC6809 ? "6809" : "6309", printed.size(), high); + for (uint8_t byte : printed) std::printf(" %02X", unsigned(byte)); + std::printf("\n"); + machine.printer().clear(); + type("10 PRINT \"HELLO FROM PRINTER\"\rLLIST\r"); frames(300); + XCTAssertEqual(text7(), std::string("10 PRINT \"HELLO FROM PRINTER\"\r"), "BASIC LLIST reaches the same serial capture exactly"); + XCTAssertEqual(machine.printer().droppedBytes(), 0u); + std::printf("BASIC printer %s: LLIST captured %zu bytes: %s\n", + cpu == Processor::MC6809 ? "6809" : "6309", machine.printer().bytes().size(), text7().c_str()); + machine.printer().setEnabled(false); + const auto stopped = machine.printer().bytes(); + type("PRINT #-2,\"HELLO FROM PRINTER\"\r"); frames(300); + XCTAssertTrue(machine.printer().bytes() == stopped, "Stopping capture leaves the guest running without collecting more output"); + } +} +- (void)testPrinterFramingRawBytesAndBound { + VCC::Mac::PrinterCapture capture; + auto send = [&](uint8_t byte) { + capture.sample(1); capture.sample(0); + for (unsigned bit = 0; bit < 8; ++bit) capture.sample((byte >> bit) & 1); + capture.sample(1); capture.sample(1); + }; + send(0x41); XCTAssertTrue(capture.bytes().empty()); + capture.setEnabled(true); + for (uint8_t value : {0x00, 0x41, 0x80, 0xff, 0x0d, 0x0a}) send(value); + const std::vector expected{0x00, 0x41, 0x80, 0xff, 0x0d, 0x0a}; + XCTAssertTrue(capture.bytes() == expected); // No 7-bit masking or newline conversion. + const auto saved = capture.bytes(); + auto revision = capture.revision(); + capture.clear(); XCTAssertTrue(capture.bytes().empty()); XCTAssertGreaterThan(capture.revision(), revision); + XCTAssertTrue(saved == expected); // Immutable copy survives Clear. + for (std::size_t i = 0; i < capture.capacity + 7; ++i) send(uint8_t(i)); + XCTAssertEqual(capture.bytes().size(), capture.capacity); XCTAssertEqual(capture.droppedBytes(), 7u); + XCTAssertEqual(capture.bytes().front(), 0u); XCTAssertEqual(capture.bytes().back(), 255u); + revision = capture.revision(); + capture.setEnabled(false); send(0x55); XCTAssertEqual(capture.droppedBytes(), 7u); + XCTAssertEqual(capture.revision(), revision, "Capture toggles do not change exported content"); + capture.clear(); XCTAssertEqual(capture.droppedBytes(), 0u); XCTAssertFalse(capture.enabled()); +} +- (void)testPrinterPartialCharactersAndReset { + VCC::Mac::PrinterCapture capture; capture.setEnabled(true); + capture.sample(0); capture.sample(1); capture.sample(1); // Start and two bits of FF. + capture.clear(); + for (int i = 0; i < 6; ++i) capture.sample(1); + XCTAssertEqual(capture.bytes().size(), 1u); XCTAssertEqual(capture.bytes()[0], 0xffu); + capture.sample(0); capture.sample(1); // Truncated next byte. + capture.resetFraming(); + capture.sample(1); capture.sample(0); + for (int i = 0; i < 8; ++i) capture.sample(0); + XCTAssertEqual(capture.bytes().size(), 2u); XCTAssertEqual(capture.bytes()[1], 0u); + capture.sample(0); capture.sample(1); + capture.setEnabled(false); capture.setEnabled(true); // Resume starts at a new character. + capture.sample(0); + for (int i = 0; i < 8; ++i) capture.sample(0); + XCTAssertEqual(capture.bytes().size(), 3u); XCTAssertEqual(capture.bytes()[2], 0u); +} +- (void)testGuestPrinterOutputBothProcessorsAndLifetime { + using namespace VCC::Mac; + for (auto processor : {Processor::MC6809, Processor::HD6309}) { + MachineSession machine; + std::vector rom(0x8000, 0x12); + std::vector code{0x86,0x04,0xb7,0xff,0x21}; // Select PIA1 data register. + auto sample = [&](unsigned value) { code.insert(code.end(), {0x86,uint8_t(value << 1),0xb7,0xff,0x20}); }; + const std::vector message{'H','E','L','L','O',0x0d,0x80}; + for (uint8_t byte : message) { + sample(1); sample(0); + for (unsigned bit = 0; bit < 8; ++bit) sample((byte >> bit) & 1); + sample(1); + } + code.insert(code.end(), {0x20,0xfe}); // Guest waits without writing again. + std::copy(code.begin(), code.end(), rom.begin()); rom[0x7ffe] = 0x80; rom[0x7fff] = 0; + machine.printer().setEnabled(true); machine.load(rom, processor); + machine.resume(); machine.advance(); machine.pause(); + XCTAssertTrue(machine.printer().bytes() == message); + const auto before = machine.snapshot(); + machine.printer().setEnabled(false); machine.printer().setEnabled(true); + XCTAssertEqual(machine.snapshot().generation, before.generation); + XCTAssertEqual(machine.snapshot().cycles, before.cycles); + machine.softReset(); XCTAssertTrue(machine.printer().bytes() == message); + machine.reset(); XCTAssertTrue(machine.printer().bytes() == message); + auto configuration = machine.snapshot().configuration; configuration.ram = 2; + machine.configure(configuration); XCTAssertTrue(machine.printer().bytes() == message); + machine.loadDiagnostic(processor); XCTAssertTrue(machine.printer().bytes() == message); + machine.shutdown(); XCTAssertTrue(machine.printer().bytes() == message); XCTAssertTrue(machine.printer().enabled()); + } +} +- (void)testMachineMemorySettings { [self check:CheckMachineMemorySettings]; } +- (void)testMachinePresentationSettings { [self check:CheckMachinePresentationSettings]; } +- (void)testConfiguredOverclock { [self check:CheckConfiguredOverclock]; } +- (void)testGraphicsPreviewModes { [self check:CheckGraphicsPreviewModes]; } +- (void)testGraphicsPreviewColorSets { [self check:CheckGraphicsPreviewColorSets]; } +- (void)testSessionVideoOutput { [self check:CheckSessionVideoOutput]; } +- (void)testFramePacing { [self check:CheckFramePacing]; } +- (void)testAudioProgress { [self check:CheckAudioProgress]; } +- (void)testAcceleratedTiming { [self check:CheckAcceleratedTiming]; } +- (void)testJoystickComparator { [self check:CheckJoystickComparator]; } +- (void)testJoystickRamps { [self check:CheckJoystickRamps]; } +- (void)testJoystickSession { [self check:CheckJoystickSession]; } +- (void)check:(void (*)())operation { + try { operation(); } + catch (const std::exception& error) { XCTFail(@"%s", error.what()); } +} +- (void)testSessionClipboard { [self check:CheckSessionClipboard]; } +- (void)testDriveWireProtocol { [self check:CheckDriveWireProtocol]; } +- (void)testRamDiskBanks { [self check:CheckRamDisk]; } +- (void)testMicrocontrollerExecution { [self check:CheckMicrocontroller]; } +- (void)testCartridgeBusIsolation { [self check:CheckCartridgeBus]; } +- (void)testExistingCPU { XCTAssertEqual(smoke_cpu(), 0); } +- (void)testExistingSpeech { XCTAssertEqual(smoke_sp0256(), 0); } +- (void)testExistingPSG { XCTAssertEqual(smoke_ay8913(), 0); } +- (void)testExistingCartridgeIntegration { XCTAssertEqual(smoke_ssc_core(), 0); } +- (void)test6809Execution { [self check:Check6809Execution]; } +- (void)test6309Execution { [self check:Check6309Execution]; } +- (void)test6809Interrupts { [self check:Check6809Interrupts]; } +- (void)test6309Interrupts { [self check:Check6309Interrupts]; } +- (void)test6309Native { [self check:Check6309Native]; } +- (void)testCpuDebugHooks { [self check:CheckCpuDebugHooks]; } +- (void)testEventScheduler { [self check:CheckEventScheduler]; } +- (void)testMmuMapping { [self check:CheckMmuMapping]; } +- (void)testMmuRomAndVectors { [self check:CheckMmuRomAndVectors]; } +- (void)testMmuLifecycle { [self check:CheckMmuLifecycle]; } +- (void)testGimeRegisters { [self check:CheckGimeRegisters]; } +- (void)testPiaRegisters { [self check:CheckPiaRegisters]; } +- (void)testPiaInterrupts { [self check:CheckPiaInterrupts]; } +- (void)testMappedCpuExecution { [self check:CheckMappedCpuExecution]; } +- (void)testVideoPixels { [self check:CheckVideoPixels]; } +- (void)testVideoModes { [self check:CheckVideoModes]; } +- (void)testRasterTiming { [self check:CheckRasterTiming]; } +- (void)testGimeTimers { [self check:CheckGimeTimers]; } +- (void)testVideoLifecycle { [self check:CheckVideoLifecycle]; } +- (void)testFrameStops { [self check:CheckFrameStops]; } +- (void)testRasterPixels { [self check:CheckRasterPixels]; } +- (void)testSessionLifecycle { [self check:CheckSessionLifecycle]; } +- (void)testSessionReset { [self check:CheckSessionReset]; } +- (void)testSessionFrameOwnership { [self check:CheckSessionFrameOwnership]; } +- (void)testSessionExclusion { [self check:CheckSessionExclusion]; } +- (void)testSessionRomValidation { [self check:CheckSessionRomValidation]; } +- (void)testSessionAutomaticBoot { [self check:CheckSessionAutomaticBoot]; } +- (void)testSessionKeyboard { [self check:CheckSessionKeyboard]; } +- (void)testAudioBuffer { [self check:CheckAudioBuffer]; } +- (void)testAudioScheduling { [self check:CheckAudioScheduling]; } +- (void)testAudioRouting { [self check:CheckAudioRouting]; } +- (void)testCassetteImages { [self check:CheckCassetteImages]; } +- (void)testCassetteMachine { [self check:CheckCassetteMachine]; } +- (void)testSessionSoftReset { [self check:CheckSessionSoftReset]; } +- (void)testDiskImages { [self check:CheckDiskImages]; } +- (void)testFloppyCommands { [self check:CheckFloppyCommands]; } +- (void)testFloppyTransfers { [self check:CheckFloppyTransfers]; } +- (void)testFloppyProtection { [self check:CheckFloppyProtection]; } +- (void)testBuiltinDeviceBus { [self check:CheckBuiltinDeviceBus]; } +- (void)testFloppySession { [self check:CheckFloppySession]; } +- (void)testBinaryParsing { [self check:CheckBinaryParsing]; } +- (void)testBinaryValidation { [self check:CheckBinaryValidation]; } +- (void)testBinarySession { [self check:CheckBinarySession]; } +- (void)testBinaryMappedWrites { [self check:CheckBinaryMappedWrites]; } +@end diff --git a/platforms/macos/Tests/DebugSourceTests.swift b/platforms/macos/Tests/DebugSourceTests.swift new file mode 100644 index 0000000..72560b6 --- /dev/null +++ b/platforms/macos/Tests/DebugSourceTests.swift @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest +import AppKit + +final class DebugSourceTests: XCTestCase { + private func row(_ address: String = "8000", _ bytes: String = "7C4000", _ source: String = "loop inc $4000", file: String = "hello.asm", number: Int = 1, marker: String = " ") -> String { + address + marker + bytes.padding(toLength: 16, withPad: " ", startingAt: 0) + " (" + String(repeating: " ", count: max(0, 17 - file.count)) + file + String(format: "):%05d ", number) + source + } + private func parse(_ text: String) throws -> DebugSourceListing { try .parse(Data(text.utf8), name: "test.lst") } + + func testLWASMMetadataSourceAndExactAddressAssociation() throws { + let listing = try parse(row("0000", "12", "start nop", number: 1) + "\n" + row("0001", "20FD", " bra start", file: "include.asm", number: 42)) + XCTAssertEqual(listing.lines.count, 2) + XCTAssertEqual(listing.lines[0].address, 0) + XCTAssertEqual(listing.lines[0].bytes, [0x12]) + XCTAssertEqual(listing.lines[1].location, "include.asm:42") + XCTAssertTrue(listing.lines[1].text.contains("bra start")) + XCTAssertEqual(listing.line(at: 0, preferring: nil), 0, "Zero address and first line are valid") + XCTAssertNil(listing.line(at: 2, preferring: nil), "Never guess source by nearest address") + } + func testDuplicateAddressesRemainVisibleAndSearchWraps() throws { + let listing = try parse(row("8000", "7C4000", "first nop") + "\n" + row("8000", "7C4000", "second nop") + "\n" + row("8001", "12", "third nop")) + XCTAssertEqual(listing.byAddress[0x8000], [0, 1]) + XCTAssertEqual(listing.line(at: 0x8000, preferring: 1), 1) + XCTAssertEqual(listing.line(at: 0x8000, preferring: 2), 0) + XCTAssertEqual(listing.find("FIRST", after: 2), 0) + XCTAssertEqual(listing.find("hello.asm", after: 0), 1) + XCTAssertNil(listing.find("missing", after: nil)) + } + func testDirectivesContinuationAndMalformedAddressesDoNotCreateBreakpoints() throws { + let listing = try parse([ + row(), row("8003", "", "org $8003"), row("0020", "12", "data fcb $12", marker: "."), + row("0010", "", "field rmb 1", marker: "s"), row("GGGG", "12"), row("8004", "123"), + row("8005", "????"), " 0102030405060708", "Symbol: DEAD = 1234", "80001234 plain text" + ].joined(separator: "\n")) + XCTAssertEqual(listing.addressedLineCount, 1) + XCTAssertTrue(listing.lines.dropFirst().allSatisfy { $0.address == nil }) + XCTAssertEqual(listing.lines[7].text, " 0102030405060708", "Preserve unassociated continuation text") + } + func testNoFilenameCycleColumnsAndTextEncodings() throws { + let noFile = "8000 1234 00001 [4] nop" + let listing = try parse(noFile) + XCTAssertEqual(listing.lines[0].sourceLine, 1) + XCTAssertNil(listing.lines[0].sourceFile) + XCTAssertEqual(listing.lines[0].bytes, [0x12, 0x34]) + XCTAssertTrue(listing.lines[0].text.contains("[4]")) + let text = "\u{feff}" + row("8000", "7C4000", "* café") + "\r\n" + row("8003", "12") + "\r" + XCTAssertEqual(try parse(text).addressedLineCount, 2) + XCTAssertEqual(try DebugSourceListing.parse(XCTUnwrap(text.data(using: .utf16)), name: "utf16.lst").addressedLineCount, 2) + XCTAssertThrowsError(try DebugSourceListing.parse(Data([0xff, 0, 1]), name: "bad.lst")) + } + func testImportBoundsAndUnsupportedFilesAreRejected() throws { + XCTAssertThrowsError(try parse("8000 is ordinary text, not a listing")) + XCTAssertThrowsError(try parse(row() + "\n" + String(repeating: "x", count: 4097))) + XCTAssertThrowsError(try parse(row() + String(repeating: "\n", count: 50_001))) + XCTAssertThrowsError(try DebugSourceListing.parse(Data(repeating: 32, count: DebugSourceListing.maximumBytes + 1), name: "huge.lst")) + XCTAssertThrowsError(try DebugSourceListing.read(FileManager.default.temporaryDirectory)) + XCTAssertThrowsError(try parse(row(" ", "", " SECTION code") + "\n" + row())) { error in + XCTAssertTrue(error.localizedDescription.contains("linker map")) + } + XCTAssertEqual(try parse(row("8000", "12", "* SECTION is only a comment")).addressedLineCount, 1) + } + + func testFilenamePaddingUsesUTF8Bytes() throws { + let filename = "café.asm" + let padded = String(repeating: " ", count: 17 - filename.utf8.count) + filename + let listing = try parse("8000 12 (" + padded + "):00001 nop") + XCTAssertEqual(listing.lines[0].sourceFile, filename) + XCTAssertEqual(listing.lines[0].address, 0x8000) + } + + func testAuthenticLWASMFixture() throws { + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + let listing = try DebugSourceListing.read(root.appendingPathComponent("platforms/macos/Tests/Fixtures/debugger-source.lst")) + XCTAssertEqual(listing.addressedLineCount, 6) + XCTAssertEqual(listing.byAddress[0x8000], [4]) + XCTAssertEqual(listing.lines[4].bytes, [0x7c, 0x40, 0x00]) + XCTAssertEqual(listing.lines[4].sourceLine, 5) + XCTAssertEqual(listing.byAddress[0], [13]) + XCTAssertNil(listing.lines[10].address) + } + + @MainActor func testSourceImportSearchNavigationFailureAndSharedBreakpointsPreserveMachine() async throws { + _ = NSApplication.shared + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let suite = "VCCSourceTests-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let machine = MachineModel(diskStore: .init(url: folder.appendingPathComponent("disks.json")), displayDefaults: defaults, inputStore: .init(url: folder.appendingPathComponent("input.json"))) + let debugger = DebuggerModel(machine: machine) + let polling = Task { await debugger.poll() } + func until(_ condition: () -> Bool) async throws { + for _ in 0..<500 { if condition() { return }; try await Task.sleep(nanoseconds: 10_000_000) } + throw NSError(domain: "SourceTestTimeout", code: 1) + } + do { + try await until { !machine.busy } + machine.loadDiagnostic() + try await until { debugger.snapshot?.machine.state == .paused && !machine.busy } + let generation = debugger.snapshot?.machine.generation, cycles = debugger.snapshot?.machine.cycles, focus = machine.focusRequest + let url = folder.appendingPathComponent("diagnostic.lst") + try (row() + "\n" + row("8003", "20FB", " bra loop", number: 2)).write(to: url, atomically: true, encoding: .utf8) + await debugger.loadListing(url) + XCTAssertEqual(debugger.codePane, .source) + XCTAssertEqual(debugger.currentSourceLine, 0) + debugger.sourceSearch = "bra loop"; debugger.findSource() + XCTAssertEqual(debugger.selectedSourceLine, 1); XCTAssertFalse(debugger.sourceFollowPC) + debugger.toggleBreakpoint(at: 0x8003) + try await until { debugger.breakpoints == [0x8003] && !debugger.commandPending } + debugger.step() + try await until { debugger.programCounter == 0x8003 && !debugger.commandPending } + XCTAssertEqual(debugger.currentSourceLine, 1) + debugger.showDisassembly(at: 0x8003) + XCTAssertEqual(debugger.codePane, .disassembly) + XCTAssertEqual(machine.focusRequest, focus) + XCTAssertEqual(debugger.snapshot?.machine.generation, generation) + XCTAssertGreaterThan(debugger.snapshot?.machine.cycles ?? 0, cycles ?? 0) + let bad = folder.appendingPathComponent("bad.lst") + try "invalid".write(to: bad, atomically: true, encoding: .utf8) + await debugger.loadListing(bad) + XCTAssertNotNil(debugger.sourceMessage); XCTAssertEqual(debugger.listing?.name, "diagnostic.lst") + debugger.unloadListing() + XCTAssertNil(debugger.listing); XCTAssertEqual(debugger.breakpoints, [0x8003]) + XCTAssertEqual(machine.state, .paused) + } catch { + polling.cancel(); await polling.value + await withCheckedContinuation { done in machine.shutdown { done.resume() } } + throw error + } + polling.cancel(); await polling.value + await withCheckedContinuation { done in machine.shutdown { done.resume() } } + } +} diff --git a/platforms/macos/Tests/DebuggerCoreTests.mm b/platforms/macos/Tests/DebuggerCoreTests.mm new file mode 100644 index 0000000..eb628c1 --- /dev/null +++ b/platforms/macos/Tests/DebuggerCoreTests.mm @@ -0,0 +1,249 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import +#include "../../../src/core/MachineSession.h" +#include "../../../src/core/tcc1014mmu.h" +#include "../../../src/core/tcc1014registers.h" +#include "../../../src/core/mc6821.h" +#include "../../../src/core/Event.h" +#include "../../../src/core/mc6809.h" +#include "../../../src/core/hd6309.h" +#include +#include +using namespace VCC::Mac; +namespace { +template bool rejects(F action) { try { action(); } catch (const std::exception&) { return true; } return false; } +struct ReadProbe : VCC::Devices::CartridgeDevice { + unsigned reads = 0; + void reset() override {} + void horizontalSync(VCC::Devices::DeviceHost&) override {} + std::uint8_t readMemory(std::uint16_t) const override { return 0xff; } + std::uint8_t readPort(std::uint8_t, VCC::Devices::DeviceHost&) override { ++reads; return 0x5a; } + void writePort(std::uint8_t, std::uint8_t, VCC::Devices::DeviceHost&) override {} +}; +} +@interface DebuggerCoreTests : XCTestCase +@end +@implementation DebuggerCoreTests +- (void)testCSourceStepIntoOverOutAndPermanentBreakpointsOnBothCPUs { + for (auto cpu : {Processor::MC6809, Processor::HD6309}) { + MachineSession machine; machine.loadDiagnostic(cpu); + machine.debuggerWriteMemory(0x4000, {0x10,0xce,0x70,0x00, 0xce,0x6f,0xfe, 0xbd,0x40,0x20, 0x7c,0x41,0x00, 0x20,0xf8}); + machine.debuggerWriteMemory(0x4020, {0x34,0x40, 0x33,0xe4, 0xbd,0x40,0x30, 0x35,0xc0}); + machine.debuggerWriteMemory(0x4030, {0x7c,0x41,0x01, 0x39}); + const std::vector source{ + {0x4007,1,{0xbd,0x40,0x20}}, {0x400a,1,{0x7c,0x41,0x00}}, {0x400d,2,{0x20,0xf8}}, + {0x4020,10,{0x34,0x40}}, {0x4022,10,{0x33,0xe4}}, {0x4024,11,{0xbd,0x40,0x30}}, + {0x4027,12,{0x35,0xc0}}, {0x4030,20,{0x7c,0x41,0x01}}, {0x4033,21,{0x39}}}; + auto begin = [&](SourceStepMode mode) { + const auto at = machine.snapshot(); + machine.debuggerStepSource(mode, source, at.generation, at.debuggerProgramRevision, + at.debuggerMappingFingerprint, at.cpu.PC); + XCTAssertTrue(machine.snapshot().debuggerSourceStepping); + for (unsigned i = 0; i < 10 && machine.snapshot().state == RunState::Running; ++i) machine.advance(); + XCTAssertEqual(machine.snapshot().state, RunState::Paused); + XCTAssertFalse(machine.snapshot().debuggerSourceStepping); + XCTAssertEqual(machine.snapshot().generation, at.generation); + }; + auto initialize = [&] { machine.debuggerSetPC(0x4000); machine.debuggerStep(); machine.debuggerStep(); }; + initialize(); machine.debuggerSetBreakpoints({0x4007}); + begin(SourceStepMode::Into); XCTAssertEqual(machine.snapshot().cpu.PC, 0x4020); + begin(SourceStepMode::Out); XCTAssertEqual(machine.snapshot().cpu.PC, 0x400a); + XCTAssertEqual(machine.snapshot().cpu.S, 0x7000); + initialize(); begin(SourceStepMode::Over); XCTAssertEqual(machine.snapshot().cpu.PC, 0x400d); + XCTAssertEqual(machine.debuggerSnapshot().breakpoints, (std::vector{0x4007})); + initialize(); machine.debuggerSetBreakpoints({0x4007,0x4030}); + begin(SourceStepMode::Over); XCTAssertEqual(machine.snapshot().cpu.PC, 0x4030); + XCTAssertEqual(machine.debuggerSnapshot().stopReason, std::string("Breakpoint")); + XCTAssertEqual(machine.debuggerSnapshot().breakpoints, (std::vector{0x4007,0x4030})); + initialize(); machine.debuggerSetBreakpoints({0x4007,0x400a}); + begin(SourceStepMode::Into); XCTAssertEqual(machine.snapshot().cpu.PC,0x4020); + begin(SourceStepMode::Out); XCTAssertEqual(machine.snapshot().cpu.PC,0x400a); + XCTAssertEqual(machine.debuggerSnapshot().stopReason,std::string("Returned from C function")); + const auto value = machine.debuggerSnapshot(0x4100,1).memory[0]; + machine.resume(); machine.advance(); + XCTAssertEqual(machine.snapshot().cpu.PC,0x4007); // no immediate re-break at the caller return + XCTAssertEqual(machine.debuggerSnapshot(0x4100,1).memory[0],std::uint8_t(value+1)); + XCTAssertEqual(machine.debuggerSnapshot().breakpoints,(std::vector{0x4007,0x400a})); + } +} +- (void)testCSourceStepRejectsStaleStateAndCodeAndHonorsCancellationAndBounds { + for (auto cpu : {Processor::MC6809, Processor::HD6309}) { + MachineSession machine; machine.loadDiagnostic(cpu); + machine.debuggerWriteMemory(0x4000, {0x12,0x20,0xfe}); machine.debuggerSetPC(0x4000); + const std::vector source{{0x4000,1,{0x12}}}; + auto at = machine.snapshot(); + auto start = [&](unsigned limit = 100) { machine.debuggerStepSource(SourceStepMode::Over, source, + at.generation, at.debuggerProgramRevision, at.debuggerMappingFingerprint, at.cpu.PC, limit, 3); }; + XCTAssertTrue(rejects([&] { machine.debuggerStepSource(SourceStepMode::Into, source, at.generation + 1, + at.debuggerProgramRevision, at.debuggerMappingFingerprint, at.cpu.PC); })); + XCTAssertTrue(rejects([&] { machine.debuggerStepSource(SourceStepMode::Into, source, at.generation, + at.debuggerProgramRevision + 1, at.debuggerMappingFingerprint, at.cpu.PC); })); + XCTAssertTrue(rejects([&] { machine.debuggerStepSource(SourceStepMode::Into, source, at.generation, + at.debuggerProgramRevision, at.debuggerMappingFingerprint + 1, at.cpu.PC); })); + XCTAssertTrue(rejects([&] { machine.debuggerStepSource(SourceStepMode::Into, source, at.generation, + at.debuggerProgramRevision, at.debuggerMappingFingerprint, at.cpu.PC + 1); })); + start(); machine.pause(); XCTAssertFalse(machine.snapshot().debuggerSourceStepping); + XCTAssertEqual(machine.snapshot().cpu.PC, at.cpu.PC); + XCTAssertEqual(machine.debuggerSnapshot().stopReason, std::string("C step canceled")); + start(16); machine.advance(); XCTAssertEqual(machine.snapshot().state, RunState::Paused); + XCTAssertEqual(machine.snapshot().cpu.PC, 0x4001); + XCTAssertNotEqual(machine.debuggerSnapshot().stopReason.find("limit"), std::string::npos); + machine.debuggerSetPC(0x4000); MemWrite8(0x13,0x4000); at = machine.snapshot(); + XCTAssertTrue(rejects([&] { start(); })); XCTAssertEqual(machine.snapshot().cpu.PC, 0x4000); + machine.debuggerWriteMemory(0x4000, {0x20,0xfe}); at = machine.snapshot(); + machine.debuggerStepSource(SourceStepMode::Into, {{0x4000,1,{0x20,0xfe}}}, at.generation, + at.debuggerProgramRevision, at.debuggerMappingFingerprint, at.cpu.PC); + machine.advance(); XCTAssertEqual(machine.snapshot().cpu.PC, 0x4000); + XCTAssertEqual(machine.debuggerSnapshot().stopReason, std::string("C source location reached")); + } +} +- (void)testCSourceStepPreservesInterruptExecutionWithoutEnteringItsSource { + for (auto cpu : {Processor::MC6809, Processor::HD6309}) { + std::vector rom(32768,0x12); + rom[0x7ff8] = 0x40; rom[0x7ff9] = 0x80; rom[0x7ffe] = 0x80; rom[0x7fff] = 0; + MachineSession machine; machine.load(rom,cpu); + machine.debuggerWriteMemory(0x4000,{0x10,0xce,0x70,0x00, 0x1c,0xef, 0x12,0x12}); + // Mask the saved IRQ flag before RTI, so the synthetic asserted source + // is serviced once; no host shortcut skips the actual IRQ/RTI stack. + machine.debuggerWriteMemory(0x4080,{0xa6,0xe4, 0x8a,0x10, 0xa7,0xe4, 0x7c,0x41,0x00, 0x3b}); + machine.debuggerWriteMemory(0x4100,{0}); + machine.debuggerSetPC(0x4000); machine.debuggerStep(); machine.debuggerStep(); + const auto at = machine.snapshot(); + if (cpu == Processor::MC6809) MC6809AssertInterupt(IS_GIME,INT_IRQ); else HD6309AssertInterupt(IS_GIME,INT_IRQ); + machine.debuggerStepSource(SourceStepMode::Into, {{0x4006,1,{0x12}},{0x4007,2,{0x12}}, + {0x4080,90,{0xa6,0xe4}},{0x4082,91,{0x8a,0x10}},{0x4084,92,{0xa7,0xe4}}, + {0x4086,93,{0x7c,0x41,0x00}},{0x4089,94,{0x3b}}}, at.generation, + at.debuggerProgramRevision, at.debuggerMappingFingerprint, at.cpu.PC); + for (unsigned i=0;i<3 && machine.snapshot().state==RunState::Running;++i) machine.advance(); + XCTAssertEqual(machine.snapshot().state,RunState::Paused); + XCTAssertEqual(machine.snapshot().cpu.PC,0x4007); XCTAssertEqual(machine.snapshot().cpu.S,0x7000); + XCTAssertEqual(machine.debuggerSnapshot(0x4100,1).memory[0],1); + if (cpu == Processor::MC6809) MC6809DeAssertInterupt(IS_GIME,INT_IRQ); else HD6309DeAssertInterupt(IS_GIME,INT_IRQ); + } +} +- (void)testCSourceStepStopsForSelfModificationMappingChangesAndWaitLoops { + for (auto cpu : {Processor::MC6809, Processor::HD6309}) { + MachineSession machine; machine.loadDiagnostic(cpu); + machine.debuggerWriteMemory(0x4000,{0x86,0x39, 0xb7,0x40,0x05, 0x12}); machine.debuggerSetPC(0x4000); + auto at = machine.snapshot(); + machine.debuggerStepSource(SourceStepMode::Into, {{0x4000,1,{0x86,0x39}},{0x4002,1,{0xb7,0x40,0x05}},{0x4005,2,{0x12}}}, + at.generation,at.debuggerProgramRevision,at.debuggerMappingFingerprint,at.cpu.PC); + machine.advance(); XCTAssertEqual(machine.snapshot().cpu.PC,0x4005); + XCTAssertNotEqual(machine.debuggerSnapshot().stopReason.find("bytes changed"),std::string::npos); + machine.debuggerWriteMemory(0x4000,{0xb7,0xff,0xdf, 0x12}); machine.debuggerSetPC(0x4000); at=machine.snapshot(); + machine.debuggerStepSource(SourceStepMode::Into, {{0x4000,1,{0xb7,0xff,0xdf}},{0x4003,2,{0x12}}}, + at.generation,at.debuggerProgramRevision,at.debuggerMappingFingerprint,at.cpu.PC); + machine.advance(); XCTAssertEqual(machine.snapshot().cpu.PC,0x4003); + XCTAssertNotEqual(machine.debuggerSnapshot().stopReason.find("mapping changed"),std::string::npos); + machine.debuggerWriteMemory(0x4000,{0x13}); machine.debuggerSetPC(0x4000); at=machine.snapshot(); + machine.debuggerStepSource(SourceStepMode::Into, {{0x4000,1,{0x13}}}, + at.generation,at.debuggerProgramRevision,at.debuggerMappingFingerprint,at.cpu.PC,100,1); + for (unsigned i=0;i<3 && machine.snapshot().state==RunState::Running;++i) machine.advance(); + XCTAssertEqual(machine.snapshot().state,RunState::Paused); + XCTAssertNotEqual(machine.debuggerSnapshot().stopReason.find("limit"),std::string::npos); + } +} +- (void)testInstructionStepUsesBothProcessorsAndPreservesSession { + for (auto cpu : {Processor::MC6809, Processor::HD6309}) { + MachineSession machine; machine.loadDiagnostic(cpu); + const auto before = machine.debuggerSnapshot(0x4000, 1); + const auto clocks = VCC::gEvents.GetClocks(); + machine.debuggerStep(); + const auto after = machine.debuggerSnapshot(0x4000, 1); + XCTAssertEqual(after.cpu.PC, 0x8003); XCTAssertEqual(after.memory[0], std::uint8_t(before.memory[0] + 1)); + XCTAssertEqual(after.state, RunState::Paused); XCTAssertEqual(after.generation, before.generation); + XCTAssertGreaterThan(after.cycles, before.cycles); XCTAssertGreaterThan(VCC::gEvents.GetClocks(), clocks); + XCTAssertEqual(after.stopReason, std::string("Instruction stepped")); + machine.debuggerStep(); XCTAssertEqual(machine.debuggerSnapshot().cpu.PC, 0x8000); + XCTAssertTrue(machine.takeAudio().empty()); + const auto still = machine.snapshot(); machine.advance(); + XCTAssertEqual(machine.snapshot().cycles, still.cycles); + machine.resume(); XCTAssertTrue(rejects([&] { machine.debuggerStep(); })); + machine.advance(); XCTAssertGreaterThan(machine.snapshot().frames, 0u); + } +} +- (void)testBreakpointsContinueExactlyOnceAndSurviveResets { + for (auto cpu : {Processor::MC6809, Processor::HD6309}) { + MachineSession machine; machine.loadDiagnostic(cpu); + machine.debuggerSetBreakpoints({0x8000,0x8000}); + machine.resume(); machine.advance(); + auto stopped = machine.debuggerSnapshot(0x4000, 1); + XCTAssertEqual(stopped.state, RunState::Paused); XCTAssertEqual(stopped.cpu.PC, 0x8000); + XCTAssertEqual(stopped.cycles, 0u); XCTAssertEqual(stopped.breakpoints.size(), 1u); + XCTAssertEqual(stopped.stopReason, std::string("Breakpoint")); + machine.resume(); machine.advance(); + const auto again = machine.debuggerSnapshot(0x4000, 1); + XCTAssertEqual(again.state, RunState::Paused); XCTAssertEqual(again.cpu.PC, 0x8000); + XCTAssertEqual(again.memory[0], std::uint8_t(stopped.memory[0] + 1)); + XCTAssertGreaterThan(again.cycles, stopped.cycles); + machine.debuggerStep(); XCTAssertEqual(machine.debuggerSnapshot().cpu.PC, 0x8003); + machine.resume(); machine.advance(); XCTAssertEqual(machine.debuggerSnapshot().cpu.PC, 0x8000); + machine.softReset(); XCTAssertEqual(machine.debuggerSnapshot().breakpoints.size(), 1u); + machine.reset(); XCTAssertEqual(machine.debuggerSnapshot().breakpoints.size(), 1u); + machine.resume(); machine.advance(); XCTAssertEqual(machine.snapshot().state, RunState::Paused); + machine.debuggerSetBreakpoints({}); machine.resume(); machine.advance(); + XCTAssertEqual(machine.snapshot().state, RunState::Running); XCTAssertGreaterThan(machine.snapshot().frames, 0u); + } +} +- (void)testSafeMemorySnapshotsNeverReadDevicePortsOrAcknowledgeInterrupts { + MachineSession machine; auto probe = std::make_shared(); + machine.cartridges().configure({probe,nullptr,nullptr,nullptr,nullptr}, false, 4); + machine.loadDiagnostic(); + MemWrite8(5, 0xff01); irq_hs(FALLING); + const auto controlBefore = MemRead8(0xff01); + XCTAssertNotEqual(controlBefore & 128, 0); + const auto full = machine.debuggerSnapshot(0,65536); + XCTAssertEqual(full.memory.size(), 65536u); XCTAssertEqual(full.memoryAvailable.size(), 65536u); + XCTAssertEqual(probe->reads, 0u); XCTAssertEqual(MemRead8(0xff01), controlBefore); + XCTAssertEqual(full.memoryAvailable[0xff00], 0); XCTAssertEqual(full.memoryAvailable[0xff40], 0); + XCTAssertEqual(full.memoryAvailable[0xffe0], 0); XCTAssertEqual(full.memoryAvailable[0xff92], 1); + XCTAssertEqual(full.memoryAvailable[0xfffe], 1); XCTAssertEqual(full.memory[0xfffe], 0x80); + const auto wrapped = machine.debuggerSnapshot(0xfffe, 4); + XCTAssertEqual(wrapped.memory[0], full.memory[0xfffe]); XCTAssertEqual(wrapped.memory[2], full.memory[0]); + XCTAssertTrue(rejects([&] { machine.debuggerSnapshot(0,65537); })); +} +- (void)testMemoryEditsPreflightWholeSpanAndRequirePausedRAM { + MachineSession machine; + XCTAssertTrue(machine.debuggerSnapshot().memory.empty()); + XCTAssertTrue(rejects([&] { machine.debuggerStep(); })); + XCTAssertTrue(rejects([&] { machine.debuggerSetPC(0x4000); })); + machine.loadDiagnostic(); + const auto generation = machine.snapshot().generation; + machine.debuggerWriteMemory(0x4000,{0x86,0x5a,0x12}); + const auto saved = machine.debuggerSnapshot(0x4000,3); + machine.debuggerSetPC(0x4000); machine.debuggerStep(); + XCTAssertEqual(machine.debuggerSnapshot().cpu.A, 0x5a); XCTAssertEqual(machine.debuggerSnapshot().cpu.PC,0x4002); + XCTAssertEqual(machine.snapshot().generation,generation); + const auto lastRAM = machine.debuggerSnapshot(0x7fff,1).memory[0]; + XCTAssertTrue(rejects([&] { machine.debuggerWriteMemory(0x7fff,{0xa5,0x5a}); })); + XCTAssertEqual(machine.debuggerSnapshot(0x7fff,1).memory[0],lastRAM); + XCTAssertTrue(rejects([&] { machine.debuggerWriteMemory(0xffff,{1,2}); })); + XCTAssertTrue(rejects([&] { machine.debuggerWriteMemory(0xff00,{1}); })); + XCTAssertTrue(rejects([&] { machine.debuggerWriteMemory(0x4000,{}); })); + XCTAssertTrue(rejects([&] { machine.debuggerWriteMemory(0x4000,std::vector(257)); })); + machine.debuggerWriteMemory(0x4000,{0x12}); XCTAssertEqual(saved.memory[0],0x86); + machine.resume(); + XCTAssertTrue(rejects([&] { machine.debuggerWriteMemory(0x4000,{0x13}); })); + XCTAssertTrue(rejects([&] { machine.debuggerSetPC(0x4000); })); +} +- (void)testContinueFromBreakpointHonorsPendingInterruptAndHandlerBreakpoint { + for (auto cpu : {Processor::MC6809,Processor::HD6309}) { + MachineSession machine; std::vector rom(0x8000,0x12); + rom[0x7ffe]=0x40; rom[0x7fff]=0; rom[0x7ff8]=0x50; rom[0x7ff9]=0; + machine.load(rom,cpu); + machine.debuggerWriteMemory(0x4000,{0x10,0xce,0x70,0x00,0x1c,0xef,0x12,0x20,0xfd}); + machine.debuggerWriteMemory(0x5000,{0x3b}); + machine.debuggerSetBreakpoints({0x4006,0x5000}); + machine.resume(); machine.advance(); XCTAssertEqual(machine.debuggerSnapshot().cpu.PC,0x4006); + MemWrite8(1,0xff95); MemWrite8(0x62,0xff90); MemWrite8(0x20,0xff92); GimeAssertTimerInterupt(); + machine.resume(); + if (machine.snapshot().state == RunState::Running) machine.advance(); + const auto interrupted = machine.debuggerSnapshot(); + XCTAssertEqual(interrupted.state,RunState::Paused); XCTAssertEqual(interrupted.cpu.PC,0x5000); + XCTAssertEqual(interrupted.cpu.S,0x6ff4); + (void)MemRead8(0xff92); + machine.resume(); machine.advance(); + XCTAssertEqual(machine.debuggerSnapshot().cpu.PC,0x4006); XCTAssertEqual(machine.debuggerSnapshot().cpu.S,0x7000); + } +} +@end diff --git a/platforms/macos/Tests/DebuggerMMUBridgeTests.swift b/platforms/macos/Tests/DebuggerMMUBridgeTests.swift new file mode 100644 index 0000000..f8cad39 --- /dev/null +++ b/platforms/macos/Tests/DebuggerMMUBridgeTests.swift @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class DebuggerMMUBridgeTests: XCTestCase { + @MainActor func testBankedGuardBridgeFreezesModulesAndPreservesManualPoints() async { + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command(controller.loadDiagnostic) + _ = await command { controller.debuggerWriteMemory(address: 0x4000, data: Data([0x12,0x20,0xfe]), completion: $0) } + _ = await command { controller.debuggerSetPC(0x4000, completion: $0) } + _ = await command { controller.debuggerSetBreakpoints([0x4567], completion: $0) } + let initial = await capture(controller, includePhysical: false) + let physical = Int(initial.mmu.effective[2].sourceAddress / 8192) + let pages = [["logicalPage": 2, "physicalPage": physical]] + let mutableBytes = NSMutableData(data: Data([0x12])) + let module: [String: Any] = ["id": "resident", "pages": pages, + "addresses": [0x4000,0x4001], "bytes": [mutableBytes, NSData(data: Data([0x20,0xfe]))], "breakpoints": [0x4000]] + let armed = await command { + controller.debuggerArmBankedDevelopmentBreakpoints([0x4000], modules: [module], completion: $0) + mutableBytes.mutableBytes.storeBytes(of: UInt8(0x39), as: UInt8.self) + } + XCTAssertNil(armed.errorMessage) + XCTAssertTrue(armed.debuggerBankedDevelopment); XCTAssertTrue(armed.debuggerDevelopmentAttached) + XCTAssertEqual(armed.generation, initial.machine.generation) + XCTAssertEqual(armed.debuggerProgramRevision, initial.machine.debuggerProgramRevision) + let invalidPages: [[String: Any]] = [["logicalPage": 2.5, "physicalPage": physical]] + let invalid: [String: Any] = ["id": "invalid", "pages": invalidPages, + "addresses": [0x4000], "bytes": [Data([0x12])]] + let rejected = await command { controller.debuggerArmBankedDevelopmentBreakpoints([0x4000], modules: [invalid], completion: $0) } + XCTAssertNotNil(rejected.errorMessage); XCTAssertTrue(rejected.debuggerBankedDevelopment) + XCTAssertTrue(rejected.debuggerDevelopmentAttached, "Invalid replacements must retain the verified existing attachment") + for points: Any in [[0x4001], [0x4000,0x4000], [true], [16384.5], "4000"] { + var invalidQualification = module + invalidQualification["breakpoints"] = points + let definition = invalidQualification + let invalid = await command { controller.debuggerArmBankedDevelopmentBreakpoints([0x4000], modules: [definition], completion: $0) } + XCTAssertNotNil(invalid.errorMessage) + XCTAssertTrue(invalid.debuggerDevelopmentAttached, "Invalid point qualification preserves the current source connection") + } + let stale = await command { + controller.debuggerStepBankedSource(mode: 0, addresses: [0x4000,0x4001], locations: [1,2], + bytes: [Data([0x12]),Data([0x20,0xfe])], moduleIdentifiers: ["resident","resident"], + generation: armed.generation, programRevision: armed.debuggerProgramRevision, + mappingFingerprint: armed.debuggerMappingFingerprint &+ 1, programCounter: 0x4000, completion: $0) + } + XCTAssertNotNil(stale.errorMessage); XCTAssertEqual(stale.state, .paused) + let cleared = await command(controller.debuggerClearDevelopmentBreakpoints) + XCTAssertFalse(cleared.debuggerBankedDevelopment); XCTAssertFalse(cleared.debuggerDevelopmentAttached) + let capture = await capture(controller, includePhysical: false) + XCTAssertEqual(capture.breakpoints.map(\.uint16Value), [0x4567]) + _ = await command(controller.shutdown) + } + @MainActor private func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { continuation in operation { continuation.resume(returning: $0) } } + } + @MainActor private func capture(_ controller: VCCMachineController, physical: UInt32 = 0, + includePhysical: Bool = true) async -> VCCDebuggerSnapshot { + await withCheckedContinuation { continuation in + controller.debuggerSnapshot(address: 0x8000, followPC: false, memoryAddress: 0x8000, + physicalAddress: physical, physicalMemory: includePhysical) { + continuation.resume(returning: $0) + } + } + } + @MainActor func testPhysicalCaptureMatchesMappedRAMWithoutROMOverlayForAllCapacities() async { + for use6309 in [false, true] { + for (ram, capacity) in [0x20000, 0x80000, 0x200000, 0x800000].enumerated() { + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command { controller.configureMachine(use6309: use6309, ram: ram, overclock: 1, frameInterval: 1, fastForward: false, completion: $0) } + let loaded = await command { controller.loadDiagnostic(use6309: use6309, completion: $0) } + let before = await capture(controller, includePhysical: false) + XCTAssertEqual(before.mmu.ramByteCount, UInt32(capacity)) + XCTAssertEqual(before.mmu.task0.count, 8); XCTAssertEqual(before.mmu.task1.count, 8) + XCTAssertEqual(before.mmu.effective.count, 8); XCTAssertFalse(before.mmu.enabled) + XCTAssertTrue(before.physicalMemory.isEmpty) + XCTAssertEqual(before.memory[0], 0x7c, "CPU $8000 is the diagnostic ROM") + XCTAssertEqual(before.mmu.effective[4].source, 1) + let physicalROM = await capture(controller, physical: before.mmu.effective[4].ramAddress) + XCTAssertEqual(physicalROM.physicalMemory[0], 0, "Physical RAM beneath the ROM is not the ROM image") + _ = await command { controller.debuggerWriteMemory(address: 0x4000, data: Data([0x5a]), completion: $0) } + let physicalRAM = await capture(controller, physical: before.mmu.effective[2].ramAddress) + XCTAssertEqual(physicalRAM.physicalMemory[0], 0x5a) + XCTAssertEqual(physicalRAM.machine.cycles, loaded.cycles) + XCTAssertEqual(physicalRAM.machine.generation, loaded.generation) + XCTAssertEqual(physicalRAM.machine.state, .paused) + XCTAssertEqual(physicalROM.physicalMemory[0], 0, "Owned captures don't change after later writes") + _ = await command(controller.shutdown) + } + } + } + @MainActor func testPhysicalEndAndRAMResizeRecoverCursorWithoutChangingSession() async { + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command { controller.configureMachine(use6309: false, ram: 3, overclock: 1, frameInterval: 1, fastForward: false, completion: $0) } + _ = await command(controller.loadDiagnostic) + let last = await capture(controller, physical: 0x7fffff) + XCTAssertEqual(last.physicalAddress, 0x7fffff); XCTAssertEqual(last.physicalMemory.count, 1) + let changed = await command { controller.configureMachine(use6309: false, ram: 0, overclock: 1, frameInterval: 1, fastForward: false, completion: $0) } + let recovered = await capture(controller, physical: 0x7fffff) + XCTAssertNil(recovered.machine.errorMessage) + XCTAssertEqual(recovered.physicalAddress, 0x1ff00); XCTAssertEqual(recovered.physicalMemory.count, 256) + XCTAssertEqual(recovered.machine.generation, changed.generation) + XCTAssertEqual(recovered.mmu.ramByteCount, 0x20000) + _ = await command(controller.resume) + let running = await capture(controller) + XCTAssertEqual(running.machine.state, .running); XCTAssertEqual(running.machine.generation, changed.generation) + _ = await command(controller.shutdown) + let closed = await capture(controller) + XCTAssertEqual(closed.machine.state, .closed); XCTAssertEqual(closed.mmu.ramByteCount, 0) + XCTAssertTrue(closed.physicalMemory.isEmpty); XCTAssertTrue(closed.mmu.effective.isEmpty) + } +} diff --git a/platforms/macos/Tests/DebuggerMemoryModelTests.swift b/platforms/macos/Tests/DebuggerMemoryModelTests.swift new file mode 100644 index 0000000..2265918 --- /dev/null +++ b/platforms/macos/Tests/DebuggerMemoryModelTests.swift @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class DebuggerMemoryModelTests: XCTestCase { + @MainActor private func until(_ condition: () -> Bool) async throws { + for _ in 0..<500 { + if condition() { return } + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTFail("Memory inspector operation timed out") + throw NSError(domain: "DebuggerMemoryTimeout", code: 1) + } + + @MainActor func testPhysicalAddressParserKeepsFullWidthAndBounds() { + XCTAssertEqual(DebuggerModel.hexadecimalAddress("$7FFFFF", maximum: 0x7fffff), 0x7fffff) + XCTAssertEqual(DebuggerModel.hexadecimalAddress("0x070000", maximum: 0x7ffff), 0x70000) + XCTAssertNil(DebuggerModel.hexadecimalAddress("080000", maximum: 0x7ffff)) + XCTAssertNil(DebuggerModel.hexadecimalAddress("100000000", maximum: UInt32.max)) + XCTAssertNil(DebuggerModel.hexadecimalAddress("-1", maximum: 0x7fffff)) + XCTAssertNil(DebuggerModel.hexadecimal("10000", maximum: 0x7fffff), "CPU addresses must remain 16-bit even when a caller supplies a wider limit") + XCTAssertEqual(DebuggerModel.hex(UInt32(0x7fffff), width: 6), "7FFFFF") + } + + @MainActor func testPhysicalBrowsingMappedEditsAndRAMResizePreserveStateAndDrafts() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let suite = "VCCDebuggerMemoryTests-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let machine = MachineModel(diskStore: .init(url: folder.appendingPathComponent("disks.json")), + displayDefaults: defaults, inputStore: .init(url: folder.appendingPathComponent("input.json"))) + let debugger = DebuggerModel(machine: machine) + let polling = Task { await debugger.poll() } + do { + try await until { !machine.busy } + machine.loadDiagnostic() + try await until { !machine.busy && debugger.snapshot?.machine.state == .paused } + let generation = try XCTUnwrap(debugger.snapshot).machine.generation + let focus = machine.focusRequest + debugger.showMemory(at: 0x4000) + debugger.editAddressText = "4000"; debugger.editByteText = "5A"; debugger.writeByte() + try await until { !debugger.commandPending && debugger.memory.first == 0x5a } + let backing = try XCTUnwrap(debugger.snapshot?.mmu.effective[2]).ramAddress + debugger.memoryPane = .mmu + debugger.showPhysicalMemory(at: backing) + try await until { debugger.snapshot?.physicalAddress == backing && debugger.memory.first == 0x5a } + XCTAssertEqual(debugger.memoryPane, .memory) + XCTAssertTrue(debugger.physical); XCTAssertFalse(debugger.canEditMemory) + XCTAssertEqual(debugger.memoryAddressWidth, 6) + XCTAssertEqual(debugger.memoryLocation(offset: 0), backing) + debugger.editByteText = "A5"; debugger.writeByte() + try await Task.sleep(nanoseconds: 250_000_000) + XCTAssertEqual(debugger.memory.first, 0x5a, "Physical inspection must not expose the mapped-memory write action") + debugger.physicalAddressText = "7F" + try await Task.sleep(nanoseconds: 250_000_000) + XCTAssertEqual(debugger.physicalAddressText, "7F", "Polling preserves the unfinished physical-address draft") + debugger.setMemorySpace(.mapped) + XCTAssertEqual(debugger.memoryAddressText, "4000") + XCTAssertEqual(debugger.memory.first, 0x5a) + XCTAssertEqual(debugger.snapshot?.machine.generation, generation) + XCTAssertEqual(machine.focusRequest, focus) + + var settings = machine.settings; settings.ram = 3 + machine.applyMachineSettings(settings) + try await until { !machine.busy && debugger.installedRAM == 0x800000 } + debugger.setMemorySpace(.physical) + debugger.physicalAddressText = "7FFFFF"; debugger.goToMemory() + try await until { debugger.displayedMemoryAddress == 0x7ffff0 && debugger.memory.count == 16 } + XCTAssertEqual(debugger.memoryLocation(offset: 15), 0x7fffff) + XCTAssertFalse(debugger.canNextMemory) + debugger.pageMemory(forward: true) + XCTAssertEqual(debugger.physicalAddressText, "7FFFF0") + debugger.physicalAddressText = "800000"; debugger.goToMemory() + XCTAssertNotNil(debugger.validationMessage) + XCTAssertEqual(debugger.displayedMemoryAddress, 0x7ffff0) + + debugger.physicalAddressText = "abc" + settings.ram = 0; machine.applyMachineSettings(settings) + try await until { !machine.busy && debugger.installedRAM == 0x20000 && debugger.displayedMemoryAddress < 0x20000 } + XCTAssertEqual(debugger.physicalAddressText, "abc", "Shrinking RAM must not replace unfinished input") + XCTAssertLessThanOrEqual(debugger.memory.count, 256) + XCTAssertNil(machine.error) + debugger.pageMemory(forward: false) + try await until { debugger.memory.count == 256 } + XCTAssertTrue(debugger.physical) + XCTAssertEqual(machine.state, .paused) + } catch { + polling.cancel(); await polling.value + await withCheckedContinuation { done in machine.shutdown { done.resume() } } + throw error + } + polling.cancel(); await polling.value + await withCheckedContinuation { done in machine.shutdown { done.resume() } } + } +} diff --git a/platforms/macos/Tests/DebuggerMemoryTests.mm b/platforms/macos/Tests/DebuggerMemoryTests.mm new file mode 100644 index 0000000..9208404 --- /dev/null +++ b/platforms/macos/Tests/DebuggerMemoryTests.mm @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import +#include "../../../src/core/MachineSession.h" +#include "../../../src/core/tcc1014mmu.h" +#include "../../../src/core/Event.h" +#include +#include +using namespace VCC::Mac; +namespace { +template bool rejectsMemory(F action) { try { action(); } catch (const std::exception&) { return true; } return false; } +constexpr unsigned sizes[] = {0x20000, 0x80000, 0x200000, 0x800000}; +} +@interface DebuggerMemoryTests : XCTestCase +@end +@implementation DebuggerMemoryTests +- (void)testPhysicalSnapshotsReachAllInstalledRAMSizesOnBothCPUs { + for (auto cpu : {Processor::MC6809, Processor::HD6309}) for (unsigned ram = 0; ram < 4; ++ram) { + MachineSession machine; MachineConfiguration config; config.processor = cpu; config.ram = ram; + machine.configure(config); machine.loadDiagnostic(cpu); + const auto last = sizes[ram] - 1; + SetMem(0, 0x11); SetMem(0xffff, 0x22); SetMem(0x10000, 0x33); SetMem(last, 0x5a); + const auto before = machine.snapshot(); const auto clocks = VCC::gEvents.GetClocks(); + auto first = machine.debuggerSnapshot(0, 0, 0, 1); + auto crossing = machine.debuggerSnapshot(0, 0, 0xffff, 2); + auto end = machine.debuggerSnapshot(0, 0, last, 256); + XCTAssertEqual(first.physicalMemory, (std::vector{0x11})); + XCTAssertEqual(crossing.physicalMemory, (std::vector{0x22,0x33})); + XCTAssertEqual(end.physicalMemory, (std::vector{0x5a})); + XCTAssertEqual(end.physicalAddress, last); XCTAssertEqual(end.mmu.RAMBytes, sizes[ram]); + XCTAssertEqual(end.cpu.PC, before.cpu.PC); XCTAssertEqual(end.state, before.state); + XCTAssertEqual(end.cycles, before.cycles); XCTAssertEqual(end.generation, before.generation); + XCTAssertEqual(VCC::gEvents.GetClocks(), clocks); XCTAssertEqual(GetMem(last), 0x5a); + SetMem(last, 0xa5); XCTAssertEqual(end.physicalMemory[0], 0x5a, "Snapshot owns immutable bytes"); + XCTAssertTrue(rejectsMemory([&] { machine.debuggerSnapshot(0,0,sizes[ram],1); })); + XCTAssertTrue(rejectsMemory([&] { machine.debuggerSnapshot(0,0,std::numeric_limits::max(),256); })); + XCTAssertTrue(rejectsMemory([&] { machine.debuggerSnapshot(0,0,0,257); })); + machine.shutdown(); + XCTAssertEqual(machine.debuggerSnapshot().mmu.RAMBytes, 0u); + XCTAssertEqual(GetMMUState().RAMBytes, 0u); + } +} +- (void)testBothTaskBanksAndDisabledFixedMappingAreReportedExactly { + for (auto cpu : {Processor::MC6809, Processor::HD6309}) for (unsigned ram = 0; ram < 4; ++ram) { + MachineSession machine; MachineConfiguration config; config.processor = cpu; config.ram = ram; + machine.configure(config); machine.loadDiagnostic(cpu); + MemWrite8(0, 0xffdf); // all RAM + MemWrite8(5, 0xffa0); MemWrite8(9, 0xffa8); + SetMem(5 * 8192, 0x55); SetMem(9 * 8192, 0x99); + MemWrite8(0x40, 0xff90); + auto task0 = machine.debuggerSnapshot(0,1,5*8192,1); + XCTAssertTrue(task0.mmu.Enabled); XCTAssertTrue(task0.mmu.AllRAM); + XCTAssertEqual(task0.mmu.ActiveTask,0); XCTAssertEqual(task0.mmu.Task0[0],5); XCTAssertEqual(task0.mmu.Task1[0],9); + XCTAssertEqual(task0.mmu.Effective[0].Page,5); XCTAssertEqual(task0.mmu.Effective[0].RAMStart,5u*8192); + XCTAssertEqual(task0.memory[0],0x55); XCTAssertEqual(task0.memory,task0.physicalMemory); + MemWrite8(1, 0xff91); + auto task1 = machine.debuggerSnapshot(0,1,9*8192,1); + XCTAssertEqual(task1.mmu.ActiveTask,1); XCTAssertEqual(task1.mmu.Effective[0].Page,9); + XCTAssertEqual(task1.memory[0],0x99); XCTAssertEqual(task1.memory,task1.physicalMemory); + MemWrite8(0,0xff90); + auto fixed = machine.debuggerSnapshot(0,1); + XCTAssertFalse(fixed.mmu.Enabled); XCTAssertEqual(fixed.mmu.ActiveTask,1); + XCTAssertEqual(fixed.mmu.Task0[0],5); XCTAssertEqual(fixed.mmu.Task1[0],9); + const auto base = ram == 0 ? 8 : 56; + for (unsigned bank = 0; bank < 8; ++bank) { + XCTAssertEqual(fixed.mmu.Effective[bank].Page,base+bank); + XCTAssertEqual(fixed.mmu.Effective[bank].Source,VCC::MMUSource::RAM); + XCTAssertEqual(fixed.mmu.Effective[bank].SourceStart,(base+bank)*8192u); + } + } +} +- (void)testROMOverlaysAndVectorExceptionsDoNotMasqueradeAsPhysicalRAM { + for (unsigned ram = 0; ram < 4; ++ram) { + MachineSession machine; MachineConfiguration config; config.ram = ram; + machine.configure(config); machine.loadDiagnostic(); + const unsigned base = ram == 0 ? 8 : 56; + const unsigned vectorPage = ram == 0 ? 15 : 63; + for (unsigned map = 0; map < 4; ++map) { + MemWrite8(map,0xff90); + const auto snapshot = machine.debuggerSnapshot(); + XCTAssertEqual(snapshot.mmu.RomMap,map); XCTAssertFalse(snapshot.mmu.AllRAM); + for (unsigned bank = 0; bank < 4; ++bank) { + const auto& entry = snapshot.mmu.Effective[bank+4]; + XCTAssertEqual(entry.Page,base+4+bank); XCTAssertEqual(entry.RAMStart,(base+4+bank)*8192u); + const bool internal = map == 2 || (map < 2 && bank < 2); + XCTAssertEqual(entry.Source,internal ? VCC::MMUSource::InternalROM : VCC::MMUSource::CartridgeROM); + XCTAssertEqual(entry.SourceStart,(internal ? bank : bank^2)*8192u); + } + } + MemWrite8(0,0xffdf); + auto ramMapping = machine.debuggerSnapshot(); + for (const auto& entry : ramMapping.mmu.Effective) XCTAssertEqual(entry.Source,VCC::MMUSource::RAM); + MemWrite8(0x40,0xff90); MemWrite8(1,0xffa7); + SetMem(0x2000+0x1e00,0x17); SetMem(vectorPage*8192+0x1e00,0x63); + auto ordinary = machine.debuggerSnapshot(0xfe00,1); + XCTAssertEqual(ordinary.memory[0],0x17); XCTAssertFalse(ordinary.mmu.RamVectors); + MemWrite8(0x48,0xff90); + auto vectors = machine.debuggerSnapshot(0xfe00,1,vectorPage*8192+0x1e00,1); + XCTAssertTrue(vectors.mmu.RamVectors); XCTAssertEqual(vectors.memory[0],0x63); + XCTAssertEqual(vectors.mmu.RAMVectorAddress,vectorPage*8192+0x1e00); + XCTAssertEqual(vectors.mmu.Effective[7].SourceStart,0x2000u, "FE00 override must not relabel the whole E000 bank"); + XCTAssertEqual(vectors.physicalMemory,vectors.memory); + auto resetVector = machine.debuggerSnapshot(0xfffe,2); + XCTAssertEqual(resetVector.memory,(std::vector{0x80,0x00}), "SAM vectors remain internal ROM even in all-RAM mode"); + } +} +- (void)testExtendedPagesLatchedPrefixAndPhysicalAliasing { + MachineSession machine; MachineConfiguration config; config.ram = 3; + machine.configure(config); machine.loadDiagnostic(); + MemWrite8(0x40,0xff90); MemWrite8(0x30,0xff9b); MemWrite8(0xab,0xffa0); + SetMem(0x3ab*8192+0x123,0x7c); + auto high = machine.debuggerSnapshot(0x123,1,0x3ab*8192+0x123,1); + XCTAssertEqual(high.mmu.Prefix,0x300); XCTAssertEqual(high.mmu.Task0[0],0x3ab); + XCTAssertEqual(high.mmu.Effective[0].Page,0x3ab); XCTAssertEqual(high.mmu.Effective[0].SourceStart,0x3ab*8192u); + XCTAssertEqual(high.memory,high.physicalMemory); XCTAssertEqual(high.memory[0],0x7c); + MemWrite8(0,0xff9b); + auto prefixChanged = machine.debuggerSnapshot(); + XCTAssertEqual(prefixChanged.mmu.Prefix,0); XCTAssertEqual(prefixChanged.mmu.Task0[0],0x3ab, "Prefix changes apply to subsequent writes, not latched pages"); + config.ram = 0; machine.configure(config); + // A raw page index can alias installed RAM without receiving the ROM + // overlay assigned to the lower reserved page index. + SetMmuPrefix(3); SetMmuRegister(0,15); Set_MmuEnabled(1); + SetMem(15*8192,0xa4); + auto alias = machine.debuggerSnapshot(0,1,15*8192,1); + XCTAssertEqual(alias.mmu.Effective[0].Page,0x30f); + XCTAssertEqual(alias.mmu.Effective[0].RAMStart,15u*8192); + XCTAssertEqual(alias.mmu.Effective[0].Source,VCC::MMUSource::RAM); + XCTAssertEqual(alias.memory,alias.physicalMemory); XCTAssertEqual(alias.memory[0],0xa4); +} +@end diff --git a/platforms/macos/Tests/DebuggerMemoryToolsTests.mm b/platforms/macos/Tests/DebuggerMemoryToolsTests.mm new file mode 100644 index 0000000..f6b2dfa --- /dev/null +++ b/platforms/macos/Tests/DebuggerMemoryToolsTests.mm @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import +#include "../../../src/core/MachineSession.h" +#include "../../../src/core/DebugDisassembler.h" +#include +using namespace VCC::Mac; +@interface DebuggerMemoryToolsTests : XCTestCase +@end +@implementation DebuggerMemoryToolsTests +- (void)testRangeCaptureIsExactBoundedAndSideEffectFree { + for (auto cpu : {Processor::MC6809, Processor::HD6309}) { + MachineSession machine; + MachineConfiguration config; config.processor = cpu; config.ram = 3; + machine.configure(config); machine.loadDiagnostic(cpu); + machine.debuggerWriteMemory(0x4000, {0x86,0x2a,0x39}); + const auto before = machine.snapshot(); + const auto mapped = machine.debuggerMemoryRange(0x4000, 3, false); + XCTAssertEqual(mapped.bytes, (std::vector{0x86,0x2a,0x39})); + const auto mmu = machine.debuggerSnapshot().mmu; + const auto physical = machine.debuggerMemoryRange(mmu.Effective[2].RAMStart, 3, true); + XCTAssertEqual(mapped.bytes, physical.bytes); + XCTAssertEqual(machine.debuggerMemoryRange(0x7fffff, 1, true).bytes.size(), 1u); + const auto all = machine.debuggerMemoryRange(0, 0x800000, true); + XCTAssertEqual(all.bytes.size(), 0x800000u); + XCTAssertEqual(all.available.back(), 1); + for (const auto params : {std::pair{0,0}, {0x7fffff,2}, {0x800000,1}, {0xfffffff0,0x100}}) { + bool rejected = false; + try { machine.debuggerMemoryRange(params.first, params.second, true); } + catch (const std::invalid_argument&) { rejected = true; } + XCTAssertTrue(rejected); + } + bool mappedWrap = false; + try { machine.debuggerMemoryRange(0xffff, 2, false); } + catch (const std::invalid_argument&) { mappedWrap = true; } + XCTAssertTrue(mappedWrap); + const auto io = machine.debuggerMemoryRange(0xff00, 256, false); + XCTAssertEqual(io.available[0], 0); XCTAssertEqual(io.available[0x90], 1); XCTAssertEqual(io.available[0xf0], 1); + XCTAssertEqual(machine.snapshot().cycles, before.cycles); + XCTAssertEqual(machine.snapshot().generation, before.generation); + XCTAssertEqual(machine.snapshot().cpu.PC, before.cpu.PC); + machine.debuggerWriteMemory(0x4000, {0x12}); + XCTAssertEqual(mapped.bytes.front(), 0x86); + } +} +- (void)testPhysicalDisassemblyUsesExplicitLogicalOriginAndTruncatesAtEnd { + for (bool enhanced : {false,true}) { + const auto rows = DisassembleRange({0x20,0xfe,0x8e,0x12}, {}, enhanced, 0xffff, 128); + XCTAssertEqual(rows.size(), 2u); XCTAssertEqual(rows[0].address, 0xffff); + XCTAssertEqual(rows[0].operand, "$FFFF"); XCTAssertEqual(rows[1].address, 1); + XCTAssertEqual(rows[1].bytes, (std::vector{0x8e,0x12})); + XCTAssertEqual(rows[1].mnemonic, "FCB"); XCTAssertFalse(rows[1].valid); + const auto hidden = DisassembleRange({0x86,0xff,0x12}, {1,0,1}, enhanced, 0, 128); + XCTAssertEqual(hidden.size(), 3u); XCTAssertFalse(hidden[0].available); XCTAssertFalse(hidden[1].available); + XCTAssertEqual(hidden[2].mnemonic, "NOP"); + XCTAssertTrue(DisassembleRange({}, {}, enhanced, 0, 10).empty()); + } +} +- (void)testOS9ServicesRemainOptInAndUnknownServicesStayNumeric { + const std::vector bytes{0x10,0x3f,0x89,0x10,0x3f,0x17,0x10,0x3f,0xfe}; + for (bool enhanced : {false,true}) { + const auto plain = DisassembleRange(bytes, {}, enhanced, 0x8000, 1); + XCTAssertEqual(plain[0].mnemonic, "SWI2"); XCTAssertEqual(plain[0].bytes.size(), 2u); + const auto os9 = DisassembleRange(bytes, {}, enhanced, 0x8000, 3, true); + XCTAssertEqual(os9[0].mnemonic, "OS9"); XCTAssertEqual(os9[0].operand, "I$Read ($89)"); + XCTAssertEqual(os9[1].operand, "F$CRC ($17)"); XCTAssertEqual(os9[2].operand, "#$FE"); + XCTAssertEqual(os9[2].address, 0x8006); XCTAssertEqual(os9[2].bytes.size(), 3u); + const auto shortCall = DisassembleRange({0x10,0x3f}, {}, enhanced, 0, 1, true); + XCTAssertEqual(shortCall[0].mnemonic, "FCB"); XCTAssertEqual(shortCall[0].bytes.size(), 2u); + } +} +- (void)testOS9ModuleHeadersRequireParityAndPreserveEntryBoundary { + std::vector bytes{0x87,0xcd,0x00,0x20,0x00,0x0d,0x11,0x81,0,0,0x10,0,0x20,0x12}; + bytes[8] = 0xff; + for (unsigned i = 0; i < 8; ++i) bytes[8] ^= bytes[i]; + const auto rows = DisassembleRange(bytes, {}, false, 0x1000, 2, true); + XCTAssertEqual(rows[0].mnemonic, "MODULE"); XCTAssertEqual(rows[0].bytes.size(), 13u); + XCTAssertNotEqual(rows[0].operand.find("entry +$0010"), std::string::npos); + XCTAssertEqual(rows[1].address, 0x100d); XCTAssertEqual(rows[1].mnemonic, "NOP"); + bytes[8] ^= 1; + XCTAssertNotEqual(DisassembleRange(bytes, {}, false, 0, 1, true)[0].mnemonic, "MODULE"); +} +@end diff --git a/platforms/macos/Tests/DebuggerModelTests.swift b/platforms/macos/Tests/DebuggerModelTests.swift new file mode 100644 index 0000000..6bd719f --- /dev/null +++ b/platforms/macos/Tests/DebuggerModelTests.swift @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class DebuggerModelTests: XCTestCase { + @MainActor private func until(_ condition: () -> Bool) async throws { + for _ in 0..<500 { + if condition() { return } + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTFail("Debugger model operation timed out") + throw NSError(domain: "DebuggerModelTimeout", code: 1) + } + + @MainActor func testGraphicsAddressAndSingleStepOverlay() { + let model = GraphicsPreviewModel() + model.inspectAddress(0x1a00, physical: false) + model.addressText = "10000" + model.applyAddress() + XCTAssertNotNil(model.addressError) + XCTAssertEqual(model.request.address, 0x1a00) + model.inspectAddress(0x60000, physical: true) + XCTAssertNil(model.addressError) + XCTAssertEqual(model.addressText, "060000") + let before = Data([0, 0, 0, 255, 0, 255, 0, 255]) + let after = Data([0, 0, 255, 255, 0, 255, 0, 255]) + let (mask, count) = GraphicsPreviewModel.differences(before, after) + XCTAssertEqual(count, 1) + XCTAssertGreaterThan(mask[3], 0) + XCTAssertEqual(mask[7], 0) + XCTAssertEqual(GraphicsPreviewModel.differences(after, after).1, 0) + } + + @MainActor func testHexadecimalInputRejectsOverflowAndNonHexCharacters() { + for (input, value) in [("0", 0), ("ffff", 65535), (" $a0 ", 160), ("0X7f", 127), ("0020", 32)] { + XCTAssertEqual(DebuggerModel.hexadecimal(input), UInt16(value), input) + } + for input in ["", "$", "0x", "-1", "+1", "1_00", "10 00", "10000", "FFFFF", "12G0", "12", "é"] { + XCTAssertNil(DebuggerModel.hexadecimal(input), input) + } + XCTAssertEqual(DebuggerModel.hexadecimal("FF", maximum: 255), 255) + XCTAssertNil(DebuggerModel.hexadecimal("100", maximum: 255)) + XCTAssertEqual(DebuggerModel.hex(0xa5, width: 2), "A5") + XCTAssertEqual(DebuggerModel.hex(0xa5), "00A5") + } + + @MainActor func testInspectorCommandsPreserveFocusDraftsAndSession() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let suite = "VCCDebuggerModelTests-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let machine = MachineModel(diskStore: .init(url: folder.appendingPathComponent("disks.json")), + displayDefaults: defaults, inputStore: .init(url: folder.appendingPathComponent("input.json"))) + let debugger = DebuggerModel(machine: machine) + let polling = Task { await debugger.poll() } + do { + try await until { !machine.busy && !debugger.commandPending } + machine.loadDiagnostic() + try await until { !machine.busy && !debugger.commandPending && debugger.snapshot?.machine.state == .paused } + let generation = try XCTUnwrap(debugger.snapshot).machine.generation + let focus = machine.focusRequest + debugger.addressText = "123"; debugger.memoryAddressText = "456" + debugger.pcText = "8000"; debugger.breakpointText = "8000" + debugger.setPC() + try await until { !machine.busy && !debugger.commandPending && debugger.programCounter == 0x8000 } + debugger.addBreakpoint() + try await until { !machine.busy && !debugger.commandPending && debugger.breakpoints == [0x8000] } + let graphics = GraphicsPreviewModel() + graphics.inspectAddress(0x4000, physical: false) + let previewTask = Task { await graphics.poll(machine: machine) } + defer { previewTask.cancel() } + try await until { graphics.readyToStep(machine: machine) && graphics.frame != nil } + let beforeStep = try XCTUnwrap(graphics.frame?.capture) + debugger.step() + try await until { !machine.busy && !debugger.commandPending && debugger.programCounter == 0x8003 } + try await until { graphics.readyToStep(machine: machine) && graphics.frame?.changes != nil } + let afterStep = try XCTUnwrap(graphics.frame) + let expected = GraphicsPreviewModel.differences(beforeStep.rgba, afterStep.capture.rgba).1 + XCTAssertEqual(afterStep.changes, expected) + let initialByte = try XCTUnwrap(beforeStep.pixel(x: 0, y: 0)).value + XCTAssertEqual(afterStep.capture.pixel(x: 0, y: 0)?.value, initialByte &+ 1) + previewTask.cancel() + await previewTask.value + XCTAssertTrue(debugger.changedRegisters.contains("PC")) + XCTAssertEqual(machine.state, .paused) + debugger.toggleExecution() + try await until { !machine.busy && !debugger.commandPending && machine.state == .paused && debugger.programCounter == 0x8000 } + XCTAssertEqual(debugger.snapshot?.machine.generation, generation) + debugger.removeAllBreakpoints() + try await until { !machine.busy && !debugger.commandPending && debugger.breakpoints.isEmpty } + debugger.toggleExecution() + try await until { !machine.busy && !debugger.commandPending && machine.state == .running && machine.frames > 0 } + debugger.toggleExecution() + try await until { !machine.busy && !debugger.commandPending && machine.state == .paused } + XCTAssertEqual(machine.focusRequest, focus, "Debugger commands must not steal focus from its text fields") + XCTAssertEqual(debugger.addressText, "123", "Polling preserves unfinished address entry") + XCTAssertEqual(debugger.memoryAddressText, "456") + debugger.editAddressText = "4000"; debugger.editByteText = "2A" + debugger.showMemory(at: 0x4000) + debugger.writeByte() + try await until { !machine.busy && !debugger.commandPending && debugger.memory.first == 0x2a } + XCTAssertEqual(machine.focusRequest, focus) + XCTAssertEqual(debugger.snapshot?.machine.generation, generation) + XCTAssertEqual(debugger.editByteText, "2A") + // Invalid input changes neither the machine nor an existing breakpoint set. + debugger.breakpointText = "10000"; debugger.addBreakpoint() + XCTAssertNotNil(debugger.validationMessage); XCTAssertTrue(debugger.breakpoints.isEmpty) + XCTAssertEqual(machine.state, .paused) + } catch { + polling.cancel(); await polling.value + await withCheckedContinuation { done in machine.shutdown { done.resume() } } + throw error + } + polling.cancel(); await polling.value + let pausedSnapshot = debugger.snapshot + try await Task.sleep(nanoseconds: 300_000_000) + XCTAssertTrue(debugger.snapshot === pausedSnapshot, "Closing an inspector stops its polling") + XCTAssertEqual(machine.state, .paused, "Closing an inspector does not resume the machine") + await withCheckedContinuation { done in machine.shutdown { done.resume() } } + } +} diff --git a/platforms/macos/Tests/DebuggerTFMTests.mm b/platforms/macos/Tests/DebuggerTFMTests.mm new file mode 100644 index 0000000..aa1fd47 --- /dev/null +++ b/platforms/macos/Tests/DebuggerTFMTests.mm @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import +#include "../../../src/core/MachineSession.h" +#include "../../../src/core/hd6309.h" +#include +using namespace VCC::Mac; +namespace { +void prepare(MachineSession& machine, std::uint16_t count, bool native = false, std::uint8_t post = 0x12) { + std::vector rom(0x8000,0x12); + rom[0x7ffe]=0x40; rom[0x7fff]=0; + rom[0x7ff0]=0x50; rom[0x7ff1]=0; + machine.load(rom,Processor::HD6309); + machine.debuggerWriteMemory(0x4000,{ + 0x10,0xce,0x70,0x00, // LDS #$7000 + 0x8e,0x60,0x00, // LDX #$6000 + 0x10,0x8e,0x61,0x00, // LDY #$6100 + 0x10,0x86,std::uint8_t(count >> 8),std::uint8_t(count), // LDW #count + 0x11,0x38,post,0x12}); // TFM X+,Y+; NOP + machine.debuggerWriteMemory(0x6000,{0xa5,0x5a,0x42}); + machine.debuggerWriteMemory(0x5000,{0x7c,0x62,0x00,0x20,0xfb}); // Handler must not run during trapping step. + if (native) { + machine.debuggerWriteMemory(0x5100,{0x11,0x3d,1}); + machine.debuggerSetPC(0x5100); machine.debuggerStep(); machine.debuggerSetPC(0x4000); + } + for (unsigned i=0;i<4;++i) machine.debuggerStep(); +} +} +@interface DebuggerTFMTests : XCTestCase +@end +@implementation DebuggerTFMTests +- (void)testCSourceStepDoesNotMistakeTFMTransfersForOneLineLoopIterations { + for (bool native : {false,true}) { + MachineSession machine; prepare(machine,3,native); + const auto at = machine.snapshot(); + machine.debuggerStepSource(SourceStepMode::Into, {{0x400f,1,{0x11,0x38,0x12}},{0x4012,2,{0x12}}}, + at.generation,at.debuggerProgramRevision,at.debuggerMappingFingerprint,at.cpu.PC); + machine.advance(); + const auto after = machine.debuggerSnapshot(0x6100,3); + XCTAssertEqual(after.state,RunState::Paused); XCTAssertEqual(after.cpu.PC,0x4012); + XCTAssertEqual(after.cpu.X,0x6003); XCTAssertEqual(after.cpu.Y,0x6103); + XCTAssertEqual(after.cpu.E,0); XCTAssertEqual(after.cpu.F,0); + XCTAssertEqual(after.memory,(std::vector{0xa5,0x5a,0x42})); + } +} +- (void)testTFMStepCompletesWholeTransferInBoth6309Modes { + for (bool native : {false,true}) { + MachineSession machine; prepare(machine,3,native); + const auto before=machine.debuggerSnapshot(); + machine.debuggerStep(); + const auto after=machine.debuggerSnapshot(0x6100,3); + XCTAssertEqual(after.cpu.PC,0x4012); XCTAssertEqual(after.cpu.X,0x6003); XCTAssertEqual(after.cpu.Y,0x6103); + XCTAssertEqual(after.cpu.E,0); XCTAssertEqual(after.cpu.F,0); + XCTAssertEqual(after.cpu.IsNative6309,native); + XCTAssertEqual(after.memory,(std::vector{0xa5,0x5a,0x42})); + XCTAssertEqual(after.state,RunState::Paused); XCTAssertEqual(after.generation,before.generation); + XCTAssertEqual(after.cycles-before.cycles,15u); + machine.debuggerStep(); XCTAssertEqual(machine.debuggerSnapshot().cpu.PC,0x4013); + } +} +- (void)testPCChangeAndResetAbandonPreviousTFMContinuation { + for (bool reset : {false,true}) { + MachineSession machine; prepare(machine,100); + machine.debuggerSetPC(0x400f); // Release the preceding step's halt for one ordinary CPU slice. + HD6309Exec(1); + XCTAssertEqual(machine.debuggerSnapshot().cpu.PC,0x400f); + XCTAssertEqual(machine.debuggerSnapshot().cpu.F,99); + if (reset) { + machine.softReset(); + machine.debuggerStep(); + XCTAssertEqual(machine.debuggerSnapshot().cpu.PC,0x4004); + } else { + machine.debuggerWriteMemory(0x5200,{0x12,0x20,0xfd}); + machine.debuggerSetPC(0x5200); machine.debuggerStep(); + XCTAssertEqual(machine.debuggerSnapshot().cpu.PC,0x5201); + } + } +} +- (void)testInvalidTFMStopsAtTrapWithoutExecutingHandler { + MachineSession machine; prepare(machine,3,false,0x56); + const auto before=machine.debuggerSnapshot(0x6200,1); + machine.debuggerStep(); + const auto after=machine.debuggerSnapshot(0x6200,1); + XCTAssertEqual(after.cpu.PC,0x5000); XCTAssertNotEqual(after.cpu.MD & 0x40,0); + XCTAssertEqual(after.memory,before.memory); XCTAssertEqual(after.state,RunState::Paused); + machine.debuggerStep(); XCTAssertEqual(machine.debuggerSnapshot().cpu.PC,0x5003); +} +- (void)testLargeTFMAccountsForEveryCompletedVideoFrame { + MachineSession machine; prepare(machine,20000); + // TFM X,Y+ reads a constant byte; keep the destination away from the + // instruction and stack so this is a long transfer, not self-modifying code. + machine.debuggerWriteMemory(0x400f,{0x11,0x3b,0x12}); + machine.debuggerWriteMemory(0x4012,{0x12}); + machine.debuggerSetPC(0x400f); + const auto before=machine.snapshot(); + machine.debuggerStep(); + const auto after=machine.snapshot(); + XCTAssertEqual(after.cpu.PC,0x4012); XCTAssertGreaterThan(after.frames-before.frames,1u); + XCTAssertNotEqual(after.frame,nullptr); XCTAssertEqual(after.frame->number,after.frames); + XCTAssertEqual(after.cycles-before.cycles,60006u); XCTAssertEqual(after.state,RunState::Paused); +} +@end diff --git a/platforms/macos/Tests/DebuggerTests.swift b/platforms/macos/Tests/DebuggerTests.swift new file mode 100644 index 0000000..de4fa37 --- /dev/null +++ b/platforms/macos/Tests/DebuggerTests.swift @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class DebuggerTests: XCTestCase { + @MainActor private func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { continuation in operation { continuation.resume(returning: $0) } } + } + @MainActor private func capture(_ controller: VCCMachineController, address: UInt16 = 0x8000, + memory: UInt16 = 0x4000, followPC: Bool = true) async -> VCCDebuggerSnapshot { + await withCheckedContinuation { continuation in + controller.debuggerSnapshot(address: address, followPC: followPC, memoryAddress: memory) { + continuation.resume(returning: $0) + } + } + } + @MainActor func testDebuggerBridgeSnapshotsEditsAndBreakpointsBothCPUs() async { + for use6309 in [false, true] { + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + let loaded = await command { controller.loadDiagnostic(use6309: use6309, completion: $0) } + let before = await capture(controller) + XCTAssertTrue(Thread.isMainThread) + XCTAssertEqual(before.machine.state, .paused) + XCTAssertEqual(before.instructions.first?.mnemonic, "INC") + XCTAssertEqual(before.instructions.first?.address, 0x8000) + XCTAssertEqual(before.registers["PC"]?.uint16Value, 0x8000) + XCTAssertEqual(before.registers["E"] != nil, use6309) + XCTAssertEqual(before.memory.count, 256) + let stepped = await command(controller.debuggerStep) + XCTAssertNil(stepped.errorMessage); XCTAssertEqual(stepped.programCounter, 0x8003) + XCTAssertEqual(stepped.generation, loaded.generation); XCTAssertEqual(stepped.state, .paused) + XCTAssertGreaterThan(stepped.cycles, before.machine.cycles) + let after = await capture(controller) + XCTAssertEqual(after.memory[0], before.memory[0] &+ 1) + XCTAssertEqual(before.instructions.first?.address, 0x8000, "Published snapshots remain immutable") + let written = await command { controller.debuggerWriteMemory(address: 0x4000, data: Data([0x5A, 0xA5]), completion: $0) } + XCTAssertNil(written.errorMessage) + let edited = await capture(controller) + XCTAssertEqual(edited.memory.prefix(2), Data([0x5A, 0xA5])) + _ = await command { controller.debuggerSetPC(0x8000, completion: $0) } + _ = await command { controller.debuggerSetBreakpoints([0x8003], completion: $0) } + let running = await command(controller.resume) + XCTAssertEqual(running.state, .running) + var hit = running + for _ in 0..<100 { + hit = await command(controller.snapshot) + if hit.state == .paused { break } + try? await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertEqual(hit.state, .paused); XCTAssertEqual(hit.programCounter, 0x8003) + let stopped = await capture(controller) + XCTAssertEqual(stopped.breakpoints, [0x8003]) + XCTAssertEqual(hit.generation, loaded.generation) + _ = await command(controller.resume) + for _ in 0..<100 { + hit = await command(controller.snapshot) + if hit.state == .paused { break } + try? await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertGreaterThan(hit.cycles, stopped.machine.cycles, "Continue must pass the current breakpoint before stopping again") + XCTAssertEqual(hit.programCounter, 0x8003) + _ = await command(controller.shutdown) + } + } + @MainActor func testDebuggerRejectionsAndUnavailableMemoryAreSafe() async { + let controller = VCCMachineController() + let empty = await capture(controller) + XCTAssertEqual(empty.machine.state, .empty); XCTAssertTrue(empty.instructions.isEmpty) + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command(controller.loadDiagnostic) + let before = await capture(controller, address: 0xFF00, memory: 0xFF00, followPC: false) + XCTAssertEqual(before.memoryAvailable[0], 0) + XCTAssertFalse(before.instructions.first?.valid ?? true) + XCTAssertEqual(before.instructions.first?.bytes.count, 0) + let boundary = await capture(controller, address: 0xFF8F, memory: 0xFF80, followPC: false) + XCTAssertFalse(boundary.instructions[0].valid) + XCTAssertEqual(boundary.instructions[1].address, 0xFF90, + "An unavailable port must not consume the first safe GIME byte as an operand") + for (address, data) in [(UInt16(0x8000), Data([0])), (0xFF00, Data([0])), (0xFFFF, Data([1, 2]))] { + let rejected = await command { controller.debuggerWriteMemory(address: address, data: data, completion: $0) } + XCTAssertNotNil(rejected.errorMessage) + XCTAssertEqual(rejected.cycles, before.machine.cycles) + XCTAssertEqual(rejected.generation, before.machine.generation) + } + for values: [NSNumber] in [[-1], [65536], [1.5], [NSNumber(value: Double.nan)]] { + let rejected = await command { controller.debuggerSetBreakpoints(values, completion: $0) } + XCTAssertNotNil(rejected.errorMessage) + } + _ = await command(controller.resume) + let edit = await command { controller.debuggerSetPC(0x5000, completion: $0) } + XCTAssertNotNil(edit.errorMessage); XCTAssertEqual(edit.state, .running) + let rejectedStep = await command(controller.debuggerStep) + XCTAssertNotNil(rejectedStep.errorMessage); XCTAssertEqual(rejectedStep.state, .running) + _ = await command(controller.shutdown) + let closed = await capture(controller) + XCTAssertEqual(closed.machine.state, .closed); XCTAssertTrue(closed.instructions.isEmpty) + } +} diff --git a/platforms/macos/Tests/DebuggerTraceBridgeTests.swift b/platforms/macos/Tests/DebuggerTraceBridgeTests.swift new file mode 100644 index 0000000..2c3223c --- /dev/null +++ b/platforms/macos/Tests/DebuggerTraceBridgeTests.swift @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest + +final class DebuggerTraceBridgeTests: XCTestCase { + @MainActor private func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { c in operation { c.resume(returning: $0) } } + } + @MainActor private func trace(_ controller: VCCMachineController, offset: UInt = 0) async -> VCCTraceSnapshot { + await withCheckedContinuation { c in controller.debuggerTrace(offset: offset) { rows, _ in c.resume(returning: rows) } } + } + @MainActor func testHistoricalTraceBridgeRangeExportAndValidationBothCPUs() async { + for use6309 in [false, true] { + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + let loaded = await command { controller.loadDiagnostic(use6309: use6309, completion: $0) } + let started = await command { controller.debuggerStartTrace(2, starts: [], stops: [], screen: false, scheduler: false, completion: $0) } + XCTAssertNil(started.errorMessage); XCTAssertEqual(started.generation, loaded.generation); XCTAssertEqual(started.cycles, loaded.cycles) + _ = await command(controller.debuggerStep); _ = await command(controller.debuggerStep) + let rows = await trace(controller) + XCTAssertEqual(rows.total, 2); XCTAssertFalse(rows.armed); XCTAssertEqual(rows.records.count, 2) + XCTAssertTrue(rows.records[0].instruction.contains("INC")); XCTAssertTrue(rows.records[1].instruction.contains("BRA")) + XCTAssertTrue(rows.records[0].before.contains("PC 8000")); XCTAssertTrue(rows.records[0].after.contains("PC 8003")) + XCTAssertEqual(rows.records[0].after.contains("MD"), use6309) + let text: String? = await withCheckedContinuation { c in controller.debuggerExportTrace(first: 1, count: 1) { value, _ in c.resume(returning: value) } } + XCTAssertTrue(text?.contains("BRA") == true); XCTAssertFalse(text?.contains("INC") == true) + let rejected = await command { controller.debuggerStartTrace(1, starts: [-1], stops: [], screen: false, scheduler: false, completion: $0) } + XCTAssertNotNil(rejected.errorMessage); let retained = await trace(controller); XCTAssertEqual(retained.total, 2) + _ = await command(controller.debuggerClearTrace) + let cleared = await trace(controller); XCTAssertEqual(cleared.total, 0); XCTAssertEqual(rows.total, 2) + _ = await command(controller.shutdown) + } + } + @MainActor func testTraceAddressParserAndAtomicBreakpointBridge() async { + XCTAssertEqual(TraceModel.addresses(" $8000, 0x8003 FFFF "), [0x8000, 0x8003, 0xffff]) + XCTAssertEqual(TraceModel.addresses(""), []) + for input in ["10000", "-1", "XYZ", Array(repeating: "8000", count: 33).joined(separator: " ")] { XCTAssertNil(TraceModel.addresses(input)) } + let controller = VCCMachineController() + _ = await command(controller.loadDiagnostic) + let configured = await command { controller.debuggerConfigureBreakpoints([0x8000], disabled: [0x8003], completion: $0) } + XCTAssertNil(configured.errorMessage) + let snapshot: VCCDebuggerSnapshot = await withCheckedContinuation { c in + controller.debuggerSnapshot(address: 0x8000, followPC: false, memoryAddress: 0) { c.resume(returning: $0) } + } + XCTAssertEqual(snapshot.breakpoints, [0x8000]); XCTAssertEqual(snapshot.disabledBreakpoints, [0x8003]) + _ = await command(controller.shutdown) + } + @MainActor func testAsyncTraceSaveAndFailurePreserveCapture() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let suite = "VCCTraceSaveTests-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let machine = MachineModel(diskStore: .init(url: folder.appendingPathComponent("disks.json")), + displayDefaults: defaults, inputStore: .init(url: folder.appendingPathComponent("input.json"))) + let model = TraceModel(machine: machine) + func until(_ ready: () -> Bool) async throws { + for _ in 0..<500 { + if ready() { return } + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTFail("Trace save fixture timed out") + throw NSError(domain: "TraceSaveTimeout", code: 1) + } + do { + try await until { !machine.busy } + machine.loadDiagnostic() + try await until { !machine.busy && machine.state == .paused } + model.maximum = "2"; model.start() + try await until { !model.pending && !machine.busy } + await withCheckedContinuation { done in machine.debuggerStep { done.resume() } } + await withCheckedContinuation { done in machine.debuggerStep { done.resume() } } + model.refresh() + try await until { model.snapshot?.total == 2 } + let original = try XCTUnwrap(model.snapshot) + let text: String? = await withCheckedContinuation { done in model.export { done.resume(returning: $0) } } + let csv = try XCTUnwrap(text) + let destination = folder.appendingPathComponent("Trace.csv") + await model.save(csv, to: destination) + XCTAssertEqual(try String(contentsOf: destination, encoding: .utf8), csv) + XCTAssertNil(model.error); XCTAssertNotNil(model.saveMessage); XCTAssertFalse(model.pending) + await model.save(csv, to: folder.appendingPathComponent("Missing/Trace.csv")) + XCTAssertNotNil(model.error); XCTAssertNil(model.saveMessage); XCTAssertFalse(model.pending) + XCTAssertEqual(try String(contentsOf: destination, encoding: .utf8), csv) + model.refresh() + try await until { model.snapshot !== original && model.snapshot?.identifier == original.identifier && model.snapshot?.total == 2 } + XCTAssertEqual(machine.state, .paused) + XCTAssertEqual(original.records[0].instruction, model.snapshot?.records[0].instruction) + } catch { + await withCheckedContinuation { done in machine.shutdown { done.resume() } } + throw error + } + await withCheckedContinuation { done in machine.shutdown { done.resume() } } + } + +} diff --git a/platforms/macos/Tests/DebuggerTraceTests.mm b/platforms/macos/Tests/DebuggerTraceTests.mm new file mode 100644 index 0000000..63edee9 --- /dev/null +++ b/platforms/macos/Tests/DebuggerTraceTests.mm @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import +#include "../../../src/core/MachineSession.h" +#include "../../../src/core/CpuHost.h" +#include "../../../src/core/mc6809.h" +#include "../../../src/core/hd6309.h" +#include "../../../src/core/tcc1014mmu.h" +#include +using namespace VCC::Mac; +namespace { template bool rejectsTrace(F f) { try { f(); } catch (const std::exception&) { return true; } return false; } } +@interface DebuggerTraceTests : XCTestCase +@end +@implementation DebuggerTraceTests +- (void)testInstructionCaptureBoundDoesNotPauseOrMutateGuest { + for (auto cpu : {Processor::MC6809, Processor::HD6309}) { + MachineSession machine; machine.loadDiagnostic(cpu); + auto before = machine.snapshot(); + machine.debuggerStartTrace(3, {}, {}, false, false); + XCTAssertEqual(machine.snapshot().state, RunState::Paused); + machine.resume(); machine.advance(); + auto trace = machine.debuggerTrace(); + XCTAssertEqual(trace.total, 3u); XCTAssertFalse(trace.armed); XCTAssertFalse(trace.capturing); + XCTAssertEqual(trace.status, std::string("Sample limit reached")); + XCTAssertEqual(machine.snapshot().state, RunState::Running); + XCTAssertEqual(machine.snapshot().generation, before.generation); + XCTAssertEqual(trace.records[0].before.PC, 0x8000); XCTAssertEqual(trace.records[0].after.PC, 0x8003); + XCTAssertEqual(trace.records[0].bytes[0], 0x7c); XCTAssertGreaterThan(trace.records[0].cycles, 0); + XCTAssertLessThan(trace.records[0].clock, trace.records[1].clock); + machine.advance(); XCTAssertEqual(machine.debuggerTrace().total, 3u); + auto csv = machine.debuggerExportTrace(0, 2); + XCTAssertTrue(csv.find("INC") != std::string::npos); XCTAssertTrue(csv.find("BRA") != std::string::npos); + XCTAssertTrue(rejectsTrace([&] { machine.debuggerExportTrace(2, 2); })); + } +} +- (void)testMultipleTriggersAndStepTracing { + for (auto cpu : {Processor::MC6809, Processor::HD6309}) { + MachineSession machine; machine.loadDiagnostic(cpu); + machine.debuggerStartTrace(100, {0x9999, 0x8003}, {0x8000, 0x8888}, false, false); + machine.debuggerStep(); XCTAssertEqual(machine.debuggerTrace().total, 0u); + machine.debuggerStep(); + auto trace = machine.debuggerTrace(); XCTAssertEqual(trace.total, 1u); + XCTAssertEqual(trace.records[0].before.PC, 0x8003); XCTAssertEqual(trace.records[0].after.PC, 0x8000); + machine.debuggerStep(); trace = machine.debuggerTrace(); + XCTAssertFalse(trace.armed); XCTAssertEqual(trace.total, 1u); + XCTAssertEqual(trace.status, std::string("Stop address reached (before instruction)")); + XCTAssertEqual(machine.snapshot().cpu.PC, 0x8003, "Trace stop never prevents guest instruction execution"); + machine.debuggerStartTrace(10, {0x9000}, {}, false, false); + machine.resume(); machine.advance(); XCTAssertTrue(machine.debuggerTrace().armed); XCTAssertFalse(machine.debuggerTrace().capturing); + machine.debuggerStopTrace(); XCTAssertFalse(machine.debuggerTrace().armed); + } +} +- (void)testRealScreenAndSchedulerEventsAndImmutablePages { + MachineSession machine; machine.loadDiagnostic(); + machine.debuggerStartTrace(100000, {}, {}, true, true); + machine.resume(); machine.advance(); machine.advance(); machine.debuggerStopTrace(); + auto first = machine.debuggerTrace(0, 256); auto total = first.total; + bool screen = false, scheduler = false; + std::uint64_t lastClock = 0; + for (std::size_t offset = 0; offset < total; offset += 256) { + for (const auto& row : machine.debuggerTrace(offset).records) { + screen |= row.event == VCC::TraceEvent::ScreenHSYNCLow; + scheduler |= row.event == VCC::TraceEvent::EmulatorCycle; + XCTAssertGreaterThanOrEqual(row.clock, lastClock); lastClock = row.clock; + } + } + XCTAssertTrue(screen); XCTAssertTrue(scheduler); + auto exported = machine.debuggerTraceForExport(1, 2); + machine.debuggerClearTrace(); XCTAssertEqual(machine.debuggerTrace().total, 0u); + const auto historicalCSV = FormatDebugTraceCSV(exported); + XCTAssertTrue(historicalCSV.find("\n2,") != std::string::npos); + XCTAssertTrue(historicalCSV.find("\n3,") != std::string::npos); + XCTAssertEqual(first.total, total); XCTAssertFalse(first.records.empty()); + XCTAssertTrue(rejectsTrace([&] { machine.debuggerTrace(0, 257); })); + XCTAssertTrue(rejectsTrace([&] { machine.debuggerStartTrace(100001, {}, {}, false, false); })); +} +- (void)testIRQStagesAndResetRetainStoppedCapture { + MachineSession machine; machine.loadDiagnostic(); machine.debuggerStartTrace(100, {}, {}, false, false); + machine.debuggerStep(); + // Same synchronous hooks used by the retained CPU interrupt engines; no + // interrupt inference from CC masks or polling of device registers. + auto state = machine.snapshot().cpu; + VCC::CpuDebugger().TraceCaptureInterruptRequest(INT_IRQ, 0, state); + VCC::CpuDebugger().TraceCaptureInterruptServicing(INT_IRQ, 0, state); + VCC::CpuDebugger().TraceCaptureInterruptExecuting(INT_IRQ, 0, state); + auto trace = machine.debuggerTrace(); XCTAssertEqual(trace.total, 4u); + XCTAssertEqual(trace.records[1].event, VCC::TraceEvent::IRQRequested); + XCTAssertEqual(trace.records[2].event, VCC::TraceEvent::IRQServicing); + XCTAssertEqual(trace.records[3].event, VCC::TraceEvent::IRQExecuting); + machine.softReset(); XCTAssertFalse(machine.debuggerTrace().armed); XCTAssertEqual(machine.debuggerTrace().total, 4u); + machine.reset(); XCTAssertEqual(machine.debuggerTrace().total, 4u); +} +- (void)testRetainedCPUInterruptEnginesEmitActualIRQStages { + for (auto cpu : {Processor::MC6809, Processor::HD6309}) { + std::vector rom(0x8000, 0x12); + const std::uint8_t program[] = {0x10,0xce,0x70,0x00,0x1c,0xef,0x20,0xfe,0x3b}; + std::copy(std::begin(program), std::end(program), rom.begin()); + rom[0x7ffe]=0x80; rom[0x7fff]=0; rom[0x7ff8]=0x80; rom[0x7ff9]=8; + MachineSession machine; machine.load(rom, cpu); + machine.debuggerStep(); machine.debuggerStep(); + machine.debuggerStartTrace(100, {}, {}, false, false); machine.debuggerStep(); + if (cpu == Processor::MC6809) MC6809AssertInterupt(IS_GIME, INT_IRQ); + else HD6309AssertInterupt(IS_GIME, INT_IRQ); + machine.resume(); machine.advance(); + const auto trace = machine.debuggerTrace(); + bool requested=false, servicing=false, vector=false; + for (const auto& row : trace.records) { + requested |= row.event == VCC::TraceEvent::IRQRequested; + servicing |= row.event == VCC::TraceEvent::IRQServicing; + vector |= row.event == VCC::TraceEvent::IRQExecuting; + } + XCTAssertTrue(requested); XCTAssertTrue(servicing); XCTAssertTrue(vector); + } +} +- (void)testDisabledBreakpointsShareAtomicAuthoritativeState { + MachineSession machine; machine.loadDiagnostic(); + machine.debuggerConfigureBreakpoints({}, {0x8000}); + machine.resume(); machine.advance(); XCTAssertEqual(machine.snapshot().state, RunState::Running); + machine.debuggerConfigureBreakpoints({0x8000}, {}); machine.advance(); + XCTAssertEqual(machine.snapshot().state, RunState::Paused); + machine.debuggerConfigureBreakpoints({0x8000}, {0x8003}); + machine.softReset(); machine.reset(); + XCTAssertEqual(machine.debuggerSnapshot().disabledBreakpoints.size(), 1u); + XCTAssertTrue(rejectsTrace([&] { machine.debuggerConfigureBreakpoints({0x8000}, {0x8000}); })); + XCTAssertEqual(machine.debuggerSnapshot().disabledBreakpoints[0], 0x8003); + machine.debuggerSetBreakpoints({}); XCTAssertTrue(machine.debuggerSnapshot().disabledBreakpoints.empty()); +} +@end diff --git a/platforms/macos/Tests/DisassemblerTests.mm b/platforms/macos/Tests/DisassemblerTests.mm new file mode 100644 index 0000000..f6a9beb --- /dev/null +++ b/platforms/macos/Tests/DisassemblerTests.mm @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#import +#include "../../../src/core/DebugDisassembler.h" +#include +using namespace VCC::Mac; +namespace { +DebugInstruction decode(std::initializer_list bytes, bool use6309 = false, + std::uint16_t address = 0x8000, bool native = false) { + std::vector memory(65536, 0x12); + auto cursor = address; + for (auto byte : bytes) memory[cursor++] = byte; + VCC::CPUState state; state.IsNative6309 = native; + return Disassemble(memory, state, use6309, address, 1).front(); +} +} +@interface DisassemblerTests : XCTestCase +@end +@implementation DisassemblerTests +- (void)testBasicInstructionsAndSignedBranchTargets { + const auto load = decode({0x86, 0x7f}); + XCTAssertEqual(load.mnemonic, "LDA"); XCTAssertEqual(load.operand, "#$7F"); + XCTAssertEqual(load.bytes.size(), 2u); XCTAssertTrue(load.valid); + XCTAssertEqual(decode({0x8e, 0x12, 0x34}).operand, "#$1234"); + XCTAssertEqual(decode({0x7c, 0x40, 0}).operand, "$4000"); + XCTAssertEqual(decode({0x96, 0x42}).operand, "<$42"); + XCTAssertEqual(decode({0x20, 0xfb}).operand, "$7FFD"); + XCTAssertEqual(decode({0x20, 0x7f}).operand, "$8081"); + XCTAssertEqual(decode({0x10, 0x26, 0xff, 0xfc}).operand, "$8000"); + XCTAssertEqual(decode({0x16, 0x7f, 0xff}).operand, "$0002"); +} +- (void)testIndexedSignedOffsetsIndirectAndPCRelative { + XCTAssertEqual(decode({0xa6, 0x1f}).operand, "-1,X"); + XCTAssertEqual(decode({0xa6, 0x88, 0x80}).operand, "-128,X"); + XCTAssertEqual(decode({0xa6, 0xa9, 0xff, 0xfe}).operand, "-2,Y"); + XCTAssertEqual(decode({0xa6, 0x9f, 0xff, 0xfe}).operand, "[$FFFE]"); + XCTAssertEqual(decode({0xa6, 0x9c, 0xfc}).operand, "[-4,PCR]"); + XCTAssertEqual(decode({0xa6, 0xf3}).operand, "[,--S]"); + XCTAssertFalse(decode({0xa6, 0x87}).valid); + XCTAssertEqual(decode({0xa6, 0x87}, true).operand, "E,X"); + XCTAssertEqual(decode({0xa6, 0x8f}, true).operand, ",W"); + XCTAssertEqual(decode({0xa6, 0xbe}, true).operand, "[W,Y]"); + XCTAssertFalse(decode({0xa6, 0xbe}, false).valid); +} +- (void)testRegisterListsAndTransfers { + XCTAssertEqual(decode({0x34, 0xff}).operand, "CC,A,B,DP,X,Y,U,PC"); + XCTAssertEqual(decode({0x36, 0x40}).operand, "S"); + XCTAssertEqual(decode({0x1f, 0x01}).operand, "D,X"); + XCTAssertFalse(decode({0x1f, 0x61}).valid); + XCTAssertEqual(decode({0x1f, 0x61}, true).operand, "W,X"); + XCTAssertEqual(decode({0x10, 0x30, 0x12}, true).operand, "X,Y"); + XCTAssertEqual(decode({0x11, 0x38, 0x12}, true).operand, "X+,Y+"); + XCTAssertEqual(decode({0x11, 0x39, 0x34}, true).operand, "U-,S-"); + XCTAssertEqual(decode({0x11, 0x3a, 0x12}, true).operand, "X+,Y"); + XCTAssertEqual(decode({0x11, 0x3b, 0x12}, true).operand, "X,Y+"); + XCTAssertFalse(decode({0x11, 0x38, 0x56}, true).valid); +} +- (void)test6309ImmediateMemoryBitOperationsAndNativeIdentity { + const auto emulation = decode({0xcd, 0x12, 0x34, 0x56, 0x78}, true); + const auto native = decode({0xcd, 0x12, 0x34, 0x56, 0x78}, true, 0x8000, true); + XCTAssertEqual(emulation.mnemonic, "LDQ"); XCTAssertEqual(emulation.operand, "#$12345678"); + XCTAssertEqual(native.operand, emulation.operand); XCTAssertEqual(native.bytes, emulation.bytes); + XCTAssertFalse(decode({0xcd, 0x12, 0x34, 0x56, 0x78}).valid); + XCTAssertFalse(decode({0x10, 0xec, 0x84}).valid); + XCTAssertEqual(decode({0x01, 0x80, 0x42}, true).operand, "#$80,<$42"); + const auto indexed = decode({0x61, 0x80, 0x88, 0xff}, true); + XCTAssertEqual(indexed.operand, "#$80,-1,X"); XCTAssertEqual(indexed.bytes.size(), 4u); + XCTAssertEqual(decode({0x71, 0x80, 0x12, 0x34}, true).operand, "#$80,$1234"); + XCTAssertEqual(decode({0x11, 0x30, 0x53, 0x42}, true).operand, "A,2,3,<$42"); + XCTAssertFalse(decode({0x11, 0x30, 0xc0, 0x42}, true).valid); +} +- (void)testInstructionFetchWrapAndInvalidProgress { + XCTAssertFalse(decode({0x15}).valid); + XCTAssertFalse(decode({0x11, 0x3e}).valid); + const auto wrap = decode({0x8e, 0x12, 0x34}, false, 0xffff); + XCTAssertEqual(wrap.address, 0xffff); XCTAssertEqual(wrap.operand, "#$1234"); + XCTAssertEqual(decode({0x20, 0xfe}, false, 0xffff).operand, "$FFFF"); + std::vector memory(65536, 0x12); + memory[0xffff] = 0x10; memory[0] = 0; + const auto rows = Disassemble(memory, {}, false, 0xffff, 2); + XCTAssertFalse(rows[0].valid); XCTAssertEqual(rows[0].mnemonic, "FCB"); + XCTAssertEqual(rows[0].operand, "$10,$00"); XCTAssertEqual(rows[1].address, 1); + XCTAssertEqual(rows[1].mnemonic, "NOP"); + const auto original = memory; + for (bool use6309 : {false, true}) for (unsigned opcode = 0; opcode < 256; ++opcode) { + memory[0x8000] = opcode; + const auto instruction = Disassemble(memory, {}, use6309, 0x8000, 1).front(); + XCTAssertGreaterThan(instruction.bytes.size(), 0u); XCTAssertLessThanOrEqual(instruction.bytes.size(), 6u); + } + memory[0x8000] = original[0x8000]; XCTAssertEqual(memory, original); +} +- (void)testSnapshotAndInstructionCountValidation { + bool shortRejected = false, countRejected = false; + try { Disassemble(std::vector(65535), {}, false, 0, 1); } + catch (const std::invalid_argument&) { shortRejected = true; } + try { Disassemble(std::vector(65536), {}, false, 0, 1025); } + catch (const std::invalid_argument&) { countRejected = true; } + XCTAssertTrue(shortRejected); XCTAssertTrue(countRejected); + XCTAssertTrue(Disassemble(std::vector(65536), {}, false, 0, 0).empty()); +} +@end diff --git a/platforms/macos/Tests/DiskAutosaveTests.swift b/platforms/macos/Tests/DiskAutosaveTests.swift new file mode 100644 index 0000000..b9c1308 --- /dev/null +++ b/platforms/macos/Tests/DiskAutosaveTests.swift @@ -0,0 +1,256 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest +import SwiftUI +import AppKit + +private actor SaveGate { + private var release: CheckedContinuation? + private(set) var started = false + func wait() async { started = true; await withCheckedContinuation { release = $0 } } + func open() { release?.resume(); release = nil } +} + +final class DiskAutosaveTests: XCTestCase { + private struct Fixture { + let folder: URL, disk: URL, store: DiskAssignmentStore + let original = Data(repeating: 0, count: 161280) + init(temporary: Bool = false, protected: Bool = false) throws { + folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + disk = folder.appendingPathComponent("Autosave é.DSK") + try original.write(to: disk) + let rom = folder.appendingPathComponent("authored.rom") + try Data(repeating: 0, count: 8192).write(to: rom) + store = DiskAssignmentStore(url: folder.appendingPathComponent("settings.json")) + var settings = DiskAssignments(); settings.rom = rom + settings.drives[0] = .init(url: disk, writeProtected: protected, temporary: temporary) + try store.save(settings) + } + func remove() { try? FileManager.default.removeItem(at: folder) } + } + // Authored code shared by both CPU engines: fill sector 1, commit, then loop. + private func writerROM(_ value: UInt8 = 0x5a, repeating: Bool = false) -> Data { + var program: [UInt8] = [0x86,0x29,0xb7,0xff,0x40,0x86,1,0xb7,0xff,0x4a, + 0x86,0xa0,0xb7,0xff,0x48,0x8e,1,0,0x86,value, + 0xb7,0xff,0x4b,0x30,0x1f,0x26,0xf9,0xb7,0xff,0x4b,0x20,0xfe] + if repeating { + program.removeLast(2) + // Idle between writes so the controller can capture complete sectors. + program += [0x8e,0x40,0x00,0x30,0x1f,0x26,0xfc] + let back = UInt8(bitPattern: Int8(-(program.count + 2))) + program += [0x20, back] + } + var rom = Data(repeating: 0, count: 32768); rom.replaceSubrange(0.. Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { continuation in action { continuation.resume(returning: $0) } } + } + @MainActor private func until(_ condition: () -> Bool) async throws { + for _ in 0..<500 { + if condition() { return } + try await Task.sleep(nanoseconds: 20_000_000) + } + XCTFail("Timed out waiting for disk saving") + throw NSError(domain: "TestTimeout", code: 1) + } + @MainActor private func settled(_ model: MachineModel) async throws { + try await until { !model.busy && !model.diskSaving } + } + @MainActor private func close(_ model: MachineModel) async { + await withCheckedContinuation { continuation in model.shutdown { continuation.resume() } } + } + @MainActor private func runWriter(_ controller: VCCMachineController, use6309: Bool = false, value: UInt8 = 0x5a) async { + let s = await step { controller.loadROM(writerROM(value), use6309: use6309, completion: $0) } + XCTAssertNil(s.errorMessage) + _ = await step(controller.resume) + } + func testAutomaticFileWriteRejectsConflictsMissingAndReadOnlyFiles() throws { + let f = try Fixture(); defer { f.remove() } + let changed = Data(repeating: 0x5a, count: 161280) + try DiskFiles.saveAutomatically(changed, to: f.disk, expected: f.original) + XCTAssertEqual(try Data(contentsOf: f.disk), changed) + XCTAssertThrowsError(try DiskFiles.saveAutomatically(f.original, to: f.disk, expected: f.original)) + XCTAssertEqual(try Data(contentsOf: f.disk), changed) + try FileManager.default.setAttributes([.posixPermissions: 0o444], ofItemAtPath: f.disk.path) + XCTAssertThrowsError(try DiskFiles.saveAutomatically(f.original, to: f.disk, expected: changed)) + XCTAssertEqual(try Data(contentsOf: f.disk), changed) + try FileManager.default.removeItem(at: f.disk) + XCTAssertThrowsError(try DiskFiles.saveAutomatically(changed, to: f.disk, expected: changed)) + XCTAssertFalse(FileManager.default.fileExists(atPath: f.disk.path)) + let target = f.folder.appendingPathComponent("image-without-extension") + try f.original.write(to: target) + try FileManager.default.createSymbolicLink(at: f.disk, withDestinationURL: target) + try DiskFiles.saveAutomatically(changed, to: f.disk.resolvingSymlinksInPath(), expected: f.original) + XCTAssertEqual(try Data(contentsOf: target), changed) + XCTAssertEqual(try FileManager.default.destinationOfSymbolicLink(atPath: f.disk.path), target.path) + } + func testOlderSettingsDefaultToAutomaticSaving() throws { + let f = try Fixture(temporary: true); defer { f.remove() } + var json = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: f.store.url)) as? [String: Any]) + var drives = try XCTUnwrap(json["drives"] as? [Any]) + var first = try XCTUnwrap(drives[0] as? [String: Any]); first.removeValue(forKey: "temporary") + drives[0] = first; json["drives"] = drives + try JSONSerialization.data(withJSONObject: json).write(to: f.store.url) + XCTAssertFalse(try XCTUnwrap(f.store.load().drives[0]).temporary) + } + @MainActor func testGuestWritesSaveWithoutPausingOnBothCPUs() async throws { + for (cpu, mpi) in [(false, false), (true, false), (false, true), (true, true)] { + let f = try Fixture(); defer { f.remove() } + if mpi { + var settings = try f.store.load(); var layout = CartridgeAssignments() + layout.multiPak = true; layout.mpiConfigured = true; layout.slots[4].kind = .floppy + settings.cartridges = layout; try f.store.save(settings) + } + let controller = VCCMachineController(); let model = MachineModel(diskStore: f.store, controller: controller) + do { + try await settled(model); await runWriter(controller, use6309: cpu) + try await until { (try? Data(contentsOf: f.disk).first) == 0x5a && !model.diskSaving && !model.disks[0].dirty } + XCTAssertEqual(model.state, .running); XCTAssertTrue(model.diskSaveErrors.isEmpty) + let bytes = try Data(contentsOf: f.disk) + XCTAssertEqual(bytes.prefix(256), Data(repeating: 0x5a, count: 256)) + XCTAssertEqual(bytes.dropFirst(256), f.original.dropFirst(256)) + } catch { await close(model); throw error } + await close(model) + let reopened = MachineModel(diskStore: f.store) + try await settled(reopened); XCTAssertTrue(reopened.disks[0].mounted); XCTAssertFalse(reopened.disks[0].dirty) + await close(reopened) + } + } + @MainActor func testTemporaryModeAndProtectionKeepSourceUnchanged() async throws { + for protected in [false, true] { + let f = try Fixture(temporary: !protected, protected: protected); defer { f.remove() } + let controller = VCCMachineController(); let model = MachineModel(diskStore: f.store, controller: controller) + do { + try await settled(model); XCTAssertEqual(model.diskTemporary[0], !protected) + await runWriter(controller) + try await until { model.frames > 20 } + await withCheckedContinuation { continuation in model.prepareToQuit { continuation.resume() } } + XCTAssertEqual(try Data(contentsOf: f.disk), f.original) + XCTAssertEqual(model.disks[0].dirty, !protected) + XCTAssertEqual(model.unsavedMedia, !protected) + XCTAssertEqual(model.needsMediaAttention, !protected, "Temporary changes must still need attention") + if !protected { + model.setDiskTemporary(0, false); try await settled(model) + XCTAssertFalse(try XCTUnwrap(f.store.load().drives[0]).temporary) + await withCheckedContinuation { continuation in model.prepareToQuit { continuation.resume() } } + XCTAssertFalse(model.unsavedMedia); XCTAssertEqual(try Data(contentsOf: f.disk).first, 0x5a) + } + } catch { await close(model); throw error } + await close(model) + } + } + @MainActor func testExternalEditPausesAndRetainsChangesUntilRetry() async throws { + let f = try Fixture(); defer { f.remove() } + let controller = VCCMachineController(); let model = MachineModel(diskStore: f.store, controller: controller) + do { + try await settled(model) + let external = Data(repeating: 7, count: 161280); try external.write(to: f.disk) + await runWriter(controller) + try await until { model.diskSaveErrors[0] != nil && !model.diskSaving } + XCTAssertEqual(model.state, .paused); XCTAssertTrue(model.disks[0].dirty) + XCTAssertTrue(model.needsMediaAttention, "Real autosave failures must remain visible") + XCTAssertEqual(try Data(contentsOf: f.disk), external) + await withCheckedContinuation { continuation in model.prepareToQuit { continuation.resume() } } + XCTAssertTrue(model.unsavedMedia); XCTAssertEqual(try Data(contentsOf: f.disk), external) + try f.original.write(to: f.disk) + model.retryDiskSave(0) + try await until { !model.diskSaving && !model.disks[0].dirty } + XCTAssertTrue(model.diskSaveErrors.isEmpty); XCTAssertEqual(try Data(contentsOf: f.disk).first, 0x5a) + XCTAssertFalse(model.needsMediaAttention) + } catch { await close(model); throw error } + await close(model) + } + @MainActor func testRepeatedWritesKeepAttentionAndNativeDisplayStable() async throws { + let f = try Fixture(); defer { f.remove() } + var assignments = try f.store.load() + var layout = CartridgeAssignments(); layout.multiPak = true; layout.mpiConfigured = true + layout.slots[4].kind = .floppy; assignments.cartridges = layout; try f.store.save(assignments) + let suite = "VCCRepeatedWrites-" + UUID().uuidString + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let controller = VCCMachineController(), gate = SaveGate() + let model = MachineModel(diskStore: f.store, controller: controller, displayDefaults: defaults, + inputStore: .init(url: f.folder.appendingPathComponent("input.json")), + automaticDiskWriter: { data, url, expected in + if !(await gate.started) { await gate.wait() } + try DiskFiles.saveAutomatically(data, to: url, expected: expected) + }) + let presentation = PresentationSettings(defaults: defaults) + let host = NSHostingView(rootView: MachineView(machine: model, presentation: presentation, showManualHome: {})) + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1100, height: 820), + styleMask: [.titled, .resizable], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false; window.contentView = host + defer { window.close() } + func display(_ view: NSView) -> KeyboardDisplay? { + if let result = view as? KeyboardDisplay { return result } + return view.subviews.lazy.compactMap { display($0) }.first + } + do { + try await settled(model) + XCTAssertFalse(model.hardware.custom, "System checks must use the illustrated layout, not its conventional fallback") + _ = await step { controller.loadROM(writerROM(repeating: true), use6309: false, completion: $0) } + for mode in [PresentationSettings.Mode.display, .system] { + presentation.mode = mode + try await Task.sleep(nanoseconds: 100_000_000); host.layoutSubtreeIfNeeded() + let screen = try XCTUnwrap(display(host)) + let original = screen.convert(screen.bounds, to: host) + _ = await step(controller.resume) + for _ in 0..<500 { if await gate.started { break }; try await Task.sleep(nanoseconds: 10_000_000) } + let started = await gate.started; XCTAssertTrue(started) + let before = await step(controller.snapshot) + for _ in 0..<30 { + model.poll(); try await Task.sleep(nanoseconds: 20_000_000) + host.layoutSubtreeIfNeeded() + XCTAssertTrue(model.unsavedMedia, "Quit protection must include pending host writes") + XCTAssertFalse(model.needsMediaAttention, "Normal repeated saves must not toggle a warning row") + XCTAssertEqual(screen.convert(screen.bounds, to: host), original, "Disk activity must not resize the live display") + } + let after = await step(controller.snapshot) + XCTAssertGreaterThan(after.frames, before.frames) + XCTAssertGreaterThan(after.disks[0].writeEvents, before.disks[0].writeEvents) + XCTAssertEqual(after.generation, before.generation) + _ = await step(controller.pause) + } + await gate.open() + await withCheckedContinuation { done in model.prepareToQuit { done.resume() } } + XCTAssertFalse(model.unsavedMedia); XCTAssertFalse(model.needsMediaAttention) + XCTAssertEqual(try Data(contentsOf: f.disk).prefix(256), Data(repeating: 0x5a, count: 256)) + } catch { await gate.open(); await close(model); throw error } + await close(model) + } + @MainActor func testQuitWaitsForPendingSaveAndFlushesNewerGuestWrites() async throws { + let f = try Fixture(); defer { f.remove() } + let controller = VCCMachineController(); let gate = SaveGate() + let model = MachineModel(diskStore: f.store, controller: controller, automaticDiskWriter: { data, url, expected in + if !(await gate.started) { await gate.wait() } + try DiskFiles.saveAutomatically(data, to: url, expected: expected) + }) + do { + try await settled(model); await runWriter(controller) + for _ in 0..<500 { + if await gate.started { break } + try await Task.sleep(nanoseconds: 20_000_000) + } + let started = await gate.started; XCTAssertTrue(started); XCTAssertTrue(model.diskSaving) + XCTAssertEqual(try Data(contentsOf: f.disk), f.original) + // Write a newer version while the first snapshot's host write waits. + await runWriter(controller, value: 0x6b) + let start = await step(controller.snapshot) + for _ in 0..<100 { + let s = await step(controller.snapshot) + if s.frames > start.frames + 2 { break } + try await Task.sleep(nanoseconds: 20_000_000) + } + var quitReady = false + model.prepareToQuit { quitReady = true } + try await Task.sleep(nanoseconds: 50_000_000) + XCTAssertFalse(quitReady, "Quit must wait for outstanding file I/O") + await gate.open() + try await until { quitReady } + XCTAssertFalse(model.unsavedMedia); XCTAssertEqual(model.state, .paused) + XCTAssertEqual(try Data(contentsOf: f.disk).prefix(256), Data(repeating: 0x6b, count: 256)) + } catch { await gate.open(); await close(model); throw error } + await close(model) + } +} diff --git a/platforms/macos/Tests/DiskEditorSafetyTests.swift b/platforms/macos/Tests/DiskEditorSafetyTests.swift new file mode 100644 index 0000000..06e3b56 --- /dev/null +++ b/platforms/macos/Tests/DiskEditorSafetyTests.swift @@ -0,0 +1,932 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest +import AppKit + +final class DiskEditorSafetyTests: XCTestCase { + private let original = Data(repeating: 0, count: 161280) + @MainActor private func step(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { continuation in operation { continuation.resume(returning: $0) } } + } + @MainActor private func capture(_ controller: VCCMachineController) async -> (VCCDiskEditCapture?, VCCMachineSnapshot) { + await withCheckedContinuation { continuation in + controller.beginDiskEditor(inDrive: 0) { continuation.resume(returning: ($0, $1)) } + } + } + @MainActor private func prepare(_ controller: VCCMachineController, _ token: UInt64, _ data: Data) async -> (Bool, VCCMachineSnapshot) { + await withCheckedContinuation { continuation in + controller.prepareDiskEditor(token: token, data: data) { continuation.resume(returning: ($0, $1)) } + } + } + @MainActor private func commit(_ controller: VCCMachineController, _ token: UInt64, confirmed: Bool, saved: Bool) async -> (Bool, VCCMachineSnapshot) { + await withCheckedContinuation { continuation in + controller.commitDiskEditor(token: token, restartConfirmed: confirmed, sourceSaved: saved) { continuation.resume(returning: ($0, $1)) } + } + } + @MainActor private func setup(_ controller: VCCMachineController, cpu: Bool, readOnly: Bool = false) async { + let diagnostic = await step { controller.loadDiagnostic(use6309: cpu, completion: $0) } + XCTAssertNil(diagnostic.errorMessage) + let rom = await step { controller.loadDiskROM(Data(repeating: 0, count: 8192), name: "authored.rom", completion: $0) } + XCTAssertNil(rom.errorMessage) + let mount = await step { controller.mountDisk(original, drive: 0, name: "fixture.dsk", readOnly: readOnly, completion: $0) } + XCTAssertNil(mount.errorMessage) + } + @MainActor func testLeaseBlocksExecutionAndMediaOnBothCPUsAndCancelRetainsBytes() async throws { + for cpu in [false, true] { + let controller = VCCMachineController() + await setup(controller, cpu: cpu) + _ = await step(controller.resume) + let (optional, locked) = await capture(controller) + let edit = try XCTUnwrap(optional) + XCTAssertTrue(locked.diskEditorLocked); XCTAssertEqual(locked.state, .paused) + XCTAssertEqual(edit.data, original) + let refused = [ + await step(controller.resume), await step(controller.reset), await step(controller.debuggerStep), + await step { controller.ejectDisk(inDrive: 0, discard: true, completion: $0) }, + await step { controller.mountDisk(original, drive: 0, name: "other.dsk", readOnly: false, completion: $0) }, + await step { controller.loadDiagnostic(use6309: !cpu, completion: $0) } + ] + for result in refused { + XCTAssertNotNil(result.errorMessage); XCTAssertTrue(result.diskEditorLocked) + XCTAssertEqual(result.generation, locked.generation); XCTAssertEqual(result.frames, locked.frames) + XCTAssertEqual(result.state, .paused) + } + var edited = original; edited[1000] = 0x5a + let (valid, _) = await prepare(controller, edit.token, edited); XCTAssertTrue(valid) + let cancelled = await step { controller.cancelDiskEditor(token: edit.token, completion: $0) } + XCTAssertNil(cancelled.errorMessage); XCTAssertFalse(cancelled.diskEditorLocked) + let (next, _) = await capture(controller) + XCTAssertEqual(next?.data, original, "Private changes must not reach the mounted disk on Cancel") + let stale = await step { controller.cancelDiskEditor(token: edit.token, completion: $0) } + XCTAssertNotNil(stale.errorMessage); XCTAssertTrue(stale.diskEditorLocked) + _ = await step { controller.cancelDiskEditor(token: next!.token, completion: $0) } + let resumed = await step(controller.resume); XCTAssertNil(resumed.errorMessage) + _ = await step(controller.shutdown) + } + } + @MainActor func testValidationProtectionRestartAndDirtySemanticsOnBothCPUs() async throws { + for cpu in [false, true] { + let controller = VCCMachineController(); await setup(controller, cpu: cpu) + let (optional, before) = await capture(controller); let edit = try XCTUnwrap(optional) + let invalid = await prepare(controller, edit.token, Data(repeating: 0, count: 184320)) + XCTAssertFalse(invalid.0); XCTAssertNotNil(invalid.1.errorMessage) + var bytes = original; bytes[1000] = 0xa5 + let valid = await prepare(controller, edit.token, bytes); XCTAssertTrue(valid.0) + let unconfirmed = await commit(controller, edit.token, confirmed: false, saved: false) + XCTAssertFalse(unconfirmed.0); XCTAssertEqual(unconfirmed.1.generation, before.generation) + let applied = await commit(controller, edit.token, confirmed: true, saved: false) + XCTAssertTrue(applied.0); XCTAssertNil(applied.1.errorMessage) + XCTAssertFalse(applied.1.diskEditorLocked); XCTAssertTrue(applied.1.disks[0].dirty) + XCTAssertGreaterThan(applied.1.generation, before.generation); XCTAssertEqual(applied.1.state, .paused) + let (current, _) = await capture(controller); XCTAssertEqual(current?.data, bytes) + _ = await step { controller.cancelDiskEditor(token: current!.token, completion: $0) } + _ = await step(controller.shutdown) + let readOnly = VCCMachineController(); await setup(readOnly, cpu: cpu, readOnly: true) + let (protected, _) = await capture(readOnly); XCTAssertFalse(protected!.canApply) + let refusal = await prepare(readOnly, protected!.token, bytes) + XCTAssertFalse(refusal.0); XCTAssertNotNil(refusal.1.errorMessage) + _ = await step { readOnly.cancelDiskEditor(token: protected!.token, completion: $0) } + _ = await step(readOnly.shutdown) + } + } + @MainActor func testHardDiskLeasesAndRestartApplyRetainOtherMediaOnBothCPUs() async throws { + for cpu in [false, true] { + for drive in 0..<2 { + let controller = VCCMachineController(); await setup(controller, cpu: cpu) + let disk = Data(repeating: UInt8(0x20 + drive), count: 20 * 1024 * 1024) + let other = Data(repeating: 0x71, count: 1024) + _ = await step { controller.mountHardDisk(disk, drive: drive, name: "authored.vhd", readOnly: false, completion: $0) } + _ = await step { controller.mountHardDisk(other, drive: 1 - drive, name: "other.vhd", readOnly: false, completion: $0) } + _ = await step(controller.resume) + let (optional, before): (VCCDiskEditCapture?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.beginHardDiskEditor(inDrive: drive) { continuation.resume(returning: ($0, $1)) } + } + let edit = try XCTUnwrap(optional) + XCTAssertEqual(edit.data, disk); XCTAssertTrue(edit.canApply) + XCTAssertTrue(before.diskEditorLocked); XCTAssertEqual(before.state, .paused) + for result in [await step(controller.resume), await step(controller.reset), + await step { controller.hardDiskAction(1, drive: drive, completion: $0) }, + await step { controller.mountHardDisk(other, drive: 1 - drive, name: "replacement.vhd", readOnly: false, completion: $0) }, + await step { controller.ejectDisk(inDrive: 0, discard: true, completion: $0) }] { + XCTAssertNotNil(result.errorMessage); XCTAssertTrue(result.diskEditorLocked) + XCTAssertEqual(result.generation, before.generation) + } + var edited = disk; edited[edited.count - 1] = 0x5a + let invalid = await prepare(controller, edit.token, edited.dropLast(256)) + XCTAssertFalse(invalid.0) + let valid = await prepare(controller, edit.token, edited); XCTAssertTrue(valid.0) + let declined = await commit(controller, edit.token, confirmed: false, saved: false) + XCTAssertFalse(declined.0); XCTAssertEqual(declined.1.generation, before.generation) + let applied = await commit(controller, edit.token, confirmed: true, saved: false) + XCTAssertTrue(applied.0); XCTAssertFalse(applied.1.diskEditorLocked) + XCTAssertTrue(applied.1.hardDisks[drive].dirty); XCTAssertTrue(applied.1.disks[0].mounted) + XCTAssertTrue(applied.1.hardDisks[1 - drive].mounted) + XCTAssertGreaterThan(applied.1.generation, before.generation); XCTAssertEqual(applied.1.state, .paused) + let (check, _): (VCCDiskEditCapture?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.beginHardDiskEditor(inDrive: drive) { continuation.resume(returning: ($0, $1)) } + } + XCTAssertEqual(check?.data, edited) + let stale = await prepare(controller, edit.token, disk); XCTAssertFalse(stale.0) + _ = await step { controller.cancelDiskEditor(token: check!.token, completion: $0) } + let (preserved, _): (VCCDiskEditCapture?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.beginHardDiskEditor(inDrive: 1 - drive) { continuation.resume(returning: ($0, $1)) } + } + XCTAssertEqual(preserved?.data, other) + _ = await step { controller.cancelDiskEditor(token: preserved!.token, completion: $0) } + _ = await step(controller.shutdown) + } + } + } + @MainActor func testHardDiskEditorReadOnlyAndOtherDirtyMediaAreRefused() async throws { + let controller = VCCMachineController(); await setup(controller, cpu: false) + let data = Data(repeating: 0, count: 4096) + _ = await step { controller.mountHardDisk(data, drive: 0, name: "protected.vhd", readOnly: true, completion: $0) } + let (optional, _): (VCCDiskEditCapture?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.beginHardDiskEditor(inDrive: 0) { continuation.resume(returning: ($0, $1)) } + } + let edit = try XCTUnwrap(optional); XCTAssertFalse(edit.canApply) + let refused = await prepare(controller, edit.token, data); XCTAssertFalse(refused.0) + _ = await step { controller.cancelDiskEditor(token: edit.token, completion: $0) } + _ = await step { controller.hardDiskAction(1, drive: 0, completion: $0) } + _ = await step { controller.mountHardDisk(data, drive: 0, name: "writable.vhd", readOnly: false, completion: $0) } + _ = await step { controller.createHardDisk(inDrive: 1, size: 4096, completion: $0) } + let (second, _): (VCCDiskEditCapture?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in + controller.beginHardDiskEditor(inDrive: 0) { continuation.resume(returning: ($0, $1)) } + } + let dirtyRefusal = await prepare(controller, second!.token, data) + XCTAssertFalse(dirtyRefusal.0); XCTAssertTrue(dirtyRefusal.1.diskEditorLocked) + _ = await step { controller.cancelDiskEditor(token: second!.token, completion: $0) } + _ = await step(controller.shutdown) + } + @MainActor func testHardDiskModelTemporaryAutomaticExternalChangeAndAliases() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let disk = folder.appendingPathComponent("authored.vhd"), alias = folder.appendingPathComponent("alias.dsk") + let rom = folder.appendingPathComponent("authored.rom") + let data = Data(repeating: 0x11, count: 161280) + try data.write(to: disk); try FileManager.default.linkItem(at: disk, to: alias) + try Data(repeating: 0, count: 8192).write(to: rom) + let store = DiskAssignmentStore(url: folder.appendingPathComponent("settings.json")) + var settings = DiskAssignments(), hard = HardDiskAssignments() + settings.rom = rom; settings.drives[0] = .init(url: alias, writeProtected: false, temporary: true) + hard.drives[0] = .init(url: disk, writeProtected: false, temporary: true); settings.hardDisks = hard + try store.save(settings) + let conflictedModel = MachineModel(diskStore: store) + for _ in 0..<500 { if !conflictedModel.busy && !conflictedModel.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + XCTAssertEqual(conflictedModel.mountedHardDiskEditorDrive(for: alias), 0) + let conflicted = try await conflictedModel.beginHardDiskEditor(inDrive: 0) + XCTAssertFalse(conflicted.canApply) + try await conflictedModel.cancelDiskEditor(conflicted) + await withCheckedContinuation { continuation in conflictedModel.shutdown { continuation.resume() } } + settings.drives[0] = nil; try store.save(settings) + let model = MachineModel(diskStore: store) + for _ in 0..<500 { if !model.busy && !model.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + let temporary = try await model.beginHardDiskEditor(inDrive: 0) + XCTAssertTrue(temporary.hardDisk); XCTAssertTrue(temporary.canApply) + var edited = data; edited[1000] = 0x4a + try await model.applyDiskEditor(temporary, data: edited, restartConfirmed: true) + XCTAssertEqual(try Data(contentsOf: disk), data); XCTAssertTrue(model.hardDisks[0].dirty) + XCTAssertTrue(model.hardTemporary[0]) + let current = try await model.beginHardDiskEditor(inDrive: 0) + XCTAssertEqual(current.data, edited); try await model.cancelDiskEditor(current) + model.setHardTemporary(0, false) + for _ in 0..<500 { + if !model.busy && !model.diskSaving && !model.hardDisks[0].dirty { break } + try await Task.sleep(nanoseconds: 20_000_000) + } + XCTAssertFalse(model.hardDisks[0].dirty) + XCTAssertEqual(try Data(contentsOf: disk), edited, "Later automatic saving retains editor sector changes") + await withCheckedContinuation { continuation in model.shutdown { continuation.resume() } } + try data.write(to: disk, options: .atomic) + hard.drives[0] = .init(url: disk, writeProtected: false, temporary: false); settings.hardDisks = hard; try store.save(settings) + let automatic = MachineModel(diskStore: store) + for _ in 0..<500 { if !automatic.busy && !automatic.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + let session = try await automatic.beginHardDiskEditor(inDrive: 0) + var external = data; external[1001] = 0x7e; try external.write(to: disk, options: .atomic) + do { try await automatic.applyDiskEditor(session, data: edited, restartConfirmed: true); XCTFail("External bytes must survive") } + catch { XCTAssertTrue(automatic.diskEditorLocked) } + XCTAssertEqual(try Data(contentsOf: disk), external) + try await automatic.cancelDiskEditor(session) + let changed = try await automatic.beginHardDiskEditor(inDrive: 0); XCTAssertFalse(changed.canApply) + try await automatic.cancelDiskEditor(changed) + try data.write(to: disk, options: .atomic) + let fresh = try await automatic.beginHardDiskEditor(inDrive: 0) + try await automatic.applyDiskEditor(fresh, data: edited, restartConfirmed: true) + XCTAssertEqual(try Data(contentsOf: disk), edited); XCTAssertFalse(automatic.hardDisks[0].dirty) + let check = try await automatic.beginHardDiskEditor(inDrive: 0) + XCTAssertEqual(check.data, edited); try await automatic.cancelDiskEditor(check) + await withCheckedContinuation { continuation in automatic.shutdown { continuation.resume() } } + } + @MainActor func testModelHardLinkConflictTemporaryApplyAndExternalChange() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let disk = folder.appendingPathComponent("fixture.dsk"), alias = folder.appendingPathComponent("alias.dsk") + let rom = folder.appendingPathComponent("authored.rom") + try original.write(to: disk); try Data(repeating: 0, count: 8192).write(to: rom) + try FileManager.default.linkItem(at: disk, to: alias) + let store = DiskAssignmentStore(url: folder.appendingPathComponent("settings.json")) + var assignments = DiskAssignments(); assignments.rom = rom + assignments.drives[0] = .init(url: disk, writeProtected: false, temporary: true) + assignments.drives[1] = .init(url: alias, writeProtected: false, temporary: true) + try store.save(assignments) + let controller = VCCMachineController(); let model = MachineModel(diskStore: store, controller: controller) + for _ in 0..<500 { if !model.busy && !model.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + XCTAssertFalse(model.busy); XCTAssertEqual(model.mountedEditorDrive(for: alias), 0) + let conflicted = try await model.beginDiskEditor(inDrive: 0) + XCTAssertFalse(conflicted.canApply); XCTAssertNotNil(conflicted.applyRestriction) + try await model.cancelDiskEditor(conflicted) + XCTAssertEqual(try Data(contentsOf: disk), original) + await withCheckedContinuation { continuation in model.shutdown { continuation.resume() } } + assignments.drives[1] = nil; try store.save(assignments) + let second = MachineModel(diskStore: store) + for _ in 0..<500 { if !second.busy && !second.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + let editable = try await second.beginDiskEditor(inDrive: 0); XCTAssertTrue(editable.canApply) + var edited = original; edited[1000] = 0x6b + try await second.applyDiskEditor(editable, data: edited, restartConfirmed: true) + XCTAssertEqual(try Data(contentsOf: disk), original) + XCTAssertTrue(second.disks[0].dirty); XCTAssertTrue(second.diskTemporary[0]) + let check = try await second.beginDiskEditor(inDrive: 0); XCTAssertEqual(check.data, edited) + try await second.cancelDiskEditor(check) + // A changed host source becomes copy-only; its bytes must never be overwritten. + var external = original; external[1001] = 0x7c; try external.write(to: disk, options: .atomic) + let changed = try await second.beginDiskEditor(inDrive: 0); XCTAssertFalse(changed.canApply) + try await second.cancelDiskEditor(changed) + XCTAssertEqual(try Data(contentsOf: disk), external) + await withCheckedContinuation { continuation in second.shutdown { continuation.resume() } } + } + @MainActor func testAutomaticApplyUsesAtomicSourceCheckAndLeavesCleanMountedBytes() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let disk = folder.appendingPathComponent("fixture.dsk"), rom = folder.appendingPathComponent("authored.rom") + try original.write(to: disk); try Data(repeating: 0, count: 8192).write(to: rom) + let store = DiskAssignmentStore(url: folder.appendingPathComponent("settings.json")) + var assignments = DiskAssignments(); assignments.rom = rom + assignments.drives[0] = .init(url: disk, writeProtected: false, temporary: false); try store.save(assignments) + let model = MachineModel(diskStore: store) + for _ in 0..<500 { if !model.busy && !model.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + let session = try await model.beginDiskEditor(inDrive: 0) + var edited = original; edited[1000] = 0x45 + var external = original; external[1001] = 0x7e; try external.write(to: disk, options: .atomic) + do { try await model.applyDiskEditor(session, data: edited, restartConfirmed: true); XCTFail("External edits must be preserved") } + catch { XCTAssertTrue(model.diskEditorLocked) } + XCTAssertEqual(try Data(contentsOf: disk), external) + try await model.cancelDiskEditor(session) + try original.write(to: disk, options: .atomic) + let fresh = try await model.beginDiskEditor(inDrive: 0) + XCTAssertEqual(fresh.data, original, "A failed host write cannot replace mounted bytes") + try await model.applyDiskEditor(fresh, data: edited, restartConfirmed: true) + XCTAssertEqual(try Data(contentsOf: disk), edited); XCTAssertFalse(model.disks[0].dirty) + XCTAssertFalse(model.diskEditorLocked) + let current = try await model.beginDiskEditor(inDrive: 0); XCTAssertEqual(current.data, edited) + try await model.cancelDiskEditor(current) + await withCheckedContinuation { continuation in model.shutdown { continuation.resume() } } + } + + @MainActor func testFinderInsertionExecutionChoicesOnBothCPUs() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let disk = folder.appendingPathComponent("insert.dsk"), rom = folder.appendingPathComponent("authored.rom") + try original.write(to: disk); try Data(repeating: 0, count: 8192).write(to: rom) + for cpu in [false, true] { + let store = DiskAssignmentStore(url: folder.appendingPathComponent(UUID().uuidString + ".json")) + var assignments = DiskAssignments(); assignments.rom = rom; try store.save(assignments) + let controller = VCCMachineController(); let model = MachineModel(diskStore: store, controller: controller) + for _ in 0..<500 { if !model.busy && !model.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + _ = await step { controller.loadDiagnostic(use6309: cpu, completion: $0) } + for execution in DiskInsertionExecution.allCases { + for running in [false, true] { + let initial = await step(running ? controller.resume : controller.pause) + try await model.insertDiskFromMedia(disk, drive: 2, execution: execution) + let after = await step(controller.snapshot) + let shouldRun = execution == .run || (execution == .keepCurrentState && running) + XCTAssertEqual(after.state, shouldRun ? .running : .paused) + XCTAssertEqual(after.generation, initial.generation, "Insertion must not boot or reset the guest") + XCTAssertTrue(after.disks[2].mounted); XCTAssertEqual(after.disks[2].name, disk.lastPathComponent) + XCTAssertEqual(model.diskAssignments.drives[2]?.url, disk) + XCTAssertEqual(try Data(contentsOf: disk), original) + } + } + let invalid = folder.appendingPathComponent("missing.dsk") + let beforeInvalid = await step(controller.resume) + do { try await model.insertDiskFromMedia(invalid, drive: 2, execution: .pause, reset: .coldRestart); XCTFail("An unavailable disk must fail preflight before resetting") } + catch { } + let afterInvalid = await step(controller.snapshot) + XCTAssertEqual(afterInvalid.state, .running); XCTAssertEqual(afterInvalid.generation, beforeInvalid.generation) + XCTAssertEqual(model.diskAssignments.drives[2]?.url, disk) + _ = await step(controller.pause) + _ = await step { controller.createDisk(inDrive: 3, completion: $0) } + let beforeRefusal = await step(controller.resume) + do { try await model.insertDiskFromMedia(disk, drive: 2, execution: .run, reset: .coldRestart); XCTFail("Unsaved unrelated media must block replacement and reset") } + catch { } + let refused = await step(controller.snapshot) + XCTAssertEqual(refused.state, .paused); XCTAssertTrue(refused.disks[3].dirty) + XCTAssertEqual(refused.generation, beforeRefusal.generation) + XCTAssertEqual(model.diskAssignments.drives[2]?.url, disk) + await withCheckedContinuation { continuation in model.shutdown { continuation.resume() } } + } + } + + @MainActor func testFinderInsertionResetChoicesProtectRAMAndRespectExecutionOnBothCPUs() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let disk = folder.appendingPathComponent("insert.dsk"), invalid = folder.appendingPathComponent("malformed.dsk") + let rom = folder.appendingPathComponent("authored.rom") + try original.write(to: disk); try Data([1, 2, 3]).write(to: invalid) + try Data(repeating: 0, count: 8192).write(to: rom) + for cpu in [false, true] { + let store = DiskAssignmentStore(url: folder.appendingPathComponent(UUID().uuidString + ".json")) + var assignments = DiskAssignments(); assignments.rom = rom; try store.save(assignments) + let controller = VCCMachineController(); let model = MachineModel(diskStore: store, controller: controller) + for _ in 0..<500 { if !model.busy && !model.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + _ = await step { controller.loadDiagnostic(use6309: cpu, completion: $0) } + // A marker in ordinary guest RAM distinguishes retained RAM from a + // cold restart without depending on private ROM initialization. + func marker() async -> Data { + let memory: VCCDebugMemoryCapture = await withCheckedContinuation { continuation in + controller.debuggerMemory(address: 0x6000, count: 2, physical: false, logicalAddress: 0x6000, + os9: false, decode: false) { continuation.resume(returning: $0) } + } + return memory.bytes + } + let beforeInvalid = await step { controller.debuggerWriteMemory(address: 0x6000, data: Data([0xa5, 0x5a]), completion: $0) } + for reset in [DiskInsertionReset.softReset, .coldRestart] { + do { try await model.insertDiskFromMedia(invalid, drive: 2, execution: .pause, reset: reset); XCTFail("Malformed images must fail before reset") } + catch { } + let afterInvalid = await step(controller.snapshot) + XCTAssertEqual(afterInvalid.generation, beforeInvalid.generation) + XCTAssertFalse(afterInvalid.disks[2].mounted) + let bytes = await marker(); XCTAssertEqual(bytes, Data([0xa5, 0x5a])) + } + for reset in [DiskInsertionReset.softReset, .coldRestart] { + for execution in DiskInsertionExecution.allCases { + for running in [false, true] { + _ = await step(controller.pause) + _ = await step { controller.debuggerWriteMemory(address: 0x6000, data: Data([0xa5, 0x5a]), completion: $0) } + let initial = await step(running ? controller.resume : controller.pause) + try await model.insertDiskFromMedia(disk, drive: 2, execution: execution, reset: reset) + let after = await step(controller.snapshot) + let shouldRun = execution == .run || (execution == .keepCurrentState && running) + XCTAssertEqual(after.state, shouldRun ? .running : .paused) + XCTAssertEqual(after.generation, initial.generation + 1, "Exactly the selected reset precedes insertion") + XCTAssertTrue(after.disks[2].mounted); XCTAssertEqual(after.disks[2].name, disk.lastPathComponent) + XCTAssertEqual(model.diskAssignments.drives[2]?.url, disk) + _ = await step(controller.pause) + let bytes = await marker() + if reset == .softReset { XCTAssertEqual(bytes, Data([0xa5, 0x5a])) } + else { XCTAssertNotEqual(bytes, Data([0xa5, 0x5a])) } + } + } + } + XCTAssertEqual(try Data(contentsOf: disk), original) + await withCheckedContinuation { continuation in model.shutdown { continuation.resume() } } + } + } + + @MainActor func testEditorExportsProtectAssignedAliasesAndExternalChanges() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let disk = folder.appendingPathComponent("fixture.dsk"), alias = folder.appendingPathComponent("alias.dsk") + let rom = folder.appendingPathComponent("authored.rom"), export = folder.appendingPathComponent("export.txt") + try original.write(to: disk); try FileManager.default.linkItem(at: disk, to: alias) + try Data(repeating: 0, count: 8192).write(to: rom) + let store = DiskAssignmentStore(url: folder.appendingPathComponent("settings.json")) + var assignments = DiskAssignments(); assignments.rom = rom + assignments.drives[0] = .init(url: disk, writeProtected: false, temporary: true); try store.save(assignments) + let model = MachineModel(diskStore: store) + for _ in 0..<500 { if !model.busy && !model.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + XCTAssertTrue(model.diskEditorSourceIsAssigned(alias)) + XCTAssertFalse(model.diskEditorSourceIsAssigned(export)) + let session = try await model.beginDiskEditor(inDrive: 0) + do { try await model.saveDiskEditorExport(Data([1]), to: alias, protecting: nil); XCTFail("A mounted hard-link alias is protected") } catch { } + XCTAssertEqual(try Data(contentsOf: disk), original) + try await model.saveDiskEditorExport(Data(), to: export, protecting: disk, requireNew: true) + XCTAssertEqual(try Data(contentsOf: export), Data(), "Empty files must export without dropping the edit lease") + do { try await model.saveDiskEditorExport(Data([2]), to: export, protecting: disk, requireNew: true); XCTFail("A Finder promise cannot overwrite a later file") } catch { } + try Data([3]).write(to: export) + do { try await model.saveDiskEditorExport(Data([4]), to: export, protecting: disk, replacing: Data()); XCTFail("Changed export destination must be preserved") } catch { } + XCTAssertEqual(try Data(contentsOf: export), Data([3])) + XCTAssertTrue(model.diskEditorLocked); XCTAssertFalse(model.busy) + try await model.cancelDiskEditor(session) + var edited = original; edited[1000] = 0x71 + do { try await model.saveOfflineDiskEditor(edited, to: alias, replacing: original); XCTFail("Offline save cannot replace a mounted alias") } catch { } + XCTAssertEqual(try Data(contentsOf: disk), original) + await withCheckedContinuation { continuation in model.shutdown { continuation.resume() } } + } + + @MainActor func testNativeDiskOpenChoicesRetainOS9HardDiskDestinations() { + let floppy = DiskMediaOpenOptions(preferred: nil) + XCTAssertEqual(floppy.action.itemTitles, ["Edit Disk Image", "Insert into Floppy Drive"]) + XCTAssertFalse(floppy.drive.isEnabled); XCTAssertFalse(floppy.execution.isEnabled) + XCTAssertFalse(floppy.reset.isEnabled) + XCTAssertEqual(floppy.reset.itemTitles, ["No Reset", "Soft Reset", "Cold Restart"]) + XCTAssertEqual(floppy.reset.indexOfSelectedItem, 0) + floppy.action.selectItem(at: 1); floppy.update() + XCTAssertEqual(floppy.drive.itemTitles, ["FD0", "FD1", "FD2", "FD3"]) + XCTAssertTrue(floppy.execution.isEnabled) + XCTAssertTrue(floppy.reset.isEnabled) + let os9 = DiskMediaOpenOptions(preferred: .hardDisk(1), supportsHardDisk: true) + XCTAssertEqual(os9.action.itemTitles, ["Edit Disk Image", "Insert into Floppy Drive", "Insert into Hard Disk"]) + XCTAssertEqual(os9.action.indexOfSelectedItem, 2) + XCTAssertEqual(os9.drive.itemTitles, ["HD0", "HD1"]); XCTAssertEqual(os9.drive.indexOfSelectedItem, 1) + XCTAssertTrue(os9.drive.isEnabled); XCTAssertFalse(os9.execution.isEnabled) + XCTAssertFalse(os9.reset.isEnabled) + os9.action.selectItem(at: 1); os9.update() + os9.drive.selectItem(at: 3) + XCTAssertEqual(os9.drive.itemTitles, ["FD0", "FD1", "FD2", "FD3"]); XCTAssertTrue(os9.execution.isEnabled) + os9.action.selectItem(at: 2); os9.update() + XCTAssertEqual(os9.drive.indexOfSelectedItem, 1); XCTAssertFalse(os9.execution.isEnabled) + os9.action.selectItem(at: 1); os9.update() + XCTAssertEqual(os9.drive.indexOfSelectedItem, 3) + os9.action.selectItem(at: 0); os9.update() + XCTAssertFalse(os9.drive.isEnabled); XCTAssertFalse(os9.execution.isEnabled) + XCTAssertFalse(os9.reset.isEnabled) + } + + @MainActor func testOS9ImportReplacementRecognizesDifferentFilenameCase() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/OS9.dsk") + let original = try Data(contentsOf: fixture) + let store = try DiskImageEditorStore(data: original) + let contents = try await store.contents(at: "") + let machine = MachineModel(diskStore: DiskAssignmentStore(url: folder.appendingPathComponent("settings.json"))) + for _ in 0..<500 { if !machine.busy && !machine.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + let editor = DiskImageEditorModel(store: store, machine: machine, session: nil, sourceURL: nil, + name: "OS9.dsk", original: original, contents: contents, sourceReadOnly: false) + let host = folder.appendingPathComponent("readme.txt") + let replacement = Data("Case-varied replacement preserves one existing OS-9 entry.\r".utf8) + try replacement.write(to: host) + let needsReplacement = editor.importNeedsReplacement([host]) + XCTAssertTrue(needsReplacement, "The native replacement confirmation must recognize OS-9 filename casing") + XCTAssertFalse(editor.importNeedsReplacement([folder.appendingPathComponent("NEW.TXT")])) + let after = try await store.change(.importFiles([host], type: 3, ascii: true, replace: needsReplacement), path: "") + XCTAssertEqual(after.entries.count, contents.entries.count) + let result = try await store.read("README.TXT"); XCTAssertEqual(result, replacement) + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + @MainActor func testSaveEditedCopyRejectsNewAndChangedDestinationConflicts() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk") + let original = try Data(contentsOf: fixture) + let store = try DiskImageEditorStore(data: original) + let contents = try await store.contents(at: "") + let machine = MachineModel(diskStore: DiskAssignmentStore(url: folder.appendingPathComponent("settings.json"))) + for _ in 0..<500 { if !machine.busy && !machine.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + let editor = DiskImageEditorModel(store: store, machine: machine, session: nil, sourceURL: fixture, + name: "DECB.dsk", original: original, contents: contents, sourceReadOnly: false) + let destination = folder.appendingPathComponent("Edited.dsk") + let unrelated = Data("A file appeared after choosing the destination.".utf8) + try unrelated.write(to: destination) + do { try await editor.saveCopy(to: destination, replacing: nil); XCTFail("A new copy cannot overwrite a file that appeared later") } catch { } + XCTAssertEqual(try Data(contentsOf: destination), unrelated) + let changed = Data("The previously approved copy changed.".utf8) + try changed.write(to: destination) + do { try await editor.saveCopy(to: destination, replacing: unrelated); XCTFail("An externally changed destination must be preserved") } catch { } + XCTAssertEqual(try Data(contentsOf: destination), changed) + try await editor.saveCopy(to: destination, replacing: changed) + XCTAssertEqual(try Data(contentsOf: destination), contents.bytes) + XCTAssertEqual(try Data(contentsOf: fixture), original) + let newDestination = folder.appendingPathComponent("New Edited.dsk") + try await editor.saveCopy(to: newDestination, replacing: nil) + XCTAssertEqual(try Data(contentsOf: newDestination), contents.bytes) + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + + @MainActor func testDiskFilePromiseFactoryRetainsDelegateWithoutSubclass() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let source = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/OS9.dsk") + let bytes = try Data(contentsOf: source), store = try DiskImageEditorStore(data: bytes) + let initialContents = try await store.contents(at: "") + let entry = try XCTUnwrap(initialContents.entries.first) + let machine = MachineModel(diskStore: DiskAssignmentStore(url: folder.appendingPathComponent("settings.json"))) + for _ in 0..<500 { if !machine.busy && !machine.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + var provider: NSFilePromiseProvider? + weak var delegate: AnyObject? + autoreleasepool { + provider = DiskEditorFilePromise.make(bytes: bytes, entry: entry, machine: machine, sourceURL: source) + delegate = provider?.userInfo as AnyObject? + } + XCTAssertNotNil(delegate, "The ordinary provider must strongly retain its weak delegate through userInfo") + XCTAssertEqual(ObjectIdentifier(type(of: try XCTUnwrap(provider))), ObjectIdentifier(NSFilePromiseProvider.self)) + XCTAssertTrue((provider?.delegate as AnyObject?) === delegate) + XCTAssertEqual(provider?.delegate?.filePromiseProvider(try XCTUnwrap(provider), fileNameForType: provider!.fileType), "README.TXT") + autoreleasepool { provider = nil } + XCTAssertNil(delegate, "The delegate must not form a retain cycle with its provider") + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + + @MainActor func testDiskTablePasteboardPromiseExportsImmutableOS9BytesAfterFolderCreation() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/OS9.dsk") + let original = try Data(contentsOf: fixture), source = folder.appendingPathComponent("original.dsk") + try original.write(to: source) + let store = try DiskImageEditorStore(data: original) + let contents = try await store.change(.folder("DOCS"), path: "") + let machine = MachineModel(diskStore: DiskAssignmentStore(url: folder.appendingPathComponent("settings.json"))) + for _ in 0..<500 { if !machine.busy && !machine.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + let editor = DiskImageEditorModel(store: store, machine: machine, session: nil, sourceURL: source, + name: "original.dsk", original: original, contents: contents, sourceReadOnly: false) + let coordinator = DiskEditorFileTable.Coordinator(editor), table = NSTableView() + coordinator.rows = contents.entries + let fileRow = try XCTUnwrap(coordinator.rows.firstIndex { $0.name == "README.TXT" }) + let folderRow = try XCTUnwrap(coordinator.rows.firstIndex { $0.name == "DOCS" }) + XCTAssertNil(coordinator.tableView(table, pasteboardWriterForRow: folderRow)) + XCTAssertNil(coordinator.tableView(table, pasteboardWriterForRow: -1)) + let provider = try XCTUnwrap(coordinator.tableView(table, pasteboardWriterForRow: fileRow) as? NSFilePromiseProvider) + weak var retainedDelegate = provider.userInfo as AnyObject? + let pasteboard = NSPasteboard.withUniqueName() + defer { pasteboard.clearContents(); pasteboard.releaseGlobally() } + XCTAssertTrue(pasteboard.writeObjects([provider])) + XCTAssertFalse(provider.writableTypes(for: pasteboard).isEmpty) + XCTAssertFalse(try XCTUnwrap(pasteboard.pasteboardItems).isEmpty) + // The working image can change after dragging. The promised bytes must + // still belong to the original dragged snapshot, independent of the UI. + let changed = try await store.change(.delete([coordinator.rows[fileRow]]), path: "") + XCTAssertFalse(changed.entries.contains { $0.name == "README.TXT" }) + XCTAssertNotNil(retainedDelegate, "The provider must keep its snapshot delegate alive after serialization and subsequent edits") + let destination = folder.appendingPathComponent("Finder Drop", isDirectory: true) + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: false) + let exported = destination.appendingPathComponent("README.TXT") + let completed = expectation(description: "File promise fulfilled") + let delegate = try XCTUnwrap(provider.delegate) + // NSFilePromiseReceiver requires a genuine AppKit drag session. Exercise + // serialization above and the real asynchronous writer here; Finder's + // receiving side remains a separate desktop integration check. + delegate.filePromiseProvider(provider, writePromiseTo: exported) { error in + XCTAssertNil(error); completed.fulfill() + } + await fulfillment(of: [completed], timeout: 10) + XCTAssertEqual(try Data(contentsOf: exported), Data("VCC Plus authored Disk Image Editor fixture.\rDECB and OS-9 round trips preserve exact file bytes.\r".utf8)) + XCTAssertEqual(try Data(contentsOf: source), original) + XCTAssertEqual(try Data(contentsOf: fixture), original) + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + + @MainActor func testDiskFilePromiseRefusesSourceAliasesAndExistingDestinations() async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/OS9.dsk") + let original = try Data(contentsOf: fixture), source = folder.appendingPathComponent("original.dsk") + try original.write(to: source) + let alias = folder.appendingPathComponent("alias.dsk") + try FileManager.default.linkItem(at: source, to: alias) + let store = try DiskImageEditorStore(data: original) + let initialContents = try await store.contents(at: "") + let entry = try XCTUnwrap(initialContents.entries.first) + let machine = MachineModel(diskStore: DiskAssignmentStore(url: folder.appendingPathComponent("settings.json"))) + for _ in 0..<500 { if !machine.busy && !machine.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + let provider = DiskEditorFilePromise.make(bytes: original, entry: entry, machine: machine, sourceURL: source) + let delegate = try XCTUnwrap(provider.delegate) + for destination in [source, alias] { + let error: Error? = await withCheckedContinuation { continuation in + delegate.filePromiseProvider(provider, writePromiseTo: destination) { continuation.resume(returning: $0) } + } + XCTAssertNotNil(error) + XCTAssertEqual(try Data(contentsOf: destination), original) + } + let destination = folder.appendingPathComponent("README.TXT"), unrelated = Data("Keep this later file.".utf8) + try unrelated.write(to: destination) + let error: Error? = await withCheckedContinuation { continuation in + delegate.filePromiseProvider(provider, writePromiseTo: destination) { continuation.resume(returning: $0) } + } + XCTAssertNotNil(error) + XCTAssertEqual(try Data(contentsOf: destination), unrelated) + XCTAssertEqual(try Data(contentsOf: source), original) + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + @MainActor private func finishMoveEditorWork(_ editor: DiskImageEditorModel) async throws { + for _ in 0..<500 { + if !editor.busy { return } + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTFail("The disk editor did not finish its operation") + throw ProfileFailure.message("Disk editor test operation timed out") + } + @MainActor private func withMoveEditor(_ operation: @MainActor (MachineModel, DiskImageEditorModel, DiskImageEditorStore, URL) async throws -> Void) async throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/OS9.dsk") + let bytes = try Data(contentsOf: fixture), source = folder.appendingPathComponent("source.dsk") + try bytes.write(to: source) + let controller = VCCMachineController() + await setup(controller, cpu: false) + let mounted = await step { controller.mountDisk(bytes, drive: 0, name: "source.dsk", readOnly: false, completion: $0) } + XCTAssertNil(mounted.errorMessage) + let machine = MachineModel(diskStore: DiskAssignmentStore(url: folder.appendingPathComponent("settings.json")), controller: controller) + for _ in 0..<500 { if !machine.busy && !machine.diskSaving { break }; try await Task.sleep(nanoseconds: 20_000_000) } + let store = try DiskImageEditorStore(data: bytes) + let contents = try await store.change(.folder("DEST"), path: "") + let editor = DiskImageEditorModel(store: store, machine: machine, session: nil, sourceURL: source, + name: "source.dsk", original: bytes, contents: contents, sourceReadOnly: false) + let before = await step(controller.snapshot) + do { + try await operation(machine, editor, store, source) + XCTAssertEqual(try Data(contentsOf: source), bytes) + XCTAssertEqual(try Data(contentsOf: fixture), bytes) + let after = await step(controller.snapshot) + XCTAssertEqual(after.generation, before.generation); XCTAssertEqual(after.frames, before.frames) + let (mountedCopy, _) = await capture(controller) + XCTAssertEqual(mountedCopy?.data, bytes, "Private working edits cannot reach the mounted disk") + if let mountedCopy { _ = await step { controller.cancelDiskEditor(token: mountedCopy.token, completion: $0) } } + } catch { + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + throw error + } + await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } + } + + @MainActor func testMoveModelRejectsForeignEditedUndoneAndNavigatedRequests() async throws { + try await withMoveEditor { machine, editor, store, source in + let originalWorking = editor.contents.bytes + let entry = try XCTUnwrap(editor.contents.entries.first { $0.name == "README.TXT" }) + let request = try XCTUnwrap(editor.moveRequest(for: [entry])) + let otherStore = try DiskImageEditorStore(data: originalWorking) + let otherContents = try await otherStore.contents(at: "") + let other = DiskImageEditorModel(store: otherStore, machine: machine, session: nil, sourceURL: source, + name: "Same bytes, separate editor", original: originalWorking, contents: otherContents, sourceReadOnly: false) + XCTAssertFalse(other.moveSourceIsCurrent(request)) + other.move(request, to: "DEST") + XCTAssertNotNil(other.error); XCTAssertEqual(other.contents.bytes, originalWorking) + editor.change(.folder("NEW")); try await self.finishMoveEditorWork(editor) + XCTAssertNil(editor.error); XCTAssertFalse(editor.moveSourceIsCurrent(request)) + let edited = editor.contents.bytes + editor.move(request, to: "DEST") + XCTAssertNotNil(editor.error); XCTAssertEqual(editor.contents.bytes, edited) + editor.undo(); try await self.finishMoveEditorWork(editor) + XCTAssertNil(editor.error); XCTAssertEqual(editor.contents.bytes, originalWorking) + XCTAssertFalse(editor.moveSourceIsCurrent(request), "Undo must not resurrect an earlier request after an intervening edit") + let fresh = try XCTUnwrap(editor.moveRequest(for: [entry])) + editor.navigate("DEST"); try await self.finishMoveEditorWork(editor) + XCTAssertNil(editor.error); XCTAssertEqual(editor.path, "DEST") + XCTAssertFalse(editor.moveSourceIsCurrent(fresh)) + do { _ = try await editor.moveDestination(fresh, path: ""); XCTFail("A request from another displayed source folder must be refused") } catch { } + editor.move(fresh, to: "") + XCTAssertNotNil(editor.error) + let retained = try await store.contents(at: "") + XCTAssertEqual(retained.bytes, originalWorking) + XCTAssertTrue(retained.entries.contains { $0.name == "README.TXT" }) + } + } + + @MainActor func testMoveModelCollisionStaleDestinationAndSuccessfulUndoRedo() async throws { + try await withMoveEditor { _, editor, store, source in + let host = source.deletingLastPathComponent().appendingPathComponent("SECOND.DAT") + let payload = Data("Second file moves in the same transaction.\r".utf8) + try payload.write(to: host) + editor.change(.importFiles([host], type: 3, ascii: true, replace: false)); try await self.finishMoveEditorWork(editor) + editor.change(.folder("BUSY")); try await self.finishMoveEditorWork(editor) + let collision = source.deletingLastPathComponent().appendingPathComponent("readme.txt") + try Data("Keep the destination's existing file.".utf8).write(to: collision) + _ = try await store.change(.importFiles([collision], type: 3, ascii: true, replace: false), path: "BUSY") + editor.refresh(); try await self.finishMoveEditorWork(editor) + let before = editor.contents.bytes + let files = editor.contents.entries.filter { !$0.directory } + XCTAssertEqual(files.count, 2) + let request = try XCTUnwrap(editor.moveRequest(for: files)) + for destination in ["MISSING", "README.TXT", "BUSY"] { + editor.move(request, to: destination); try await self.finishMoveEditorWork(editor) + XCTAssertNotNil(editor.error); XCTAssertEqual(editor.contents.bytes, before) + let current = try await store.contents(at: "") + XCTAssertEqual(current.bytes, before, "An invalid destination or one collision must retain the entire batch") + } + let preview = try await editor.moveDestination(request, path: "DEST") + let changed = try await store.change(.folder("LATE"), path: "DEST") + editor.move(request, to: "DEST", expectedDestination: preview); try await self.finishMoveEditorWork(editor) + XCTAssertNotNil(editor.error) + let stillChanged = try await store.contents(at: "") + XCTAssertEqual(stillChanged.bytes, changed.bytes, "A stale destination preview cannot move either source file") + editor.refresh(); try await self.finishMoveEditorWork(editor) + let latest = editor.contents.bytes + let fresh = try XCTUnwrap(editor.moveRequest(for: editor.contents.entries.filter { !$0.directory })) + let freshDestination = try await editor.moveDestination(fresh, path: "DEST") + editor.move(fresh, to: "DEST", expectedDestination: freshDestination); try await self.finishMoveEditorWork(editor) + XCTAssertNil(editor.error); XCTAssertNotNil(editor.notice) + let moved = editor.contents.bytes + XCTAssertNotEqual(moved, latest) + XCTAssertFalse(editor.contents.entries.contains { !$0.directory }) + let readback = try await store.read("DEST/SECOND.DAT"); XCTAssertEqual(readback, payload) + editor.undo(); try await self.finishMoveEditorWork(editor) + XCTAssertNil(editor.error); XCTAssertEqual(editor.contents.bytes, latest) + editor.redo(); try await self.finishMoveEditorWork(editor) + XCTAssertNil(editor.error); XCTAssertEqual(editor.contents.bytes, moved) + let final = try await store.contents(at: "DEST") + XCTAssertEqual(Set(final.entries.map(\.name)), ["LATE", "README.TXT", "SECOND.DAT"]) + } + } + @MainActor func testOwnedMovePromiseAdvertisesPayloadBeforePasteboardSerialization() async throws { + try await withMoveEditor { machine, editor, _, source in + let entry = try XCTUnwrap(editor.contents.entries.first { $0.name == "README.TXT" }) + let request = try XCTUnwrap(editor.moveRequest(for: [entry])) + let payload = try JSONEncoder().encode(DiskEditorDragPayload(request)) + let ownedType = NSPasteboard.PasteboardType("com.brianholman.vccplus.disk-editor-files") + let pasteboard = NSPasteboard.withUniqueName() + defer { pasteboard.clearContents(); pasteboard.releaseGlobally() } + let plain = DiskEditorFilePromise.make(bytes: editor.contents.bytes, entry: entry, machine: machine, sourceURL: source) + // Construct the actual owned subtype, including its designated + // initializer, before any dragging callback could add a type. + let provider = DiskEditorFilePromise.make(bytes: editor.contents.bytes, entry: entry, machine: machine, + sourceURL: source, movePayload: payload) + weak var delegate = provider.userInfo as AnyObject? + let standardTypes = Set(plain.writableTypes(for: pasteboard)) + let ownedTypes = Set(provider.writableTypes(for: pasteboard)) + XCTAssertFalse(standardTypes.isEmpty) + XCTAssertFalse(standardTypes.contains(ownedType)) + XCTAssertTrue(ownedTypes.isSuperset(of: standardTypes), "Local move identity must retain all ordinary file-promise types") + XCTAssertTrue(ownedTypes.contains(ownedType)) + XCTAssertEqual(provider.pasteboardPropertyList(forType: ownedType) as? Data, payload) + XCTAssertEqual(provider.writingOptions(forType: ownedType, pasteboard: pasteboard), []) + for type in standardTypes { + XCTAssertEqual(provider.writingOptions(forType: type, pasteboard: pasteboard), plain.writingOptions(forType: type, pasteboard: pasteboard)) + } + XCTAssertTrue(pasteboard.writeObjects([provider])) + XCTAssertEqual(pasteboard.data(forType: ownedType), payload) + let serialized = try XCTUnwrap(pasteboard.pasteboardItems?.first) + XCTAssertTrue(Set(serialized.types).isSuperset(of: standardTypes)) + XCTAssertEqual(serialized.data(forType: ownedType), payload) + XCTAssertNotNil(delegate, "The payload provider retains its immutable export delegate through userInfo") + XCTAssertTrue((provider.delegate as AnyObject?) === delegate) + XCTAssertEqual(provider.delegate?.filePromiseProvider(provider, fileNameForType: provider.fileType), "README.TXT") + } + } + @MainActor func testConcurrentFilePromisesPreserveExistingDestinationAndCompleteRemainingExports() async throws { + try await withMoveEditor { machine, editor, store, source in + let entry = try XCTUnwrap(editor.contents.entries.first { $0.name == "README.TXT" }) + let snapshot = editor.contents.bytes + let count = 25 // 24 new exports plus one existing-destination refusal. + let providers = (0..