packages feed

reactivity (empty) → 0.2.3.0

raw patch · 13 files changed

+3225/−0 lines, 13 filesdep +ConcurrentUtilsdep +Displayabledep +Win32setup-changed

Dependencies added: ConcurrentUtils, Displayable, Win32, array, base, bmp, bytestring, comonad, containers, ghc-prim, list-extras, monad-loops, monads-tf, parallel, random, time, transformers

Files

+ COPYING view
@@ -0,0 +1,661 @@+                    GNU AFFERO GENERAL PUBLIC LICENSE+                       Version 3, 19 November 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++                            Preamble++  The GNU Affero General Public License is a free, copyleft license for+software and other kinds of works, specifically designed to ensure+cooperation with the community in the case of network server software.++  The licenses for most software and other practical works are designed+to take away your freedom to share and change the works.  By contrast,+our General Public Licenses are intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users.++  When we speak of free software, we are referring to freedom, not+price.  Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++  Developers that use our General Public Licenses protect your rights+with two steps: (1) assert copyright on the software, and (2) offer+you this License which gives you legal permission to copy, distribute+and/or modify the software.++  A secondary benefit of defending all users' freedom is that+improvements made in alternate versions of the program, if they+receive widespread use, become available for other developers to+incorporate.  Many developers of free software are heartened and+encouraged by the resulting cooperation.  However, in the case of+software used on network servers, this result may fail to come about.+The GNU General Public License permits making a modified version and+letting the public access it on a server without ever releasing its+source code to the public.++  The GNU Affero General Public License is designed specifically to+ensure that, in such cases, the modified source code becomes available+to the community.  It requires the operator of a network server to+provide the source code of the modified version running there to the+users of that server.  Therefore, public use of a modified version, on+a publicly accessible server, gives the public access to the source+code of the modified version.++  An older license, called the Affero General Public License and+published by Affero, was designed to accomplish similar goals.  This is+a different license, not a version of the Affero GPL, but Affero has+released a new version of the Affero GPL which permits relicensing under+this license.++  The precise terms and conditions for copying, distribution and+modification follow.++                       TERMS AND CONDITIONS++  0. Definitions.++  "This License" refers to version 3 of the GNU Affero General Public License.++  "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++  "The Program" refers to any copyrightable work licensed under this+License.  Each licensee is addressed as "you".  "Licensees" and+"recipients" may be individuals or organizations.++  To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy.  The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++  A "covered work" means either the unmodified Program or a work based+on the Program.++  To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy.  Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++  To "convey" a work means any kind of propagation that enables other+parties to make or receive copies.  Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++  An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License.  If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++  1. Source Code.++  The "source code" for a work means the preferred form of the work+for making modifications to it.  "Object code" means any non-source+form of a work.++  A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++  The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form.  A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++  The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities.  However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work.  For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++  The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++  The Corresponding Source for a work in source code form is that+same work.++  2. Basic Permissions.++  All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met.  This License explicitly affirms your unlimited+permission to run the unmodified Program.  The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work.  This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++  You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force.  You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright.  Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++  Conveying under any other circumstances is permitted solely under+the conditions stated below.  Sublicensing is not allowed; section 10+makes it unnecessary.++  3. Protecting Users' Legal Rights From Anti-Circumvention Law.++  No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++  When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++  4. Conveying Verbatim Copies.++  You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++  You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++  5. Conveying Modified Source Versions.++  You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++    a) The work must carry prominent notices stating that you modified+    it, and giving a relevant date.++    b) The work must carry prominent notices stating that it is+    released under this License and any conditions added under section+    7.  This requirement modifies the requirement in section 4 to+    "keep intact all notices".++    c) You must license the entire work, as a whole, under this+    License to anyone who comes into possession of a copy.  This+    License will therefore apply, along with any applicable section 7+    additional terms, to the whole of the work, and all its parts,+    regardless of how they are packaged.  This License gives no+    permission to license the work in any other way, but it does not+    invalidate such permission if you have separately received it.++    d) If the work has interactive user interfaces, each must display+    Appropriate Legal Notices; however, if the Program has interactive+    interfaces that do not display Appropriate Legal Notices, your+    work need not make them do so.++  A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit.  Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++  6. Conveying Non-Source Forms.++  You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++    a) Convey the object code in, or embodied in, a physical product+    (including a physical distribution medium), accompanied by the+    Corresponding Source fixed on a durable physical medium+    customarily used for software interchange.++    b) Convey the object code in, or embodied in, a physical product+    (including a physical distribution medium), accompanied by a+    written offer, valid for at least three years and valid for as+    long as you offer spare parts or customer support for that product+    model, to give anyone who possesses the object code either (1) a+    copy of the Corresponding Source for all the software in the+    product that is covered by this License, on a durable physical+    medium customarily used for software interchange, for a price no+    more than your reasonable cost of physically performing this+    conveying of source, or (2) access to copy the+    Corresponding Source from a network server at no charge.++    c) Convey individual copies of the object code with a copy of the+    written offer to provide the Corresponding Source.  This+    alternative is allowed only occasionally and noncommercially, and+    only if you received the object code with such an offer, in accord+    with subsection 6b.++    d) Convey the object code by offering access from a designated+    place (gratis or for a charge), and offer equivalent access to the+    Corresponding Source in the same way through the same place at no+    further charge.  You need not require recipients to copy the+    Corresponding Source along with the object code.  If the place to+    copy the object code is a network server, the Corresponding Source+    may be on a different server (operated by you or a third party)+    that supports equivalent copying facilities, provided you maintain+    clear directions next to the object code saying where to find the+    Corresponding Source.  Regardless of what server hosts the+    Corresponding Source, you remain obligated to ensure that it is+    available for as long as needed to satisfy these requirements.++    e) Convey the object code using peer-to-peer transmission, provided+    you inform other peers where the object code and Corresponding+    Source of the work are being offered to the general public at no+    charge under subsection 6d.++  A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++  A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling.  In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage.  For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product.  A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++  "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source.  The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++  If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information.  But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++  The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed.  Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++  Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++  7. Additional Terms.++  "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law.  If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++  When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it.  (Additional permissions may be written to require their own+removal in certain cases when you modify the work.)  You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++  Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++    a) Disclaiming warranty or limiting liability differently from the+    terms of sections 15 and 16 of this License; or++    b) Requiring preservation of specified reasonable legal notices or+    author attributions in that material or in the Appropriate Legal+    Notices displayed by works containing it; or++    c) Prohibiting misrepresentation of the origin of that material, or+    requiring that modified versions of such material be marked in+    reasonable ways as different from the original version; or++    d) Limiting the use for publicity purposes of names of licensors or+    authors of the material; or++    e) Declining to grant rights under trademark law for use of some+    trade names, trademarks, or service marks; or++    f) Requiring indemnification of licensors and authors of that+    material by anyone who conveys the material (or modified versions of+    it) with contractual assumptions of liability to the recipient, for+    any liability that these contractual assumptions directly impose on+    those licensors and authors.++  All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10.  If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term.  If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++  If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++  Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++  8. Termination.++  You may not propagate or modify a covered work except as expressly+provided under this License.  Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++  However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++  Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++  Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License.  If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++  9. Acceptance Not Required for Having Copies.++  You are not required to accept this License in order to receive or+run a copy of the Program.  Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance.  However,+nothing other than this License grants you permission to propagate or+modify any covered work.  These actions infringe copyright if you do+not accept this License.  Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++  10. Automatic Licensing of Downstream Recipients.++  Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License.  You are not responsible+for enforcing compliance by third parties with this License.++  An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations.  If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++  You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License.  For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++  11. Patents.++  A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based.  The+work thus licensed is called the contributor's "contributor version".++  A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version.  For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++  Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++  In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement).  To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++  If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients.  "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++  If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++  A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License.  You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++  Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++  12. No Surrender of Others' Freedom.++  If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License.  If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all.  For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++  13. Remote Network Interaction; Use with the GNU General Public License.++  Notwithstanding any other provision of this License, if you modify the+Program, your modified version must prominently offer all users+interacting with it remotely through a computer network (if your version+supports such interaction) an opportunity to receive the Corresponding+Source of your version by providing access to the Corresponding Source+from a network server at no charge, through some standard or customary+means of facilitating copying of software.  This Corresponding Source+shall include the Corresponding Source for any work covered by version 3+of the GNU General Public License that is incorporated pursuant to the+following paragraph.++  Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU General Public License into a single+combined work, and to convey the resulting work.  The terms of this+License will continue to apply to the part which is the covered work,+but the work with which it is combined will remain governed by version+3 of the GNU General Public License.++  14. Revised Versions of this License.++  The Free Software Foundation may publish revised and/or new versions of+the GNU Affero General Public License from time to time.  Such new versions+will be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++  Each version is given a distinguishing version number.  If the+Program specifies that a certain numbered version of the GNU Affero General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation.  If the Program does not specify a version number of the+GNU Affero General Public License, you may choose any version ever published+by the Free Software Foundation.++  If the Program specifies that a proxy can decide which future+versions of the GNU Affero General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++  Later license versions may give you additional or different+permissions.  However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++  15. Disclaimer of Warranty.++  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++  16. Limitation of Liability.++  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++  17. Interpretation of Sections 15 and 16.++  If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++                     END OF TERMS AND CONDITIONS++            How to Apply These Terms to Your New Programs++  If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++  To do so, attach the following notices to the program.  It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++    <one line to give the program's name and a brief idea of what it does.>+    Copyright (C) <year>  <name of author>++    This program is free software: you can redistribute it and/or modify+    it under the terms of the GNU Affero General Public License as published by+    the Free Software Foundation, either version 3 of the License, or+    (at your option) any later version.++    This program is distributed in the hope that it will be useful,+    but WITHOUT ANY WARRANTY; without even the implied warranty of+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+    GNU Affero General Public License for more details.++    You should have received a copy of the GNU Affero General Public License+    along with this program.  If not, see <http://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++  If your software can interact with users remotely through a computer+network, you should also make sure that it provides a way for users to+get its source.  For example, if your program is a web application, its+interface could display a "Source" link that leads users to an archive+of the code.  There are many ways you could offer source, and different+solutions will be better for different programs; see section 13 for the+specific requirements.++  You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU AGPL, see+<http://www.gnu.org/licenses/>.
+ Setup.lhs view
@@ -0,0 +1,3 @@+#!/usr/bin/env runhaskell+> import Distribution.Simple+> main = defaultMain
+ reactivity.cabal view
@@ -0,0 +1,39 @@+Name:                reactivity+Version:             0.2.3.0+Synopsis:            (Yet another) alternate implementation of push-pull FRP. This is based on the Reactive package (http://haskell.org/haskellwiki/reactive).+Category:            reactivity, FRP+Description:+Author:              James Candy+Maintainer:          info@alkalisoftware.net+Homepage:            http://haskell.org/haskellwiki/reactive+Package-Url:         http://code.haskell.org/reactivity+Bug-Reports:         http://trac.haskell.org/reactivity++Copyright:           (c) 2015 by James Candy+Cabal-Version:       >= 1.2+License:             OtherLicense+License-File:        COPYING+Stability:           provisional+Build-Type:          Simple+Extra-Source-Files:+Library+    Build-Depends:       base >=4 && <5, time >= 1.5.0.1, random,+                         Win32, Displayable >= 0.2.0.0, bmp >= 1.2.5.2,+                         monad-loops >= 0.4.2.1, monads-tf >= 0.1.0.2, transformers >= 0.3.0.0, comonad,+                         bytestring >= 0.10.0.2, array >= 0.4.0.1, ghc-prim, containers >=0.5.3.1, ConcurrentUtils >=0.4.0.0, parallel, list-extras+    if impl(ghc < 6.9) {+      buildable: False+    }+    Hs-Source-Dirs:      src+    Exposed-Modules:+        FRP.Reactivity++        FRP.Reactivity.Combinators+        FRP.Reactivity.UI+        FRP.Reactivity.Basic+        FRP.Reactivity.Draw+        FRP.Reactivity.Hook+        FRP.Reactivity.Extras+        FRP.Reactivity.Examples+        Data.XSizeable+        Data.WeakDict
+ src/Data/WeakDict.hs view
@@ -0,0 +1,122 @@+{-# LANGUAGE ExistentialQuantification, DeriveDataTypeable, RecursiveDo #-}
+{-# LANGUAGE Trustworthy #-}
+
+module Data.WeakDict (Dyn, value, makeDyn, WeakDict, emptyWeak, sizeWeak, assocsWeak, filterWeak, insertWeak, fastDeleteWeak, deleteWeak, lookupWeak, fastDeleteWeakDyn) where
+
+import GHC.Weak
+import Control.Monad
+import Data.Dynamic
+import Data.IORef
+
+import System.Exit
+
+-- | Dynamic values equipped with the ability to compare to other values.
+data Dyn = forall t. (Eq t, Typeable t) => Dyn t (t -> Bool)
+
+value (Dyn x _) = cast x
+
+makeDyn x = Dyn x (x==)
+
+instance Eq Dyn where
+	Dyn _ eq == Dyn x _ = maybe False eq (cast x)
+
+-----------------------------------
+
+data WeakDict0 t u = Empty | Cons !(Weak t) u !(WeakDict t u)
+
+data WeakDict t u = WeakDict {-# NOUNPACK #-} !(IORef (WeakDict0 t u)) deriving Typeable
+
+-- | An empty WeakDict.
+emptyWeak = liftM WeakDict $ newIORef Empty
+
+-- | Size of a WeakDict.
+sizeWeak :: WeakDict t u -> IO Int
+sizeWeak dict = size dict 0 where
+	size (WeakDict r) n = do
+		dict <- readIORef r
+		case dict of
+			Cons _ _ dict -> size dict (n + 1)
+			Empty -> return n
+
+assocsWeak :: WeakDict t u -> IO [(t, u)]
+assocsWeak (WeakDict r) = do
+	dict <- readIORef r
+	case dict of
+		Cons w x dict -> do
+			y <- deRefWeak w
+			case y of
+				Just y -> liftM ((y, x):) $ assocsWeak dict
+				Nothing -> assocsWeak dict
+		Empty -> return []
+
+-- | Filtering contents by a predicate.
+filterWeak f (WeakDict r) = do
+	dict <- readIORef r
+	case dict of
+		Cons w x dict -> deRefWeak w >>= maybe
+			(filterWeak f dict)
+			(\k -> if f k x then
+					-- Entries before the entry to be deleted have to be reconstructed with 'insertWeak'.
+					filterWeak f dict >>= insertWeak k x
+				else
+					filterWeak f dict)
+		Empty -> return (WeakDict r)
+
+-- | Insert a key-value pair into the dictionary, in such a way as that the pair does not keep the key (or value) alive.
+insertWeak k x dict = mdo
+	weak1 <- mkWeak k k $ Just $ deRefWeak weak >>= maybe (return ()) (fastDeleteWeak k)
+	dict1 <- liftM WeakDict
+		$ newIORef
+		$! Cons weak1 x dict
+	weak <- mkWeak dict1 dict1 Nothing
+	return dict1
+
+-- | Deletes a key-value pair, updating the original structure.
+fastDeleteWeak k (WeakDict r) = do
+	dict <- readIORef r
+	case dict of
+		Cons w2 _ (WeakDict r2) -> deRefWeak w2 >>= maybe
+			(do
+				fastDeleteWeak k (WeakDict r2)
+				readIORef r2 >>= writeIORef r)
+			(\k2 -> if k == k2 then
+					readIORef r2 >>= writeIORef r
+				else
+					fastDeleteWeak k (WeakDict r2))
+		Empty -> return ()
+
+-- | Deletes a key-value pair, so that the original structure is not affected.
+deleteWeak k (WeakDict r) = do
+	dict <- readIORef r
+	case dict of
+		Cons w2 x dict -> deRefWeak w2 >>= maybe
+			(deleteWeak k dict)
+			(\k2 -> if k == k2 then
+					return dict
+				else
+					deleteWeak k dict >>= insertWeak k2 x)
+
+-- | Look up a value based on a key.
+lookupWeak k (WeakDict r) = do
+	dict <- readIORef r
+	case dict of
+		Cons w2 x dict -> deRefWeak w2 >>= maybe
+			(lookupWeak k dict)
+			(\k2 -> if k == k2 then
+					return $! Just x
+				else
+					lookupWeak k dict)
+		Empty -> return Nothing
+
+fastDeleteWeakDyn k (WeakDict r) = do
+	dict <- readIORef r
+	case dict of
+		Cons w2 _ (WeakDict r2) -> deRefWeak w2 >>= maybe
+			(do
+				fastDeleteWeakDyn k (WeakDict r2)
+				readIORef r2 >>= writeIORef r)
+			(\k2 -> if maybe False (==k) $ fromDynamic k2 then
+				readIORef r2 >>= writeIORef r
+			else
+				fastDeleteWeakDyn k (WeakDict r2))
+		Empty -> return ()
+ src/Data/XSizeable.hs view
@@ -0,0 +1,103 @@+{-# LANGUAGE FlexibleInstances, FlexibleContexts, MultiParamTypeClasses, ScopedTypeVariables, OverlappingInstances, DeriveDataTypeable #-}
+
+-- | A resizable array, equivalent to C++'s std::vector. Manipulate them with the Data.Array.MArray class.
+--
+--   Use with multiple threads has to be synchronized.
+module Data.XSizeable (memset, SA, getPtr, Resizable(..)) where
+
+import Foreign.Storable
+import Foreign.Ptr
+import Foreign.Marshal.Alloc
+import Foreign.C.Types
+import System.Mem.Weak
+import Data.Int
+import Data.Word
+import Control.Monad
+import Data.IORef
+import Data.Array.IO
+import Data.Array.Base
+import Data.Typeable
+import System.Win32.Mem
+
+newtype SA i e = SA (IORef (i, i, Int, Ptr e)) deriving (Eq, Typeable)
+
+-- | Returns internal data about the array. But it cannot be counted on to be valid
+--   after the next call to 'resize'.
+--
+--   Also use this to free the array once it is not needed.
+getPtr (SA ref) = liftM (\(_, _, sz, p) -> (sz, p)) $ readIORef ref
+
+instance (Storable e) => MArray SA e IO where
+	getBounds (SA ref) = liftM (\(l, h, _, _) -> (l, h)) $ readIORef ref
+	getNumElements = liftM rangeSize . getBounds
+	newArray_ (l, h) = do
+		let required = sizeOf (undefined :: e) * rangeSize (l, h)
+		p <- mallocBytes required
+		memset p 0 (fromIntegral required)
+		ref <- newIORef (l, h, required, p)
+		return (SA ref)
+	unsafeRead (SA ref) i = do
+		tup@(_, _, _, p) <- readIORef ref
+		peekByteOff p (sizeOf (undefined :: e) * i)
+	unsafeWrite (SA ref) i x = do
+		tup@(_, _, _, p) <- readIORef ref
+		let loc = sizeOf (undefined :: e) * i
+		pokeByteOff p loc x
+
+-- A resize that only works on single-dimensional arrays.
+resizeBuffer :: forall i e. (Storable e) => (Ix i) => (i, i) -> SA i e -> IO ()
+resizeBuffer (l', h') sa@(SA ref) = do
+	(l, h, sz, p) <- readIORef ref
+	let wasRequired = sizeOf (undefined :: e) * rangeSize (l, h)
+	let nowRequired = sizeOf (undefined :: e) * rangeSize (l', h')
+	-- I want to maintain about 50% residency in the array.
+	(sz, p) <- if 4 * rangeSize (l', h') <= sz then
+			-- If the array gets small enough, resize it so it is 50% used.
+			let newSz = 2 * rangeSize (l', h') in
+			liftM ((,) newSz) $ reallocBytes p newSz
+		else if rangeSize (l', h') <= sz then
+			return (sz, p)
+		else
+			-- If the array exceeds its buffer, at least double it in size.
+			let newSz = nowRequired `max` (2 * wasRequired) in
+			liftM ((,) newSz) $ reallocBytes p newSz
+	when (nowRequired > wasRequired) $ memset (plusPtr p wasRequired) 0 (fromIntegral $ nowRequired - wasRequired)
+	writeIORef ref (l', h', sz, p)
+
+__resize (l', h') sa = do
+	(l, _) <- getBounds sa
+	resizeBuffer (l', h') sa
+	when (l /= l') $ __resize1 (l', h') sa
+
+__resize1 oldBnd sa = mapM_ (\i -> unsafeRead sa (index oldBnd i) >>= writeArray sa i) (range oldBnd)
+
+-- | Mutable arrays that can in addition be resized.
+class (Ix i, MArray a e m) => Resizable a i e m where
+	resize :: (i, i) -> a i e -> m ()
+
+instance (Storable e) => Resizable SA Int e IO where
+	resize = __resize
+
+instance (Storable e) => Resizable SA Int8 e IO where
+	resize = __resize
+
+instance (Storable e) => Resizable SA Int16 e IO where
+	resize = __resize
+
+instance (Storable e) => Resizable SA Int32 e IO where
+	resize = __resize
+
+instance (Storable e) => Resizable SA Word8 e IO where
+	resize = __resize
+
+instance (Storable e) => Resizable SA Word16 e IO where
+	resize = __resize
+
+instance (Storable e) => Resizable SA Word32 e IO where
+	resize = __resize
+
+instance (Storable e, Ix i) => Resizable SA i e IO where
+	resize bnd sa = do
+		resizeBuffer bnd sa
+		__resize1 bnd sa
+
+ src/FRP/Reactivity.hs view
@@ -0,0 +1,329 @@+{-# LANGUAGE Trustworthy, DeriveFunctor, DeriveDataTypeable #-}
+
+-- | A different presentation of functional reactive programming, based on the Reactive
+-- library on Hackage. The functionals in Combinators are based on those from Reactive.
+module FRP.Reactivity (module Data.Time.Clock.POSIX, Time, Event, firstRestE,
+-- * Primitive event combinators (see also Monad and MonadPlus instances)
+cons, corec, withTime, withRest, once, over, displace, list, Stream(Stream), addToEvent, getEvent, chanSource,
+-- * Executing events
+FrameOfReference, startT, setupFrame, makeFrame, runFrame, diagnostic) where
+
+import GHC.Prim (Any)
+import Control.Concurrent
+import qualified Control.CUtils.FChan as C
+import qualified Control.CUtils.Conc as CC
+import Control.Monad
+import Control.Applicative
+import Control.Comonad
+import Data.Maybe
+import Data.List hiding (union)
+import Data.Monoid hiding (Any)
+import Data.Function
+import Data.Typeable
+import qualified Data.Map as M
+import Data.List.Extras.Argmax
+import Data.Time.Clock.POSIX
+import Data.IORef
+import System.IO.Unsafe
+import Unsafe.Coerce
+import System.IO
+import System.Mem.Weak
+
+{- Desirable properties of functional reactive systems, and how this system addresses
+ - them:
+ -
+ - * Temporal monotonicity: This is accomplished using a global lock. By forcing
+ -   channel submissions to be ordered, one can ensure a consistent ordering on
+ -   external inputs. Monotonicity is further preserved by the primitive combinators.
+ - * Glitch-freedom: Once external inputs are acquired, they are preseved in
+ -   channels.
+ - * Recursion-friendly: Consider the term 'let e = return 1 <> delayE 4 e in e'.
+ -   Without lower bounds this is bottom, but an a priori lower bound makes this
+ -   a productive recursion.
+ - * Leak-freedom: running a program should take constant space in situations where it
+ -   could in principle take constant space.-}
+
+type Time = Double
+
+data Handler t u = Handler
+	!(Channel (t, Time))
+	!(t -> Time -> Event u) deriving Functor
+
+-- | A type of event streams.
+data Event t = Event
+	(Maybe t, Time, Event t)
+	-- Wait for the first external event in the dictionary. The Time parameter provides a time
+	-- limit, after which we will continue with the event parameter.
+	!(M.Map Integer (Handler Any t)) deriving (Typeable, Functor)
+
+pureOccurrences (Event (_, t, _) _) | t == 1/0 = []
+pureOccurrences (Event (Nothing, _, e) _) = pureOccurrences e
+pureOccurrences (Event (Just x, t, e) _) = (x, t) : pureOccurrences e
+
+instance (Show t) => Show (Event t) where
+	showsPrec _ e = ("One possible sequence is:"++) . showsPrec 11 (pureOccurrences e)
+
+{-# NOINLINE lock #-}
+lock = unsafePerformIO (newMVar ())
+
+-- | Find out if any of the channels contain occurrences.
+firstRestE (Event (x, t, rest) mp) = do
+	when (M.size mp >= 1000) (modifyMVar_ lock $ \_ -> hPutStrLn stderr "Reactivity: Number of event sources getting large (>=1000)")
+	available <- liftM catMaybes $ mapM (\(Handler (Channel ref) f) -> do
+		my <- readIORef ref
+		return (fmap (\((x, t), _) -> (f x t, t)) my)) (M.elems mp)
+	let (e, t2) = argmin snd available
+	if null available || t <= t2 then
+			if t == 1/0 then do
+				when (M.null mp) (modifyMVar_ lock $ \_ -> hPutStrLn stderr "Reactivity: Event stream is empty!")
+				return Nothing
+			else if isJust x then
+				return (Just (fromJust x, t, rest))
+			else
+				firstRestE rest
+		else
+			firstRestE e
+
+{-# INLINE cons #-}
+cons x t e = Event (Just x, t, displace t e) M.empty
+
+-- | Carry some kind of value which gets updated from occurrence to occurrence, and collect
+--   the results in an event.
+corec :: (t -> u -> Time -> (t, v, Time)) -> t -> Event u -> Event v
+corec f x e = over e (\y t rest -> case f x y t of
+	(y, z, t2) -> cons z t2 (corec f y rest))
+
+{-# INLINE withTime #-}
+-- | Get the time of event occurrences along with their values.
+withTime e = corec (\_ x t -> ((), (x, t), t)) () e
+
+-- | This functional lets you get an idea of the future starting from a certain point
+-- in time. It is similar to the 'tails' function for lists.
+withRest :: Event t -> Event (t, Event t)
+withRest e = over e (\x t rest -> cons (x, rest) t (withRest rest))
+
+instance Comonad Event where
+	duplicate e = over e (\x t rest -> cons (cons x t rest) t (duplicate rest))
+	extract e = unsafePerformIO $ do
+		-- Sticky counts
+		atomicModifyIORef waiting (\x -> (if x == maxBound then x else succ x, ()))
+		res <- loop e
+		atomicModifyIORef waiting (\x -> (if x == maxBound then x else pred x, ()))
+		return res where
+		loop e = do
+			my <- firstRestE e
+			case my of
+				Just (x, _, _) -> return x
+				Nothing -> -- There is a semaphore that gets pulsed any time an occurrence
+				-- enters the system.
+					waitQSem sem >> loop e
+
+{-# INLINE once #-}
+once e = over e (\x t _ -> cons x t mzero)
+
+-- | A case analysis on events.
+over :: Event t -> (t -> Time -> Event t -> Event u) -> Event u
+over (Event (x, t, rest) mp) f = if isNothing x then
+		Event (Nothing, t, over rest f) mappedMp
+	else case f (fromJust x) t rest of
+		-- Get hold of the first limiting occurrence
+		Event (y, t2, rest2) mp2 ->
+			let mappedMp2 = fmap (\(Handler ref g) -> Handler ref (\x t2 -> displace t (g x t2))) mp2 in
+				-- Get the external alternatives and limit them at 't',
+				-- Switch in the external alternatives from 'f'; they have to be displaced
+				-- to beyond 't' for monotonicity.
+				Event (Nothing, t, Event (y, t`max`t2, rest2) mappedMp2) mappedMp
+	where
+	mappedMp = fmap (\(Handler ref g) -> Handler ref (\x t -> over (g x t) f))
+		mp
+
+displace' :: Time -> Event t -> Event t
+displace' t e@(Event (x, t2, rest) mp) = Event (if t <= t2 then
+		(x, t2, rest)
+	else
+		(x, t`max`t2, displace' t rest))
+	(fmap (\(Handler ref f) -> Handler ref (\x t2 -> if t <= t2 then
+		f x t2
+	else
+		displace' t (f x t2))) mp)
+
+-- | Displace occurrences to at least 't'.
+displace t e = Event (Nothing, t, displace' t e) M.empty
+-- Starting with a lower bound at 't' helps recursion be productive.
+
+-- | Turns a plain list of occurrences (and times) into an Event.
+list ((x, t):xs) = cons x t (list xs)
+list [] = mzero
+
+instance MonadPlus Event where
+	mzero = Event (Nothing, 1/0, mzero) M.empty
+	mplus (Event (_, t, _) mp) e2 | t == 1/0 && M.null mp = e2
+	mplus e (Event (_, t, _) mp) | t == 1/0 && M.null mp = e
+	mplus e@(Event (x, t, rest) mp) e2@(Event (x2, t2, rest2) mp2) = Event
+		(if t <= t2 then
+			(x, t, mplus rest e2)
+		else
+			(x2, t2, mplus e rest2))
+		(fmap (\ei -> case ei of
+			Left ei2 -> case ei2 of
+				Left (Handler ref f) -> Handler ref (\x t -> mplus (f x t) e2)
+				Right (Handler ref f) -> Handler ref (\x t -> mplus e (f x t))
+			Right h -> h)
+		$ M.unionWith
+			(\(Left (Left (Handler ref f))) (Left (Right (Handler _ g))) -> Right (Handler ref (\x t -> f x t `mplus` g x t)))
+			(fmap (Left . Left) mp)
+			(fmap (Left . Right) mp2))
+
+data Stream t = Stream !(t -> IO ()) !(Event t) deriving Typeable
+
+addToEvent ~(Stream f _) = f
+
+getEvent ~(Stream _ e) = e
+
+{-# NOINLINE counter #-}
+counter :: IORef Integer
+counter = unsafePerformIO (newIORef 0)
+
+unsafeCast :: Handler t u -> Handler v u
+unsafeCast = unsafeCoerce
+
+chanSource :: FrameOfReference -> IO (Stream t)
+chanSource frame = do
+	n <- atomicModifyIORef counter (\x -> (succ x, x))
+	chn <- liftM Channel $ newIORef Nothing
+	end <- newIORef chn
+	let chanLoop chn@(Channel ref) = do
+		e <- unsafeInterleaveIO (do
+			Just (_, chn') <- readIORef ref
+			chanLoop chn')
+		return (Event (Nothing, 1/0, mzero) (M.singleton n (unsafeCast (Handler chn (\x t -> cons x t e)))))
+	event <- chanLoop chn
+	let strm = Stream
+		(\x -> modifyMVar_ (remainder frame) (\e@(Event tup mp) -> do
+		-- Lock is for monotonicity
+		t1 <- getPOSIXTime
+		let t = fromRational (toRational (t1 - startT frame))
+		-- Write into the channel
+		chanWrite end (x, t)
+		-- ...and deliver directly to the waiting handler
+		let my = M.lookup n mp
+		e' <- maybe
+			(return e)
+			(\hnd -> do
+			let Handler _ f = unsafeCast hnd
+			immediates t (f x t))
+			my
+
+		return e') >> wakeup)
+		event
+	mkWeak end end (Just (void $ forkIO $ modifyMVar_ (remainder frame) (\(Event tup mp) -> return (Event tup (M.delete n mp)))))
+	return strm where
+	immediates t e = firstRestE e >>=
+		maybe
+			(return e)
+			(\(x, t1, rest) -> if t1 <= t then do
+					x
+					immediates t rest
+				else
+					return e)
+
+instance Alternative Event where
+	empty = mzero
+	(<|>) = mplus
+
+instance Monoid (Event t) where
+	mempty = mzero
+	mappend = mplus
+
+--   The monad for Event is much like the list monad:
+--     * 'join' - instead of concatenating, it interleaves result events according to their times.
+--     * 'unit' - yields a "boring" one-point event at t = 0.
+instance Monad Event where
+	return x = cons x 0 mzero
+	e >>= f = over e (\x _ rest -> f x <> (rest >>= f))
+	fail _ = mzero
+
+instance Applicative Event where
+	pure = return
+	(<*>) = ap
+
+data Channel t = Channel !(IORef (Maybe (t, Channel t)))
+
+{-# INLINE chanWrite #-}
+chanWrite chnEnd x = do
+	chn' <- newIORef Nothing
+	Channel chn <- readIORef chnEnd
+	writeIORef chnEnd (Channel chn')
+	writeIORef chn (Just (x, Channel chn'))
+
+-------------------------------------------
+-- Executing events
+
+data FrameOfReference = FrameOfReference
+	!(MVar (Event (IO ()))) -- The remainder as of the present time
+	!POSIXTime -- A start time
+	deriving Typeable
+
+remainder ~(FrameOfReference mv _) = mv
+
+startT ~(FrameOfReference _ start) = start
+
+{-# NOINLINE waiting #-}
+waiting :: IORef Int
+waiting = unsafePerformIO (newIORef 0)
+
+-- This is a condition variable that wakes up all waiting threads.
+{-# NOINLINE sem #-}
+sem = unsafePerformIO (newQSem 0)
+
+{-# INLINE wakeup #-}
+wakeup = do
+	n <- readIORef waiting
+	modifyMVar_ lock (\_ -> hPutStrLn stderr (show n ++ " bumps"))
+	replicateM_ n (signalQSem sem)
+
+-- | Create a frame of reference from an event and handler.
+{-# INLINE makeFrame #-}
+makeFrame e = do
+	mv <- newMVar e
+	startT <- getPOSIXTime
+	return (FrameOfReference mv startT)
+
+{-# INLINE setupFrame #-}
+setupFrame frame e = do
+	tryTakeMVar (remainder frame)
+	putMVar (remainder frame) e
+
+-- | Run a frame of reference in the current thread -- but N.B. that some executions of the
+--   frame's 'sink' may occur in other threads.
+--
+--   See FRP.Reactivity.Basic for a more elaborate scheme that gets the results
+--   from I/O as event occurrences.
+runFrame :: FrameOfReference -> IO a
+runFrame frame = do
+	e <- takeMVar (remainder frame)
+	my <- firstRestE e
+	let (x, t, rest) = case my of
+		Just tup -> tup
+		Nothing -> (undefined, 1/0, mzero)
+	t1 <- getPOSIXTime
+	let time = t - fromRational (toRational (t1 - startT frame))
+	if time <= 0 then do
+			x
+			putMVar (remainder frame) rest
+		else if time == 1/0 then do
+			atomicModifyIORef waiting (\x -> (if x == maxBound then x else succ x, ()))
+			putMVar (remainder frame) e
+			waitQSem sem
+			atomicModifyIORef waiting (\x -> (if x == maxBound then x else pred x, ()))
+		else do
+			putMVar (remainder frame) e
+			modifyMVar_ lock (\_ -> hPutStrLn stderr ("Wait for " ++ show time))
+			threadDelay (round (1000000 * time))
+	runFrame frame
+
+diagnostic (Event (my, t, _) mp) = do
+	putStr (if isJust my then "occurrence" else "bound")
+	putStr (" at " ++ show t ++ ", map:")
+	ls <- mapM (\(n, Handler (Channel ref) _) -> liftM ((,) n . isJust) (readIORef ref)) (M.assocs mp)
+	print ls
+ src/FRP/Reactivity/Basic.hs view
@@ -0,0 +1,147 @@+{-# LANGUAGE Trustworthy, DeriveDataTypeable, GeneralizedNewtypeDeriving, DeriveFunctor, ScopedTypeVariables, ForeignFunctionInterface #-}
+
+module FRP.Reactivity.Basic (start, ticks, nil, defaultFrame, Act(Action), liftE, liftS, allOccs, corecA, run) where
+
+import Control.Monad.Loops
+import Control.Monad.IO.Class
+import Control.Monad.Fix
+import Control.Monad.Reader
+import Control.Monad
+import Control.Applicative
+import Control.CUtils.FChan
+import Control.Concurrent hiding (newChan)
+import Control.Exception
+import Control.Comonad
+import Data.IORef
+import Data.Monoid hiding (Any)
+import Data.Typeable (Typeable)
+import Data.Bits
+import Data.Time.Clock.POSIX
+import System.IO.Unsafe
+import System.Mem
+import FRP.Reactivity.Combinators
+import System.Win32
+import Graphics.Win32
+import Graphics.Win32Extras
+
+start :: POSIXTime
+start = startT defaultFrame
+
+{-# NOINLINE ticks #-}
+ticks :: Stream ()
+ticks = unsafePerformIO (chanSource defaultFrame)
+
+nil = Stream (const (return ())) mzero
+
+{-# NOINLINE defaultFrame #-}
+defaultFrame = unsafePerformIO (makeFrame mzero)
+
+-- | The Act type, comprising an initial I/O action and a sequence of scheduled actions.
+newtype Act a = Action { unAction :: IO (Event (IO (Maybe a))) } deriving (Typeable, Functor)
+
+instance Applicative Act where
+	pure = return
+	(<*>) = ap
+
+-- The monad for Act continues with the actions expressed in 'f', for every tick in 'm'.
+instance Monad Act where
+	return = liftIO . return
+	Action m >>= f = Action $ do
+		ev <- m
+		stream <- chanSource defaultFrame
+		return $ fmap (\m -> m >>= maybe (return ()) ((>>= addToEvent stream) . unAction . f) >> return Nothing) ev
+			<> join (getEvent stream)
+	fail _ = Action $ return mempty
+
+-- The Act monad has fixpoints.
+instance MonadFix Act where
+	mfix f = Action $ do
+		mv <- newEmptyMVar
+		x <- unsafeInterleaveIO $ readMVar mv
+		ev <- unAction (f x)
+		return $ fmap (\m -> m >>=
+			maybe (return Nothing) (\x -> tryPutMVar mv x >> return (Just x))) ev
+
+instance Monoid (Act a) where
+	mempty = Action $ return mempty
+	mappend m m2 = Action $ do
+		ev <- unAction m
+		ev2 <- unAction m2
+		return (ev <> ev2)
+
+instance Alternative Act where
+	empty = mempty
+	(<|>) = mappend
+
+instance MonadPlus Act where
+	mzero = mempty
+	mplus = mappend
+
+instance MonadIO Act where
+	liftIO m = Action $ liftM (return . return . Just) m
+
+-- | A basic event lifter -- continues at all event occurrences.
+liftE :: Event (IO t) -> Act t
+liftE ev = Action $ return $ fmap (fmap Just) ev
+
+-- | A variant of 'liftE' which publishes occurrences under 'stream', and only continues once, immediately.
+liftS :: Stream t -> Event (IO t) -> Act ()
+liftS stream ev = Action $ return $ return (return (Just ())) <> fmap (\m -> m >>= addToEvent stream >> return Nothing) ev
+
+-- | Return all return values of the parameter 'a' in a single event.
+--
+--   (The occurrences receive new timestamps, which may differ from the old.)
+allOccs :: Act t -> Act (Event t)
+allOccs a = do
+	e' <- liftIO (chanSource defaultFrame)
+	(a >>= liftIO . addToEvent e' >> mzero) <> return (getEvent e')
+
+corecA' :: (t -> u -> Time -> IO (t, v, Time)) -> t -> Event (u, Time) -> Act v
+corecA' f x e = do
+	((y, t), rest) <- liftE (fmap return (once (withRest e)))
+	(x, z, t) <- liftIO (f x y t)
+	liftE (cons (return z) t mzero) <> corecA' f x rest
+
+-- | An I/O version of 'corec'
+corecA f x = corecA' f x . withTime
+
+run :: Act a -> IO ()
+run action = do
+	-- Register window class
+	hdl <- getModuleHandle Nothing
+	cursor <- loadCursor Nothing iDC_ARROW
+	null <- getStockBrush nULL_BRUSH
+	let name = mkClassName "Frame"
+	registerClass (0, hdl, Nothing, Just cursor, Just null, Nothing, name)
+
+	-- Build and run the event stream
+	ev <- unAction action
+	(f, chn) <- newChan
+	setupFrame defaultFrame (fmap f (withTime ev))
+	forkIO (runFrame defaultFrame)
+
+	-- Pump messages
+	allocaMessage $ \msg -> do
+	let m = do
+		-- Process all messages in the queue.
+		whileM_
+			(liftM (/=0) $ c_PeekMessage msg nullPtr 0 0 pM_REMOVE)
+			$ do
+			translateMessage msg
+			dispatchMessage msg
+
+		-- Wait until either a message is received or the timeout elapses.
+		res <- msgWaitForMultipleObjects [] True 200 qS_ALLEVENTS
+
+		when (res == wAIT_TIMEOUT) $ addToEvent ticks ()
+
+	foldM_ (\chn _ ->
+		-- Process all available messages
+		tryTakeChan chn >>= maybe
+			(m >> return chn)
+			(\((m, _), rest) -> m >> return rest)
+		-- and repeat.
+		)
+		chn
+		(repeat ())
+
+ src/FRP/Reactivity/Combinators.hs view
@@ -0,0 +1,347 @@+{-# LANGUAGE Trustworthy, DeriveFunctor, CPP #-}
+
+-- | A different presentation of functional reactive programming, based on the Reactive
+-- library on Hackage. Push-pull FRP is due to Conal Elliott. The functionals here
+-- are directly based on those from Reactive.
+module FRP.Reactivity.Combinators (module FRP.Reactivity,
+-- * Derived event combinators
+list, tick, untilE, eitherOf, holdE, zipE, simultE, intersectE, differenceE, unionE, filterE, justE, duplicateE, withPrev, switchE, scanlE, calmE, count, takeE, dropE, delayE, slowE, rests, startAt, splitE,
+-- * Reactive behaviors
+Behavior, time, switcher, stepper, snapshot, flipFlop, history, scan, delay, slow, monoid, throttle, sumE, derivative, supersample, integral, threshold) where
+
+import Control.Monad
+import Control.Monad.Fix
+import Control.Monad.Loops
+import Control.Applicative
+import Control.Exception
+import Control.Comonad
+import Control.Parallel.Strategies
+import Control.Parallel
+import Data.Maybe
+import Data.List
+import Data.Monoid
+import Data.Function
+import qualified Data.Map as M
+import Data.IORef
+import FRP.Reactivity
+
+-- | A convenience to generate a tick on a regular interval.
+{-# INLINE tick #-}
+tick t = list (map (\t -> (t, t)) [0,t..])
+
+_untilE e = over e (\ei t rest -> either (\x -> cons x t (_untilE rest)) (\_ -> mzero) ei)
+
+-- | This functional can be used to terminate an event early.
+{-# INLINE untilE #-}
+untilE :: Event t -> Event u -> Event t
+untilE e u = _untilE (eitherOf e u)
+
+{-# INLINE eitherOf #-}
+eitherOf e e2 = fmap Left e <> fmap Right e2
+
+-- | Give the event times of 'e', but latching onto the ticks of 'e2'. Prior to 'e2' ticking, gives 'x'.
+{-# INLINE holdE #-}
+holdE :: Event t -> Event u -> u -> Event (t, u)
+holdE e e2 x = justE
+	$ corec (\x ei t -> either (\y -> (x, Just (y, x), t)) (\y2 -> (y2, Nothing, t)) ei) x
+	$ eitherOf e e2
+
+swap (x, y) = (y, x)
+
+{-# INLINE zipE #-}
+zipE e x e2 y = holdE e e2 y <> fmap swap (holdE e2 e x)
+
+{-# INLINE cozip #-}
+cozip ls = (catMaybes (map (either Just (const Nothing)) ls), catMaybes (map (either (const Nothing) Just) ls))
+
+{-# INLINE groupOn #-}
+groupOn ls = map (\ls -> (map fst ls, snd (head ls))) $ groupBy ((==) `on` snd) ls
+
+{-# INLINE ungroup #-}
+ungroup ls = [ (y, x) | (l, x) <- ls, y <- l ]
+
+-- | Pair values from 'e' to simultaneous occurrences from 'a'. Multiple occurrences
+--   are paired up as with 'zip'. Excess occurrences from 'a' are discarded, while
+--   excess occurrences from 'e' are paired with 'Nothing'.
+{-# INLINE simultE #-}
+simultE :: Event t -> Event u -> Event (t, Maybe u)
+simultE e a = justE
+	$ fmap (\(x, _, _) -> x)
+	$ scanlE (\(_, prev, ti) (ei, t) -> if ti < t then
+			-- Discard old occurrences
+			either
+			(\y -> (Nothing, [y], t))
+			(\x -> (Just (x, Nothing), [], t))
+			ei
+		else
+			-- Zip up occurrences at a single time
+			either
+			(\y -> (Nothing, prev ++ [y], t))
+			(\x -> case prev of { y:ys -> (Just (x, Just y), ys, t); [] -> (Just (x, Nothing), [], t) })
+			ei)
+	(Nothing, [], 0)
+	$ withTime
+	$ eitherOf a e
+
+-- | Set operations on events
+{-# INLINE differenceE #-}
+differenceE e a = justE $ fmap (\(x, m) -> maybe (Just x) (const Nothing) m) $ simultE e a
+
+{-# INLINE intersectE #-}
+intersectE e a = justE $ fmap (uncurry fmap) $ simultE e a
+
+{-# INLINE unionE #-}
+unionE :: (Monoid t) => Event t -> Event t -> Event t
+unionE e e2 = intersectE (fmap (<>) e) e2
+	<> differenceE e e2
+	<> differenceE e2 e
+
+-- | Drop event occurrences that fail the predicate 'f'.
+filterE f e = over e (\x t rest -> if f x then cons x t (filterE f rest) else filterE f rest)
+
+{-# INLINE justE #-}
+justE e = fmap fromJust (filterE isJust e)
+
+{-# INLINE duplicateE #-}
+duplicateE e = fmap (\(x, e) -> return x <> e) (withRest e)
+
+{-# INLINE withPrev #-}
+withPrev e = justE $ corec (\may y t -> (Just y, fmap (\x -> (x, y)) may, t)) Nothing e
+
+{-# INLINE switchE #-}
+switchE e = withRest e >>= \(x, u) -> x `untilE` u
+
+{-# INLINE scanlE #-}
+scanlE f x e = corec (\x y t -> let x' = f x y in (x', x', t)) x e
+
+-- | "Calms" an event so that only one event occurs at a given time.
+{-# INLINE calmE #-}
+calmE e = once e
+	<>
+	fmap (fst . snd)
+	(filterE (\((_, t), (_, t1)) -> t < t1)
+	$ withPrev
+	$ withTime e)
+
+{-# INLINE count #-}
+count e = corec (\n x t -> (n + 1, (x, n + 1), t)) 0 e
+
+-- | Event versions of 'drop' and 'take'.
+{-# INLINE dropE #-}
+dropE n e = fmap fst $ filterE ((>n) . snd) $ count e
+
+{-# INLINE takeE #-}
+takeE :: (Num n, Ord n) => n -> Event t -> Event t
+takeE n e = fmap fst $ filterE ((<=n) . snd) (c `untilE` delayE epsilon (filterE ((>n) . snd) c)) where
+	c = count e
+
+-- | Gives all the events of 'e', but delayed 't' seconds.
+{-# INLINE delayE #-}
+delayE :: Time -> Event t -> Event t
+delayE t e = rec t e where
+	rec t1 e = displace t1 (over e (\x t1 rest -> let t2 = t + t1 in cons x t2 (rec t2 rest)))
+
+-- rec t e where
+--	rec t1 e = displace t1 (over e (\x t1 rest -> let t2 = t + t1 in cons x t2 (rec t2 rest)))
+
+{-# INLINE slowE #-}
+slowE x e = withTime e >>= \(y, t) -> list [(y, (x - 1) * t)]
+
+-- | Get the remainder events of 'e' looking forward from particular occurrences in 'a'
+{-# INLINE rests #-}
+rests e a = holdE a (fmap snd (withRest e)) e
+
+-- | The opposite of 'untilE', waits until 'a' ticks before it starts ticking.
+{-# INLINE startAt #-}
+startAt e a = once (rests e a) >>= snd
+
+-- | Divides 'e' into chunks based on the ticks of 'a', and returns those chunks in an event.
+--   The occurrences of 'e' prior to the first occurrence of 'a' are omitted.
+{-# INLINE splitE #-}
+splitE e a = fmap (\((_, a), e) -> e `untilE` a) $ rests e (withRest a)
+
+{-# INLINE sumE #-}
+sumE :: (Num t) => Event t -> Event t
+sumE = corec (\x y t -> let x' = x + y in (x', x', t)) 0
+
+{-fixpoint :: (Event t -> Event t) -> Event t
+fixpoint f = E
+	(\schedule disp g -> do
+		-- When the event ticks, the current tick has to be in hand prior to evaluation.
+		current <- newEmptyMVar
+		let e = f $ E
+			(\schedule _ g -> do
+			-- Feeds the value to the handler (prior to its calculation!).
+			let loop = do
+				~(x, t) <- unsafeInterleaveIO $ takeMVar current
+				g mempty x t
+				threadDelay 100000
+				loop
+			thd <- forkIO loop
+			return (killThread thd))
+			0
+		-- When a value is obtained, provide it in the variable.
+		internalRunEvent schedule disp e (\_ x t -> do
+			tryPutMVar current (x, t)
+			processEvent schedule g mempty x t))
+	0
+
+instance MonadFix Event where
+	mfix f = join $ fixpoint $ fmap (>>= f)-}
+
+-------------------------------------------
+-- Reactive behaviors
+
+data Behavior t = Switcher !(Time -> t) (Event (Time -> t)) deriving Functor
+
+{-# INLINE time #-}
+time = Switcher id mempty
+
+{-# INLINE switcher #-} 
+switcher (Switcher f e) e2 = Switcher f (switchE $ return e <> fmap (\(Switcher f e) -> return f <> e) e2)
+
+{-# INLINE stepper #-}
+stepper x e = Switcher (const x) (fmap const e)
+
+{-# INLINE snapshot #-}
+snapshot e (Switcher f e2) = fmap (\((x, f), t) -> (x, f t))
+	$ withTime
+	$ holdE e e2 f
+
+{-# INLINE flipFlop #-}
+flipFlop e e2 = stepper False (fmap (const True) e <> fmap (const False) e2)
+
+-- | Keep a history of 't' seconds as a "moving window" -- giving values for
+-- the behavior, 't' seconds prior to the current time. Outside of this
+-- moving window, gives a flat behavior.
+--
+-- This functional should be enough for all "history-dependent" behaviors -- there
+-- should be some 't' which is a constant bound on a behavior's history,
+-- in order to conserve memory.
+history :: Time -> Behavior t -> Behavior (Time -> t)
+history t (Switcher f e) = function
+	<$> stepper [(f, 0)] windowFunctions
+	<*> time where
+	function ls t1 t2 = if t1 <= t2 then fst (head ls) t1
+		else maybe (fst (last ls) (t1-t)) (($t2) . fst)
+			$ find ((<=t2) . snd) ls
+	windowFunctions = corec (\ls f t1 -> let ls' = (f, t1) : map fst (takeWhile ((<t1-t) . snd . snd) $ zip ls $ tail ls) `using` evalList rseq in
+		(ls, ls, t1))
+		[(f, 0)]
+		e
+
+-- | A scan for behaviors.
+scan :: Behavior (t -> Event t) -> t -> Event t
+scan b x = return x <> (snapshot (extract b x) (duplicate b) >>= uncurry (flip scan))
+
+_monoid e b = return b <> (snapshot (once (withRest e)) (duplicate b) >>= \((x, e), b2) -> _monoid e (b <> b2))
+
+-- | Collect the event occurrences and add them together into a single behavior, using a monoid.
+{-# INLINE monoid #-}
+monoid :: (Monoid t) => Event (Behavior t) -> Behavior t
+monoid e = switcher mempty $ _monoid e mempty
+
+-- | Each event occurrence casts a "shadow" for 't' seconds in the behavior.
+{-# INLINE throttle #-}
+throttle :: Time -> Event t -> Behavior (Maybe t)
+throttle t e = fmap getLast $ monoid (fmap (\(x, ti) -> stepper (Last Nothing) (list [(Last (Just x), ti), (Last Nothing, t + ti)])) (withTime e))
+
+-- | Delay by 't' seconds before continuing as the behavior.
+{-# INLINE delay #-}
+delay t (Switcher f e) = Switcher (f . subtract t) (fmap (. subtract t) (delayE t e))
+
+-- | Slow down the behavior by a factor of 'x'.
+{-# INLINE slow #-}
+slow x (Switcher f e) = Switcher (f . (/x)) (slowE x (fmap (. (/x)) e))
+
+instance (Monoid t) => Monoid (Behavior t) where
+	mempty = pure mempty
+	mappend e e2 = mappend <$> e <*> e2
+
+instance Alternative Behavior where
+	empty = error "FRP.Reactivity.empty: use Monoid instead"
+	(<|>) = error "FRP.Reactivity.<|>: use Monoid instead"
+
+instance Applicative Behavior where
+	pure x = Switcher (const x) mempty
+	Switcher f e <*> Switcher f2 e2 = Switcher (f <*> f2)
+		$ fmap (uncurry (<*>))
+		$ zipE e f e2 f2
+
+{-# INLINE cutoff #-}
+cutoff t f t1 = f (max t t1)
+
+-- The Behavior functor forms a /Comonad/. Its
+--   * 'duplicate' - produces, for a time 't', a version of the Behavior with a flat behavior up to 't'.
+--   If the original behavior (snapshotted) looks like [1,2,3,4,5], the duplicated
+--   behavior looks like [[1,2,3,4,5],[2,2,3,4,5],[3,3,3,4,5],[4,4,4,4,5],[5,5,5,5,5]].
+--
+--   * 'extract' - gets the value of the flat behavior, by sampling at t = 0. In the example, 'extract'
+--   would pull out the first element of each list, giving [1,2,3,4,5].
+instance Comonad Behavior where
+	extract (Switcher f _) = f 0
+	duplicate (Switcher f e) = Switcher (\t -> Switcher (cutoff t f) e) (fmap (\(f, e) t -> Switcher (cutoff t f) e) (withRest e))
+
+-------------------------------------------
+-- Integration
+
+epsilon = 0.0001
+
+-- | Estimate the derivative of a behavior.
+derivative :: (Real t, Fractional t) => Behavior t -> Behavior t
+derivative b = (\x x1 -> (x1 - x) / fromRational (toRational epsilon)) <$> delay epsilon b <*> b
+
+-- | Adaptively supersample a behavior.
+supersample b = scan
+	((\t x deriv _ -> list [((t, x), if t < epsilon then t + epsilon else t + fromRational (toRational $ 0.1 / (1 + abs deriv)))]) <$> time <*> b <*> derivative b)
+	(extract b, 0)
+
+-- | Integral of behaviors
+integral b =
+	-- Obtain the integral (trapezoidal integration)
+	stepper 0
+	$ sumE
+	$ fmap (\((t, x), (t1, x1)) -> 0.5 * (x1 + x) * fromRational (toRational (t1 - t)))
+	$ withPrev
+	$ supersample b
+
+-- | Given a differentiable behavior, find the times at which
+-- a certain value could be found. The result is an event which ticks
+-- when (an approximation of) the value is encountered.
+threshold b x = justE
+	$ fmap (\(b, m) -> fmap (const b) m)
+	$ scanlE (\(gt, _) (t, y) -> if gt == (y < x) then (not gt, Just t) else (gt, Nothing)) (extract b > x, Nothing)
+	$ supersample b
+
+-------------------------------------------
+-- Laws
+--
+-- mempty >>= f = mempty
+-- (e <> e2) >>= f = (e >>= f) <> (e2 >>= f)
+-- e <> e2 <> e3 = e <> (e2 <> e3)
+-- mempty <> e = e
+-- The monad laws
+--
+-- withTimeE (withTimeE e) = fmap (\(x, t) -> ((x, t), t)) (withTimeE e)
+--
+-- e `untilE` e = mempty
+-- e `untilE` u `untilE` u2 = e `untilE` (u <> u2)
+--
+-- filterE f e = e >>= \x -> guard (f x) >> return x
+--
+-- fmap fst (withRestE e) = e
+-- calmE (join (duplicateE e)) = calmE e
+-- fmap (\(_, t) -> e `startAt` listE [((), t)]) (withTimeE e) = duplicateE e
+--
+-- (e `untilE` a) <> (e `startAt` a) = e
+-- e `startAt` e = e
+-- e `startAt` a `startAt` a2 = e `startAt` (a >> a2)
+-- e `startAt` (e <> e2) = e
+-- e2 `startAt` (e <> e2) = e2
+-- e `untilE` a `startAt` a2 = e `startAt` a2 `untilE` a
+--
+-- delayE 0 e = e
+-- delayE t (delayE t2 e) = delayE (t + t2) e
+--
+-- join (splitE e a) = startAt e a
+-- switchE (splitE e a) = startAt e a
+ src/FRP/Reactivity/Draw.hs view
@@ -0,0 +1,567 @@+{-# LANGUAGE Unsafe, ScopedTypeVariables, FlexibleInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving, ImplicitParams, ForeignFunctionInterface #-}
+
+-- | A Draw monad for drawing in bitmaps.
+module FRP.Reactivity.Draw (defBackground, Draw(unDraw), pack, onNewBitmap, unsafeOnBitmap, newBitmap, onBitmap, askDims, getPixel, setPixel, askDims', getPixel', getRValue, getGValue, getBValue, rgb, blend, mask, Font, defFont, textOut, textDimensions, areaFill, useFilter, convolve, flipped, swap, correlate, blur, enTuple, unTuple, resample, horzGradient, vertGradient, laplacian, fillRect, function, function', drawBitmap, graffito, spline, ellipse) where
+
+import Foreign.Ptr
+import Foreign.Storable
+import Foreign.C.Types
+import Foreign.Marshal.Alloc
+import Foreign.Marshal.Utils
+import Data.ByteString (copy, index, replicate)
+import qualified Data.ByteString as B
+import Data.ByteString.Unsafe
+import Data.Bits
+import Data.Int
+import Data.Word
+import Data.Fixed
+import Data.Array hiding (index)
+import Control.Arrow
+import Control.Monad.Reader
+import Control.Monad.Trans
+import Control.Applicative
+import Control.Exception hiding (mask)
+import Control.Monad
+import Control.CUtils.Conc
+import Control.Concurrent
+import Codec.BMP
+import System.IO.Unsafe
+import System.Mem.Weak
+import Graphics.Win32 hiding (ellipse, fillRect, textOut)
+import Graphics.Win32Extras
+import Prelude hiding (replicate)
+
+defBackground = rgb 245 246 247
+
+newtype Draw t = Draw { unDraw :: ReaderT ((Int32, Int32), Ptr CChar, Maybe (Chan (Int32, Int32, COLORREF))) IO t } deriving (Functor, Applicative, Monad)
+
+bi bmp = case bmpBitmapInfo bmp of
+	InfoV3 b -> b
+	InfoV4 b -> dib4InfoV3 b
+
+sizeOfFileHeader :: Int
+sizeOfFileHeader = 14
+
+-- | Magic number that should come at the start of a BMP file.
+bmpMagic :: Word16
+bmpMagic = 0x4d42
+
+-- | Size of `BitmapInfoV3` header (in bytes)
+sizeOfBitmapInfoV3 :: Int
+sizeOfBitmapInfoV3 = 40
+
+-- 
+-- | Pack a 24-bit bitmap, but without error checking.
+pack width height str = let
+	fileHeader
+		= FileHeader
+		{ fileHeaderType	= bmpMagic
+
+		, fileHeaderFileSize	= fromIntegral
+					$ sizeOfFileHeader + sizeOfBitmapInfoV3	+ B.length str
+
+		, fileHeaderReserved1	= 0
+		, fileHeaderReserved2	= 0
+		, fileHeaderOffset	= fromIntegral (sizeOfFileHeader + sizeOfBitmapInfoV3) }
+
+	bitmapInfoV3
+		= BitmapInfoV3
+		{ dib3Size		= fromIntegral sizeOfBitmapInfoV3
+		, dib3Width		= fromIntegral width
+		, dib3Height		= fromIntegral height
+		, dib3HeightFlipped	= False
+		, dib3Planes		= 1
+		, dib3BitCount		= 24
+		, dib3Compression	= CompressionRGB
+		, dib3ImageSize		= fromIntegral $ (3 * width + 3) `quot` 4 * 4 * height
+		, dib3PelsPerMeterX	= 2834
+		, dib3PelsPerMeterY	= 2834
+
+		, dib3ColorsUsed	= 0
+		, dib3ColorsImportant	= 0 }
+		
+   in BMP 
+		{ bmpFileHeader		= fileHeader
+		, bmpBitmapInfo		= InfoV3 bitmapInfoV3
+		, bmpRawImageData	= str }
+
+-- | Create a new bitmap and draw on it.
+{-# NOINLINE onNewBitmap #-}
+onNewBitmap :: (Int32, Int32) -> Draw t -> (BMP, t)
+onNewBitmap (wd32, ht32) draw = unsafePerformIO $ do
+	let sz = fromIntegral $ nBytes wd32 ht32
+	p <- mallocBytes sz
+	let Draw st = fillRect defBackground (0, 0, wd32, ht32) >> draw
+	x <- runReaderT st ((wd32, ht32), p, Nothing)
+	ar <- unsafePackCStringLen (p, sz)
+	addFinalizer ar (free p)
+	return (pack wd ht ar, x) where
+	wd = fromIntegral wd32
+	ht = fromIntegral ht32
+
+-- | Create a new blank bitmap.
+{-# INLINE newBitmap #-}
+newBitmap dim = fst $ onNewBitmap dim (return ())
+
+-- | Make a copy of a bitmap and draw on it. This only works with 24-bit bitmaps
+--   (but the Codec.BMP library provides conversion functions)
+{-# NOINLINE onBitmap #-}
+onBitmap bmp draw = unsafeOnBitmap (bmp { bmpRawImageData = copy $ bmpRawImageData bmp }) draw
+
+-- | An unsafe version of 'onBitmap' that scribbles on the old bitmap, violating
+--   referential transparency.
+{-# NOINLINE unsafeOnBitmap #-}
+unsafeOnBitmap :: BMP -> Draw t -> (BMP, t)
+unsafeOnBitmap bmp draw = unsafePerformIO $ unsafeUseAsCString (bmpRawImageData bmp) $ \p -> do
+	let Draw st = draw
+	x <- runReaderT st ((wd32, ht32), p, Nothing)
+	return (pack wd ht (bmpRawImageData bmp), x) where
+	(wd32, ht32) = askDims' bmp
+	wd = fromIntegral wd32
+	ht = fromIntegral ht32
+
+calculateByte wid x y = (3 * wid + 3) `quot` 4 * 4 * y + 3 * x
+
+nBytes wd32 ht32 = calculateByte wd32 0 ht32
+
+-- | Retrieve the bitmap's dimensions.
+askDims = Draw $ liftM (\(pr, _, _) -> pr) ask
+
+{-# INLINE unsafeGetPixel #-}
+unsafeGetPixel (x, y) = Draw $ do
+	((wid, _), ar, _) <- ask
+	let byte = calculateByte wid x y
+	lift $ do
+		b <- peekByteOff ar (fromIntegral byte)
+		g <- peekByteOff ar (fromIntegral $ byte + 1)
+		r <- peekByteOff ar (fromIntegral $ byte + 2)
+		return (rgb r g b)
+
+-- |
+getPixel (x, y) = do
+	b <- inBounds (x, y)
+	unless b $ do
+		(wid, ht) <- askDims
+		Draw $ lift $ throwIO $ IndexOutOfBounds $ "FRP.Draw.getPixel: " ++ show (x, y) ++ " not in " ++ show wid ++ "x" ++ show ht ++ " bitmap"
+	unsafeGetPixel (x, y)
+
+makeLPARAM x y = shiftL y 16 .|. x
+
+{-# INLINE unsafeSetPixel #-}
+unsafeSetPixel (x, y) clr = Draw $ do
+	((wid, _), ar, chn) <- ask
+	let byte = calculateByte wid x y
+	lift $ maybe
+		(do
+		pokeByteOff ar (fromIntegral byte) (getBValue clr)
+		pokeByteOff ar (fromIntegral $ byte + 1) (getGValue clr)
+		pokeByteOff ar (fromIntegral $ byte + 2) (getRValue clr))
+		(\chn -> writeChan chn (x, y, clr))
+		chn
+
+-- |
+setPixel pt clr = do
+	b <- inBounds pt
+	when b $ unsafeSetPixel pt clr
+
+-- |
+askDims' :: BMP -> (Int32, Int32)
+askDims' bmp = (fromIntegral (dib3Width (bi bmp)), fromIntegral (dib3Height (bi bmp)))
+
+-- |
+getPixel' (x, y) bmp = rgb
+	(index dat (byte + 2))
+	(index dat (byte + 1))
+	(index dat byte) where
+	dat = bmpRawImageData bmp
+	wid = fst (askDims' bmp)
+	byte = fromIntegral $ calculateByte wid x y
+
+-- | Blend a colour into a pixel with a certain intensity.
+blend :: Double -> (Int32, Int32) -> COLORREF -> Draw ()
+blend intensity pt clr = do
+	b <- inBounds pt
+	when b $ do
+		clr2 <- unsafeGetPixel pt
+		let formula f = round $ fromIntegral (f clr) * intensity + fromIntegral (f clr2) * (1 - intensity)
+		unsafeSetPixel pt $ rgb
+			(formula getRValue)
+			(formula getGValue)
+			(formula getBValue)
+
+-- | Fill a region according to the given mask bitmap.
+mask intensity (x, y) bmp = do
+	let (wid, ht) = askDims' bmp
+	let f = if intensity >= 1 then
+			\x2 y2 -> setPixel (x + x2, y + y2)
+		else
+			\x2 y2 -> blend intensity (x + x2, y + y2)
+	mapM_ (\y2 -> mapM_ (\x2 -> f x2 y2 (getPixel' (x2, y2) bmp)) [0..wid-1]) [0..ht-1]
+
+foreign import stdcall unsafe "windows.h GetDIBits"
+  c_GetDIBits :: HDC -> HBITMAP -> INT -> INT -> LPVOID -> LPBITMAPINFO -> ColorFormat -> IO INT
+
+type Font = (COLORREF, COLORREF, String, Int32, DWORD, Bool, Bool)
+
+-- | A default font option
+defFont :: Font
+defFont = (defBackground, 0, "Tahoma", 14, fW_NORMAL, False, False)
+
+-- | Draw some text at the point in the bitmap.
+textOut :: String -> POINT -> Font -> Draw ()
+textOut text pt (bgclr, fgclr, font, sz, weight, italic, underline) = void $ Draw $ ask >>= \tup -> lift $ do
+	-- This procedure draws the text in a DDB, grabs that DDB into a DIB, then masks it into the original image.
+	dc <- getDC Nothing
+	finally
+	 (do
+	 cdc <- createCompatibleDC (Just dc)
+	 finally
+	  (withRECT (0, 0, 32767, 32767) $ \p -> do
+	  setBkColor cdc bgclr
+	  setTextColor cdc fgclr
+	  fhdl <- createFont (sz * 72 `quot` 96) 0 0 0 weight italic underline False dEFAULT_CHARSET 0 0 0 0 font
+	  finally
+	   (do
+	   oldFont <- selectFont cdc fhdl
+	   finally
+	    (do
+	    -- Measure text
+	    withTStringLen text $ \(s, l) -> c_DrawText cdc s (fromIntegral l) p dT_CALCRECT
+	    -- Create a DDB
+	    rt@(_, _, x, y) <- peekRECT p
+	    bmp <- createCompatibleBitmap dc x y
+	    finally
+	     (runReaderT
+		(unDraw $ mask 1 pt $ fst $ onNewBitmap (x, y) $ Draw $ ask >>= \(_, pbits, _) -> lift $ do
+			oldBmp <- selectBitmap cdc bmp
+			finally
+			 (do
+			 drawText cdc text rt 0
+			 withBITMAP (bmpBitmapInfo (pack x y B.empty)) $ \p -> c_GetDIBits cdc bmp 0 y (castPtr pbits) p dIB_RGB_COLORS)
+				(selectBitmap cdc oldBmp))
+		tup)
+		(deleteBitmap bmp))
+		(selectFont cdc oldFont))
+		(deleteFont fhdl))
+		(deleteDC cdc))
+		(releaseDC Nothing dc)
+
+-- | Get the dimensions of a piece of text in a given font. (Note: this may be slightly different
+--   on different platforms).
+textDimensions :: String -> Font -> POINT
+textDimensions text (_, _, font, sz, weight, italic, underline) = unsafePerformIO $ do	
+	dc <- getDC Nothing
+	finally
+	 (do
+	 fhdl <- createFont (sz * 72 `quot` 96) 0 0 0 weight italic underline False dEFAULT_CHARSET 0 0 0 0 font
+	 finally
+	  (do
+	  oldFont <- selectFont dc fhdl
+	  finally
+	   (withRECT (0, 0, 32767, 32767) $ \p -> do
+		withTStringLen text $ \(s, l) -> c_DrawText dc s (fromIntegral l) p dT_CALCRECT
+		(_, _, x, y) <- peekRECT p
+		return (x, y))
+		(selectFont dc oldFont))
+		(deleteFont fhdl))
+		(releaseDC Nothing dc)
+
+----------------------------------------
+-- Area fill
+
+inBounds (x, y) = do
+	(wid, ht) <- askDims
+	return (inRange (0, wid - 1) x && inRange (0, ht - 1) y)
+
+areaFillImpl _ [] _ _ = return ()
+areaFillImpl 0 _ _ _ = return ()
+areaFillImpl n frontier clrFill clrMatch = do
+	mapM_ (\pt -> unsafeSetPixel pt clrFill) frontier
+	let choices = concat [ [(x - 1, y), (x, y - 1), (x + 1, y), (x, y + 1)] | (x, y) <- frontier ]
+	ok <- mapM (\pt -> do
+		b <- inBounds pt
+		if b then
+				liftM (==clrMatch) (getPixel pt)
+			else
+				return False) choices
+	areaFillImpl (n - 1) (map fst $ filter snd $ zip choices ok) clrFill clrMatch
+
+-- | Do an area fill with the given colour.
+areaFill clr pt@(x, y) = do
+	clrMatch <- getPixel pt
+	unsafeSetPixel pt clr
+	let choices = listArray (0, 3) [(x - 1, y), (x, y - 1), (x + 1, y), (x, y + 1)]
+	Draw $ do
+		d <- ask
+		let ?seq = True
+		lift $ conc_ (fmap (\choice -> runReaderT (unDraw $ areaFillImpl 10 [choice] clr clrMatch) d) choices)
+
+----------------------------------------
+-- Convolution
+
+{-# INLINE useFilter #-}
+useFilter filter shift im x y = let
+		(kw, kh) = askDims' filter
+		(wid, ht) = askDims' im
+		halfX = kw `quot` 2
+		halfY = kh `quot` 2
+		x1 = (x - halfX) `max` 0
+		y1 = (y - halfY) `max` 0
+		x2 = (x + halfX) `min` wid
+		y2 = (y + halfY) `min` ht
+		shiftBy = fromIntegral (if shift then 127 else 0)
+		sz = if shift then
+				fromIntegral $ (y2 - y1) * (x2 - x1) * 127
+			else
+				sum (map (\y -> sum $ map (\x -> enTuple (getPixel' (x, y) filter))
+					[0..x2-x1-1]) [0..y2-y1-1]) `max` 1 in
+	shiftBy + sum (map (\y -> sum $ map (\x -> (enTuple (getPixel' (x, y) filter) - shiftBy) * enTuple (getPixel' (x1 + x, y1 + y) im)) [0..x2-x1-1]) [0..y2-y1-1]) / sz
+
+-- | Standard convolution (with cutoffs).
+convolve :: BMP -> Bool -> BMP -> Draw ()
+convolve filter shift bmp = function' (\x y -> unTuple $ useFilter filter shift bmp x y)
+
+-- | Flip the current image corner to corner.
+flipped = do
+	(wid, ht) <- askDims
+	mapM_ (\y -> mapM_ (\x -> unsafeSwap (x, y) (wid - 1 - x, ht - 1 - y)) [0..wid-1]) [0..ht`div`2-1]
+
+unsafeSwap pt pt2 = do
+	clr <- unsafeGetPixel pt
+	clr2 <- unsafeGetPixel pt2
+	unsafeSetPixel pt clr2
+	unsafeSetPixel pt2 clr
+
+-- | Swaps two pixels.
+swap pt pt2 = do
+	clr <- getPixel pt
+	clr2 <- getPixel pt2
+	unsafeSetPixel pt clr2
+	unsafeSetPixel pt2 clr
+
+-- | Standard correlation
+correlate :: BMP -> Bool -> BMP -> Draw ()
+correlate kernel = convolve (fst $ onBitmap kernel flipped)
+
+intensity x = rgb n n n where
+	n = round $ 255 * x
+
+-- | Gaussian blur filter.
+blur :: Double -> BMP
+blur sigma = fst $ onNewBitmap (2 * dist, 2 * dist) $ function' $ \x y -> intensity $ f (x - dist, y - dist) where
+	dist = round (3 * sigma)
+	f (x, y) = exp (-0.5 * (fromIntegral x ^ 2 + fromIntegral y ^ 2) / sigma ^ 2) / (2 * pi)
+
+----------------------------------------
+-- Bilinear resampling
+
+instance (Num t, Num u, Num v) => Num (t, u, v) where
+	(n1, n2, n3) + (m1, m2, m3) = (n1 + m1, n2 + m2, n3 + m3)
+	negate (n1, n2, n3) = (-n1, -n2, -n3)
+	(n1, n2, n3) * (m1, m2, m3) = (n1 * m1, n2 * m2, n3 * m3)
+	signum (n1, n2, n3) = (signum n1, signum n2, signum n3)
+	abs (n1, n2, n3) = (abs n1, abs n2, abs n3)
+	fromInteger n = (fromInteger n, fromInteger n, fromInteger n)
+
+instance (Fractional t, Fractional u, Fractional v) => Fractional (t, u, v) where
+	fromRational n = (fromRational n, fromRational n, fromRational n)
+	recip (n1, n2, n3) = (recip n1, recip n2, recip n3)
+
+enTuple :: COLORREF -> (Fixed E6, Fixed E6, Fixed E6)
+enTuple x = (fromIntegral $ getRValue x, fromIntegral $ getGValue x, fromIntegral $ getBValue x)
+
+unTuple :: (Fixed E6, Fixed E6, Fixed E6) -> COLORREF
+unTuple (r, g, b) = rgb (round r) (round g) (round b)
+
+{-# INLINE weights #-}
+weights f (lo, hi) = if floor lo == floor hi then
+		f (floor lo)
+	else fromRational (recip (hi - lo)) * (fromRational (fromIntegral (ceiling lo) - lo) * f (floor lo)
+		+ fromRational (hi - fromIntegral (floor hi)) * f (floor hi)
+		+ sum (map f [ceiling lo..floor hi-1]))
+
+{-# INLINE weightsSpecial1 #-}
+weightsSpecial1 factor f (lo, hi) = fromRational (recip (fromIntegral factor)) * sum (map f [ceiling lo..floor hi-1])
+
+{-# INLINE weightsSpecial2 #-}
+weightsSpecial2 f (lo, _) = f (floor lo)
+
+{-# INLINE weightsSpecial3 #-}
+weightsSpecial3 f (lo, hi) = fromRational (recip (hi - lo)) * (fromRational (fromIntegral (ceiling lo) - lo) * f (floor lo)
+	+ fromRational (hi - fromIntegral (floor hi)) * f (floor hi)
+	+ sum (map f [ceiling lo..floor hi-1]))
+
+-- | Averages over the pixels in the given rectangle.
+{-# INLINE sample #-}
+sample weights im ((loX, loY), (hiX, hiY)) = unTuple $ weights (\y -> weights (\x -> enTuple $ getPixel' (x, y) im) (loX, hiX)) (loY, hiY)
+
+rescale2 hi hi2 x = fromIntegral (x * (hi2 + 1)) / fromIntegral (hi + 1)
+
+-- | Rescales a coordinate by moving it from the given first rectangle to the proportionate spot in the second rectangle.
+rescale (hiX, hiY) (hiX2, hiY2) (x, y) = (rescale2 hiX hiX2 x, rescale2 hiY hiY2 y)
+
+down1 (x, y) = (x - 1, y - 1)
+
+-- | Resamples the given image into the current image.
+resample :: BMP -> Draw ()
+resample im = do
+	bnds <- askDims
+	if bnds == askDims' im then
+			mask 1 (0, 0) im
+		else let (factor, m) = divMod (fst (askDims' im)) (fst bnds) in
+			function' $ \x y -> sample
+				-- These are optimizations for the case when the input image is an integral multiple of the output in size...
+				(if m == 0 && snd (askDims' im) `mod` snd bnds == 0 then
+					weightsSpecial1 factor
+				-- and the opposite...
+				else if fst bnds `mod` fst (askDims' im) == 0 && snd bnds `mod` snd (askDims' im) == 0 then
+					weightsSpecial2
+				-- and for when the image is being downsampled.
+				else if fst bnds < fst (askDims' im) && snd bnds < snd (askDims' im) then
+					weightsSpecial3
+				else
+					weights)
+				im (rescale (down1 bnds) (down1 $ askDims' im) (x, y), rescale (down1 bnds) (down1 $ askDims' im) (x + 1, y + 1))
+
+horzGradient = fst $ onNewBitmap (3, 3) $ function' $ \x _ -> intensity (fromIntegral x / 2)
+
+vertGradient = fst $ onNewBitmap (3, 3) $ function' $ \_ y -> intensity (fromIntegral y / 2)
+
+laplacian = fst $ onNewBitmap (3, 3) $ function' $ curry (listArray ((0, 0), (2, 2)) [0,-1,0,-1,10,-1,0,-1,0] !)
+
+----------------------------------------
+-- Quadratic splines
+
+stepsI :: Int
+stepsI = 100
+
+steps :: Double
+steps = fromIntegral stepsI
+
+graph (ax, ay, len) (x, y, direction, ddydirection, dy, t) = (x + direction / steps, y + direction * dy / steps, direction, ddydirection, dy + 2 * direction * ddydirection * ay / ax * step, t + step) where
+	step = sqrt (1 + dy ^ 2) / len / steps
+
+-- Compute pixel intensities for a piece of the spline.
+-- TODO: Some parameter signs and flags need to be twiddled for the various quadrants, so this doesn't work currently.
+intensities _ [] _ = []
+intensities swapped (parm@(ax, bx, cx, ay, by, cy):parms) tuple =
+	-- The intensities made by 'graph' only make sense in a certain range,
+	-- so when you get to a 45 degree angle, you switch x and y.
+	processed ++ if t >= 1 then
+		intensities swapped parms (x, y, direction, direction * ddydirection, dy, 0)
+	else
+		intensities (not swapped) ((ay, by, cy, ax, bx, cx):parms) (y, x, signum dy * direction, direction * ddydirection, recip dy, t)
+	where
+	(ok, (x, y, direction, ddydirection, dy, t):_) = break (\(_, _, _, _, dy, t) -> abs dy > 1 || t >= 1) $ iterate (graph (ax, ay, len parm)) tuple
+	processed = map (\(x, y, _, _, _, _) -> let
+		(y', n) = properFraction y
+		(a, b) = if swapped then (y', floor x) else (floor x, y') in
+		-- Intensity can't be 0, or we can't area fill.
+		((a, b), recip 255 `max` if {-(dx > 0) == -}dy > 0 then 1 - n else n)) ok
+
+rotate1 ls = tail ls ++ [head ls]
+
+unrotate1 ls = last ls : init ls
+
+pairUp ls = zip ls (rotate1 ls)
+
+-- Compute the length of a piece of the spline.
+len (a, b, _, c, d, _) = f 1 - f 0 where
+	f t = x t * (a ^ 2 * t + a * b + c * (c * t + d)) / 2 / (a ^ 2 + c ^ 2) + 1 / 2 / (a ^ 2 + c ^ 2) ** 1.5 * (b * c - a * d) ^ 2 * log (sqrt (a ^ 2 + c ^ 2) * x t + a ^ 2 * t + a * b + c ^ 2 * t + c * d)
+	x t = sqrt (t ^ 2 * (a ^ 2 + c ^ 2) + 2 * a * b * t + b ^ 2 + 2 * c * d * t + d ^ 2)
+
+windows _ [] = []
+windows n ls = tk : windows n dr where
+	(tk, dr) = splitAt n ls
+
+-- Draw the fringe of a spline.
+drawAA aa parms@((_, bx, cx, _, by, cy):_) = mapM_ (\(pt, i) -> (if aa then blend i else setPixel) pt (rgb 255 255 255))
+	$ map head $ windows stepsI $ drop (stepsI `quot` 2)
+	$ intensities
+		False
+		parms
+		(cx, cy, 1, 1, by / bx, 0)
+
+-- Compute parameters of the spline.
+splineCoefficients = tail . scanl (\(accel, slope, _) (x1, x2) -> let slope' = 2 * accel + slope in
+	(x2 - x1 - slope', slope', x1)) (0, 0, 0) . pairUp
+
+-- | Draw an antialiased filled spline.
+-- The first knot should be roughly at the bottom of the spline, and they should
+-- go around counter clockwise.
+spline aa clr knots = do
+	let parmX = unrotate1 $ splineCoefficients $ rotate1 $ map fst knots
+	let parmY = splineCoefficients $ map snd knots
+	let parameters = zipWith (\(ax, bx, cx) (ay, by, cy) -> (ax, bx, cx, ay, by, cy)) parmX parmY
+	dims <- askDims
+	let (bmp, _) = onNewBitmap dims $ do
+		drawAA aa parameters
+		-- areaFill (rgb 255 255 255) (ceiling *** ((+1) . ceiling) $ head knots)
+	mask 1 (0, 0) bmp
+
+----------------------------------------
+-- Basic shapes
+
+clipRect (x1, y1, x2, y2) (x1a, y1a, x2a, y2a) = (x1 `max` x1a, y1 `max` y1a, x2 `min` x2a, y2 `min` y2a)
+
+-- | Fill a rectangle.
+fillRect clr rect = do
+	(wid, ht) <- askDims
+	function rect (\_ _ _ -> clr)
+
+-- | Fill using a functional.
+function :: (Int32, Int32, Int32, Int32) -> (COLORREF -> Int32 -> Int32 -> COLORREF) -> Draw ()
+function rt f = Draw $ do
+	d <- ask
+	let ?seq = True
+	(wid, ht) <- unDraw askDims
+	let (x1, y1, x2, y2) = clipRect rt (0, 0, wid, ht)
+	lift $ concF_ (fromIntegral (y2 - y1)) (\y -> mapM_ (\x -> runReaderT (unDraw $ unsafeGetPixel (x, fromIntegral y + y1) >>= \c -> unsafeSetPixel (x, fromIntegral y + y1) (f c x (fromIntegral y + y1))) d) [x1..x2-1])
+
+function' f = do
+	(wid, ht) <- askDims
+	function (0, 0, wid, ht) (const f)
+
+mean x y = (y - x) / 2 + x
+
+-- | A filled ellipse.
+ellipse aa clr (x1, y1, x2, y2) = spline aa clr [(mean x1 x2, y1), (x2, mean y1 y2), (mean x1 x2, y2), (x1, mean y1 y2)]
+
+----------------------------------------
+-- Drawing in a device context.
+
+drawBitmap wnd hdc wd ht p = do
+	let wd32 = fromIntegral wd
+	let ht32 = fromIntegral ht
+	-- Draw the bitmap
+	withBITMAP (InfoV3 (BitmapInfoV3 40 wd ht False 1 24 CompressionRGB (4 * wd32 * ht32) 0 0 0 0)) $ \pBmp ->
+		c_SetDIBitsToDevice hdc 0 0 wd32 ht32 0 0 0 ht32 p pBmp dIB_RGB_COLORS
+
+-- | Put up a quick window to visualize the drawing as it's being drawn.
+graffito (x1, y1, x2, y2) d = do
+	chn <- newChan
+	wnd <- frameWindow Nothing Nothing nullPtr "Graffito" $ \wnd msg wParam lParam -> do
+		if msg == wM_CREATE then do
+			moveWindow wnd (fromIntegral x1) (fromIntegral y1) (fromIntegral (x2 - x1)) (fromIntegral (y2 - y1)) True
+			else if msg == wM_PAINT then
+				allocaPAINTSTRUCT $ \ps -> do
+					hdc <- beginPaint wnd ps
+					forkIO $ runReaderT (unDraw d) ((x2 - x1, y2 - y1), nullPtr, Just chn) >> writeChan chn (-1, 0, 0)
+					let loop = do { (x, y, clr) <- readChan chn; when (x >= 0) $ do { set hdc x (y2 - y1 - 1 - y) clr; loop } } in
+						loop
+					endPaint wnd ps
+			else if msg == wM_CLOSE then
+				void $ postMessage nullPtr wM_QUIT 0 0
+			else
+			return ()
+		defWindowProc (Just wnd) msg wParam lParam
+	postMessage wnd wM_CREATE 0 0
+	allocaMessage $ \msg ->
+		let loop =
+			do
+				b <- getMessage msg Nothing
+				when b $ do
+					translateMessage msg
+					dispatchMessage msg
+					loop in
+			loop
+ src/FRP/Reactivity/Examples.hs view
@@ -0,0 +1,60 @@+{-# LANGUAGE ScopedTypeVariables #-}++module FRP.Reactivity.Examples where++import Codec.BMP+import Control.Monad.IO.Class+import Control.Monad+import Control.Monad.Trans+import Control.Monad.Fix+import Foreign.Ptr+import Data.Int+import Data.Monoid+import FRP.Reactivity.Combinators+import qualified FRP.Reactivity.Draw as D+import FRP.Reactivity.UI+import FRP.Reactivity.Hook+import FRP.Reactivity.Extras+import Control.Applicative+import Graphics.Win32++-- Examples++-- | Counter app - counts the number of times the button is pressed+counter = run $ do+	-- Create a generic frame window...+	wnd <- create desktop "Frame" (pure (Appearance mempty "Counter" (0, 0, 400, 300)))++	-- and a button...+	w <- create wnd "BUTTON" (pure (mempty { rect = (0, 0, 200, 20), text = "Count" }))++	-- Make a label with a behavior that shows the count...+	let beh = stepper mempty $ corec (\pr@(_, n) msg t -> case msg of+		Mouse _ Down _ -> ((Appearance mempty (show $ n + 1) (0, 20, 200, 40), n + 1),+			Appearance mempty (show $ n + 1) (0, 20, 200, 40),+			t)+		_ -> (pr, fst pr, t))+		(mempty, 0 :: Int) (event w)+	create wnd "STATIC" beh++	-- Finally wait to close...+	Close <- liftE $ fmap return $ event wnd+	liftIO $ destroyWindow $ hwnd wnd++-- | Make a graph of the sine function.+animation = fmap (\b -> Appearance b "Graph" (0, 0, 250, 150)) $ graphBehavior (fmap sin time) (pure (0, 0, 250, 150)) (-1, 1) 10 (\_ -> rgb 212 100 0)++graphing = run $ runHook $ hCreate "Frame" animation autoclose++trackingBox ev = stepper mempty (fmap (\(x, y) -> Appearance (D.fillRect (rgb 0 255 0) (x - 20, y - 20, x + 20, y + 20)) "Tracker" (0, 0, 400, 300)) (mousePos ev))++mouseTracker = run $ do+	ev <- liftIO (chanSource defaultFrame)+	runHook (hCreate "Frame" (trackingBox (getEvent ev)) (autoclose >> window >>= \w -> lift (liftE (fmap return (event w))) >>= liftIO . addToEvent ev))++-- Scrollbars+scrollbars = run $ runHook $+	hCreate "Frame" (mempty { rect = (0, 0, 400, 300) }, mempty) $ do+		scroll $ hCreate' "BUTTON" (Appearance (return ()) "" (500, 300, 700, 330), mempty)+		autoclose+
+ src/FRP/Reactivity/Extras.hs view
@@ -0,0 +1,298 @@+{-# LANGUAGE Trustworthy, FlexibleContexts, ScopedTypeVariables #-}
+
+-- | Extra utilities.
+module FRP.Reactivity.Extras where
+
+import FRP.Reactivity.Hook
+import FRP.Reactivity.UI
+import FRP.Reactivity.Draw
+import FRP.Reactivity.Combinators
+import Control.Monad
+import Control.Monad.Trans
+import Control.Monad.Fix
+import Control.Applicative
+import Control.Comonad (duplicate)
+import Control.Exception
+import Control.Concurrent.MVar
+import Data.Int
+import Data.Monoid
+import Data.Fixed
+import Data.Maybe
+import qualified Data.Map as M
+import Graphics.Win32 hiding (textOut, fillRect)
+import Codec.BMP
+import Prelude hiding (until)
+
+import System.IO.Unsafe
+
+-- |
+dragNDrop :: (Monoid r) => (POINT -> Appearance) -> Maybe RECT -> Hook r (Event Message) Act t -> Hook r (Event Message) Act (Either t (Window, Btn, POINT, POINT))
+dragNDrop appr rect h = do
+	w <- window
+	(x, child) <- getReturns mempty id h
+	tellReturn child
+	return (Left x) <> do
+		-- Pick a child to follow
+		w2 <- lift $ liftE $ fmap return child
+
+		-- Wait for a child to be clicked
+		(btn, pt@(origX, origY), rest) <- lift $ liftE $ justE $ fmap (\(e, rest) -> case e of
+			Mouse b Down pt -> Just (return (b, pt, rest))
+			_ -> Nothing)
+			(withRest (event w2))
+
+		let pos = mousePos rest
+
+		-- Wait for the mouse to exit a "guard region" which prevents unwanted drags.
+		-- If the mouse is released before exiting the guard region, the drag operation is aborted.
+		lift $ liftE $ fmap return $ once $ filterE (\(x, y) -> abs (x - origX) > 20 && abs (y - origY) > 20) pos `untilE` filterE (\e -> case e of Mouse _ Up _ -> True; _ -> False) rest
+
+		liftIO (putStrLn "Dragging")
+
+		-- Move the drag icon in a drag operation.
+		liftM fst $ getReturns1 mempty id $ hCreate "STATIC" (stepper mempty $ fmap appr pos)
+			(do
+			drag <- window
+			lift $ liftE $ once $ justE (fmap (\e -> case e of Mouse _ Up pt2 -> Just (destroyWindow (hwnd drag) >> return (Right (w2, btn, pt, pt2))); _ -> Nothing) rest))
+
+-- |
+draggable :: (POINT -> Appearance) -> Maybe RECT -> Hook (Appearance, Event (Appearance -> Appearance)) (Event Message) Act t -> Hook (Appearance, Event (Appearance -> Appearance)) (Event Message) Act t
+draggable appr rt h = do
+	dragEvents <- liftIO (chanSource defaultFrame)
+	(ei, child) <- getReturns (mempty, fmap (\(_, _, (x1, y1), (x2, y2)) a -> a { rect = shift (x2 - x1, y2 - y1) (rect a) }) (getEvent dragEvents)) id $ dragNDrop appr rt h
+	either
+		(\ei -> tellReturn child >> return ei)
+		(\tup -> lift (liftS dragEvents $ return $ return tup) >> mzero)
+		ei
+
+dragMargin = 5
+
+data Side = Ll | Rr | U | D | N deriving Eq
+
+updateRect (Ll, U) (_, _, x2, y2) (x, y) = (x, y, x2, y2)
+updateRect (Rr, U) (x1, _, _, y2) (x, y) = (x1, y, x, y2)
+updateRect (Ll, D) (_, y1, x2, _) (x, y) = (x, y1, x2, y)
+updateRect (Rr, D) (x1, y1, _, _) (x, y) = (x1, y1, x, y)
+updateRect (Ll, N) (_, y1, x2, y2) (x, _) = (x, y1, x2, y2)
+updateRect (Rr, N) (x1, y1, _, y2) (x, _) = (x1, y1, x, y2)
+updateRect (N, U) (x1, _, x2, y2) (_, y) = (x1, y, x2, y2)
+updateRect (N, D) (x1, y1, x2, _) (_, y) = (x1, y1, x2, y)
+updateRect (N, N) rt _ = rt
+
+isRight (Right _) = True
+isRight _ = False
+
+-- | Functional which makes windows from the parameter 'h' into sizeable windows with draggable edges.
+sizeable :: Hook (Appearance, Event (Appearance -> Appearance)) (Event Message) Act t ->
+	Hook (Appearance, Event (Appearance -> Appearance)) (Event Message) Act t
+sizeable h = do
+	w <- window
+	wit <- liftIO (chanSource defaultFrame)
+	(x, child) <- getReturns (mempty, getEvent wit) (fmap (\(_, _, _, e, _) -> e) . filterE (\(hside, vside, _, _, _) -> hside == N && vside == N) . findDragEvents) h
+	tellReturn child
+	return x <> do
+		-- Pick a child
+		w2 <- lift $ liftE $ fmap return child
+
+		-- Wait for a child to be sized
+		(hside, vside, rt@(left, top, _, _), _, eRest) <- lift $ liftE $ fmap return $ findDragEvents (event w2)
+
+		guard (hside /= N || vside /= N)
+
+		let resizeRects = justE (fmap (\e -> case e of
+			Mouse _ Mv (x, y) -> Just (updateRect (hside, vside) rt (left + x, top + y))
+			_ -> Nothing) eRest)
+		let endResizeRect = justE (fmap (\e -> case e of
+			Mouse _ Up (x, y) -> Just (updateRect (hside, vside) rt (left + x, top + y))
+			_ -> Nothing) eRest)
+
+		-- Draw selection rectangle (the four borders)
+		-- This illustrates how static controls can be used to draw shapes
+		let initAppearance = Appearance (fillRect 0 (0, 0, 65536, 65536)) "" (0, 0, 0, 0)
+		s1 <- hCreate' "STATIC" (initAppearance, fmap (\(x1, y1, x2, y2) a -> a { rect = (x1, y1, x2, y1 + dragMargin) }) resizeRects)
+		s2 <- hCreate' "STATIC" (initAppearance, fmap (\(x1, y1, x2, y2) a -> a { rect = (x1, y1 + dragMargin, x1 + dragMargin, y2 - dragMargin) }) resizeRects)
+		s3 <- hCreate' "STATIC" (initAppearance, fmap (\(x1, y1, x2, y2) a -> a { rect = (x2 - dragMargin, y1 + dragMargin, x2, y2 - dragMargin) }) resizeRects)
+		s4 <- hCreate' "STATIC" (initAppearance, fmap (\(x1, y1, x2, y2) a -> a { rect = (x1, y2 - dragMargin, x2, y2) }) resizeRects)
+
+		-- Wait for mouse cursor to release
+		newRt <- lift $ liftE $ fmap return $ once endResizeRect
+
+		-- Remove selection rectangle
+		liftIO $ destroyWindow (hwnd s1) >> destroyWindow (hwnd s2) >> destroyWindow (hwnd s3) >> destroyWindow (hwnd s4)
+
+		-- Update the rectangle
+		lift $ liftS wit $ return $ return $ \a -> a { rect = newRt }
+		mzero where
+	findDragEvents e = fmap (\(((e, eRest), rt@(x1, y1, x2, y2)), t) -> case e of
+			Mouse _ Down (x, y) ->
+				let
+					hside = if x < dragMargin then Ll else if x >= x2 - x1 - dragMargin then Rr else N
+					vside = if y < dragMargin then U else if y >= y2 - y1 - dragMargin then D else N in
+					(hside, vside, rt, e, startAt eRest (list [(t, 0.1)]))
+			_ -> (N, N, rt, e, startAt eRest (list [(t, 0.1)])))
+			$ withTime
+			$ holdE (withRest e) (position e) (0, 0, 0, 0)
+
+-- | Perform an action when the window is closed.
+onClose :: (HWND -> IO ()) -> Hook r x Act ()
+onClose f = void $ do
+	w <- window
+	lift $ liftS nil $ fmap (\msg -> case msg of Close -> liftIO $ f (hwnd w); _ -> return ()) (event w)
+
+-- | Causes the current window to close when the user closes it.
+autoclose :: Hook r x Act ()
+autoclose = onClose destroyWindow
+
+realign (lo, hi) (mn, mx) x = if x < lo then
+		mn
+	else if x > hi then
+		mx
+	else
+		(x - lo) * (mx - mn) / (hi - lo) + mn
+
+-- | Given,
+--   * A behavior 'b'
+--   * An event
+--   * A display range 'rng'
+--   * Sampling rate (number of samples per second)
+--   * And a colour functional 'clrF',
+--   Gives a behavior that graphs 'b' in the range 'rng'. The event indicates when to resize
+--   the graph in the display window.
+graphBehavior :: (RealFrac t) => Behavior t -> Event RECT -> (t, t) -> Int32 -> (t -> COLORREF) -> Behavior (Draw ())
+graphBehavior b pos (nY, mY) samps clr = switcher (pure mempty)
+	$ fmap (\(rt@(x1, y1, x2, y2), b) -> (\t f -> graph (t - fromIntegral (x2 - x1) / fromIntegral samps, nY, t, mY) (dim rt) f clr)
+		<$> time
+		<*> history (fromIntegral $ samps * (x2 - x1)) b)
+		(snapshot pos (duplicate b))
+
+vertLine x (y1, y2) = fillRect 0 (x, y1, x + 1, y2)
+
+horzLine (x1, x2) y = fillRect 0 (x1, y, x2, y + 1)
+
+maxOfRange :: (RealFrac t) => t -> (Int32, Fixed E6)
+maxOfRange mx = (ceiling (mx / 10 ^^ n), 10 ^^ n)
+	where n = floor (log (fromRational (toRational mx) * 0.75) / log 10)
+
+-- | Graphs a function in a specific range.
+--
+-- Parameters;
+--
+--   * (mX, mY) - The maximum data values of the graph.
+--
+--   * (x1, y1) - The dimensions of the graph, in pixels.
+--
+--   * f - The function to graph.
+--
+--   * clrF - A colour functional.
+graph :: (RealFrac t, RealFrac u) => (t, u, t, u) -> POINT -> (t -> u) -> (u -> COLORREF) -> Draw ()
+graph (nX, nY, mX, mY) (x1, y1) f clrF = do
+	-- Draw abscissa/ordinate
+	mapM_ (\n -> do
+		let x2 = 30 + (x1 - 40) * n `div` mxX
+		textOut (showFixed True $ fromRational (toRational nX) + fromIntegral n * incrementX) (x2 - 5, 5) defFont
+		vertLine x2 (20, 25)) [0..mxX]
+	mapM_ (\n -> do
+		let y2 = 25 + (y1 - 35) * n `div` mxY
+		textOut (showFixed True $ fromRational (toRational nY) + fromIntegral n * incrementY) (0, y2 - 5) defFont
+		horzLine (25, 30) y2) [0..mxY]
+	horzLine (30, x1) 25
+	vertLine 30 (25, y1)
+
+	-- Draw graph
+	function (31, 26, x1, y1) (\c x y -> let
+			v = f (realign (31, fromIntegral (x1 - 10)) (nX, mX) (fromIntegral x))
+			aln = realign (nY, mY) (26, fromIntegral $ y1 - 10) v in
+		if y > floor aln then c else clrF v)
+	where
+		(mxX, incrementX) = maxOfRange (mX - nX)
+		(mxY, incrementY) = maxOfRange (mY - nY)
+
+-- | This is for anything with text. Upon double-clicking on the object, it displays
+--   an edit control (which can be dismissed by hitting ENTER).
+editableText :: Hook (Appearance, Event (Appearance -> Appearance)) (Event Message) Act t ->
+	Hook (Appearance, Event (Appearance -> Appearance)) (Event Message) Act t
+editableText h = do
+	wnd <- window
+	changes <- liftIO (chanSource defaultFrame)
+	(x, child) <- getReturns (mempty, fmap (\t a -> a { text = t }) (getEvent changes)) id h
+	tellReturn child
+	return x <> do
+		((w, txt), rect) <- lift $ liftE $ child >>= \w -> fmap return $ holdE (holdE (fmap (const w) $ filterE (\e -> case e of
+			Mouse _ Dbl _ -> True
+			_ -> False) (event w)) (texts (event w)) "")
+			(position (event w)) (0, 0, 0, 0)
+		
+		liftIO $ showWindow (hwnd w) sW_HIDE
+		w2 <- hCreate' "EDIT" (Appearance mempty txt rect, mempty)
+
+		let finish = fmap (\(_, txt) -> destroyWindow (hwnd w2) >> return txt) $ once $ holdE (filterE (\e -> case e of
+			Key True key -> key == vK_RETURN
+			_ -> False) (event w2))
+			(texts (event w2)) txt
+
+		liftIO $ showWindow (hwnd w) sW_SHOW
+		lift $ liftS changes finish
+		mzero
+
+data Pair t u = Pair t u deriving Show
+
+instance (Ord t, Ord u, Bounded t, Bounded u) => Monoid (Pair t u) where
+	mempty = Pair minBound minBound
+	mappend (Pair a1 b1) (Pair a2 b2) = Pair (max a1 a2) (max b1 b2)
+
+{-# INLINE convert #-}
+convert reac ev = (mempty { text = "0,0,0" },
+	(\(pos, (rt, mx)) _ -> let (wid, ht) = dim rt in
+	Appearance (return ()) (show mx
+		++ ',' : show (max wid ht)
+		++ ',' : show pos) rt)
+	<$>
+	snapshot ev reac)
+
+{-# INLINE extent #-}
+extent = monoid . fmap (stepper (Pair 0 0) . justE . fmap (\msg -> case msg of
+	Move (_, _, x, y) -> Just (Pair x y)
+	Close -> Just (Pair 0 0)
+	_ -> Nothing))
+
+-- | If some child controls are out of view,
+-- adds scroll bars that allow the user to access them.
+scroll :: Hook (Appearance, Event (Appearance -> Appearance)) (Event Message) Act t -> Hook (Appearance, Event (Appearance -> Appearance)) (Event Message) Act t
+scroll h = liftM fst $ mfix $ \ ~(_, functional) -> do
+	wnd <- window
+	adjustStream <- liftIO $ chanSource defaultFrame
+	~(x, children) <- getReturns (mempty, getEvent adjustStream) id h
+	let changes = justE $ fmap (\msg -> case msg of Move rt -> Just (dim rt); _ -> Nothing) (event wnd)
+	let hDim = fmap (\(wid, ht) -> (0, ht - barSize, wid - barSize, ht)) changes
+	let vDim = fmap (\(wid, ht) -> (wid - barSize, 0, wid, ht - barSize)) changes
+	let ext = extent (fmap event children)
+	hw <- hCreate' "SCROLLBAR" $ convert ((,)
+		<$> stepper empt hDim
+		<*> fmap (\(Pair x _) -> x) ext)
+		(position (event wnd))
+	vw <- hCreate' "SCROLLBAR" $ convert ((,)
+		<$> stepper empt vDim
+		<*> fmap (\(Pair _ x) -> x) ext)
+		(position (event wnd))
+	-- Add a hook to move controls around
+	-- and a hook to make this invisible to other components
+ 	let adjust = (\(xPos, yPos) appr@(Appearance _ _ (x, y, _, _)) ->
+		appr { rect = shift (x - xPos, y - yPos) (rect appr) })
+		<$>
+		zipE (getChanges (event hw)) 0 (getChanges (event vw)) 0
+	let adjust2 ev = (\(msg, (xPos, yPos)) -> case msg of
+		Move rt -> Move $ shift (xPos, yPos) rt
+		_ -> msg)
+		<$>
+		holdE
+			ev
+			(zipE (getChanges (event hw)) 0 (getChanges (event vw)) 0)
+			(0, 0)
+	lift $ liftS adjustStream $ fmap return adjust
+	return (x, functional) where
+	empt = (0, 0, 0, 0)
+	getChanges = justE . fmap (\msg -> case msg of Change s -> Just (read s); _ -> Nothing)
+
+barSize :: LONG
+barSize = 18
+
+ src/FRP/Reactivity/Hook.hs view
@@ -0,0 +1,135 @@+{-# LANGUAGE Unsafe, GeneralizedNewtypeDeriving, DeriveFunctor, FlexibleInstances, Rank2Types, FunctionalDependencies, OverlappingInstances, UndecidableInstances #-}
+
+module FRP.Reactivity.Hook (Resource(..), Hook,
+-- | * Versions of UI functions that can be modified by hooks.
+hCreate, hCreate',
+-- | * Hook readers
+getFilter, window, getResource, tellReturn, getReturns, getReturns1,
+-- | * Running
+ty, runHook) where
+
+import Foreign.Ptr
+import Control.Applicative
+import Control.Monad.Reader
+import Control.Monad.Writer
+import Control.Monad.Trans
+import Control.Monad
+import Data.Monoid
+import FRP.Reactivity.Combinators
+import FRP.Reactivity.UI
+import FRP.Reactivity.Draw
+import Codec.BMP
+import Graphics.Win32
+
+newtype Hook r x m t = Hook { unHook :: WriterT (Event Window) (ReaderT (Window, r, x -> x) m) t } deriving (Monad, MonadPlus, MonadFix, Functor, Applicative, Alternative, MonadIO)
+
+instance MonadTrans (Hook r x) where
+	lift = Hook . lift . lift
+
+instance (MonadPlus m) => Monoid (Hook r x m t) where
+	mempty = mzero
+	mappend = mplus
+
+-- | Versions of UI functions that can be modified by hooks.
+{-# INLINE hCreate #-}
+hCreate :: (Monoid r, Resource r) => WndClass -> r -> Hook r (Event Message) Act t -> Hook r (Event Message) Act t
+hCreate wndclass r hook = do
+	parent <- window
+	r2 <- getResource
+	f <- getFilter
+	w <- lift $ create parent wndclass (toBeh (r2 <> r))
+	tellReturn (return w)
+	(x, y) <- lift $ runReaderT (runWriterT (unHook hook)) (w { event = f (event w) }, r2, f)
+	tellReturn y
+	return x
+
+{-# INLINE hCreate' #-}
+hCreate' wndclass r = hCreate wndclass r window
+
+-- | Filters are hooks modifying the event stream the caller sees.
+{-# INLINE getFilter #-}
+getFilter :: (Monad m) => Hook r x m (x -> x)
+getFilter = Hook $ liftM (\(_, _, f) -> f) $ lift ask
+
+-- | Resources are a way of augmenting the behaviors used by subsequent controls.
+{-# INLINE getResource #-}
+getResource :: (Monad m) => Hook r x m r
+getResource = Hook $ liftM (\(_, r, _) -> r) $ lift ask
+
+{-# INLINE tellReturn #-}
+tellReturn r = Hook $ tell r
+
+{-# INLINE getReturns #-}
+getReturns :: (Monoid r, Monad m) => r -> (x -> x) -> Hook r x m t -> Hook r x m (t, Event Window)
+getReturns r f h = do
+	w <- window
+	r2 <- getResource
+	f2 <- getFilter
+	lift $ runReaderT (runWriterT (unHook h)) (w, r <> r2, f . f2)
+
+{-# INLINE getReturns1 #-}
+getReturns1 r f h = do
+	w <- window
+	lift $ runReaderT (runWriterT (unHook h)) (w, r, f)
+
+-- | 'window' gives the identity of the parent window.
+{-# INLINE window #-}
+window :: (Monad m) => Hook r x m Window
+window = Hook $ liftM (\(w, _, _) -> w) $ lift ask
+
+-- | Functional that fixes the usual type parameters.
+{-# INLINE ty #-}
+ty :: Hook (Behavior Appearance) (Event Message) Act t -> Hook (Behavior Appearance) (Event Message) Act t
+ty = id
+
+-- | Runs a procedure in the Hook monad transformer.
+{-# INLINE runHook #-}
+runHook ~(Hook h) = runReaderT (runWriterT h) (desktop, mempty, id)
+
+err = error "FRP.Hook.toBeh: no start value"
+
+-- | These are common ways of converting data to a behavior.
+class Resource r where
+	toBeh :: r -> Behavior Appearance
+
+instance Resource (Behavior Appearance) where
+	toBeh = id
+
+instance Resource (Event Appearance) where
+	toBeh = stepper err
+
+instance Resource (Appearance, Event (Appearance -> Appearance)) where
+	toBeh (x, e) = stepper x $ corec (\x f t -> (f x, f x, t)) x e
+
+instance Resource Appearance where
+	toBeh = pure
+
+instance Resource (Draw ()) where
+	toBeh d = pure (Appearance d "" (0, 0, 0, 0))
+
+instance Resource BMP where
+	toBeh = toBeh . mask 1 (0, 0)
+
+instance Resource String where
+	toBeh s = pure (Appearance (return ()) s (0, 0, 0, 0))
+
+instance Monoid BMP where
+	mempty = newBitmap (0, 0)
+	mappend b b2 = fst $ onNewBitmap (wid `max` wid2, ht + ht2) $ do
+		mask 1 (0, 0) b
+		mask 1 (0, ht) b2 where
+		(wid, ht) = askDims' b
+		(wid2, ht2) = askDims' b2
+
+instance Monoid Appearance where
+	mempty = Appearance (return ()) "" (0, 0, 0, 0)
+	mappend a a2 = Appearance (draw a >> draw a2)
+		(text a ++ text a2)
+		(x1 `max` x3, y1 `max` y3, x2 `max` x4, y2 `max` y4) where
+		(x1, y1, x2, y2) = rect a
+		(x3, y3, x4, y4) = rect a2
+
+instance Monoid (Draw ()) where
+	mempty = return ()
+	mappend = (>>)
+
+ src/FRP/Reactivity/UI.hs view
@@ -0,0 +1,414 @@+{-# LANGUAGE Trustworthy, ScopedTypeVariables, DeriveDataTypeable #-}
+
+module FRP.Reactivity.UI (Btn(..), MouseEv(..), Message(..), Appearance(..), WndClass, isMouse, isKey, isChange, isMove, onMouse, onKey, onMove, Window(..), hwnd, event, desktop, dim, shift, inside, intersectRect, regulate, suspendUpdate, unsuspendUpdate, create, position, texts, mousePos, module FRP.Reactivity.Basic) where
+
+import Data.XSizeable
+import FRP.Reactivity.Combinators
+import FRP.Reactivity.Basic
+import FRP.Reactivity.Draw
+import Data.IORef
+import Data.Typeable
+import Data.Monoid
+import Data.Int
+import Data.Bits hiding (shift)
+import Data.Array.MArray
+import qualified Data.Map as M
+import Data.Char
+import Foreign.Storable
+import Foreign.Ptr
+import Foreign.C.Types
+import System.IO.Unsafe
+import Unsafe.Coerce
+import Graphics.Win32 hiding (fillRect)
+import System.Win32
+import Graphics.Win32Extras
+import Graphics.Subclass
+import Control.Monad
+import Control.Monad.Loops
+import Control.Monad.Reader
+import Control.Exception
+import Codec.BMP
+import Prelude hiding (until)
+
+import Data.Char
+
+data Btn = L | R deriving (Eq, Show, Typeable)
+
+data MouseEv = Down | Up | Dbl | Mv deriving (Eq, Show, Typeable)
+
+data InternalMessage =
+   IChange !String !HWND
+ | IPush !HWND
+ | IFocus !HWND
+ | Destroy
+ | Tick !HWND deriving (Eq, Show, Typeable)
+
+data Message =
+   Mouse !Btn !MouseEv !POINT
+ | Key !Bool !VKey
+ | Change !String
+ | Push
+ | Move !RECT
+ | Close
+ | Focus
+ | Internal !InternalMessage deriving (Eq, Show, Typeable)
+
+data Appearance = Appearance { draw :: !(Draw ()), text :: !String, rect :: !RECT } deriving Typeable
+
+instance Show Appearance where
+	showsPrec prec appr = showParen (prec == 11) $ ("Appearance _  "++)
+		. showsPrec 11 (text appr)
+		. (' ':)
+		. showsPrec 11 (rect appr)
+
+type WndClass = String
+
+{-# INLINE isMouse #-}
+isMouse (Mouse _ _ _) = True
+isMouse _ = False
+
+{-# INLINE isKey #-}
+isKey (Key _ _) = True
+isKey _ = False
+
+{-# INLINE isChange #-}
+isChange (Change _) = True
+isChange _ = False
+
+{-# INLINE isMove #-}
+isMove (Move _) = True
+isMove _ = False
+
+{-# INLINE onMouse #-}
+onMouse f ev = justE $ fmap (\m -> case m of Mouse b m p -> Just (f b m p); _ -> Nothing) ev
+
+{-# INLINE onKey #-}
+onKey f ev = justE $ fmap (\m -> case m of Key b n -> Just (f b n); _ -> Nothing) ev
+
+{-# INLINE onMove #-}
+onMove f ev = justE $ fmap (\m -> case m of Move rt -> Just (f rt); _ -> Nothing) ev
+
+toWPARAM :: Ptr a -> WPARAM
+toWPARAM = unsafeCoerce
+
+toLPARAM :: Ptr a -> LPARAM
+toLPARAM = unsafeCoerce
+
+{-# NOINLINE ref #-}
+ref :: IORef Appearance
+ref = unsafePerformIO $ newIORef $ Appearance (return ()) "" (0, 0, 0, 0)
+
+data Window = Window { hwnd :: !HWND, event :: Event Message } -- The type of windows.
+
+-- | A window representing the desktop.
+desktop = Window nullPtr mempty
+
+-- | Dimensions of a rectangle.
+dim (x1, y1, x2, y2) = (x2 - x1, y2 - y1)
+
+-- | Shift a rectangle.
+shift (x, y) (x1, y1, x2, y2) = (x1 + x, y1 + y, x2 + x, y2 + y)
+
+-- | Membership test for rectangles.
+inside (x1, y1, x2, y2) = inRange ((x1, y1), (x2, y2))
+
+-- | Intersection of two rectangles.
+intersectRect (x1, y1, x2, y2) (x1a, y1a, x2a, y2a) = (x1a `max` x1, y1a `max` y1, x2a `min` x2, y2a `min` y2)
+
+{-# INLINE regulate #-}
+-- | Under some circumstances, such as video playback, it can be undesirable to buffer
+--   up many frames and play them back. In order to avoid time leaks, the program
+--   can drop frames.
+regulate :: Event t -> Act (Event t)
+regulate e = liftM justE $ allOccs (corecA (\t1 x t -> do
+	t1' <- getPOSIXTime
+	if t >= fromRational (toRational (t1 - start)) then
+			return (t1', Just x, t)
+		else
+			return (t1, Nothing, t))
+	0
+	e)
+
+{-# NOINLINE suspendedUpdateWindows #-}
+suspendedUpdateWindows :: IORef (M.Map HWND ())
+suspendedUpdateWindows = unsafePerformIO (newIORef M.empty)
+
+-- | The "built-in suspending mechanism" prevents interference between the reactive behavior
+--   of a window and user input to that window.
+--   The behavior is as follows:
+--     * When the user moves/drags a window, its position stops reflecting the position
+--       in its reactive behavior.
+--     * When the user enters text in a text box, its text stops reflecting the text
+--       of the reactive behavior.
+--     * When the user moves a scroll bar, its position stops reflecting that
+--       of the reactive behavior.
+--
+--   'suspendUpdate' suspends the update of a window. Unlike the built-in mechanism
+--   for suspending, this suspends drawing on the surface of the window as well.
+suspendUpdate :: HWND -> IO ()
+suspendUpdate hwnd = modifyIORef' suspendedUpdateWindows (M.insert hwnd ())
+
+-- | Undoes any suspending of the window. This affects both 'suspendUpdate' and
+--   the built-in suspending mechanism.
+unsuspendUpdate :: HWND -> IO ()
+unsuspendUpdate hwnd = modifyIORef' suspendedUpdateWindows (M.delete hwnd)
+
+create :: Window -> WndClass -> Behavior Appearance -> Act Window
+create (Window parent parentEv) cls beh = do
+	(wnd, ev) <- liftE $ return $ createWnd parent cls
+	let ev' = return (Internal (Tick nullPtr)) <> if isFrame cls then
+			ev
+		else
+			ev <> routeChildEvents wnd parentEv
+	ev'' <- return (fmap (const Focus) (getEvent ticks) <> ev')
+	let ups = updates cls beh ev''
+	liftS nil $ fmap (\tup@((_, app), _) -> do -- Do updates
+			writeIORef ref app
+			update wnd cls tup)
+		ups
+	return (Window wnd ev') -- Return the event stream
+
+{-# INLINE routeChildEvents #-}
+routeChildEvents wnd = fmap (\msg -> case msg of
+	Internal (IChange s hwnd) -> if wnd == hwnd then Change s else msg
+	Internal (IPush hwnd) -> if wnd == hwnd then Push else msg
+	Internal (IFocus hwnd) -> if wnd == hwnd then Focus else msg
+	_ -> Internal (Tick nullPtr))
+
+read' x = if all isDigit x then read x else unsafePerformIO (print x >> return 0)
+
+update wnd cls ((msg, Appearance draw text (x, y, xx, yy)), suspend) = do
+	mp <- readIORef suspendedUpdateWindows
+	unless (M.member wnd mp) (catch (do
+		let wid = xx - x
+		let ht = yy - y
+		-- Size the window
+		(x1, y1, x2, y2) <- getWindowRect wnd
+		unless (isMove msg) $ if isFrame cls then unless suspend $ do
+				(_, _, clientWd, clientHt) <- getClientRect wnd
+				unless (fromIntegral clientWd == wid && fromIntegral clientHt == ht) $
+					setWindowPos wnd
+						nullPtr
+						(fromIntegral x1)
+						(fromIntegral y1)
+						(fromIntegral (x2 - x1 - clientWd) + fromIntegral wid)
+						(fromIntegral (y2 - y1 - clientHt) + fromIntegral ht)
+						sWP_NOZORDER
+			else unless (x1 == fromIntegral x && y1 == fromIntegral y && x2 == fromIntegral xx && y2 == fromIntegral yy) $
+				setWindowPos wnd
+					nullPtr
+					(fromIntegral x)
+					(fromIntegral y)
+					(fromIntegral wid)
+					(fromIntegral ht)
+					sWP_NOZORDER
+
+		-- Set scrollbar direction
+		when (map toUpper cls == "SCROLLBAR") $ void $ setWindowLong wnd gWLP_STYLE $ fromIntegral $ wS_VISIBLE .|. wS_CHILDWINDOW .|. if wid > ht then sBS_HORZ else sBS_VERT
+
+		-- Set the text
+		case map toUpper cls of
+			"SCROLLBAR" -> do
+				let (mx, _:rest) = break (==',') text
+				let (page, _:pos) = break (==',') rest
+				old <- getScrollInfo wnd (fromIntegral sB_CTL)
+				let mask = sIF_RANGE .|. sIF_POS .|. if suspend then 0 else sIF_POS
+				let new = SCROLLINFO mask 0 (read' mx) (read' page) (read' pos) 0
+				unless (old { fMask = mask } == new) $ void $ setScrollInfo wnd (fromIntegral sB_CTL) new
+			_ -> do
+				prev <- getText wnd
+				when (isFrame cls || not suspend && prev /= text) $ setWindowText wnd text
+
+		-- Repaint the window
+		invalidateRect (Just wnd) Nothing True
+		updateWindow wnd)
+		(\(_ :: IOError) -> return ()))
+
+-- | The rectangle of a window from its message stream.
+{-# INLINE position #-}
+position ev = corec (\rt msg t -> let rt' = case msg of Move rt -> rt; _ -> rt in
+	(rt', rt', t)) (0, 0, 0, 0) ev
+
+{-# INLINE _texts #-}
+_texts ev = corec (\s pr@(msg, _) t -> let s' = case msg of Change s -> s; _ -> s in
+	(s', (pr, s'), t)) "" ev
+
+-- | The text of a window from its message stream.
+{-# INLINE texts #-}
+texts ev = fmap snd $ _texts $ fmap (\msg -> (msg, Appearance (return ()) "" (0, 0, 1, 1))) ev
+
+-- | The position of the mouse.
+{-# INLINE mousePos #-}
+mousePos ev = corec (\pt msg t -> let pt' = case msg of Mouse _ Mv pt -> pt; _ -> pt in
+	(pt', pt', t)) (0, 0) ev
+
+-- Rules out Change messages caused by behavior updates.
+{-# INLINE behFree #-}
+behFree ev = corec (\((prevMsg, _), b) (pr@(_, app), txt) t -> let pr' = (pr, text app == txt && (isChange prevMsg || b)) in
+	(pr', pr', t))
+	((Focus, undefined), True)
+	$ _texts ev
+
+{-# INLINE userChange #-}
+userChange cls ev = if isFrame cls then
+		filterE (\(msg, _) -> isMove msg) ev
+	else
+		fmap fst $ filterE (\((msg, _), b) -> isChange msg && b) (behFree ev)
+
+{-# INLINE suspend #-}
+suspend cls ev = flipFlop (userChange cls ev) mempty
+
+-- Sample a behavior. This also takes care of suspending behaviors.
+{-# INLINE updates #-}
+updates :: WndClass -> Behavior Appearance -> Event Message -> Event ((Message, Appearance), Bool)
+updates cls beh ev = snapshot samp (suspend cls samp) where
+	ev' = ev `untilE` filterE (\m -> case m of Internal Destroy -> True; _ -> False) ev -- The event stream should not deliver messages after Destroy is delivered.
+	samp = snapshot ev' beh
+
+getText wnd = catch (getWindowText wnd) (\(_ :: IOError) -> return "")
+
+createWnd parent cls = do
+	-- Make event fed by the window
+	Stream sink ev <- chanSource defaultFrame
+	bmp :: SA Int32 CChar <- newArray_ (0, -1)
+	let handler proc wnd msg wParam lParam = do
+		may <- mapMessage (if isFrame cls then nullPtr else parent) wnd msg wParam lParam
+
+		maybe
+			(do
+			app <- readIORef ref
+			(_, _, wid, ht) <- getClientRect wnd
+			let sz = 4 * wid * ht
+			resize (0, sz - 1) bmp
+			(_, p) <- getPtr bmp
+			memset p 0 (fromIntegral sz)
+			runReaderT (unDraw (fillRect defBackground (0, 0, wid, ht) >> draw app)) ((wid, ht), p, Nothing)
+			if msg == wM_PAINT && isFrame cls then
+				allocaPAINTSTRUCT $ \ps -> do
+					hdc <- beginPaint wnd ps
+					drawBitmap wnd hdc (fromIntegral wid) (fromIntegral ht) p
+					endPaint wnd ps
+				else if msg == wM_DRAWITEM then void $ do
+					(wnd, hdc) <- catch (liftM2 (,) (peekByteOff (unsafeCoerce lParam) 20) (peekByteOff (unsafeCoerce lParam) 24)) (\(_ :: IOException) -> return (nullPtr, nullPtr))
+					drawBitmap wnd hdc (fromIntegral wid) (fromIntegral ht) p
+					drawText hdc (text app) (0, 0, wid, ht) (dT_VCENTER .|. dT_SINGLELINE)
+				else when (msg == wM_CTLCOLORSTATIC) $ void $ setBkMode (unsafeCoerce wParam) tRANSPARENT)
+			(\x -> do
+				print x
+				sink x
+				case x of
+					Mouse _ Up pt -> when (map toUpper cls == "BUTTON") $ do
+						rt <- getClientRect wnd
+						when (inside rt pt) (sink Push)
+					_ -> return ())
+			may
+
+		-- Take care of mouse capture
+		if msg `elem` [wM_LBUTTONDOWN, wM_RBUTTONDOWN] then
+				void $ setCapture wnd
+			else when (msg `elem` [wM_LBUTTONUP, wM_RBUTTONUP]) $ void releaseCapture
+
+		-- An application can't be expected to respond to WM_ENDSESSION immediately,
+		-- therefore it holes up in an event loop here, waiting for approval
+		-- from the app to close.
+		-- !!! Must do everything here that is done in event loop
+		when (msg == wM_ENDSESSION) $ allocaMessage $ \msg ->
+			untilM_
+				(return ())
+				(do
+					getMessage msg Nothing
+					translateMessage msg
+					dispatchMessage msg
+					hwnd <- peekByteOff msg 0
+					msgN <- peekByteOff msg 4
+					return $ hwnd == wnd && msgN == wM_DESTROY)
+
+		if msg == wM_CLOSE || msg == wM_DRAWITEM then
+			return 0
+			else
+			proc wnd msg wParam lParam
+
+	-- Create the window
+	hdl <- getModuleHandle Nothing
+	let name = mkClassName cls
+	wnd <- createWindow name "" (wS_CLIPCHILDREN .|. wS_VISIBLE .|. case map toUpper cls of
+		"FRAME" -> wS_OVERLAPPEDWINDOW
+		"STATIC" -> wS_CHILDWINDOW .|. sS_OWNERDRAW
+		"EDIT" -> wS_CHILDWINDOW .|. eS_AUTOHSCROLL
+		"SCROLLBAR" -> wS_CHILDWINDOW .|. sBS_HORZ
+		_ -> wS_CHILDWINDOW) (Just 0) (Just 0) (Just 0) (Just 0) (Just parent) Nothing hdl (handler (defWindowProc . Just))
+	updateWindow wnd
+
+	if isFrame cls then void $ sendMessage wnd wM_ACTIVATE 0 0
+		else void $ do
+		-- Set the font
+		font <- createFont 16 0 0 0 fW_NORMAL False False False dEFAULT_CHARSET 0 0 dEFAULT_QUALITY fF_DONTCARE "Tahoma"
+		sendMessage wnd wM_SETFONT (toWPARAM font) 0
+
+		subclassProc wnd handler
+
+		-- Send a create message to the parent on this control's behalf
+		postMessage parent wM_APP (toWPARAM wnd) 0
+
+	return (wnd, ev)
+
+isFrame cls = cls == "Frame"
+
+mapMessage parent hwnd msg wParam lParam = if msg `elem` [wM_LBUTTONUP, wM_LBUTTONDOWN, wM_RBUTTONUP, wM_RBUTTONDOWN, wM_LBUTTONDBLCLK, wM_RBUTTONDBLCLK, wM_MOUSEMOVE] then
+		return $ Just $ Mouse
+			(if msg `elem` [wM_LBUTTONDOWN, wM_LBUTTONUP, wM_LBUTTONDBLCLK] then L else R)
+			(if msg `elem` [wM_LBUTTONDOWN, wM_RBUTTONDOWN] then
+				Down
+			else if msg `elem` [wM_LBUTTONDBLCLK, wM_RBUTTONDBLCLK] then
+				Dbl
+			else if msg == wM_MOUSEMOVE then
+				Mv
+			else
+				Up)
+			(fromIntegral (fromIntegral (loWord lParam) :: Int16) :: Int32, hiWord lParam)
+	else if msg `elem` [wM_KEYDOWN, wM_KEYUP] then
+		return $ Just $ Key (msg == wM_KEYDOWN) wParam
+	else if msg == wM_COMMAND && hiWord wParam `elem` [eN_UPDATE, cBN_EDITUPDATE, cBN_SELENDOK] then
+		liftM (\s -> Just $ Internal $ IChange s (unsafeCoerce lParam)) $ getText $ unsafeCoerce lParam
+	else if msg == wM_COMMAND && hiWord wParam == bN_CLICKED then
+		return $ Just $ Internal $ IPush (unsafeCoerce lParam)
+	else if msg `elem` [wM_HSCROLL, wM_VSCROLL] then do
+		si <- getScrollInfo (unsafeCoerce lParam) (fromIntegral sB_CTL)
+		let newY = if loWord wParam == sB_LINEDOWN then
+				nPos si + 50
+			else if loWord wParam == sB_LINEUP then
+				nPos si - 50
+			else if loWord wParam == sB_PAGEDOWN then
+				nPos si + fromIntegral (nPage si)
+			else if loWord wParam == sB_PAGEUP then
+				nPos si - fromIntegral (nPage si)
+			else if loWord wParam == sB_THUMBTRACK then
+				maxBound
+			else if loWord wParam == sB_THUMBPOSITION then
+				nTrackPos si
+			else
+				nPos si
+		if newY == maxBound then
+			return Nothing
+			else do
+				setScrollInfo (unsafeCoerce lParam) (fromIntegral sB_CTL) (si { nPos = newY })
+				return $ Just $ Internal $ IChange (show $ max 0 (min newY (nMax si - fromIntegral (nPage si)))) (unsafeCoerce lParam)
+	else if msg == wM_WINDOWPOSCHANGED then do
+		rt@(x1, y1, x2, y2) <- getWindowRect hwnd
+		liftM (Just . Move) $ if parent == nullPtr then
+				return rt
+			else do
+				(cx, cy) <- clientToScreen parent (0, 0)
+				return (shift (-cx, -cy) rt)
+	else if msg == wM_ACTIVATE && wParam == 1 then
+		return $ Just Focus
+	else if msg == wM_SETFOCUS then
+		return $ Just $ Internal $ IFocus (unsafeCoerce wParam)
+	else if msg == wM_APP then
+		return $ Just $ Internal $ Tick (unsafeCoerce wParam)
+	else if msg `elem` [wM_CLOSE, wM_ENDSESSION] then
+		return $ Just Close
+	else if msg == wM_DESTROY then
+		return $ Just $ Internal Destroy
+	else
+		return Nothing