├── COPYING ├── README.md ├── examples ├── manual │ └── p106.ps ├── news │ ├── events.ps │ ├── p105.ps │ └── p87.ps └── wps │ ├── bowtie.ps │ ├── clock2.ps │ ├── fill.ps │ ├── heart.ps │ ├── rect.ps │ ├── smile.ps │ ├── squares.ps │ ├── squares2.ps │ ├── star.ps │ ├── tiger.eps │ └── triangles.ps ├── executive ├── index.html └── index.ts ├── index.org ├── lib ├── canvas.ts ├── context-transform.ts ├── corelib.ts ├── coroutine.ts ├── html5canvas.d.ts ├── index.ts ├── oop.ps ├── ps0.ts ├── stdlib.ps └── util.ts ├── package.json ├── test ├── basic.spec.ts ├── entry.js ├── examples.spec.ts └── index.html ├── tsconfig.json ├── typings.json └── webpack.config.js /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | See the [Executive page](http://dev.rsnous.com/dewdrop/executive/). 2 | -------------------------------------------------------------------------------- /examples/manual/p106.ps: -------------------------------------------------------------------------------- 1 | % Can't run automatically, since it doesn't terminate: 2 | % should print an event every 12 seconds. 3 | 4 | { 5 | createevent dup begin 6 | /Name /Hello def 7 | end expressinterest 8 | { 9 | awaitevent == 10 | createevent dup begin 11 | /Name /Hello def 12 | /TimeStamp currenttime 0.2 add def 13 | end sendevent 14 | } loop 15 | } fork 16 | 17 | createevent dup begin 18 | /Name /Hello def 19 | end sendevent 20 | 21 | waitprocess 22 | -------------------------------------------------------------------------------- /examples/news/events.ps: -------------------------------------------------------------------------------- 1 | { % Start defining a listener process. 2 | createevent dup begin 3 | /Name /Hello def 4 | end expressinterest 5 | { (awaiting) == awaitevent (awaited) == == } loop 6 | } fork % Fork the listener process. 7 | 8 | createevent dup begin 9 | /Name /Hello def 10 | /Action /Mumble def 11 | end sendevent % Send the /Hello event. The listener process will wake up and print it. 12 | 13 | createevent dup begin 14 | /Name /Goodbye def 15 | /Action /Mumble def 16 | end sendevent 17 | 18 | % Kill off the listener process -- 19 | % its process object has been on the stack all this time. 20 | killprocess 21 | -------------------------------------------------------------------------------- /examples/news/p105.ps: -------------------------------------------------------------------------------- 1 | /cv framebuffer newcanvas 2 | def 3 | framebuffer setcanvas 4 | 130 130 translate % Changed to fit in bounds of report canvas. 5 | 0 0 100 0 360 arc 6 | cv reshapecanvas 7 | cv /Mapped true put 8 | cv setcanvas 9 | erasepage 10 | { 11 | createevent dup begin 12 | /Canvas cv def 13 | /Name /LeftMouseButton def 14 | /Action /UpTransition def 15 | end expressinterest 16 | { 17 | awaitevent begin 18 | 0 0 moveto 19 | XLocation YLocation lineto stroke 20 | end 21 | } loop 22 | } fork 23 | -------------------------------------------------------------------------------- /examples/news/p87.ps: -------------------------------------------------------------------------------- 1 | /cv framebuffer newcanvas def 2 | framebuffer setcanvas 3 | 130 130 translate % Changed to fit in bounds of report canvas. 4 | 0 0 100 0 360 arc 5 | cv reshapecanvas 6 | cv /Mapped true put 7 | cv setcanvas 8 | erasepage 9 | 0 0 moveto 100 100 lineto stroke 10 | -------------------------------------------------------------------------------- /examples/wps/bowtie.ps: -------------------------------------------------------------------------------- 1 | % based on the JavaScript example from 2 | % https://developer.mozilla.org/en/drawing_graphics_with_canvas#section_6 3 | 4 | 0 0 180 180 .gbox 5 | 6 | /bowtie { % fillStyle -- 7 | 200 200 200 0.3 .rgba .setFillStyle 8 | -30 -30 60 60 rectfill 9 | .setFillStyle 1.0 .setGlobalAlpha 10 | newpath 11 | 25 25 moveto 12 | -25 -25 lineto 13 | 25 -25 lineto 14 | -25 25 lineto 15 | closepath 16 | fill 17 | } bind def 18 | 19 | /bowtieDot { % -- 20 | 0 0 0 setrgbcolor 21 | -2 -2 4 4 rectfill 22 | } bind def 23 | 24 | /bowtie1 { % fillStyle angle x y -- 25 | gsave 26 | translate 27 | rotate 28 | bowtie 29 | bowtieDot 30 | grestore 31 | } bind def 32 | 33 | 45 45 translate 34 | (red) 0 0 0 bowtie1 35 | (green) 45 85 0 bowtie1 36 | (blue) 135 0 85 bowtie1 37 | (yellow) 90 85 85 bowtie1 38 | -------------------------------------------------------------------------------- /examples/wps/clock2.ps: -------------------------------------------------------------------------------- 1 | % based on the PostScript example from 2 | % http://oreilly.com/openbook/cgi/ch06_02.html 3 | 4 | 0 0 150 150 .gbox 5 | 0 150 translate 6 | 1 -1 scale 7 | 8 | /max 150 def 9 | /width 1.5 def 10 | /marker 5 def 11 | /origin {0 0} def 12 | /center {max 2 div} bind def 13 | /radius /center load def 14 | /hsegment 0.50 radius mul def 15 | /msegment 0.80 radius mul def 16 | /ssegment 0.90 radius mul def 17 | 18 | /yellow {1 1 0 setrgbcolor} bind def 19 | /red {1 0 0 setrgbcolor} bind def 20 | /green {0 1 0 setrgbcolor} bind def 21 | /blue {0 0 1 setrgbcolor} bind def 22 | /black {0 0 0 setrgbcolor} bind def 23 | 24 | /hangle {/$h load 60 mul /$m load add 2 div neg .deg2rad} bind def 25 | /mangle {/$m load 6 mul neg .deg2rad} bind def 26 | /sangle {/$s load 6 mul neg .deg2rad} bind def 27 | 28 | /hand { % segment angle color width -- 29 | origin moveto 30 | width mul setlinewidth 31 | load exec 32 | 2 copy cos mul 33 | 3 1 roll sin mul 34 | lineto stroke 35 | } bind def 36 | 37 | /draw { 38 | /$h .date (getHours) 0 .call def 39 | /$m .date (getMinutes) 0 .call def 40 | /$s .date (getSeconds) 0 .call def 41 | gsave 42 | width setlinewidth 43 | black clippath fill % background 44 | center dup translate 45 | 90 rotate 46 | gsave % markers 47 | 12 { 48 | radius marker sub 0 moveto 49 | marker 0 rlineto red stroke 50 | 360 12 div rotate 51 | } repeat 52 | grestore 53 | newpath origin radius 0 360 arc blue stroke % circle 54 | hsegment hangle /green 2 hand % hour 55 | msegment mangle /green 1 hand % minute 56 | ssegment sangle /yellow 0.5 hand % second 57 | origin width 2 mul 0 360 arc red fill % dot 58 | grestore 59 | } bind def 60 | 61 | draw 62 | 63 | /timer false def 64 | /go {{draw} .callback 1000 .setInterval /timer exch def} bind def 65 | /halt {/timer load .clearTimeout /timer false def} bind def 66 | /callback {/timer load type (booleantype) eq {go} {halt} ifelse} bind def 67 | 68 | .gcanvas (onclick) /callback load .callback .hook 69 | -------------------------------------------------------------------------------- /examples/wps/fill.ps: -------------------------------------------------------------------------------- 1 | % based on the JavaScript example from 2 | % https://developer.mozilla.org/samples/canvas-tutorial/4_1_canvas_fillstyle.html 3 | 4 | /n 5 def 5 | /w 25 def 6 | 7 | 0 0 n w mul dup .gbox 8 | 9 | 4 dict begin 10 | 0 1 n { 11 | /i exch def 12 | /ii 1 1 n div i mul sub def 13 | 0 1 n { 14 | /j exch def 15 | /jj 1 1 n div j mul sub def 16 | ii jj 0 setrgbcolor 17 | w j mul w i mul w w rectfill 18 | } for 19 | } for 20 | end 21 | -------------------------------------------------------------------------------- /examples/wps/heart.ps: -------------------------------------------------------------------------------- 1 | % based on the JavaScript example from 2 | % https://developer.mozilla.org/samples/canvas-tutorial/2_6_canvas_beziercurveto.html 3 | 4 | 0 0 150 150 .gbox 5 | 6 | q 7 | 75 40 m 8 | 75 37 70 25 50 25 c 9 | 20 25 20 62.5 20 62.5 c 10 | 20 80 40 102 75 120 c 11 | 110 102 130 80 130 62.5 c 12 | 130 62.5 130 25 100 25 c 13 | 85 25 75 37 75 40 c 14 | f 15 | Q 16 | -------------------------------------------------------------------------------- /examples/wps/rect.ps: -------------------------------------------------------------------------------- 1 | 0 0 170 170 .gbox 2 | 3 | 1 0 0 1 80 80 cm 4 | 0 72 m 5 | 72 0 l 6 | 0 -72 l 7 | -72 0 l 8 | 4 w 9 | h S 10 | -------------------------------------------------------------------------------- /examples/wps/smile.ps: -------------------------------------------------------------------------------- 1 | % based on the JavaScript example from 2 | % http://developer.mozilla.org/samples/canvas-tutorial/2_2_canvas_moveto.html 3 | 4 | 0 0 150 150 .gbox 5 | 6 | %0 0 m % TODO m op meaning? 7 | newpath 8 | 75 75 50 0 360 arc % TODO pdf way to draw arc? 9 | S 10 | 110 75 m 11 | 75 75 35 0 180 arcn 12 | S 13 | 65 65 m 14 | 60 65 5 0 360 arc 15 | S 16 | 95 65 m 17 | 90 65 5 0 360 arc 18 | S 19 | -------------------------------------------------------------------------------- /examples/wps/squares.ps: -------------------------------------------------------------------------------- 1 | % based on the JavaScript example from 2 | % https://developer.mozilla.org/samples/canvas-tutorial/5_1_canvas_savestate.html 3 | 4 | 0 0 150 150 .gbox 5 | 6 | q 7 | 0 0 m 0 0 150 150 re f 8 | q 9 | 0 0.4 1 rg 10 | 0 0 m 15 15 120 120 re f 11 | q 12 | 1 1 1 rg 13 | 0.5 .setGlobalAlpha 14 | 0 0 m 30 30 90 90 re f 15 | Q 16 | 0 0 m 45 45 60 60 re f 17 | Q 18 | 0 0 m 60 60 30 30 re f 19 | Q 20 | -------------------------------------------------------------------------------- /examples/wps/squares2.ps: -------------------------------------------------------------------------------- 1 | % based on the JavaScript example from 2 | % https://developer.mozilla.org/en/drawing_graphics_with_canvas 3 | 4 | 0 0 100 100 .gbox 5 | 6 | q 7 | 0.8 0 0 rg 8 | 0 0 m 9 | 10 10 55 50 re 10 | f 11 | 0 0 0.8 rg 12 | 0.5 .setGlobalAlpha 13 | 0 0 m 14 | 30 30 55 50 re 15 | f 16 | Q 17 | -------------------------------------------------------------------------------- /examples/wps/star.ps: -------------------------------------------------------------------------------- 1 | % based on the PDF example from 2 | % http://www.adobe.com/technology/pdfs/presentations/KingPDFTutorial.pdf 3 | 4 | 0 0 100 100 .gbox 5 | 1 0 0 -1 0 100 cm 6 | 7 | q 8 | 0 0 1 rg 9 | 4 0 0 4 50 50 cm 10 | 0 5.5 m 11 | -4 -5.5 l 12 | 6 1 l 13 | -6 1 l 14 | 4 -5.5 l 15 | f 16 | Q 17 | -------------------------------------------------------------------------------- /examples/wps/triangles.ps: -------------------------------------------------------------------------------- 1 | % based on the PDF example from 2 | % https://developer.mozilla.org/samples/canvas-tutorial/2_3_canvas_lineto.html 3 | 4 | 0 0 150 150 .gbox 5 | 6 | 25 25 m 7 | 105 25 l 8 | 25 105 l 9 | f 10 | 11 | 125 125 m 12 | 125 45 l 13 | 45 125 l 14 | h 15 | S 16 | -------------------------------------------------------------------------------- /executive/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 27 | Dewdrop executive 28 | 29 | 30 | 31 | 32 | 33 |
34 | 35 | 36 | 37 |

Samples

38 | 39 |

Basic computation

40 |
> 2 3 add ==
 41 | 5
 42 | > (hello world) (putting stuff on stack) stack
 43 | hello world,putting stuff on stack
 44 | > exch stack
 45 | putting stuff on stack,hello world
 46 | 
47 | 48 |

Round window which draws line on each click (from The NeWS Book)

49 |
/cv framebuffer newcanvas def
 50 | framebuffer setcanvas
 51 | 130 130 translate
 52 | 0 0 100 0 360 arc
 53 | cv reshapecanvas
 54 | cv /Mapped true put
 55 | cv setcanvas
 56 | erasepage
 57 | {
 58 |   createevent dup begin
 59 |     /Canvas cv def
 60 |     /Name /LeftMouseButton def
 61 |     /Action /UpTransition def
 62 |   end expressinterest
 63 |   {
 64 |     awaitevent begin
 65 |       0 0 moveto
 66 |       XLocation YLocation lineto stroke
 67 |     end
 68 |   } loop
 69 | } fork
 70 | 
71 | 72 |

Other examples

73 |

74 | See 75 | 76 | basic tests (especially the Densmore OOP test), and 77 | 78 | examples. 79 | Check out the live test page. 80 |

81 | 82 |

References

83 | 84 | 98 | 99 |

About

100 | 101 |
102 | PostScript is the future of words on paper. 103 |
– attributed to Arthur C. Clarke
104 |
105 | 106 |

107 | Dewdrop is a work-in-progress reimplementation of Sun's 108 | 109 | NeWS 110 | (Network/extensible Window System) version 1.1, 111 | by Omar Rizwan. 112 | Its PostScript interpreter and standard library are based on 113 | Tom Hlavaty's WPS. 114 | It's licensed under the GPLv3. 115 | Source is on GitHub. 116 |

117 | 118 |

119 | NeWS is a window system and UI/graphics API based on a superset of Adobe's 120 | PostScript 121 | (a stack-based programming language made for printable graphics). NeWS adds interaction support, a UI 122 | toolkit, cooperative multitasking, and OOP on top of Adobe PostScript and its graphics model. 123 |

124 | 125 |

126 | NeWS was developed in the 1980s at Sun Microsystems and 127 | originally named "SunDew." (Many of the people behind NeWS ended up building Java.) 128 | NeWS was ahead of its time – 129 | 130 | proponents argue it was technically superior to the MIT X Window System that outcompeted it 131 | 132 | – and its design actually resembles the modern Web. (will add more here...) 133 |

134 | 135 |

136 | In the words of Don Hopkins: 137 |

138 | 139 |
140 | NeWS was architecturally similar to what is now called AJAX, except that NeWS: 141 |
    142 |
  • used PostScript code instead of JavaScript for programming.
  • 143 |
  • used PostScript graphics instead of DHTML/CSS for rendering.
  • 144 |
  • used PostScript data instead of XML/JSON for data representation.
  • 145 |
146 |
147 | 148 |

Aside

149 | 150 |

151 | Curiously, NeWS got to the same place as the modern Web, 152 | but took a very different path, decades earlier. 153 | The argument the NeWS Book makes for the NeWS architecture is basically 154 | a *compression* argument. 155 |

156 | 157 |

158 | Suppose we have two computers: one is a 'server', where logic runs, and one 159 | is a 'client' which sits on our desk. How can we build a window system where 160 | a graphical app runs remotely on the server, 161 | but we interact with it from our desk? 162 |

163 | 164 |

165 | One approach would be to stream full video of the screen from the server to 166 | our desk. Steam can do this. But that's bandwidth-intensive and hard to pull off 167 | if you're back in the 1980s. 168 |

169 | 170 |

171 | Another approach, which is taken (in theory) by the X Window System when you 172 | do `ssh -X`, is to come up with a basic set of objects, like buttons and 173 | text boxes, and have the server stream a display list of all the objects to the client. 174 | If you do this, however, then your objects are frozen in stone and 175 | might not be what applications want to use -- what if they want to have a custom UI, 176 | or what if your system button style just looks ugly? -- and if an application 177 | draws its own stuff, you end up streaming that custom stuff pixel by pixel 178 | anyway. 179 |

180 | 181 |

182 | NeWS asks: why do we need to send flat lists at all, 183 | whether of pixels or of higher-level display 184 | objects? Our client is a full-fledged computer. Why not send a small *program* 185 | from the server to the client, and let that program draw whatever it wants on the client? 186 |

187 | 188 |

189 | In fact, Adobe built PostScript to solve a very similar problem: 190 | your Mac could send your LaserWriter printer a compact PostScript program describing the pages to print, 191 | and the LaserWriter would interpret the program on its own CPU. 192 | (A faster CPU 193 | than the original Mac's CPU, by the way.) 194 |

195 | 196 | 197 | 198 | -------------------------------------------------------------------------------- /executive/index.ts: -------------------------------------------------------------------------------- 1 | import Dewdrop from '../lib/index'; 2 | import * as $ from 'jquery'; 3 | 4 | (window as any).jQuery = $; 5 | 6 | import 'jq-console'; 7 | 8 | (async function() { 9 | const framebuffer = $('#framebuffer')[0] as HTMLCanvasElement; 10 | 11 | const con = ($('#console') 12 | .appendTo(document.body) 13 | .css({ 14 | width: 640, 15 | height: 300, 16 | position: 'relative', 17 | background: 'whitesmoke' 18 | }) as any) 19 | .jqconsole('Dewdrop executive\n', '> ', '', false); 20 | 21 | const dewdrop = await Dewdrop(framebuffer, function log(arg) { 22 | console.log(arg); 23 | con.Write(arg + '\n', 'jqconsole-log'); 24 | }); 25 | 26 | (function startPrompt() { 27 | con.Prompt(true, async function(input) { 28 | try { 29 | await dewdrop.parse(input); 30 | } catch (e) { 31 | con.Write(e + '\n', 'jqconsole-error'); 32 | } 33 | startPrompt(); 34 | }); 35 | })(); 36 | })(); 37 | -------------------------------------------------------------------------------- /index.org: -------------------------------------------------------------------------------- 1 | #+title: WPS: PostScript for the Web 2 | #+description: PostScript and PDF interpreter for HTML 5 canvas 3 | #+keywords: PostScript, PDF, interpreter, HTML 5, canvas, JavaScript 4 | #+options: num:nil toc:t 5 | #+macro: ps [[http://www.capcode.de/help/$1][$1]] 6 | 7 | #+begin_html 8 |

WPS: PostScript for the Web

9 | #+end_html 10 | 11 | Welcome to WPS, a PostScript and PDF interpreter for HTML 5 canvas. 12 | 13 | Note that to see and run the examples, JavaScript must be enabled and 14 | your browser must support HTML 5 canvas (latest Firefox, Opera and 15 | Chrome should work). 16 | 17 | This document allows you to try simple PostScript programs in the WPS 18 | sandbox. A few examples are presented here accompanied by a brief 19 | description of the interpreter and listing some implementation notes 20 | for my future reference. 21 | 22 | #+begin_html 23 | 27 | #+end_html 28 | 29 | #+html: 32 | 33 | #+begin_html 34 | 35 | 41 | #+end_html 42 | 43 | * WPS sandbox 44 | 45 | #+begin_html 46 | 47 |

Sandbox:

48 |

49 | 68 |

69 | 72 | code from sandbox. 73 | #+end_html 74 | 75 | * PostScript interpreter 76 | 77 | A few initial ideas and questions: 78 | 79 | - Learn and implement a Forth like language. PostScript seems like a 80 | good choice: 81 | - It has the right syntax and stack based evaluation. 82 | - It is practical and widely used. 83 | - It has long sucessful history in print and publishing (and more). 84 | - It is a predecessor of PDF. 85 | - Almost everything (e.g. editors, pictures, documentation) can be 86 | reused to a great extent. 87 | - It is ideal for HTML 5 canvas experiments because from the 88 | PostScript point of view, canvas is just another low level device. 89 | - Flexibility and simplicity first. 90 | - Optimize for fast code change, not for raw running speed. Keep 91 | the code small and regular if possible. 92 | - Can JavaScript be used as a portable assembler for the Web? Is 93 | building scripting languages on top of JavaScript feasible and 94 | efficient enough for real-world use? If not, why? Find the 95 | limits. 96 | - Keep the language/environment specific core as small as possible. 97 | - Allow to port the interpreter to other languages on both 98 | client and server side. 99 | - Be open for the possibility of running "the same code" on both the 100 | client and server side. 101 | - Can PDF documents be displayed in web browsers without server-side 102 | image rendering? 103 | - Implement a canvas based version of PDF page contents in [[../ondoc/index.org][OnDoc]]. 104 | - It might be possible to implement different backend devices to be 105 | used instead of HTML 5 canvas, for example an SVG device. 106 | - Investigate the possibility of implementing a Lisp interpreter 107 | suitable for production use in web applications. 108 | 109 | There are several things WPS is about: 110 | 111 | - stack(s) 112 | - function (operator) dictionary 113 | - reader 114 | - interpreter/evaluator 115 | - data types 116 | - native bindings (JavaScript FFI) 117 | - PostScript and PDF API 118 | 119 | [[http://en.wikipedia.org/wiki/PostScript][PostScript]] can be seen as a crossover between [[http://en.wikipedia.org/wiki/Forth_(programming_language)][Forth]] and [[http://en.wikipedia.org/wiki/LISP][Lisp]] 120 | programming languages. It is (roughly) a programming language with 121 | [[http://en.wikipedia.org/wiki/Reverse_Polish_notation][RPN]], complex data types, garbage collection and specialized 122 | drawing operators. 123 | 124 | ** Trivial example 125 | 126 | The core essence of a RPN calculator is captured in the JavaScript 127 | code bellow. 128 | 129 | #+html:
130 | #+begin_src js2 131 | function example1() { 132 | // define stack and operators 133 | var Os = []; 134 | var Sd = {}; 135 | Sd["+"] = function() {Os.push(Os.pop() + Os.pop());}; 136 | Sd["="] = function() {alert(Os.pop());}; 137 | // compute 1 2 = 3 + = 138 | Os.push(1); 139 | Os.push(2); 140 | Sd["="](); 141 | Os.push(3); 142 | Sd["+"](); 143 | Sd["="](); 144 | } 145 | #+end_src 146 | #+html:
147 | #+begin_html 148 | 154 | 155 | "1 2 = 3 + =" 156 | #+end_html 157 | 158 | =Os= stands for Operand Stack, which holds arguments for operators. 159 | =Sd= is a System Dictionary which contains definitions of operators 160 | (JavaScript functions in this case). 161 | 162 | ** Example with PostScript reader 163 | 164 | PostScript has simple but non-trivial syntax so a reader which reads 165 | text and creates internal PostScript objects is necessary. The reader 166 | and evaluator is called =Ps0= (an empty PostScript interpreter) in the 167 | JavaScript code bellow. 168 | 169 | #+html:
170 | #+begin_src js2 171 | function example2(T) { 172 | var Os = []; 173 | var Sd = {}; 174 | var Ds = [Sd]; 175 | var Es = []; 176 | Sd[new Symbol("+")] = function() {Os.push(Os.pop() + Os.pop());}; 177 | Sd[new Symbol("dup")] = function() {var X = Os.pop(); Os.push(X); Os.push(X);}; 178 | Sd[new Symbol("=")] = function() {alert(Os.pop());}; 179 | (new Ps0(Os, Ds, Es)).parse(T); // read and interpret code T 180 | } 181 | #+end_src 182 | #+html:
183 | #+begin_html 184 | 190 | 191 | "12 34 + dup = 56 + =" 192 | #+end_html 193 | 194 | =Ds= is a Dictionary Stack allowing users to redefine existing 195 | operators and revert back to the original ones. =Es= is an Execution 196 | Stack which is used to implement a tail recursive evaluator. 197 | 198 | ** Example with recursion 199 | 200 | It is possible to write recursive code in PostScript. The following 201 | PostScript code is from the [[http://www.math.ubc.ca/~cass/graphics/manual/pdf/ch9.pdf][Recursion in PostScript PDF document]]. 202 | 203 | #+html:
204 | #+begin_src ps 205 | /factorial1 { 206 | 1 dict begin 207 | /n exch def 208 | n 0 eq {1}{n n 1 sub factorial1 mul} ifelse 209 | end 210 | } def 211 | 212 | 5 factorial1 = 213 | 214 | /factorial2 { 215 | dup 0 eq {pop 1}{dup 1 sub factorial2 mul} ifelse 216 | } def 217 | 218 | 5 factorial2 = 219 | 220 | % based on the PostScript example from 221 | % http://partners.adobe.com/public/developer/en/ps/sdk/sample/BlueBook.zip 222 | 223 | /factorial3 { 224 | dup 1 gt {dup 1 sub factorial3 mul} if 225 | } def 226 | 227 | 5 factorial3 = 228 | #+end_src 229 | #+html:
230 | #+begin_html 231 | 234 | the example. 235 | #+end_html 236 | 237 | ** Execution stack 238 | 239 | The interpreter manages its Execution Stack explicitly. 240 | 241 | Most operators simply: 242 | 243 | 1. get their arguments from the Operand Stack 244 | 2. perform some computation and/or side effects 245 | 3. push results to the Operand Stack 246 | 247 | Some operators are more complex and involve some kind of control flow, 248 | e.g. {{{ps(if)}}}, {{{ps(repeat)}}}, {{{ps(for)}}}, {{{ps(loop)}}} 249 | operators. Such operators: 250 | 251 | 1. get their arguments from the Operand Stack 252 | 2. perform single step of some computation and/or side effects 253 | 3. push the continuation (code and arguments to be executed next) to 254 | the Execution Stack 255 | 256 | [[http://en.wikipedia.org/wiki/Tail_call][Tail Call Optimisation]] is implemented using [[http://logand.com/picoWiki/trampoline][trampoline]]. The evaluator 257 | runs in a loop getting the next [[http://en.wikipedia.org/wiki/Continuation][continuation]] from the Execution Stack. 258 | Operators that want to "continue" their execution (i.e. use the 259 | interpreter to run other operators, including themselves) must perform 260 | only one step at a time and save the remaining steps (continuation) on 261 | the Execution Stack. 262 | 263 | For example, the {{{ps(if)}}} operator saves the "then" or "else" code 264 | branch to the Execution Stack depending on the value of the "test" 265 | argument. It does not "evaluate" the chosen branch directly 266 | (recursively) but leaves the control to the evaluator loop. 267 | 268 | The whole process of interpreting is fed from JavaScript strings which 269 | are obtained from the content of HTML elements (sometimes hidden from 270 | this document). 271 | 272 | ** PostScript data types 273 | 274 | PostScript has quite rich set of data types. 275 | See [[http://www.adobe.com/devnet/postscript/pdfs/PLRM.pdf][PostScript Language Reference PDF document]] for more details. 276 | 277 | | category | type | executable | example | spec | 278 | |-----------+-------------+------------+------------------------+--------------------| 279 | | simple | boolean | | true false | | 280 | | | fontID | | | | 281 | | | integer | | 42 -123 0 | | 282 | | | mark | | | | 283 | | | name | Y | draw /draw | | 284 | | | null | | null | | 285 | | | operator | Y | | | 286 | | | real | | 3.14 1e-10 | | 287 | | | save | | | | 288 | | composite | array | Y | [1 /hi 3.14] {1 2 add} | | 289 | | | condition | | | Display PostScript | 290 | | | dictionary | | <> | | 291 | | | file | | | | 292 | | | gstate | | | Level 2 | 293 | | | lock | | | Display PostScript | 294 | | | packedarray | | | Level 2 | 295 | | | string | Y | (hi) | | 296 | 297 | The following data types are implemented in WPS: 298 | 299 | | category | type | direct | literal | executable | 300 | |-----------+------------+--------+---------+------------| 301 | | simple | boolean | Y | Y | - | 302 | | | number | Y | Y | - | 303 | | | mark | - | Y | - | 304 | | | name | - | Y | Y | 305 | | | null | Y | Y | - | 306 | | | operator | Y | - | Y | 307 | | composite | array | Y | Y | - | 308 | | | proc | - | - | Y | 309 | | | dictionary | Y | Y | - | 310 | | | string | Y | Y | - | 311 | 312 | All the above types are represented directly in JavaScript except: 313 | 314 | | type | representation | 315 | |-----------------+-----------------| 316 | | mark | unique object | 317 | | literal name | quoted symbol | 318 | | executable name | unquoted symbol | 319 | | operator | function | 320 | | proc | quoted array | 321 | 322 | The interpreter needs to understand when to evaluate an argument. The 323 | distinction between a "literal" and "executable" is the key. For the 324 | "proc" type, its origin from the Execution Stack is also important. 325 | 326 | ** Quoting and execution 327 | 328 | There are two important operators to control evaluation at the 329 | PostScript language level. 330 | 331 | The {{{ps(exec)}}} operator usually leaves the argument as is except: 332 | 333 | | type | result | 334 | |-----------------+-------------------| 335 | | executable name | exec value | 336 | | operator | apply operator | 337 | | proc | exec each element | 338 | 339 | The {{{ps(cvx)}}} operator makes the argument "executable". Usually 340 | leaves the argument as is except: 341 | 342 | | from | to | how | 343 | |--------------+-----------------+---------| 344 | | literal name | executable name | unquote | 345 | | array | proc | quote | 346 | | string | proc | ~ parse | 347 | 348 | The ~ (tilde) character in the above table means that the 349 | functionality has not been implemented yet. 350 | 351 | * Drawing with PostScript 352 | 353 | As a convention, operators beginning with dot are non-standard, low 354 | level operators which are subject to change. 355 | 356 | There is a difference in how HTML 5 canvas, PostScript and PDF measure 357 | angles: 358 | 359 | | language/device | unit | 360 | |-----------------+------| 361 | | canvas | rad | 362 | | PostScript | deg | 363 | | PDF | rad | 364 | 365 | Many of the examples below set up their bounding box using the 366 | =.gbox= operator, e.g. 367 | 368 | #+begin_src ps 369 | 0 0 180 180 .gbox 370 | #+end_src 371 | 372 | Only the width and height of the canvas clipping rectangle are taken 373 | into account so far. The width and height is related to the drawing 374 | units rather than to the size of the canvas element. 375 | 376 | Both PostScript and PDF documents have the origin of the coordinate 377 | system in the bottom left corner while HTML 5 canvas in the top left 378 | corner. Thus, some of the following pictures are displayed upside 379 | down unless an explicit coordinate transformation was added. This 380 | discrepancy between the origin of the coordinate system is a problem 381 | when drawing text because a simple coordinate transformation on its 382 | own would draw the text upside-down. 383 | 384 | ** Bowtie example 385 | 386 | See the [[https://developer.mozilla.org/en/drawing_graphics_with_canvas#section_6][original example]] in JavaScript. 387 | 388 | #+html: 389 | #+html:
390 | #+include "bowtie.wps" src ps 391 | #+html:
392 | #+html: 393 | 394 | ** Analog clock example 395 | 396 | See the [[http://oreilly.com/openbook/cgi/ch06_02.html][original example]]. 397 | 398 | Click on the clock to start/stop it. (If using Chrome, you might need 399 | to reload the page for this to work. Not sure why?) 400 | 401 | #+html: 402 | 403 | #+html:
404 | #+include "clock2.wps" src ps 405 | #+html:
406 | #+html: 407 | 408 | Running the clock keeps the CPU noticeably busy. Chrome is best with 409 | very little overhead. Firefox and Opera perform significantly worse. 410 | WPS seems to be fast enough for one-off drawings, but its usability 411 | depends on the efficiency of the host JavaScript interpreter when 412 | running the interpreter in a tight loop. 413 | 414 | ** Fill example 415 | 416 | See the [[https://developer.mozilla.org/samples/canvas-tutorial/4_1_canvas_fillstyle.html][original example]] in JavaScript. 417 | 418 | #+html: 419 | #+html:
420 | #+include "fill.wps" src ps 421 | #+html:
422 | #+html: 423 | 424 | ** Tiger example 425 | 426 | The [[http://svn.ghostscript.com/viewvc/trunk/gs/examples/tiger.eps?view=co][original example]] is included with [[http://ghostscript.com/][Ghostscript]]. 427 | 428 | #+begin_html 429 | 430 | 431 |

Drawing took -- seconds.

432 | #+end_html 433 | 434 | #+html: 437 | 438 | #+begin_html 439 | 445 | 446 | 450 | 451 | 454 | the tiger (be patient). 455 | #+end_html 456 | 457 | Is this an interesting JavaScript and canvas benchmark? 458 | 459 | #+plot: title:"tiger.eps drawing times" ind:1 deps:(2 3 4) type:2d with:histograms set:"yrange [0:]" set:"xlabel 'browser'" set:"ylabel 'time [s]'" set:"style histogram gap 3" file:"tiger.png" set:"term png size 600, 300" 460 | | browser | WPS time [s] | WPS time (no bind) [s] | PostCanvas time [s] | 461 | |-------------+--------------+------------------------+---------------------| 462 | | Chrome | 2.7 | 4.1 | 1.6 | 463 | | Opera | 17.9 | 12.3 | 0 | 464 | | Firefox 3.0 | 21.0 | 19.0 | 7.0 | 465 | | Firefox 3.5 | 13.0 | 9.5 | 3.3 | 466 | | Safari | 2.9 | 0 | 0 | 467 | 468 | The above times were on Vaio T7200 Core 2 2GHz 2GB running Ubuntu. 469 | 470 | [[http://www.feiri.de/pcan/][PostCanvas]] runs this [[http://www.feiri.de/pcan/example1.html][example]] about 1.5 times (Chrome) to 3 times 471 | (Firefox) faster. I am actually surprised that WPS runs only about 472 | 1.5 times slower in Chrome even though it interprets almost everything 473 | with minimal number of operators coded directly in JavaScript 474 | (compared to PostCanvas which implements all operators directly in 475 | JavaScript). Time for Safari was reported by Will King and even 476 | though it was not run on the same machine as the other tests, it shows 477 | that the speed is comparable to Chrome. 478 | 479 | Another surprise to me is that I expected more significant speed up 480 | after implementing the {{{ps(bind)}}} operator. Why does Opera and 481 | Firefox get slower in this case? 482 | 483 | It should be fairly easy to speed WPS up by coding more operators 484 | directly in JavaScript. The speed of PostCanvas could probably be 485 | taken as the best case that could be achieved by optimizing WPS. 486 | 487 | file:tiger.png 488 | 489 | Note by Dave Chapman: 490 | 491 | #+begin_quote 492 | 493 | I've found that reducing the number of function calls in complex 494 | scripts has by far the biggest gains in speed - but I guess you 495 | already know this. For instance, when I run the Tiger demo it takes 496 | about 19sec on my machine (FF3.0, dual core, 4gb ram) but according to 497 | the firebug profiler it's making nearly 4 million function calls (as a 498 | comparison PostCanvas is *only* making about 220,000 calls). 499 | 500 | #+end_quote 501 | 502 | Note by Ray Johnson: 503 | 504 | #+begin_quote 505 | 506 | Tested Safari 4.0.4 (Win) and Firefox 3.5.5 (Win): 507 | 508 | - Safari 4.0.4 Tiger drawing time = 1.76 509 | - Firefox 3.5.5 Tiger drawing time = 6.945 510 | 511 | I’m on a Dell T7400 Xeon Quad Core 3.0 GHz with 4GB Ram and Vista SP2 32 Bit-and 512 | 513 | #+end_quote 514 | 515 | Firefox throws error about linecap and linejoin not being supported so 516 | these were not used here. Opera throws an error when running the 517 | PostCanvas example. The tiger does not look the same as rendered by 518 | [[http://projects.gnome.org/evince/][Evince]] ([[http://poppler.freedesktop.org/][poppler]]/[[http://cairographics.org/][cairo]]) so maybe the linecap and linejoin are 519 | really needed to get proper image as intended. 520 | 521 | It is also interesting to observe that PDF operators and their names 522 | probably came up from shortening/compressing common "user-space" 523 | PostScript operators in PostScript files. The tiger.eps file was 524 | created in 1990 and contains some "shortcuts" that match PDF operators 525 | standardised later. 526 | 527 | * Drawing with PDF 528 | 529 | PDF is rather complex format. WPS aims to implement only drawing 530 | operators that can be present in PDF content streams. The number of 531 | these operators is fixed and limited. Even though the full PostScript 532 | language is not required, it can be convenient to implement them in 533 | PostScript. 534 | 535 | However, some aspects (e.g. colors) are handled differently in PDF 536 | compared to PostScript and these differences are not addressed by WPS. 537 | I imagine that a supporting server-side solution like [[../ondoc/index.org][OnDoc]] would 538 | provide necessary data (e.g. decomposing PDF into pages and objects, 539 | providing HTML 5 web fonts and font metrics) and WPS would only draw 540 | preprocessed page content. 541 | 542 | Quoting from [[http://www.adobe.com/print/features/psvspdf/index.html][Adobe]]: 543 | 544 | #+begin_quote 545 | A PDF file is actually a PostScript file which has already been 546 | interpreted by a RIP and made into clearly defined objects. 547 | #+end_quote 548 | 549 | ** Heart example 550 | 551 | See also the [[https://developer.mozilla.org/samples/canvas-tutorial/2_6_canvas_beziercurveto.html][original example]] in JavaScript. 552 | 553 | #+html: 554 | #+html:
555 | #+include "heart.wps" src ps 556 | #+html:
557 | #+html: 558 | 559 | ** Rectangle example 560 | 561 | TODO find the original example 562 | 563 | #+html: 564 | #+html:
565 | #+include "rect.wps" src ps 566 | #+html:
567 | #+html: 568 | 569 | ** Triangles example 570 | 571 | See also the [[https://developer.mozilla.org/samples/canvas-tutorial/2_3_canvas_lineto.html][original example]] in JavaScript. 572 | 573 | #+html: 574 | #+html:
575 | #+include "triangles.wps" src ps 576 | #+html:
577 | #+html: 578 | 579 | ** Smile example 580 | 581 | See also the [[http://developer.mozilla.org/samples/canvas-tutorial/2_2_canvas_moveto.html][original example]] in JavaScript. 582 | 583 | #+html: 584 | #+html:
585 | #+include "smile.wps" src ps 586 | #+html:
587 | #+html: 588 | 589 | ** Star example 590 | 591 | See also the [[http://www.adobe.com/technology/pdfs/presentations/KingPDFTutorial.pdf][original PDF document]] where this example is presented. 592 | 593 | #+html: 594 | #+html:
595 | #+include "star.wps" src ps 596 | #+html:
597 | #+html: 598 | 599 | ** Squares example 600 | 601 | See also the [[https://developer.mozilla.org/samples/canvas-tutorial/5_1_canvas_savestate.html][original example]] in JavaScript. 602 | 603 | #+html: 604 | #+html:
605 | #+include "squares.wps" src ps 606 | #+html:
607 | #+html: 608 | 609 | ** Two squares example 610 | 611 | See also the [[https://developer.mozilla.org/en/drawing_graphics_with_canvas][original example]] in JavaScript. 612 | 613 | #+html: 614 | #+html:
615 | #+include "squares2.wps" src ps 616 | #+html:
617 | #+html: 618 | 619 | * Operators and JavaScript bindings 620 | 621 | WPS implements a minimum core in JavaScript and the rest is 622 | implemented in PostScript itself. 623 | 624 | Many JavaScript data types map quite easily to PostScript data types 625 | so native bindings can be implemented mostly in PostScript via 626 | PostScript dictionaries (JavaScript objects). [[http://www.whatwg.org/specs/web-apps/current-work/#the-canvas-element][HTML 5 canvas API]] 627 | bindings are quite straightforward. 628 | 629 | ** Native operators 630 | 631 | | category | in | operator | out | 632 | |----------------+------------------------+-----------------------+-----------------------------------------------------| 633 | | Trivial | | {{{ps(true)}}} | true | 634 | | | | {{{ps(false)}}} | false | 635 | | | | {{{ps(null)}}} | null | 636 | | Math | x y | {{{ps(sub)}}} | x-y | 637 | | | x y | {{{ps(mul)}}} | x*y | 638 | | | x y | {{{ps(div)}}} | x/y | 639 | | | x y | {{{ps(mod)}}} | x%y | 640 | | Stack | | {{{ps(mark)}}} | mark | 641 | | | | {{{ps(counttomark)}}} | n | 642 | | | x y | {{{ps(exch)}}} | y x | 643 | | | ... | {{{ps(clear)}}} | | 644 | | | x | {{{ps(pop)}}} | | 645 | | | x_n ... x_0 n | {{{ps(index)}}} | x_n ... x_0 x_n | 646 | | | x_(n-1) ... x_0 n j | {{{ps(roll)}}} | x_((j-1) mod n) ... x_0 ... x_(n-1) ... x_(j mod n) | 647 | | | x_1 ... x_n n | {{{ps(copy)}}} | x_1 ... x_n x_1 ... x_n | 648 | | Array | array | {{{ps(length)}}} | n | 649 | | | x_n ... x_0 array | {{{ps(astore)}}} | array | 650 | | | n | {{{ps(array)}}} | array | 651 | | Conditionals | x y | {{{ps(eq)}}} | bool | 652 | | | x y | {{{ps(lt)}}} | bool | 653 | | Control | bool then else | {{{ps(ifelse)}}} | | 654 | | | n proc | {{{ps(repeat)}}} | | 655 | | | i j k proc | {{{ps(for)}}} | | 656 | | | array/dict/string proc | {{{ps(forall)}}} | | 657 | | | any | {{{ps(exec)}}} | | 658 | | | any | {{{ps(cvx)}}} | any | 659 | | | any | {{{ps(cvlit)}}} | any | 660 | | Dictionary | n | {{{ps(dict)}}} | dict | 661 | | | dict key | {{{ps(get)}}} | any | 662 | | | dict key any | {{{ps(put)}}} | | 663 | | | dict | {{{ps(begin)}}} | | 664 | | | | {{{ps(end)}}} | | 665 | | | | {{{ps(currentdict)}}} | dict | 666 | | | sym | {{{ps(where)}}} | false / dict true | 667 | | Miscellaneous | | {{{ps(save)}}} | dstack | 668 | | | dstack | {{{ps(restore)}}} | | 669 | | | any | {{{ps(type)}}} | name | 670 | | | bool | .strictBind | | 671 | | | any | {{{ps(bind)}}} | any | 672 | | Debugging | x | {{{ps(=)}}} | | 673 | | | x | {{{ps(==)}}} | | 674 | | | | {{{ps(stack)}}} | | 675 | | | | {{{ps(pstack)}}} | | 676 | | JavaScript FFI | x_1 ... x_n dict key n | .call | any | 677 | | | | .math | Math | 678 | | | | .date | (new Date) | 679 | | | | .window | window | 680 | | | proc | .callback | callback | 681 | | HTML | m | .minv | m^-1 | 682 | | | m_1 m_2 | .mmul | (m_1 x m_2) | 683 | | | x y m | .xy | x' y' | 684 | | | r g b | .rgb | text | 685 | | | r g b a | .rgba | text | 686 | 687 | Some of the above operators could still be implemented in PostScript 688 | instead of directly in JavaScript. 689 | 690 | ** Core operators 691 | 692 | TODO update 693 | 694 | | category | in | operator | out | | 695 | |--------------+-------------+--------------------+--------+---| 696 | | Math | | {{{ps(abs)}}} | | | 697 | | | | .acos | | | 698 | | | | .asin | | | 699 | | | | {{{ps(atan)}}} | | | 700 | | | | .atan2 | | | 701 | | | | {{{ps(ceiling)}}} | | | 702 | | | | {{{ps(cos)}}} | | | 703 | | | | .exp | | | 704 | | | | {{{ps(floor)}}} | | | 705 | | | | {{{ps(log)}}} | | | 706 | | | | .max | | | 707 | | | | .min | | | 708 | | | | .pow | | | 709 | | | | .random | | | 710 | | | | {{{ps(rand)}}} | | | 711 | | | | {{{ps(round)}}} | | | 712 | | | | {{{ps(sin)}}} | | | 713 | | | | {{{ps(sqrt)}}} | | | 714 | | | | .tan | | | 715 | | | | {{{ps(truncate)}}} | | | 716 | | | | .e | | | 717 | | | | .ln2 | | | 718 | | | | .ln10 | | | 719 | | | | .log2e | | | 720 | | | | .log10e | | | 721 | | | | .pi | | | 722 | | | | .sqrt1_2 | | | 723 | | | | .sqrt2 | | | 724 | | | | {{{ps(sub)}}} | | | 725 | | | | {{{ps(idiv)}}} | | | 726 | | | num/string | {{{ps(cvr)}}} | real | | 727 | | | num/string | {{{ps(cvi)}}} | int | | 728 | | Stack | x | {{{ps(dup)}}} | x x | | 729 | | Conditionals | x y | {{{ps(ne)}}} | bool | | 730 | | | x y | {{{ps(ge)}}} | bool | | 731 | | | x y | {{{ps(le)}}} | bool | | 732 | | | x y | {{{ps(gt)}}} | bool | | 733 | | | bool proc | {{{ps(if)}}} | | | 734 | | HTML 5 | key | .gget | | | 735 | | | any key | .gput | | | 736 | | | key nargs | .gcall0 | | | 737 | | | key nargs | .gcall1 | | | 738 | | | | .gcanvas | canvas | | 739 | | | w h | .gdim | | | 740 | | | x0 y0 x1 y1 | .gbox | | | 741 | 742 | ** HTML 5 canvas methods and attributes 743 | 744 | *** Canvas methods 745 | 746 | | | in | canvas | out | ps | pdf | 747 | |---+----------------------------------------------+-----------------------+----------------+--------------------------------+-------------| 748 | | / | | | | < | < | 749 | | | | .save | | {{{ps(gsave)}}} | q | 750 | | | | .restore | | {{{ps(grestore)}}} | Q | 751 | | | x y | .scale | | {{{ps(scale)}}} | - | 752 | | | angle | .rotate | | {{{ps(rotate)}}} | - | 753 | | | x y | .translate | | {{{ps(translate)}}} | - | 754 | | | m11 m12 m21 m22 dx dy | .transform | | - | cm | 755 | | | m11 m12 m21 m22 dx dy | .setTransform | | - | - | 756 | | | x0 y0 x1 y1 | .createLinearGradient | canvasGradient | | | 757 | | | x0 y0 r0 x1 y1 r1 | .createRadialGradient | canvasGradient | | | 758 | | | image repetition | .createPattern | canvasPattern | | | 759 | | | x y w h | .clearRect | | {{{ps(rectclip)}}} | | 760 | | | x y w h | .fillRect | | {{{ps(rectfill)}}} | | 761 | | | x y w h | .strokeRect | | {{{ps(rectstroke)}}} | | 762 | | | | .beginPath | | {{{ps(newpath)}}} | m ? | 763 | | | | .closePath | | {{{ps(closepath)}}} | ~ h ? ~ n ? | 764 | | | x y | .moveTo | | {{{ps(moveto)}}} | m ? | 765 | | | x y | .lineTo | | {{{ps(lineto)}}} | l | 766 | | | cpx cpy x y | .quadraticCurveTo | | | | 767 | | | cp1x cp1y cp2x cp2y x y | .bezierCurveTo | | | c | 768 | | | x1 y1 x2 y2 radius | .arcTo | | {{{ps(arcto)}}} | | 769 | | | x y w h | .rect | | - | ~ re | 770 | | | x y radius startAngle endAngle anticlockwise | .arc | | ~ {{{ps(arc)}}} {{{ps(arcn)}}} | | 771 | | | | .fill | | {{{ps(fill)}}} | ~ f ? | 772 | | | | .stroke | | {{{ps(stroke)}}} | S | 773 | | | | .clip | | {{{ps(clip)}}} | ~ W ? | 774 | | | x y | .isPointInPath | boolean | | | 775 | | | text x y | .fillText1 | | | | 776 | | | text x y maxWidth | .fillText2 | | | | 777 | | | text x y | .strokeText1 | | | | 778 | | | text x y maxWidth | .strokeText2 | | | | 779 | | | text | .measureText | textMetrics | | | 780 | | | image dx dy | .drawImage1 | | | | 781 | | | image dx dy dw dh | .drawImage2 | | | | 782 | | | image sx sy sw sh dx dy dw dh | .drawImage3 | | | | 783 | | | imagedata | .createImageData1 | imageData | | | 784 | | | sw sh | .createImageData1 | imageData | | | 785 | | | sx sy sw sh | .getImageData | imageData | | | 786 | | | imagedata dx dy | .putImageData1 | | | | 787 | | | imagedata dx dy dirtyX dirtyY dirtyW dirtyH | .putImageData2 | | | | 788 | 789 | *** Canvas attributes 790 | 791 | | | type | attribute | values | ps | pdf | 792 | |---+------+---------------------------+----------------------------------------------------+-------------------------+-------| 793 | | / | | < | | < | < | 794 | | | num | .globalAlpha | (1.0) | | | 795 | | | str | .globalCompositeOperation | (source-over) | | | 796 | | | any | .strokeStyle | (black) | ~ {{{ps(setdash)}}} ? | ~ d ? | 797 | | | any | .fillStyle | (black) | | | 798 | | | num | .lineWidth | (1) | {{{ps(setlinewidth)}}} | w | 799 | | | str | .lineCap | (butt) round square | ~ {{{ps(setlinecap)}}} | J | 800 | | | str | .lineJoin | round bevel (miter) | ~ {{{ps(setlinejoin)}}} | j | 801 | | | num | .miterLimit | (10) | {{{ps(setmiterlimit)}}} | M | 802 | | | num | .shadowOffsetX | (0) | | | 803 | | | num | .shadowOffsetY | (0) | | | 804 | | | num | .shadowBlur | (0) | | | 805 | | | str | .shadowColor | (transparent black) | | | 806 | | | str | .font | (10px sans-serif) | | | 807 | | | str | .textAlign | (start) end left right center | | | 808 | | | str | .textBaseline | top hanging middle (alphabetic) ideographic bottom | | | 809 | 810 | *** Other operators 811 | 812 | | | in | canvas | out | ps | pdf | 813 | |---+-----------------------------+---------------+-----+----+-----| 814 | | / | | < | | | | 815 | | | canvasGradient offset color | .addColorStop | | | | 816 | 817 | *** Other attributes 818 | 819 | | | dict | type | attribute | values | ps | pdf | 820 | |---+------------------+------------------+-----------+--------+----+-----| 821 | | / | | | < | | < | < | 822 | | | textMetrics | num | width | | | | 823 | | | imageData | cnt | width | | | | 824 | | | imageData | cnt | heigth | | | | 825 | | | imageData | canvasPixelArray | data | | | | 826 | | | canvasPixelArray | cnt | length | | | | 827 | 828 | TODO [IndexGetter, IndexSetter] CanvasPixelArray 829 | 830 | ** PostScript operators 831 | 832 | TODO update 833 | 834 | | | category | in | operator | out | 835 | |---+----------+---------+-----------------------+-----| 836 | | / | | < | < | < | 837 | | | | x y [m] | {{{ps(transform)}}} | x y | 838 | | | | x y [m] | {{{ps(itransform)}}} | x y | 839 | | | | gray | {{{ps(setgray)}}} | | 840 | | | | r g b | {{{ps(setrgbcolor)}}} | | 841 | | | | ??? | {{{ps(setfont)}}} ? | | 842 | | | | | {{{ps(clippath)}}} ? | | 843 | | | | text | {{{ps(show)}}} ? | | 844 | | | | x y | {{{ps(rlineto)}}} | | 845 | 846 | ** PDF operators 847 | 848 | | | category | operator | meaning | 849 | |---+------------------------+----------+---------------------------------------------| 850 | | / | | < | | 851 | | | General graphics state | w | setlinewidth | 852 | | | | J | ~ setlinecap | 853 | | | | j | ~ setlinejoin | 854 | | | | M | setmiterlimit | 855 | | | | d | ~ setdash ? | 856 | | | | ri | | 857 | | | | i | 1 .min setflat | 858 | | | | gs | | 859 | | | Special graphics state | q | gsave | 860 | | | | Q | grestore | 861 | | | | cm | .transform | 862 | | | Path construction | m | moveto | 863 | | | | l | lineto | 864 | | | | c | .bezierCurveTo (~ curveto) | 865 | | | | v | currentpoint 6 2 roll c | 866 | | | | y | 2 copy c | 867 | | | | h | closepath | 868 | | | | re | ! x y m , x+w y l , x+w y+h l , x y+h l , h | 869 | | | Path painting | S | stroke | 870 | | | | s | h S | 871 | | | | f | ~ fill | 872 | | | | F | f | 873 | | | | f* | ~ eofill | 874 | | | | B | f S ! q f Q S | 875 | | | | B* | f* S ! q f* Q S | 876 | | | | b | h B | 877 | | | | b* | h B* | 878 | | | | n | ~ newpath | 879 | | | Clipping paths | W | clip | 880 | | | | W* | eoclip | 881 | | | Text objects | BT | ~ q | 882 | | | | ET | ~ Q | 883 | | | Text state | Tc | | 884 | | | | Tw | | 885 | | | | Tz | | 886 | | | | TL | | 887 | | | | Tf | | 888 | | | | Tr | | 889 | | | | Ts | | 890 | | | Text positioning | Td | | 891 | | | | TD | | 892 | | | | Tm | | 893 | | | | T* | | 894 | | | Text showing | Tj | ~ show | 895 | | | | TJ | | 896 | | | | ' | | 897 | | | | " | | 898 | | | Type 3 fonts | d0 | setcharwidth | 899 | | | | d1 | setcachedevice | 900 | | | Color | CS | | 901 | | | | cs | | 902 | | | | SC | | 903 | | | | SCN | | 904 | | | | sc | | 905 | | | | scn | | 906 | | | | G | g | 907 | | | | g | setgray | 908 | | | | RG | rg | 909 | | | | rg | setrgbcolor | 910 | | | | K | k | 911 | | | | k | setcmykcolor | 912 | | | Shading patterns | sh | | 913 | | | Inline images | BI | | 914 | | | | ID | | 915 | | | | EI | | 916 | | | XObjects | Do | | 917 | | | Marked content | MP | | 918 | | | | DP | | 919 | | | | BMC | | 920 | | | | BDC | | 921 | | | | EMC | | 922 | | | Compatibility | BX | | 923 | | | | EX | | 924 | 925 | * Supported Browsers 926 | 927 | I have tried the following browsers so far: 928 | 929 | | | Browser | Version | Note | 930 | |---+---------+---------------------------------+------------------------------------| 931 | | / | | < | | 932 | | | Firefox | 3.0.11 | no text drawing, linecap, linejoin | 933 | | | | 3.5b4pre | ~ same as Firefox 3.0.11? | 934 | | | | 3.5.5 Win | reported by Ray Johnson | 935 | | | Opera | 10.00 Beta | no text drawing, ugly aliasing | 936 | | | Chrome | 3.0.189.0 | lines not joined properly | 937 | | | Safari | for Mac Version 4.0.2 (5530.19) | reported by Will King | 938 | | | | 4.0.4 Win | reported by Ray Johnson | 939 | 940 | If you are using a different browser, please [[http://logand.com/contact.html][let me know]] if it works 941 | for you. 942 | 943 | * Limitations and Known Issues 944 | 945 | - many PostScript operators are still to be implemented 946 | - only small fraction of PDF operators has been implemented 947 | - text drawing and font related functionality has not been implemented 948 | 949 | * Changes 950 | 951 | 2009-07-15 v0.2 952 | 953 | - Capable of drawing tiger.eps 954 | - JavaScript callbacks and timer added 955 | - bind operator implemented 956 | - Refactored JavaScript code: parser, evaluator and PostScript 957 | interpreter separated 958 | - Improved documentation 959 | 960 | 2009-06-30 v0.1 961 | 962 | - Initial version 963 | 964 | * Links 965 | 966 | Discussions about WPS on [[http://www.reddit.com/r/programming/comments/95xll/wps_postscript_and_pdf_interpreter_for_html_5/][reddit]] and [[http://ajaxian.com/archives/wps-postscript-and-pdf-interpreter-for-html-5-canvas][ajaxian]]. 967 | 968 | [[http://www.feiri.de/pcan/][PostCanvas]] is a RPN interpreter with many PostScript operators 969 | implemented directly in JavaScript. It is faster than WPS but not a 970 | "real" PostScript. 971 | 972 | [[http://svgkit.sourceforge.net/][SVGKit]] has a PostScript interpreter on the wish list. 973 | 974 | PostScript is a registered trademark of [[http://www.adobe.com][Adobe Systems Incorporated]]. 975 | -------------------------------------------------------------------------------- /lib/canvas.ts: -------------------------------------------------------------------------------- 1 | import { Ps0 } from './ps0'; 2 | import { Symbol } from './util'; 3 | 4 | import { augmentContext, inverse, applyToPoint } from './context-transform'; 5 | 6 | export function CanvasMixin(Ps: Ps0, deviceCtx: CanvasRenderingContext2D) { 7 | var Sd = {}; 8 | Ps.Ds.push(Sd); 9 | 10 | function def(Nm, Fn) { Sd[new Symbol(Nm)] = Fn; } 11 | 12 | // TODO: Move to PostScript. 13 | const framebuffer = new DewdropCanvas(Ps, deviceCtx); 14 | def('framebuffer', function() { 15 | this.Os.push(framebuffer); 16 | }); 17 | 18 | // TODO: is framebuffer-as-default-canvas reasonable/consistent behavior? 19 | // It's nice because it lets normal PostScript programs work out of the box. 20 | let currentCanvas: DewdropCanvas; 21 | def('newcanvas', function() { 22 | const parent = this.Os.pop(); 23 | this.Os.push(new DewdropCanvas(Ps, parent)); 24 | }); 25 | def('reshapecanvas', function() { 26 | const cv = this.Os.pop(); 27 | cv.reshape(currentCanvas.bufferCtx.currentPath, currentCanvas.bufferCtx.currentTransform); 28 | }); 29 | def('setcanvas', function() { 30 | const cv = this.Os.pop(); 31 | setCanvas(cv); 32 | }); 33 | function setCanvas(cv: DewdropCanvas) { 34 | def('.$gc', cv.bufferCtx); 35 | currentCanvas = cv; 36 | } 37 | setCanvas(framebuffer); 38 | 39 | def('erasepage', function() { 40 | currentCanvas.bufferCtx.save(); 41 | currentCanvas.bufferCtx.fillStyle = 'white'; 42 | currentCanvas.bufferCtx.fill(currentCanvas.shape); 43 | currentCanvas.bufferCtx.restore(); 44 | }); 45 | 46 | (function setupAnimation() { 47 | window.requestAnimationFrame(function() { 48 | framebuffer.paint(); 49 | setupAnimation(); 50 | }); 51 | })(); 52 | } 53 | 54 | // We keep a number of virtual canvases which are purely in-memory. 55 | // Then on each paint, we walk the tree of Dewdrop canvases and paint 56 | // all of them onto the real graphics context. 57 | 58 | type DewdropRenderingContext = CanvasRenderingContext2D & { 59 | currentPath: any; 60 | currentTransform: any; 61 | }; 62 | 63 | // Just like an ordinary canvas rendering context, except 64 | // it remembers the current clip path. 65 | // This is useful because: 66 | // 1. PostScript has `clippath` 67 | // 2. I need to be able to clip window content according to window shape 68 | // when it gets painted on a larger canvas. 69 | function wrap(ctx: CanvasRenderingContext2D): DewdropRenderingContext { 70 | augmentContext(ctx); 71 | 72 | const wrapper: DewdropRenderingContext = ctx as any; 73 | 74 | // Path methods. 75 | wrapper.beginPath = function() { 76 | wrapper.currentPath = new Path2D(); 77 | // hack. see if this works... 78 | for (const key in wrapper.currentPath) { 79 | wrapper[key] = function() { 80 | wrapper.currentPath[key].apply(wrapper.currentPath, arguments); 81 | } 82 | } 83 | }; 84 | wrapper.beginPath(); 85 | 86 | // Drawing paths. 87 | // Need to intercept anything that finishes off a path. 88 | const originalFill = ctx.fill; 89 | wrapper.fill = function(path?: any) { 90 | originalFill.call(ctx, path || wrapper.currentPath); 91 | }; 92 | const originalStroke = ctx.stroke; 93 | wrapper.stroke = function(path?: any) { 94 | originalStroke.call(ctx, path || wrapper.currentPath); 95 | }; 96 | 97 | return wrapper; 98 | } 99 | 100 | class DewdropCanvas { 101 | // Real graphics context. 102 | deviceCtx: CanvasRenderingContext2D; 103 | 104 | // In-memory buffer which is drawn on after `setcanvas` is called. 105 | buffer: HTMLCanvasElement; 106 | bufferCtx: DewdropRenderingContext; 107 | 108 | // When you copy the buffer context onto the real context, 109 | // you push the shape on as clip and the transform matrix on, 110 | // which achieves the window effect. 111 | shape: Path2D; 112 | transformMatrix: SVGMatrix; 113 | 114 | parent: DewdropCanvas; 115 | children: DewdropCanvas[] = []; 116 | 117 | constructor(Ps: Ps0, parentOrDevice: DewdropCanvas | CanvasRenderingContext2D) { 118 | if (parentOrDevice instanceof DewdropCanvas) { 119 | this.parent = parentOrDevice; 120 | this.parent.children.push(this); 121 | this.deviceCtx = this.parent.deviceCtx; 122 | 123 | } else { 124 | this.deviceCtx = parentOrDevice; 125 | } 126 | 127 | // Attach events. 128 | this.deviceCtx.canvas.addEventListener('mouseup', (event) => { 129 | if (!this.shape) return; 130 | this.deviceCtx.save(); 131 | if (this.transformMatrix) { 132 | this.deviceCtx.setTransform.apply(this.deviceCtx, this.transformMatrix); 133 | } 134 | if (this.deviceCtx.isPointInPath(this.shape, event.offsetX, event.offsetY)) { 135 | const e: any = {}; 136 | e[new Symbol('Canvas')] = this; 137 | e[new Symbol('Name')] = new Symbol('LeftMouseButton'); 138 | e[new Symbol('Action')] = new Symbol('UpTransition'); 139 | const inv = inverse(this.transformMatrix); 140 | const { x, y } = applyToPoint(inv, event.offsetX, event.offsetY); 141 | e[new Symbol('XLocation')] = x; 142 | e[new Symbol('YLocation')] = y; 143 | Ps.sendEvent(e); 144 | } 145 | this.deviceCtx.restore(); 146 | }); 147 | 148 | // Bind buffer to draw on. 149 | this.buffer = document.createElement('canvas'); 150 | 151 | // Hacks for negative space. 152 | this.buffer.width = 2048; 153 | this.buffer.height = 2048; 154 | // Do before tracking transforms. Permanent transform. 155 | // Keeps negative coordinates usable. 156 | this.buffer.getContext('2d').translate(1024, 1024); 157 | 158 | this.bufferCtx = wrap(this.buffer.getContext('2d')); 159 | } 160 | 161 | // PostScript `reshapecanvas` should call this using info from the context. 162 | // See NeWS 1.1 Manual, p. 144: 163 | // Sets the shape of canvas to be the current path, and it sets the canvas' 164 | // default transformation matrix from the current transformation matrix. 165 | reshape(shape: Path2D, transformMatrix: SVGMatrix) { 166 | this.shape = shape; 167 | this.transformMatrix = transformMatrix; 168 | } 169 | 170 | paint() { 171 | this.deviceCtx.save(); 172 | 173 | if (this.transformMatrix) { 174 | this.deviceCtx.setTransform.apply(this.deviceCtx, this.transformMatrix); 175 | } 176 | if (this.shape) { 177 | this.deviceCtx.clip(this.shape); 178 | } 179 | 180 | // Adjust for permanent transform. Keeps negative coordinates usable. 181 | this.deviceCtx.drawImage(this.buffer, -1024, -1024); 182 | 183 | this.children.forEach(child => { 184 | // FIXME: Check if Mapped or not. 185 | child.paint() 186 | }); 187 | 188 | this.deviceCtx.restore(); 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /lib/context-transform.ts: -------------------------------------------------------------------------------- 1 | // References used to check the math: 2 | // https://gist.github.com/abicky/3165385 3 | // https://github.com/simonsarris/Canvas-tutorials/blob/master/transform.js 4 | 5 | // Functions returning the matrix used for the same-named Canvas transform. 6 | 7 | export const translate = function (x, y) { 8 | return [1, 0, 0, 1, x, y]; 9 | }; 10 | 11 | export const rotate = function (a) { 12 | var cos = Math.cos(a); 13 | var sin = Math.sin(a); 14 | return [cos, sin, -sin, cos, 0, 0]; 15 | }; 16 | 17 | export const scale = function (x, y) { 18 | return [x, 0, 0, y, 0, 0]; 19 | }; 20 | 21 | export const transform = function (a, b, c, d, e, f) { 22 | return [a, b, c, d, e, f]; 23 | }; 24 | 25 | const basicTransforms: any = { translate, rotate, scale, transform }; 26 | 27 | const determinant = function (m) { 28 | return m[0] * m[3] - m[1] * m[2]; 29 | }; 30 | 31 | // FIXME: Implement basic test for inverse. 32 | export const inverse = function(m) { 33 | const dt = determinant(m); 34 | return [ 35 | m[3] / dt, 36 | -m[1] / dt, 37 | -m[2] / dt, 38 | m[0] / dt, 39 | (m[2] * m[5] - m[3] * m[4]) / dt, 40 | -(m[0] * m[5] - m[1] * m[4]) /dt 41 | ]; 42 | }; 43 | 44 | export const multiply = function(m1, m2) { 45 | // Value [a,b,c,d,e,f] represents the 3 by 3 matrix 46 | // a c e 47 | // b d f 48 | // 0 0 1 49 | return [ 50 | m1[0] * m2[0] + m1[2] * m2[1], 51 | m1[1] * m2[0] + m1[3] * m2[1], 52 | m1[0] * m2[2] + m1[2] * m2[3], 53 | m1[1] * m2[2] + m1[3] * m2[3], 54 | m1[0] * m2[4] + m1[2] * m2[5] + m1[4], 55 | m1[1] * m2[4] + m1[3] * m2[5] + m1[5], 56 | ]; 57 | }; 58 | 59 | export const applyToPoint = function(m, x, y) { 60 | return { 61 | x: x * m[0] + y * m[2] + m[4], 62 | y: x * m[1] + y * m[3] + m[5] 63 | } 64 | }; 65 | 66 | // Given the current transformation matrix, a transform to apply to it, and its 67 | // arguments as an array or array-like object, return the new transformation 68 | // matrix. If an unrecognized method is provided, returns the original matrix. 69 | const processMethod = function (m, methodName, args) { 70 | // Resetting transforms. 71 | if (methodName === "resetTransform") { 72 | return [1, 0, 0, 1, 0, 0]; 73 | } else if (methodName === "setTransform") { 74 | return basicTransforms.transform.apply(null, args); 75 | // Transforms that accumulate. 76 | } else if (basicTransforms[methodName]) { 77 | return multiply(m, basicTransforms[methodName].apply(null, args)); 78 | // Bad method name. 79 | } else { 80 | return m; 81 | } 82 | }; 83 | export { processMethod as process }; 84 | 85 | // Method names recognized by processMethod, all methods on a context. 86 | var transformMethodNames = Object.keys(basicTransforms).concat([ 87 | "resetTransform", "setTransform", 88 | ]); 89 | 90 | // Given a Canvas context, add a getTransform method directly to it along with 91 | // the appropriate wrappers around the transformation methods. Noop if the 92 | // context already has a getTransform method. Assumes the context is fresh 93 | // with an identity transformation and no previous save/restore calls. 94 | export function augmentContext(ctx) { 95 | if (!ctx || typeof ctx !== "object" || !ctx.canvas) { 96 | throw new Error("augmentContext: Must pass a Canvas context."); 97 | } 98 | 99 | // Implement resetTransform if not present already. 100 | ctx.resetTransform = ctx.resetTransform || function() { 101 | this.setTransform(1, 0, 0, 1, 0, 0); 102 | }; 103 | 104 | var transform = [1, 0, 0, 1, 0, 0]; 105 | var stack = []; 106 | transformMethodNames.forEach(function (name) { 107 | var oldMethod = ctx[name]; 108 | ctx[name] = function () { 109 | transform = processMethod(transform, name, arguments); 110 | return oldMethod.apply(ctx, arguments); 111 | }; 112 | }); 113 | 114 | var oldSave = ctx.save; 115 | ctx.save = function () { 116 | stack.push(transform); 117 | return oldSave.apply(ctx, arguments); 118 | }; 119 | 120 | var oldRestore = ctx.restore; 121 | ctx.restore = function () { 122 | transform = stack.pop() || transform; 123 | return oldRestore.apply(ctx, arguments); 124 | }; 125 | 126 | Object.defineProperty(ctx, 'currentTransform', { 127 | get() { 128 | return transform; 129 | }, 130 | set(newTransform: any) { 131 | transform = newTransform; 132 | ctx.setTransform.apply(ctx, transform); 133 | } 134 | }); 135 | }; 136 | -------------------------------------------------------------------------------- /lib/corelib.ts: -------------------------------------------------------------------------------- 1 | import { Ps0 } from './ps0'; 2 | import { Symbol, symbolName, quote, unquote, inDs, isSymbol, isArray, isObject, isQuoted } from './util'; 3 | 4 | export function CorelibMixin(Ps: Ps0, log: Function = console.log.bind(console)) { 5 | var Sd = {}; 6 | Ps.Ds.push(Sd); 7 | 8 | function def(Nm, Fn) {Sd[new Symbol(Nm)] = Fn;} 9 | 10 | // Every reference to Os/whatever should be on `this` here, 11 | // so they can be dynamically rebound to the operand stack 12 | // of a forked child coroutine, instead of lexically bound to the 13 | // original Ps here. 14 | 15 | // trivial 16 | def("true", function() {this.Os.push(true);}); 17 | def("false", function() {this.Os.push(false);}); 18 | def("null", function() {this.Os.push(null);}); 19 | // math 20 | def("sub", function() {var X = this.Os.pop(); this.Os.push(this.Os.pop() - X);}); 21 | def("mul", function() {this.Os.push(this.Os.pop() * this.Os.pop());}); 22 | def("div", function() {var X = this.Os.pop(); this.Os.push(this.Os.pop() / X);}); 23 | def("mod", function() {var X = this.Os.pop(); this.Os.push(this.Os.pop() % X);}); 24 | // stack 25 | var M = {}; 26 | def("mark", function() {this.Os.push(M);}); 27 | def("counttomark", function() { 28 | var N = 0; 29 | for(var I = this.Os.length - 1; 0 <= I; I--) 30 | if(M === this.Os[I]) return this.Os.push(N); 31 | else N++; 32 | throw "Mark not found"; 33 | }); 34 | def("<<", Sd[new Symbol("mark")]); // TODO doc 35 | def(">>", function() { // TODO doc 36 | var D = {}; 37 | while(0 < this.Os.length) { 38 | var V = this.Os.pop(); 39 | if(M === V) return this.Os.push(D); 40 | D[this.Os.pop()] = V; 41 | } 42 | throw "Mark not found"; 43 | }); 44 | def("exch", function() { 45 | var Y = this.Os.pop(); 46 | var X = this.Os.pop(); 47 | this.Os.push(Y); 48 | this.Os.push(X); 49 | }); 50 | def("clear", function() {this.Os.length = 0;}); 51 | def("pop", function() {this.Os.pop();}); 52 | def("index", function() { 53 | this.Os.push(this.Os[this.Os.length - 2 - this.Os.pop()]); 54 | }); 55 | def("roll", function() { // TODO in ps 56 | var J = this.Os.pop(); 57 | var N = this.Os.pop(); 58 | var X = []; 59 | var Y = []; 60 | for(var I = 0; I < N; I++) 61 | if(I < J) X.unshift(this.Os.pop()); 62 | else Y.unshift(this.Os.pop()); 63 | for(I = 0; I < J; I++) this.Os.push(X.shift()); 64 | for(I = 0; I < N - J; I++) this.Os.push(Y.shift()); 65 | }); 66 | def("copy", function() { 67 | var N = this.Os.pop(); 68 | if(isObject(N)) { 69 | var X = this.Os.pop(); 70 | for(const I in X) 71 | N[I] = X[I]; 72 | this.Os.push(N); 73 | } else { 74 | var X: any = this.Os.length - N; 75 | for(var I: any = 0; I < N; I++) 76 | this.Os.push(this.Os[X + I]); 77 | } 78 | }); 79 | // array 80 | def("length", function() {this.Os.push(this.Os.pop().length);}); 81 | def("astore", function() { 82 | var A = this.Os.pop(); 83 | var N = A.length; 84 | for(var I = N - 1; 0 <= I; I--) 85 | A[I] = this.Os.pop(); 86 | this.Os.push(A); 87 | }); 88 | def("array", function() {this.Os.push(new Array(this.Os.pop()));}); 89 | // conditionals 90 | def("eq", function() { 91 | const Y = this.Os.pop(); 92 | const X = this.Os.pop(); 93 | // Hack so that /hello is equal to unquoted hello. 94 | if (isSymbol(X) && isSymbol(Y)) { 95 | this.Os.push(symbolName(X) === symbolName(Y)); 96 | } else { 97 | this.Os.push(X == Y); 98 | } 99 | }); 100 | def("lt", function() {var Y = this.Os.pop(); var X = this.Os.pop(); this.Os.push(X < Y);}); 101 | // control 102 | def("ifelse", function() { 103 | var N = this.Os.pop(); 104 | var P = this.Os.pop(); 105 | var C = this.Os.pop(); 106 | this.Es.push([false, C === true ? P : N]); 107 | }); 108 | def("repeat", function Xrepeat() { // TODO in ps 109 | var proc = this.Os.pop(); 110 | var N = this.Os.pop(); 111 | if(1 < N) this.Es.push([true, N - 1, proc, Xrepeat]); 112 | if(0 < N) this.Es.push([false, proc]); 113 | }); 114 | def("for", function Xfor() { // TODO in ps 115 | var B = this.Os.pop(); 116 | var L = this.Os.pop(); 117 | var K = this.Os.pop(); 118 | var J = this.Os.pop(); 119 | if(K < 0) { 120 | if(L <= J + K) this.Es.push([true, J + K, K, L, B, Xfor]); 121 | if(L <= J) this.Es.push([false, J, B]); 122 | } else { 123 | if(J + K <= L) this.Es.push([true, J + K, K, L, B, Xfor]); 124 | if(J <= L) this.Es.push([false, J, B]); 125 | } 126 | }); 127 | def("loop", function Xloop() { 128 | const proc = this.Os.pop(); 129 | this.Es.push([true, proc, Xloop]); 130 | this.Es.push([false, proc]); 131 | }); 132 | function XforallA() { 133 | var B = this.Os.pop(); 134 | var A = this.Os.pop(); 135 | var I = this.Os.pop(); 136 | var N = A.length; 137 | if(1 < N - I) this.Es.push([true, I + 1, A, B, XforallA]); 138 | if(0 < N - I) this.Es.push([false, A[I], B]); 139 | } 140 | function XforallO() { 141 | var B = this.Os.pop(); 142 | var O = this.Os.pop(); 143 | var L = this.Os.pop(); 144 | var N = L.length; 145 | var K; 146 | if(0 < N) K = L.pop(); 147 | if(1 < N) this.Es.push([true, L, O, B, XforallO]); 148 | if(0 < N) this.Es.push([false, K, O[K], B]); 149 | } 150 | def("forall", function() { // TODO in ps 151 | var B = this.Os.pop(); 152 | var O = this.Os.pop(); 153 | if(isArray(O)) { 154 | this.Os.push(0); 155 | this.Os.push(O); 156 | this.Os.push(B); 157 | XforallA.call(this); // FIXME: Explicit .call(this) is ugly. 158 | } else if(isObject(O)) { 159 | var L = []; 160 | for(var K in O) {L.push(K);} 161 | this.Os.push(L); 162 | this.Os.push(O); 163 | this.Os.push(B); 164 | XforallO.call(this); 165 | } else if("string" == typeof O) { 166 | this.Os.push(0); 167 | this.Os.push(O.split("")); 168 | this.Os.push(B); 169 | XforallA.call(this); 170 | } else throw "Cannot apply forall to " + O; 171 | }); 172 | def("exit", function() { 173 | // Drop the innermost loop (the topmost item on the execution stack with 174 | // loop flag being true). 175 | const loopIdx = this.Es 176 | .map((item, idx) => item[0] ? idx : null) 177 | .filter(idx => idx != null) 178 | .reverse() 179 | [0]; 180 | this.Es.splice(loopIdx); 181 | }); 182 | def("exec", function() {this.Es.push([false, this.Os.pop()]);}); 183 | def("xcheck", function() { 184 | const X = this.Os.pop(); 185 | this.Os.push((isSymbol(X) && !isQuoted(X)) || (isArray(X) && isQuoted(X))); 186 | }); 187 | def("cvx", function() { 188 | var X = this.Os.pop(); 189 | if(isSymbol(X) && isQuoted(X)) this.Os.push(unquote(X)); // executable name 190 | else if(isArray(X) && !isQuoted(X)) this.Os.push(quote(X)); // proc 191 | // TODO string -> parse 192 | else this.Os.push(X); 193 | }); 194 | def("cvlit", function() { 195 | var X = this.Os.pop(); 196 | if(isSymbol(X) && !isQuoted(X)) this.Os.push(quote(X)); // un-executable name 197 | else if(isArray(X) && isQuoted(X)) this.Os.push(unquote(X)); // un-proc 198 | // TODO reverse? string -> parse 199 | else this.Os.push(X); 200 | }); 201 | // dictionary 202 | def("dict", function() {this.Os.pop(); this.Os.push({});}); 203 | def("get", function() { 204 | var K = this.Os.pop(); 205 | var D = this.Os.pop(); 206 | // TODO other datatypes 207 | if(isSymbol(K)) this.Os.push(D[K]); 208 | else this.Os.push(D[K]); 209 | }); 210 | def("put", function() { 211 | var V = this.Os.pop(); 212 | var K = this.Os.pop(); 213 | var D = this.Os.pop(); 214 | // TODO other datatypes 215 | if(isSymbol(K)) D[K] = V; 216 | else D[K] = V; 217 | }); 218 | def("begin", function() {this.Ds.push(this.Os.pop());}); 219 | def("end", function() {this.Ds.pop();}); 220 | def("currentdict", function() {this.Os.push(this.Ds[this.Ds.length - 1]);}); 221 | def("where", function() { 222 | var K = this.Os.pop(); 223 | var D = inDs(this.Ds, K); 224 | if(D) { 225 | this.Os.push(D); 226 | this.Os.push(true); 227 | } else this.Os.push(false); 228 | }); 229 | // miscellaneous 230 | def("save", function() { 231 | var X = this.Ds.slice(); 232 | for(var I = 0; I < X.length; I++) { 233 | var A = X[I]; 234 | var B = {}; 235 | for(var J in A) 236 | B[J] = A[J]; 237 | X[I] = B; 238 | } 239 | this.Os.push(X); 240 | }); 241 | def("restore", function() { 242 | var X = this.Os.pop(); 243 | while(0 < this.Ds.length) 244 | this.Ds.pop(); 245 | while(0 < X.length) 246 | this.Ds.unshift(X.pop()); 247 | }); 248 | def("type", function() { 249 | var A = this.Os.pop(); 250 | var X; 251 | if(null === A) X = "nulltype"; 252 | else if(true === A || false === A) X = "booleantype"; 253 | else if(M === A) X = "marktype"; 254 | else if("string" == typeof A) X = "stringtype"; 255 | else if(isSymbol(A)) X = isQuoted(A) ? "nametype" : "operatortype"; 256 | else if("function" == typeof A) X = "operatortype"; 257 | else if(isArray(A)) X = "arraytype"; 258 | else if(isObject(A)) X = "dicttype"; 259 | else if(1 * A == A) X = A % 1 == 0 ? "integertype" : "realtype"; 260 | else throw "Undefined type '" + A + "'"; 261 | this.Os.push(X); 262 | // filetype 263 | // packedarraytype (LanguageLevel 2) 264 | // fonttype 265 | // gstatetype (LanguageLevel 2) 266 | // savetype 267 | }); 268 | var Sb = true; 269 | def(".strictBind", function() {Sb = true === this.Os.pop();}); 270 | def("bind", function() { 271 | const bind = (X) => { 272 | if(isSymbol(X) && !isQuoted(X)) { 273 | var D = inDs(this.Ds, X); 274 | if(Sb) { 275 | if(!D) 276 | throw "bind error '" + X + "'"; 277 | return bind(D[X]); 278 | } else return !D ? X : bind(D[X]); 279 | } else if(isArray(X) && isQuoted(X)) { 280 | var N = X.length; 281 | var A = []; 282 | for(var I = 0; I < N; I++) { 283 | var Xi = X[I]; 284 | var Xb = bind(Xi); 285 | if(isArray(Xi)) 286 | A = A.concat(isQuoted(Xi) ? quote([Xb]) : [Xb]); 287 | else 288 | A = A.concat(Xb); 289 | } 290 | return quote(A); 291 | } 292 | return X; 293 | } 294 | this.Os.push(bind(this.Os.pop())); 295 | }); 296 | // debugging 297 | def("=", function() {var X = this.Os.pop(); alert(X);}); // TODO 298 | def("==", function() {log(this.Os.pop());}); // TODO 299 | def("stack", function() {log(this.Os);}); // TODO 300 | def("pstack", function() {console.log(this.Os);}); // TODO 301 | // js ffi 302 | def(".call", function() { 303 | var N = this.Os.pop(); 304 | var K = this.Os.pop(); 305 | var D = this.Os.pop(); 306 | var X = []; 307 | for(var I = 0; I < N; I++) X.unshift(this.Os.pop()); 308 | this.Os.push(D[K].apply(D, X)); 309 | }); 310 | def(".debugger", function() {debugger;}); 311 | def(".math", function() {this.Os.push(Math);}); 312 | def(".date", function() {this.Os.push(new Date());}); // TODO split new and Date 313 | def(".window", function() {this.Os.push(window);}); 314 | def(".callback", function() { // TODO event arg? 315 | var X = this.Os.pop(); 316 | this.Os.push(function() { 317 | Ps.run(X, true); 318 | while(0 < this.Es.length) 319 | Ps.step(); 320 | }); 321 | }); 322 | def(".error", function() { 323 | throw new Error('Error thrown from inside program.'); 324 | }); 325 | // html5 326 | def(".minv", function() { // TODO in ps 327 | var M = this.Os.pop(); 328 | var a = M[0]; var b = M[1]; 329 | var d = M[2]; var e = M[3]; 330 | var g = M[4]; var h = M[5]; 331 | this.Os.push([e, b, d, a, d*h-e*g, b*g-a*h]); 332 | }); 333 | def(".mmul", function() { // TODO in ps 334 | var B = this.Os.pop(); 335 | var A = this.Os.pop(); 336 | var a = A[0]; var b = A[1]; 337 | var d = A[2]; var e = A[3]; 338 | var g = A[4]; var h = A[5]; 339 | var r = B[0]; var s = B[1]; 340 | var u = B[2]; var v = B[3]; 341 | var x = B[4]; var y = B[5]; 342 | this.Os.push([a*r+b*u, a*s+b*v, d*r+e*u, d*s+e*v, g*r+h*u+x, g*s+h*v+y]); 343 | }); 344 | def(".xy", function() { // TODO in ps 345 | var M = this.Os.pop(); 346 | var Y = this.Os.pop(); 347 | var X = this.Os.pop(); 348 | this.Os.push(M[0] * X + M[2] * Y + M[4]); 349 | this.Os.push(M[1] * X + M[3] * Y + M[5]); 350 | }); 351 | // TODO js ffi to manipulate strings so the following can be in ps 352 | def(".rgb", function() { // TODO in ps 353 | var B = this.Os.pop(); 354 | var G = this.Os.pop(); 355 | var R = this.Os.pop(); 356 | this.Os.push("rgb(" + R + "," + G + "," + B + ")"); 357 | }); 358 | def(".rgba", function() { // TODO in ps 359 | var A = this.Os.pop(); 360 | var B = this.Os.pop(); 361 | var G = this.Os.pop(); 362 | var R = this.Os.pop(); 363 | this.Os.push("rgba(" + R + "," + G + "," + B + "," + A + ")"); 364 | }); 365 | } 366 | -------------------------------------------------------------------------------- /lib/coroutine.ts: -------------------------------------------------------------------------------- 1 | import { Ps0 } from './ps0'; 2 | import { Symbol } from './util'; 3 | 4 | export function CoroutineMixin(Ps: Ps0) { 5 | var Sd = {}; 6 | Ps.Ds.push(Sd); 7 | 8 | function def(Nm, Fn) {Sd[new Symbol(Nm)] = Fn;} 9 | 10 | def("fork", async function() { 11 | const fn = this.Os.pop(); 12 | this.Os.push(await Ps.fork(fn)); 13 | }); 14 | 15 | def("createevent", function() { 16 | this.Os.push({}); 17 | // TODO: Do we need anything else? 18 | }); 19 | 20 | def("sendevent", async function() { 21 | const event = this.Os.pop(); 22 | await this.sendEvent(event); 23 | }); 24 | 25 | def("waitprocess", async function() { 26 | const proc = this.Os.pop(); 27 | while (this.suspended.has(proc)) { 28 | if (proc.awaitingEvent) { 29 | // FIXME: Hack so we don't wind up in a tight loop 30 | // w/o being able to yield for event dispatch. 31 | await new Promise((resolve) => { 32 | setTimeout(() => resolve(), 100); 33 | }); 34 | } 35 | await this.suspendForNext(); 36 | } 37 | this.Os.push(proc.Os.pop()); 38 | }); 39 | def("killprocess", function() { 40 | this.suspended.delete(this.Os.pop()); 41 | }); 42 | 43 | // Listener process tools. 44 | def("expressinterest", function() { 45 | const filter = this.Os.pop(); 46 | this.hasInterestIn = (event) => { 47 | for (const key in filter) { 48 | if (filter[key].nm !== event[key].nm) return false; 49 | } 50 | return true; 51 | }; 52 | }); 53 | 54 | def("awaitevent", async function() { 55 | await this.awaitEvent(); 56 | }); 57 | } 58 | -------------------------------------------------------------------------------- /lib/html5canvas.d.ts: -------------------------------------------------------------------------------- 1 | declare class Path2D { 2 | addPath(); 3 | closePath(); 4 | moveTo(); 5 | lineTo(); 6 | bezierCurveTo(); 7 | quadraticCurveTo(); 8 | arc(); 9 | arcTo(); 10 | ellipse(); 11 | rect(); 12 | } 13 | 14 | declare interface CanvasRenderingContext2D { 15 | currentTransform: SVGMatrix; 16 | clip(path: Path2D); 17 | clip(path: Path2D, fillRule?: 'nonzero' | 'evenodd'); 18 | ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise); 19 | 20 | fill(path: Path2D); 21 | stroke(path: Path2D); 22 | 23 | isPointInPath(path: Path2D, x: number, y: number); 24 | } 25 | -------------------------------------------------------------------------------- /lib/index.ts: -------------------------------------------------------------------------------- 1 | /// WPS: PostScript and PDF interpreter for HTML 5 canvas 2 | /// http://logand.com/sw/wps/index.html 3 | /// (c) 2009, 2010, 2011 Tomas Hlavaty 4 | /// Licensed under the GPLv3+ license. 5 | /// http://www.fsf.org/licensing/licenses/gpl.html 6 | 7 | import { Ps0 } from './ps0'; 8 | import { CorelibMixin } from './corelib'; 9 | import { CoroutineMixin } from './coroutine'; 10 | import { CanvasMixin } from './canvas'; 11 | 12 | const wpsLib = require('./stdlib.ps'); 13 | const oopLib = require('./oop.ps'); 14 | 15 | interface DewdropInstance { 16 | Ps: Ps0; 17 | parse: (...args: any[]) => Promise; 18 | } 19 | 20 | export default async function Dewdrop(framebuffer?: HTMLCanvasElement, log?: Function): Promise { 21 | const dewdrop = { 22 | Ps: new Ps0(), 23 | async parse(...args: any[]): Promise { // FIXME placeholder type sig 24 | if(args.length) 25 | for(var I = 0; I < args.length; I++) 26 | await this.Ps.parse(args[I]); 27 | else await this.Ps.parse(args); 28 | return this.Ps.Os; 29 | } 30 | }; 31 | 32 | CorelibMixin(dewdrop.Ps, log); 33 | CoroutineMixin(dewdrop.Ps); 34 | if (framebuffer) { 35 | // 'NeWS mode' 36 | // TODO: Have a getElementById-based option. 37 | CanvasMixin(dewdrop.Ps, framebuffer.getContext('2d')); 38 | } 39 | 40 | await dewdrop.parse(wpsLib); 41 | await dewdrop.parse(oopLib); // TODO: Only really need this for NeWS. 42 | 43 | return dewdrop; 44 | } 45 | -------------------------------------------------------------------------------- /lib/oop.ps: -------------------------------------------------------------------------------- 1 | % PostScript OOP implementation. From Densmore (1986): 2 | % https://archive.org/details/pdfy-1U9Ry1_Qj0LPSR6e 3 | 4 | % 5 | % Objects ’n stuff. 6 | % 7 | 8 | /ObjectTemplate dictbegin % All objects have these fields: 9 | /parentDict null def % link to my parent dict; stops at null. 10 | /parentDictArray null def % complete parent chain to Object! 11 | dictend def 12 | /ClassTemplate dictbegin % Class objects have these fields in addition: 13 | /instanceVars null def % this class’ additional inst vars 14 | /instanceVarDict null def % this class’ total inst vars 15 | /instanceVarExtra 10 def % extra space for class var over-rides 16 | /className null def % name of the class (as a keyword) 17 | /subClasses nullarray def % subclass list (for browsing) 18 | dictend def 19 | 20 | % Create a sub-class of the given class. 21 | % The instancevariables may be either an array or a dict. 22 | % The advantage of using a dict is that the variables will be 23 | % pre-initialized to a value you chose, rather than "null". 24 | /classbegin { % classname superclass insvars => - (newclass on dict stack) 25 | dictbegin 26 | ObjectTemplate {def} forall 27 | ClassTemplate {def} forall 28 | 29 | /instanceVars exch def 30 | /parentDict exch def 31 | /className exch def 32 | } def 33 | /classend { % - => classname newclass 34 | currentdict { 35 | dup xcheck {parentDict methodcompile def} {pop pop} ifelse 36 | } forall 37 | 38 | /instanceVarDict instanceVars def 39 | /parentDictArray [] def 40 | 41 | instanceVarDict type /arraytype eq { 42 | /instanceVarDict instanceVarDict length dict dup begin 43 | instanceVarDict {null def} forall 44 | end def 45 | } if 46 | 47 | parentDict null ne { 48 | parentDict /subClasses 2 copy get [className] append put 49 | /instanceVarDict 50 | parentDict /instanceVarDict get instanceVarDict append def 51 | /parentDictArray 52 | parentDict /parentDictArray get [parentDict] append def 53 | } if 54 | 55 | className 56 | dictend 57 | } def 58 | % Crack open the methods and fix for "super send" and "self send" 59 | /methodcompile { % method parentdict => newmethod 60 | 10 dict begin 61 | /superpending false def 62 | /selfpending false def 63 | /parentDict exch def 64 | [ exch { 65 | dup /send eq superpending selfpending or and { 66 | pop pop 67 | superpending 68 | {parentDict /className get cvx /supersend cvx} 69 | {cvx} ifelse 70 | } if 71 | dup type /arraytype eq {parentDict methodcompile} if 72 | 73 | dup /super eq /superpending exch def 74 | dup /self eq /selfpending exch def 75 | } forall 76 | ] cvx 77 | end 78 | } def 79 | 80 | % Generic Smalltalk-ish Primitives. 81 | % Send a message to an object. 82 | /send { % message object => 83 | dup /parentDictArray get {begin} forall 84 | begin 85 | cvx exec 86 | parentDictArray length 1 add {end} repeat 87 | } def 88 | % Send a message to super without poping myself. 89 | /supersend { % keywordmessage superclass => 90 | exch { 2 copy known {exit} {exch /parentDict get exch} ifelse } loop 91 | get exec 92 | } def 93 | % Put me on the operand stack. 94 | /self {/parentDict where pop} def 95 | 96 | % Your basic object! 97 | /Object null [] classbegin 98 | /new { % class => instance 99 | ObjectTemplate length instanceVarDict length instanceVarExtra 100 | add add dict dup begin 101 | instanceVarDict {def} forall 102 | ObjectTemplate {def} forall 103 | end 104 | dup /parentDict currentdict put 105 | dup /parentDictArray parentDictArray [currentdict] append put 106 | } def 107 | /doit { % proc ins => - (compile & execute the proc) 108 | parentDict /parentDict get methodcompile exec 109 | } def 110 | 111 | /set { % {/key value ...} => - stores the values in the object 112 | mark exch cvx exec 113 | counttomark 2 div {def} repeat pop % store?? 114 | } def 115 | classend def 116 | -------------------------------------------------------------------------------- /lib/ps0.ts: -------------------------------------------------------------------------------- 1 | import { Symbol, inDs, quote, isSymbol, isArray, isQuoted, symbolName } from './util'; 2 | 3 | function member(C, L) { 4 | return 0 <= L.indexOf(C); 5 | } 6 | 7 | class PsParser { 8 | constructor(public Ds: any[]) {} 9 | 10 | L: any; 11 | N: number; 12 | I: number; 13 | D: number; 14 | init(L: any) { 15 | this.L = L; 16 | this.N = L.length; 17 | this.I = 0; 18 | this.D = 0; 19 | } 20 | 21 | peek() {return this.I < this.N && this.L[this.I];} 22 | xchar() {return this.I < this.N && this.L[this.I++];} 23 | skip() { // TODO white space ffeed + null??? 24 | while(this.I < this.N && member(this.L[this.I], " \t\n")) 25 | this.I++; 26 | } 27 | comment() { 28 | while("%" == this.peek()) { 29 | while(this.peek() && "\n" != this.peek()) 30 | this.xchar(); 31 | this.skip(); 32 | } 33 | } 34 | text() { 35 | // TODO hex text in <> 36 | // TODO ASCII base-85 <~ and ~> 37 | this.xchar(); 38 | var L = []; 39 | var N = 1; 40 | while(0 < N && this.peek()) { 41 | var C = this.xchar(); 42 | switch(C) { 43 | case "(": 44 | N++; 45 | break; 46 | case ")": 47 | N--; 48 | if(N <= 0) C = false; 49 | break; 50 | case "\\": 51 | C = this.xchar(); 52 | switch(C) { 53 | case "(": break; 54 | case ")": break; 55 | case "\\": break; 56 | case "n": C = "\n"; break; 57 | case "r": C = "\r"; break; 58 | case "t": C = "\t"; break; 59 | // TODO \n (ignore \n) \b \f \ddd octal 60 | default: 61 | C = false; 62 | } 63 | break; 64 | } 65 | if(C !== false) L.push(C); 66 | } 67 | return L.join(""); 68 | } 69 | symbol() { 70 | // TODO 1e10 1E-5 real numbers 71 | // TODO radix numbers 8#1777 16#FFFE 2#1000 72 | // TODO if preceeded with / then cannot be number 73 | var C = this.xchar(); 74 | if(member(C, "()<>/% \t\n")) throw "Symbol expected, got " + C; 75 | var N = member(C, "+-0123456789."); 76 | var F = "." == C; 77 | var L: any = [C]; 78 | while(this.peek() && !member(this.peek(), "()<>[]{}/% \t\n")) { 79 | C = this.xchar(); 80 | L.push(C); 81 | if(N && !member(C, "0123456789")) { 82 | if(!F && "." == C) F = true; 83 | else N = false; 84 | } 85 | } 86 | L = L.join(""); 87 | if(1 == L.length && member(L, "+-.")) N = false; 88 | return N ? (F ? parseFloat(L) : parseInt(L, 10)) : new Symbol(L); 89 | } 90 | token() { 91 | this.skip(); 92 | switch(this.peek()) { // TODO read dict in <> <~~> 93 | case false: return undefined; 94 | case "%": return this.comment(); 95 | case "[": return new Symbol(this.xchar()); 96 | case "]": return new Symbol(this.xchar()); 97 | case "{": this.D++; return new Symbol(this.xchar()); 98 | case "}": this.D--; return new Symbol(this.xchar()); 99 | case "/": 100 | this.xchar(); 101 | if("/" == this.peek()) { 102 | this.xchar(); 103 | var X = this.symbol(); 104 | return inDs(this.Ds, X); 105 | } else { 106 | var X = this.symbol(); 107 | return quote(X); 108 | } 109 | case "(": return this.text(); 110 | case "<": 111 | this.xchar(); 112 | if("<" != this.peek()) throw "Encoded strings not implemented yet"; 113 | this.xchar(); 114 | return new Symbol("<<"); 115 | case ">": 116 | this.xchar(); 117 | if(">" != this.peek()) throw "Unexpected >"; 118 | this.xchar(); 119 | return new Symbol(">>"); 120 | default: return this.symbol(); 121 | } 122 | } 123 | } 124 | 125 | // PostScript context for a single coroutine. 126 | export class Ps0 { 127 | PsP: PsParser; 128 | constructor( 129 | public Os = [], // Operand stack 130 | public Ds = [], // Dictionary stack 131 | public Es = [] // Execution stack 132 | ) { 133 | console.log('new Ps0', Os.length, Ds.length, Es.length); 134 | this.PsP = new PsParser(this.Ds); 135 | } 136 | 137 | async run(X, Z) { 138 | if (isSymbol(X) && !isQuoted(X)) { // executable name 139 | var D = inDs(this.Ds, X); 140 | if(!D) { 141 | debugger; 142 | throw new Error("bind error '" + X + "'"); 143 | } 144 | this.Es.push([false, D[X]]); 145 | 146 | } else if (Z && isArray(X) && isQuoted(X)) { // proc from Es 147 | if (0 < X.length) { 148 | var F = X[0]; 149 | var R = quote(X.slice(1)); 150 | if(0 < R.length) { 151 | this.Es.push([false, R]); 152 | } 153 | await this.run(F, false); 154 | } 155 | 156 | } else if ("function" == typeof X) { // operator 157 | await X.call(this); 158 | 159 | } else { 160 | this.Os.push(X); 161 | } 162 | } 163 | 164 | async exec() { 165 | var X = this.Os.pop(); 166 | await this.run(X, false); 167 | } 168 | 169 | async step() { 170 | var C = this.Es.pop(); 171 | // This field is used for `exit`. TODO: Remove this useless lookup... 172 | // am I doing it wrong by mutating Es in `exit` instead of checking here? 173 | var L = C.shift(); 174 | var X = C.pop(); 175 | for(var I = 0; I < C.length; I++) { 176 | this.Os.push(C[I]); 177 | } 178 | await this.run(X, true); 179 | } 180 | 181 | async parse(L) { 182 | this.PsP.init(L); 183 | while (this.PsP.peek()) { 184 | var T = this.PsP.token(); 185 | if (T || T === 0) { 186 | this.Os.push(T); 187 | // If not inside a procedure {} block, then run everything right away. 188 | // If inside a procedure, then only run the procedure brackets. 189 | if (this.PsP.D <= 0 || 190 | (isSymbol(T) && 191 | (member(symbolName(T), "{}") || 192 | "<<" == symbolName(T) || ">>" == symbolName(T)))) { 193 | await this.exec(); 194 | while(0 < this.Es.length) { 195 | await this.step(); 196 | } 197 | } 198 | } 199 | } 200 | return this.Os; 201 | } 202 | 203 | suspended = new Set(); 204 | awaitingEvent = false; 205 | 206 | static nextIdx = 0; 207 | idx = Ps0.nextIdx++; 208 | 209 | continuation: Function; 210 | 211 | async suspendFor(next: Ps0) { 212 | // console.log('suspendFor', this.idx, next.idx); 213 | this.suspended.add(this); 214 | 215 | await new Promise((resolve) => { 216 | this.continuation = resolve; 217 | next.continuation(); 218 | // Suspended here. 219 | }); 220 | 221 | // Just woke back up. 222 | this.suspended.delete(this); 223 | this.continuation = null; 224 | } 225 | 226 | async suspendForNext() { 227 | // Called on generic pause/wait. 228 | const suspended = Array.from(this.suspended); 229 | for (const proc of suspended) { 230 | if (proc.awaitingEvent) continue; 231 | // Yield to the first process we can find that's not blocked. 232 | await this.suspendFor(proc); 233 | return; 234 | } 235 | } 236 | 237 | async awaitEvent() { 238 | this.awaitingEvent = true; 239 | await this.suspendForNext(); 240 | } 241 | 242 | async sendEvent(event: any, asyncSend: boolean = false) { 243 | if (new Symbol('TimeStamp') in event) { 244 | // Note that a future timestamp makes the sendEvent async 245 | // (so there's no immediate yield.) 246 | const timeStamp = event[new Symbol('TimeStamp')] * 60000; 247 | setTimeout(() => { 248 | delete event[new Symbol('TimeStamp')]; // FIXME: Do this properly. 249 | this.sendEvent(event, true); 250 | }, timeStamp - Date.now()); 251 | return; 252 | } 253 | 254 | // Convert to array so we can compile the loop to ES5, 255 | // and so that the suspended-list doesn't change while 256 | // we're iterating through it. 257 | const suspended = Array.from(this.suspended); 258 | for (const proc of suspended) { 259 | // If the proc hasn't expressed any interest, assume it's 260 | // not interested in anything. 261 | if (proc.hasInterestIn && proc.awaitingEvent && proc.hasInterestIn(event)) { 262 | // FIXME: Reaches directly into the other process's state. 263 | // Kind of a hack.. this maybe should be in awaitevent somehow instead. 264 | proc.awaitingEvent = false; 265 | proc.Os.push(event); 266 | if (!asyncSend) { 267 | await this.suspendFor(proc); 268 | } 269 | } 270 | } 271 | } 272 | 273 | async fork(fn: Function) { 274 | const child = new Ps0(this.Os.slice(0), this.Ds.slice(0), []); 275 | child.suspended = this.suspended; // Should share same coroutine set. 276 | child.continuation = async function() { 277 | await child.run(fn, true); 278 | while (0 < child.Es.length) 279 | await child.step(); 280 | // Child process is done now. 281 | this.suspended.values().next().value.continuation(); 282 | }; 283 | await this.suspendFor(child); 284 | return child; 285 | } 286 | } 287 | -------------------------------------------------------------------------------- /lib/stdlib.ps: -------------------------------------------------------------------------------- 1 | %%% WPS: PostScript and PDF interpreter for HTML 5 canvas 2 | %%% http://logand.com/sw/wps/index.html 3 | %%% (c) 2009, 2010, 2011 Tomas Hlavaty 4 | %%% Licensed under the GPLv3+ license. 5 | %%% http://www.fsf.org/licensing/licenses/gpl.html 6 | 7 | currentdict /systemdict 8 | currentdict 9 | put 10 | 11 | systemdict /{ 12 | /mark cvx 13 | put 14 | 15 | systemdict /[ 16 | /mark cvx 17 | put 18 | 19 | systemdict /] 20 | /counttomark cvx 21 | /array cvx 22 | /astore cvx 23 | /exch cvx 24 | /pop cvx 25 | 5 array astore cvx put 26 | 27 | systemdict /} 28 | /] cvx 29 | /cvx cvx 30 | 2 array astore cvx put 31 | 32 | systemdict /def { 33 | currentdict 2 index 34 | 2 index 35 | put 36 | pop pop 37 | } put 38 | 39 | /maxlength 1000 def % TODO 40 | /.bdef{bind def}bind def 41 | /.xdef{exch def}.bdef 42 | /dup{0 index}.bdef 43 | /load{dup where pop exch get}.bdef 44 | /.ldef{load def}.bdef 45 | /if{{}ifelse}.bdef 46 | /cleartomark{array pop}.bdef 47 | /known{exch begin where{currentdict eq}{false}ifelse end}.bdef 48 | /store{1 index where{3 1 roll put}{def}ifelse}.bdef 49 | /not{{false}{true}ifelse}.bdef 50 | /.logand{{{true}{false}ifelse}{pop false}ifelse}.bdef 51 | /and/.logand .ldef % TODO numeric and 52 | /.logor{{pop true}{{true}{false}ifelse}ifelse}.bdef 53 | /or/.logor .ldef % TODO numeric or 54 | /ne{eq not}.bdef 55 | /ge{lt not}.bdef 56 | /le{1 index 1 index eq 3 1 roll lt or}.bdef 57 | /gt{le not}.bdef 58 | /.repeat{1 1 4 2 roll for}.bdef 59 | 60 | %% stuff added to support oop.ps 61 | /dictbegin{1000 dict begin}.bdef 62 | /dictend{currentdict end}.bdef 63 | /nullarray{0 array}.bdef 64 | /append { 65 | dup type (arraytype) eq 66 | {exch (concat)1 .call} 67 | { 68 | 1000 dict 69 | 3 1 roll 70 | .window(Object)get (assign)3 .call 71 | } 72 | ifelse 73 | }.bdef 74 | 75 | %% math 76 | 77 | /floor{.math(floor)1 .call}.bdef 78 | 79 | /neg{0 exch sub}.bdef 80 | /add{neg sub}.bdef 81 | /idiv{div floor}.bdef 82 | 83 | /abs{.math(abs)1 .call}.bdef 84 | /.acos{.math(acos)1 .call}.bdef 85 | /.asin{.math(asin)1 .call}.bdef 86 | /atan{exch .math(atan)1 .call}.bdef 87 | /.atan2{.math(atan2)2 .call}.bdef 88 | /ceiling{.math(ceil)1 .call}.bdef 89 | /cos{.math(cos)1 .call}.bdef 90 | /.exp{.math(exp)1 .call}.bdef 91 | /log{.math(log)1 .call}.bdef 92 | /.max{.math(max)2 .call}.bdef 93 | /.min{.math(min)2 .call}.bdef 94 | /.pow{.math(pow)2 .call}.bdef 95 | /.random{.math(random)0 .call}.bdef 96 | /rand{.random}.bdef % TODO follow spec 97 | /round{.math(round)1 .call}.bdef 98 | /sin{.math(sin)1 .call}.bdef 99 | /sqrt{.math(sqrt)1 .call}.bdef 100 | /.tan{.math(tan)1 .call}.bdef 101 | /truncate{.math(truncate)1 .call}.bdef % TODO Math.truncate does not exist! 102 | 103 | /.e{.math(E)get}.bdef 104 | /.ln2{.math(LN2)get}.bdef 105 | /.ln10{.math(LN10)get}.bdef 106 | /.log2e{.math(LOG2E)get}.bdef 107 | /.log10e{.math(LOG10E)get}.bdef 108 | /.pi{.math(PI)get}.bdef 109 | /.sqrt1_2{.math(SQRT1_2)get}.bdef 110 | /.sqrt2{.math(SQRT2)get}.bdef 111 | 112 | /cvr{1.0 mul}.bdef 113 | /cvi{round}.bdef 114 | 115 | %% html 116 | 117 | /.setTimeout{.window(setTimeout)2 .call}.bdef % cb ms -- id 118 | /.clearTimeout{.window(clearTimeout)1 .call pop}.bdef % id -- 119 | /.setInterval{.window(setInterval)2 .call}.bdef % cb ms -- id 120 | /.clearInterval{.window(clearInterval)1 .call pop}.bdef % id -- 121 | /.document{.window(document)get}.bdef % -- document 122 | /.getElementById{.document(getElementById)1 .call}.bdef % id -- w 123 | /.hook{put}.bdef % e k cb -- 124 | 125 | %% canvas 126 | 127 | /.setGc{.getElementById (2d)exch (getContext)1 .call /.$gc .xdef}.bdef 128 | /.gc{/.$gc load}.bdef % indirection so .gc is always whatever current gc is 129 | /.gget{.gc exch get}.bdef 130 | /.gput{.gc 3 1 roll exch put}.bdef 131 | /.gcall0{.gc 3 1 roll .call pop}.bdef 132 | /.gcall1{.gc 3 1 roll .call}.bdef 133 | /.gcanvas{(canvas).gget}.bdef 134 | 135 | % Disabled because messes up translate hack / 136 | % doesn't make sense with buffered windows. 137 | %/.gdim{.gcanvas exch(height)exch put .gcanvas exch(width)exch put}.bdef 138 | /.gdim{pop pop}.bdef 139 | /.gbox{.gdim pop pop}.bdef % TODO compute properly 140 | 141 | /.save{(save)0 .gcall0}.bdef 142 | /.restore{(restore)0 .gcall0}.bdef 143 | /.scale{(scale)2 .gcall0}.bdef 144 | /.rotate{(rotate)1 .gcall0}.bdef 145 | /.translate{(translate)2 .gcall0}.bdef 146 | /.transform{(transform)6 .gcall0}.bdef 147 | /.setTransform{(setTransform)6 .gcall0}.bdef 148 | /.createLinearGradient{(createLinearGradient)4 .gcall1}.bdef 149 | /.createRadialGradient{(createRadialGradient)6 .gcall1}.bdef 150 | /.createPattern{(createPattern)2 .gcall1}.bdef 151 | /.clearRect{(clearRect)4 .gcall0}.bdef 152 | /.fillRect{(fillRect)4 .gcall0}.bdef 153 | /.strokeRect{(strokeRect)4 .gcall0}.bdef 154 | /.beginPath{(beginPath)0 .gcall0}.bdef 155 | /.closePath{(closePath)0 .gcall0}.bdef 156 | /.moveTo{(moveTo)2 .gcall0}.bdef 157 | /.lineTo{(lineTo)2 .gcall0}.bdef 158 | /.quadraticCurveTo{(quadraticCurveTo)4 .gcall0}.bdef 159 | /.bezierCurveTo{(bezierCurveTo)6 .gcall0}.bdef 160 | /.arcTo{(arcTo)5 .gcall0}.bdef 161 | /.rect{(rect)4 .gcall0}.bdef 162 | /.arc{(arc)6 .gcall0}.bdef 163 | /.fill{(fill)0 .gcall0}.bdef 164 | /.stroke{(stroke)0 .gcall0}.bdef 165 | /.clip{(clip)0 .gcall0}.bdef 166 | /.isPointInPath{(isPointInPath)2 .gcall1}.bdef 167 | /.fillText{(fillText)4 .gcall0}.bdef 168 | /.fillText{}.bdef % TODO not working in Firefox 169 | /.strokeText{(strokeText)4 .gcall0}.bdef 170 | /.strokeText{}.bdef % TODO not working in Firefox 171 | /.measureText{(measureText)1 .gcall1}.bdef 172 | /.drawImage1{(drawImage1)5 .gcall0}.bdef 173 | /.drawImage2{(drawImage2)9 .gcall0}.bdef 174 | /.createImageData1{(createImageData1)1 .gcall1}.bdef 175 | /.createImageData2{(createImageData2)2 .gcall1}.bdef 176 | /.getImageData{(getImageData)4 .gcall1}.bdef 177 | /.putImageData{(putImageData)7 .gcall0}.bdef 178 | 179 | /.getGlobalAlpha{(globalAlpha).gget}.bdef 180 | /.getGlobalCompositeOperation{(globalCompositeOperation).gget}.bdef 181 | /.getStrokeStyle{(strokeStyle).gget}.bdef 182 | /.getFillStyle{(fillStyle).gget}.bdef 183 | /.getLineWidth{(lineWidth).gget}.bdef 184 | /.getLineCap{(lineCap).gget}.bdef 185 | /.getLineJoin{(lineJoin).gget}.bdef 186 | /.getMiterLimit{(miterLimit).gget}.bdef 187 | /.getShadowOffsetX{(shadowOffsetX).gget}.bdef 188 | /.getShadowOffsetY{(shadowOffsetY).gget}.bdef 189 | /.getShadowBlur{(shadowBlur).gget}.bdef 190 | /.getShadowColor{(shadowColor).gget}.bdef 191 | /.getFont{(font).gget}.bdef 192 | /.getTextAlign{(textAlign).gget}.bdef 193 | /.getTextBaseline{(textBaseline).gget}.bdef 194 | 195 | /.setGlobalAlpha{(globalAlpha).gput}.bdef 196 | /.setGlobalCompositeOperation{(globalCompositeOperation).gput}.bdef 197 | /.setStrokeStyle{(strokeStyle).gput}.bdef 198 | /.setFillStyle{(fillStyle).gput}.bdef 199 | /.setLineWidth{(lineWidth).gput}.bdef 200 | /.setLineCap{(lineCap).gput}.bdef 201 | /.setLineJoin{(lineJoin).gput}.bdef 202 | /.setLineCap{pop}.bdef % TODO remove this later (Firefox throws) 203 | /.setLineJoin{pop}.bdef % TODO remove this later (Firefox throws) 204 | /.setMiterLimit{(miterLimit).gput}.bdef 205 | /.setShadowOffsetX{(shadowOffsetX).gput}.bdef 206 | /.setShadowOffsetY{(shadowOffsetY).gput}.bdef 207 | /.setShadowBlur{(shadowBlur).gput}.bdef 208 | /.setShadowColor{(shadowColor).gput}.bdef 209 | /.setFont{(font).gput}.bdef 210 | /.setTextAlign{(textAlign).gput}.bdef 211 | /.setTextBaseline{(textBaseline).gput}.bdef 212 | 213 | %% PostScript 214 | 215 | /.deg2rad{.pi 180 div mul}.bdef 216 | /.rad2deg{180 .pi div mul}.bdef 217 | 218 | /.$cx 0 def 219 | /.$cy 0 def 220 | /.$px 0 def 221 | /.$py 0 def 222 | /.setPoint{/.$cy .xdef/.$cx .xdef}.bdef 223 | /.setPath{/.$py .xdef/.$px .xdef}.bdef 224 | /currentpoint{/.$cx load /.$cy load}.bdef 225 | /.getPath{/.$px load /.$py load}.bdef 226 | 227 | /identmatrix{pop [1 0 0 1 0 0]}.bdef % TODO fill 228 | /matrix{6 array identmatrix}.bdef 229 | /setmatrix{/.$tm .xdef}.bdef 230 | /defaultmatrix{pop matrix}.bdef % TODO fill 231 | /initmatrix{matrix defaultmatrix setmatrix}.bdef 232 | /currentmatrix{pop /.$tm load}.bdef % TODO fill 233 | initmatrix 234 | 235 | /.getTmd{/.$tmd load}.bdef 236 | /.setTmd{/.$tmd .xdef}.bdef 237 | /.resetTmd{matrix .setTmd}.bdef 238 | .resetTmd 239 | 240 | /.update{ % m -- 241 | currentpoint 2 index % m .$cx .$cy m 242 | .xy .setPoint % m 243 | dup .getTmd exch .mmul .setTmd % (.$tmd x m) 244 | dup currentmatrix exch .mmul setmatrix % = .$tm x m 245 | }.bdef 246 | 247 | /transform{dup type(arraytype)ne{.getTmd}if .xy}.bdef 248 | /itransform{dup type(arraytype)ne{.getTmd}if .minv .xy}.bdef 249 | 250 | /.scaleM{0 0 3 2 roll 0 0 6 array astore}.bdef % x y -- [x 0 0 y 0 0] 251 | /.scale3{pop .scaleM}.bdef 252 | /.scale2{2 copy .scaleM .update .scale}.bdef 253 | /scale{dup type(arraytype)eq{.scale3}{.scale2}ifelse}.bdef 254 | 255 | /.translateM{1 0 0 1 6 4 roll 6 array astore}.bdef % x y -- [1 0 0 1 x y] 256 | /.translate3{pop .translateM}.bdef 257 | /.translate2{2 copy .translateM .update .translate}.bdef 258 | /translate{dup type(arraytype)eq{.translate3}{.translate2}ifelse}.bdef 259 | 260 | /.rotateM{dup cos exch sin dup neg 2 index 0 0 6 array astore}.bdef % a -- [c s -s c 0 0] 261 | /.rotate2{pop .deg2rad .rotateM}.bdef 262 | /.rotate1{.deg2rad dup .rotateM .update .rotate}.bdef 263 | /rotate{dup type(arraytype)eq{.rotate2}{.rotate1}ifelse}.bdef 264 | 265 | %matrix concat – Replace CTM by matrix ´ CTM 266 | %matrix1 matrix2 matrix3 concatmatrix matrix3 Fill matrix3 with matrix1 ´ matrix2 267 | 268 | %dx dy dtransform dx¢ dy¢ Transform distance (dx, dy) by CTM 269 | %dx dy matrix dtransform dx¢ dy¢ Transform distance (dx, dy) by matrix 270 | 271 | %dx¢ dy¢ idtransform dx dy Perform inverse transform of distance (dx¢, dy¢) by CTM 272 | %dx¢ dy¢ matrix idtransform dx dy Perform inverse transform of distance (dx¢, dy¢) by matrix 273 | 274 | %matrix1 matrix2 invertmatrix matrix2 Fill matrix2 with inverse of matrix1 275 | 276 | /gsave{.save}.bdef 277 | /grestore{.restore}.bdef 278 | /clip{.clip}.bdef 279 | /rectclip{.clearRect}.bdef 280 | /rectfill{.fillRect}.bdef 281 | /rectstroke{.strokeRect}.bdef 282 | /newpath{.beginPath}.bdef 283 | /closepath{.closePath}.bdef 284 | /moveto{2 copy .setPoint 2 copy .setPath .resetTmd .moveTo}.bdef 285 | /lineto{2 copy .setPoint 2 copy .setPath .resetTmd .lineTo}.bdef 286 | /arcto{.arcTo}.bdef 287 | 288 | /setlinewidth{.setLineWidth}.bdef 289 | /setlinecap{.setLineCap}.bdef % TODO 290 | /setlinejoin{.setLineJoin}.bdef % TODO 291 | /setmiterlimit{.setMiterLimit}.bdef 292 | 293 | /currentlinewidth{.getLineWidth}.bdef 294 | /currentlinecap{<> .getLineCap get}.bdef 295 | /currentlinejoin{<> .getLineJoin get}.bdef 296 | /currentmiterlimit{.getMiterLimit}.bdef 297 | 298 | /setgray{255 mul dup dup .rgb dup .setStrokeStyle .setFillStyle}.bdef 299 | /setrgbcolor{3{255 mul round 3 1 roll}repeat .rgb dup .setStrokeStyle .setFillStyle}.bdef 300 | /setcmykcolor{setrgbcolor pop}.bdef % TODO 301 | /sethsbcolor{setrgbcolor}.bdef % TODO 302 | /clippath{0 0 .gcanvas(width)get .gcanvas(height)get .rect}.bdef % TODO 303 | /show{currentpoint 3 2 roll 3 copy .fillText .strokeText}.bdef % TODO 304 | 305 | /rlineto{.getTmd .xy /.$py load add exch /.$px load add exch .getTmd .minv .xy lineto}.bdef 306 | /curveto{2 copy .setPoint 2 copy .setPath .resetTmd .bezierCurveTo}.bdef 307 | 308 | /currentflat{42}.bdef % TODO 309 | /setflat{pop}.bdef % TODO 310 | 311 | /arc{.deg2rad exch .deg2rad exch true .arc}.bdef % TODO currentpoint 312 | /arcn{.deg2rad exch .deg2rad exch false .arc}.bdef % TODO currentpoint 313 | 314 | /fill{.fill newpath currentpoint .moveTo}.bdef % TODO 315 | 316 | /setdash{pop pop}.bdef % TODO 317 | 318 | /stroke{.stroke newpath currentpoint .moveTo}.bdef 319 | 320 | /showpage{}.bdef % TODO 321 | /grestoreall{}.bdef % TODO 322 | /readonly{}.bdef % TODO 323 | /currentfile{(url?)}.bdef % TODO 324 | /eexec{pop}.bdef % TODO 325 | /findfont{}.bdef % TODO 326 | /scalefont{pop}.bdef % TODO 327 | /setfont{pop}.bdef % TODO C.font = N + "pt " + F.V; 328 | /stopped{}.bdef % TODO 329 | /string{}.bdef % TODO 330 | /pathbbox{}.bdef % TODO 331 | /urx{}.bdef % TODO 332 | /ury{}.bdef % TODO 333 | /llx{}.bdef % TODO 334 | /lly{}.bdef % TODO 335 | /pagewidth{}.bdef % TODO 336 | /pageheight{}.bdef % TODO 337 | /inwidth{}.bdef % TODO 338 | /inheight{}.bdef % TODO 339 | /usertime{}.bdef % TODO 340 | /srand{}.bdef % TODO 341 | 342 | % Current time in minutes. 343 | /currenttime{.date(getTime)0 .call 60000 div}.bdef 344 | 345 | %% PDF 346 | 347 | /w{setlinewidth}.bdef 348 | /J{setlinecap}.bdef % TODO 349 | /j{setlinejoin}.bdef % TODO 350 | /M{setmiterlimit}.bdef 351 | /d{setdash}.bdef % TODO 352 | /ri{}.bdef % TODO 353 | /i{1 .min setflat}.bdef 354 | /gs{}.bdef % TODO 355 | /q{gsave}.bdef 356 | /Q{grestore}.bdef 357 | /cm{.transform}.bdef 358 | /m{newpath moveto}.bdef % TODO only if not m previously 359 | /l{lineto}.bdef 360 | /c{.bezierCurveTo}.bdef 361 | /v{currentpoint 6 2 roll c}.bdef 362 | /y{2 copy c}.bdef 363 | /h{closepath}.bdef % TODO 364 | /re{.rect}.bdef % TODO really, or x y m , x+w y l , x+w y+h l , x y+h l , h 365 | /S{stroke}.bdef 366 | /s{h S}.bdef 367 | /f{fill}.bdef % TODO 368 | /F{f}.bdef 369 | /f*{}.bdef % TODO 370 | /B{f S}.bdef 371 | /B*{f* S}.bdef 372 | /b{h B}.bdef 373 | /b*{h B*}.bdef 374 | /n{}.bdef % TODO 375 | /W{clip}.bdef % TODO 376 | /W*{clip}.bdef % TODO 377 | /BT{}.bdef % TODO 378 | /ET{}.bdef % TODO 379 | /Tc{}.bdef % TODO 380 | /Tw{}.bdef % TODO 381 | /Tz{}.bdef % TODO 382 | /TL{}.bdef % TODO 383 | /Tf{setfont}.bdef % TODO 384 | /Tr{}.bdef % TODO 385 | /Ts{}.bdef % TODO 386 | /Td{translate 0 0 moveto}.bdef 387 | /TD{}.bdef % TODO 388 | /Tm{}.bdef % TODO 389 | /T*{}.bdef % TODO 390 | /Tj{show}.bdef % TODO 391 | /TJ{}.bdef % TODO 392 | /'{}.bdef % TODO 393 | /"{}.bdef % TODO 394 | /d0{}.bdef % TODO 395 | /d1{}.bdef % TODO 396 | /CS{}.bdef % TODO 397 | /cs{}.bdef % TODO 398 | %/SC/setcolor .ldef 399 | /SCN{}.bdef % TODO 400 | %/sc/setcolor .ldef 401 | /scn{}.bdef % TODO 402 | /G{}.bdef % TODO 403 | /g{}.bdef % TODO 404 | /RG{}.bdef % TODO 405 | /rg{setrgbcolor}.bdef % TODO 406 | /K{}.bdef % TODO 407 | /k{}.bdef % TODO 408 | /sh{}.bdef % TODO 409 | /BI{}.bdef % TODO 410 | /ID{}.bdef % TODO 411 | /EI{}.bdef % TODO 412 | /Do{}.bdef % TODO 413 | /MP{}.bdef % TODO 414 | /DP{}.bdef % TODO 415 | /BMC{}.bdef % TODO 416 | /BDC{}.bdef % TODO 417 | /EMC{}.bdef % TODO 418 | /BX{}.bdef % TODO 419 | /EX{}.bdef % TODO 420 | 421 | %% finish 422 | 423 | false .strictBind 424 | 425 | /userdict 1000 dict def 426 | userdict begin 427 | -------------------------------------------------------------------------------- /lib/util.ts: -------------------------------------------------------------------------------- 1 | export function isQuoted(V) {return V.D16322F5;} 2 | export function quote(V) {V.D16322F5 = true; return V;} 3 | export function unquote(V) {delete V.D16322F5; return V;} 4 | 5 | // random markers for quoting and toString generated using picolisp 6 | // (hex (in "/dev/random" (rd 4))) 7 | 8 | export function Symbol(N): void {this.nm = N; return this;} 9 | export function isSymbol(V) {return V && V.constructor === Symbol;} 10 | export function symbolName(V) {return V.nm;} 11 | Symbol.prototype.toString = function() {return "05E2710C" + symbolName(this);}; 12 | 13 | export function isArray(V) { 14 | return V && V.constructor === Array; 15 | } 16 | 17 | export function isObject(V) {return "object" == typeof V;} 18 | 19 | export function inDs(Ds, K) { 20 | for(var I = Ds.length - 1; 0 <= I; --I) { 21 | if("undefined" != typeof Ds[I][K]) 22 | return Ds[I]; 23 | } 24 | return false; 25 | } 26 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "dewdrop", 3 | "version": "1.0.0", 4 | "description": "NeWS implementation.", 5 | "main": "build/lib/index.js", 6 | "directories": { 7 | "example": "examples", 8 | "test": "test" 9 | }, 10 | "scripts": { 11 | "build": "webpack", 12 | "start": "webpack-dev-server", 13 | "test": "webpack" 14 | }, 15 | "repository": { 16 | "type": "git", 17 | "url": "git+https://github.com/osnr/dewdrop.git" 18 | }, 19 | "author": "Omar Rizwan ", 20 | "license": "MIT", 21 | "bugs": { 22 | "url": "https://github.com/osnr/dewdrop/issues" 23 | }, 24 | "homepage": "https://github.com/osnr/dewdrop#readme", 25 | "devDependencies": { 26 | "jq-console": "^2.13.2", 27 | "jquery": "^3.1.1", 28 | "mocha": "^3.0.2", 29 | "mocha-loader": "^1.0.0", 30 | "raw-loader": "^0.5.1", 31 | "ts-loader": "^0.8.2", 32 | "webpack": "^1.13.2", 33 | "webpack-dev-server": "^1.16.1" 34 | }, 35 | "dependencies": {} 36 | } 37 | -------------------------------------------------------------------------------- /test/basic.spec.ts: -------------------------------------------------------------------------------- 1 | import Dewdrop from '../lib/index'; 2 | import { Symbol, quote } from '../lib/util'; 3 | 4 | import * as assert from 'assert'; 5 | 6 | describe('Basic interpreter tests', function() { 7 | this.timeout(10000); 8 | 9 | async function run(ps: string): Promise { 10 | const dewdrop = await Dewdrop(); 11 | return await dewdrop.parse(ps); 12 | } 13 | it('14 literal', async function() { 14 | assert.deepEqual(await run('14'), [14]); 15 | }); 16 | it('(hello world) 7', async function() { 17 | assert.deepEqual(await run('(hello world) 7'), ['hello world', 7]); 18 | }); 19 | it('2 3 add', async function() { 20 | assert.deepEqual(await run('2 3 add'), [5]); 21 | }); 22 | it('survives after fork', async function() { 23 | assert.deepEqual((await run('{1} fork 12')).pop(), 12); 24 | }); 25 | it('has fork actually do something', async function() { 26 | assert.deepEqual(await run('{4 3 add} fork waitprocess'), [7]); 27 | }); 28 | it('repeats', async function() { 29 | assert.deepEqual(await run('5 {1} repeat'), [1, 1, 1, 1, 1]); 30 | }); 31 | it('loops and exits', async function() { 32 | assert.deepEqual(await run('0 {dup 6 ne {1 add} {exit} ifelse} loop'), [6]); 33 | }); 34 | it('nested loops and exits', async function() { 35 | assert.deepEqual(await run('1 10 {{dup 6 mod 0 ne {1 add} {1 add exit} ifelse} loop} repeat'), [61]) 36 | }); 37 | it('known bug', async function() { 38 | assert.deepEqual(await run('dictbegin /K (V) def dictend /K known'), [true]); 39 | assert.deepEqual(await run('dictbegin /K (V) def dictend /K2 known'), [false]); 40 | }); 41 | it('awaits event', async function() { 42 | assert.deepEqual(await run(` 43 | { 44 | createevent dup begin 45 | /Name /Hello def 46 | end expressinterest 47 | { awaitevent == } loop 48 | } fork 49 | 50 | createevent dup begin 51 | /Name /Hello def 52 | /Action /Mumble def 53 | end sendevent 54 | 55 | killprocess 56 | `), []); 57 | }); 58 | it('executes array inside proc', async function() { 59 | assert.deepEqual(await run('{[2 3 add]} exec'), [[5]]); 60 | }); 61 | it('append', async function() { 62 | assert.deepEqual(await run('[1 2 3] [4 5 6] append'), [[1, 2, 3, 4, 5, 6]]); 63 | assert.deepEqual(await run(` 64 | dictbegin 65 | /Name /A def 66 | /Foo /Bar def 67 | dictend 68 | dictbegin 69 | /Name /B def 70 | /Baz /Qux def 71 | dictend 72 | append 73 | dup == 74 | `), [{ 75 | [new Symbol('Name')]: quote(new Symbol('B')), 76 | [new Symbol('Foo')]: quote(new Symbol('Bar')), 77 | [new Symbol('Baz')]: quote(new Symbol('Qux')) 78 | }]); 79 | }); 80 | it('passes Densmore OOP test', async function() { 81 | assert.deepEqual(await run(` 82 | % From Densmore (1986), Appendix B. 83 | 84 | /One Object [] classbegin 85 | /test {1} def 86 | /result1 {/test self send} def 87 | classend def 88 | 89 | /Two One [] classbegin 90 | /test {2} def 91 | classend def 92 | 93 | /ex1 /new One send def 94 | /ex2 /new Two send def 95 | 96 | /test ex1 send 97 | /result1 ex1 send 98 | /test ex2 send 99 | /result1 ex2 send 100 | 101 | /Three Two [] classbegin 102 | /result2 {/result1 self send} def 103 | /result3 {/test super send} def 104 | classend def 105 | /Four Three [] classbegin 106 | /test {4} def 107 | classend def 108 | 109 | /ex3 /new Three send def 110 | /ex4 /new Four send def 111 | 112 | /test ex3 send 113 | /result1 ex4 send 114 | /result2 ex3 send 115 | /result2 ex4 send 116 | /result3 ex3 send 117 | /result3 ex4 send 118 | `), [1, 1, 2, 2, 2, 4, 2, 4, 2, 2]); 119 | }); 120 | }); 121 | -------------------------------------------------------------------------------- /test/entry.js: -------------------------------------------------------------------------------- 1 | const context = require.context('mocha!.', true, /.spec.ts$/); 2 | context.keys().forEach(context); 3 | -------------------------------------------------------------------------------- /test/examples.spec.ts: -------------------------------------------------------------------------------- 1 | import Dewdrop from '../lib/index'; 2 | 3 | declare var require: any; 4 | 5 | describe('Examples', function() { 6 | this.timeout(10000); 7 | 8 | function runExamples(req: any) { 9 | req.keys().forEach(runExample.bind(this, req)); 10 | } 11 | function runExample(req: any, examplePath: string) { 12 | const example = req(examplePath); 13 | it(examplePath, async function() { 14 | // Hack so graphical output shows inline in test report. 15 | const uls = document.getElementsByTagName('ul'); 16 | const canvas = document.createElement('canvas'); 17 | canvas.width = 300; 18 | canvas.height = 300; 19 | canvas.style.background = 'whitesmoke'; 20 | uls[uls.length - 1].appendChild(canvas); 21 | 22 | const dewdrop = await Dewdrop(canvas); 23 | await dewdrop.parse(example); 24 | }); 25 | } 26 | 27 | describe('from original WPS', function() { 28 | runExamples(require.context('../examples/wps', true, /\.ps$/)); 29 | }); 30 | 31 | describe('from NeWS', function() { 32 | runExamples(require.context('../examples/news', true, /\.ps$/)); 33 | }); 34 | }); 35 | -------------------------------------------------------------------------------- /test/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es5", 5 | "noImplicitAny": false, 6 | "sourceMap": false, 7 | "outDir": "build", 8 | "lib": ["dom", "es6"] 9 | }, 10 | "exclude": [ 11 | "node_modules" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /typings.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "dewdrop", 3 | "dependencies": {}, 4 | "globalDevDependencies": { 5 | "jquery": "registry:dt/jquery#1.10.0+20160929162922", 6 | "mocha": "registry:dt/mocha#2.2.5+20160720003353", 7 | "node": "registry:dt/node#6.0.0+20160826120425" 8 | }, 9 | "globalDependencies": {} 10 | } 11 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | var webpack = require('webpack'); 2 | var path = require('path'); 3 | 4 | module.exports = { 5 | entry: { 6 | test: './test/entry.js', 7 | executive: './executive/index.ts' 8 | }, 9 | devtool: 'cheap-module-eval-source-map', 10 | output: { 11 | filename: './dist/[name].entry.js' 12 | }, 13 | resolve: { 14 | extensions: ['', '.js', '.ts'] 15 | }, 16 | module: { 17 | loaders: [ 18 | { 19 | test: /\.ts$/, 20 | exclude: /node_modules/, 21 | loader: 'ts' 22 | }, 23 | { 24 | test: /\.ps$/, 25 | loader: 'raw' 26 | } 27 | ] 28 | }, 29 | node: { 30 | fs: 'empty' 31 | } 32 | }; 33 | --------------------------------------------------------------------------------