packages feed

manatee-ircclient (empty) → 0.0.1

raw patch · 29 files changed

+2928/−0 lines, 29 filesdep +Cabaldep +GoogleTranslatedep +MorseCodebuild-type:Customsetup-changedbinary-added

Dependencies added: Cabal, GoogleTranslate, MorseCode, array, base, bytestring, containers, dbus-client, dbus-core, fastirc, filepath, groom, gtk, gtk-serialized-event, gtksourceview2, manatee-core, mtl, nano-md5, network, regex-posix, split, stm, template-haskell, text, unix, utf8-string

Files

+ Daemon.hs view
@@ -0,0 +1,60 @@+-- Author:     Andy Stewart <lazycat.manatee@gmail.com>+-- Maintainer: Andy Stewart <lazycat.manatee@gmail.com>+-- +-- Copyright (C) 2010 Andy Stewart, all rights reserved.+-- +-- This program is free software: you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation, either version 3 of the License, or+-- any later version.+-- +-- This program is distributed in the hope that it will be useful,+-- but WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+-- GNU General Public License for more details.+-- +-- You should have received a copy of the GNU General Public License+-- along with this program.  If not, see <http://www.gnu.org/licenses/>.++{-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables #-}+{-# LANGUAGE OverloadedStrings #-}+module Main where++import Control.Concurrent.MVar+import Control.Monad (forever)+import Manatee.Core.DBus+import Manatee.Core.Types+import Manatee.Extension.IrcClient.DBus+import Manatee.Extension.IrcClient.Daemon+import Manatee.Toolkit.General.DBus+import System.Environment+import System.Posix.Types++-- | Startup daemon process to listen irc signal.+main :: IO ()+main = do+  args <- getArgs++  -- Init irc status. +  status <- ircInitStatus++  -- Build match rule listen dbus message.+  client <- mkSessionClientWithName ircDaemonBusName+  mkIrcDaemonMatchRules client +       [(Join,          ircJoin status) +       ,(Part,          ircPart status)+       ,(SendMessage,   ircSendMessage status)+       ]++  case args of+    [] -> putStrLn "IrcBuffer should call 'manatee-irc-daemon processId', and not 'manatee-irc-daemon'."+    [x] -> do+      let processId = read x :: ProcessID+      mkIrcClientSignal client processId DaemonProcessStartup DaemonProcessStartupArgs++  -- Quit process when received exit signal from manatee daemon process.+  let exitSignal = ircExitSignal status+  mkDaemonBroadcastMatchRule client (ExitDaemonProcess, \_ -> putMVar exitSignal "Exit")+  readMVar exitSignal           -- read exit signal to exit+  putStrLn "Exit irc daemon process."+
+ LICENSE view
@@ -0,0 +1,676 @@+              GNU GENERAL PUBLIC LICENSE+                Version 3, 29 June 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 General Public License is a free, copyleft license for+software and other kinds of works.++  The licenses for most software and other practical works are designed+to take away your freedom to share and change the works.  By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users.  We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors.  You can apply it to+your programs, too.++  When we speak of free software, we are referring to freedom, not+price.  Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++  To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights.  Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++  For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received.  You must make sure that they, too, receive+or can get the source code.  And you must show them these terms so they+know their rights.++  Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++  For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software.  For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++  Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so.  This is fundamentally incompatible with the aim of+protecting users' freedom to change the software.  The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable.  Therefore, we+have designed this version of the GPL to prohibit the practice for those+products.  If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++  Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary.  To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++  The precise terms and conditions for copying, distribution and+modification follow.++                TERMS AND CONDITIONS++  0. Definitions.++  "This License" refers to version 3 of the GNU General Public License.++  "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.+ +  "The Program" refers to any copyrightable work licensed under this+License.  Each licensee is addressed as "you".  "Licensees" and+"recipients" may be individuals or organizations.++  To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy.  The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++  A "covered work" means either the unmodified Program or a work based+on the Program.++  To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy.  Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++  To "convey" a work means any kind of propagation that enables other+parties to make or receive copies.  Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++  An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License.  If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++  1. Source Code.++  The "source code" for a work means the preferred form of the work+for making modifications to it.  "Object code" means any non-source+form of a work.++  A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++  The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form.  A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++  The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities.  However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work.  For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++  The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++  The Corresponding Source for a work in source code form is that+same work.++  2. Basic Permissions.++  All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met.  This License explicitly affirms your unlimited+permission to run the unmodified Program.  The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work.  This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++  You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force.  You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright.  Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++  Conveying under any other circumstances is permitted solely under+the conditions stated below.  Sublicensing is not allowed; section 10+makes it unnecessary.++  3. Protecting Users' Legal Rights From Anti-Circumvention Law.++  No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++  When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++  4. Conveying Verbatim Copies.++  You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++  You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++  5. Conveying Modified Source Versions.++  You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++    a) The work must carry prominent notices stating that you modified+    it, and giving a relevant date.++    b) The work must carry prominent notices stating that it is+    released under this License and any conditions added under section+    7.  This requirement modifies the requirement in section 4 to+    "keep intact all notices".++    c) You must license the entire work, as a whole, under this+    License to anyone who comes into possession of a copy.  This+    License will therefore apply, along with any applicable section 7+    additional terms, to the whole of the work, and all its parts,+    regardless of how they are packaged.  This License gives no+    permission to license the work in any other way, but it does not+    invalidate such permission if you have separately received it.++    d) If the work has interactive user interfaces, each must display+    Appropriate Legal Notices; however, if the Program has interactive+    interfaces that do not display Appropriate Legal Notices, your+    work need not make them do so.++  A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit.  Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++  6. Conveying Non-Source Forms.++  You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++    a) Convey the object code in, or embodied in, a physical product+    (including a physical distribution medium), accompanied by the+    Corresponding Source fixed on a durable physical medium+    customarily used for software interchange.++    b) Convey the object code in, or embodied in, a physical product+    (including a physical distribution medium), accompanied by a+    written offer, valid for at least three years and valid for as+    long as you offer spare parts or customer support for that product+    model, to give anyone who possesses the object code either (1) a+    copy of the Corresponding Source for all the software in the+    product that is covered by this License, on a durable physical+    medium customarily used for software interchange, for a price no+    more than your reasonable cost of physically performing this+    conveying of source, or (2) access to copy the+    Corresponding Source from a network server at no charge.++    c) Convey individual copies of the object code with a copy of the+    written offer to provide the Corresponding Source.  This+    alternative is allowed only occasionally and noncommercially, and+    only if you received the object code with such an offer, in accord+    with subsection 6b.++    d) Convey the object code by offering access from a designated+    place (gratis or for a charge), and offer equivalent access to the+    Corresponding Source in the same way through the same place at no+    further charge.  You need not require recipients to copy the+    Corresponding Source along with the object code.  If the place to+    copy the object code is a network server, the Corresponding Source+    may be on a different server (operated by you or a third party)+    that supports equivalent copying facilities, provided you maintain+    clear directions next to the object code saying where to find the+    Corresponding Source.  Regardless of what server hosts the+    Corresponding Source, you remain obligated to ensure that it is+    available for as long as needed to satisfy these requirements.++    e) Convey the object code using peer-to-peer transmission, provided+    you inform other peers where the object code and Corresponding+    Source of the work are being offered to the general public at no+    charge under subsection 6d.++  A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++  A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling.  In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage.  For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product.  A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++  "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source.  The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++  If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information.  But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++  The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed.  Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++  Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++  7. Additional Terms.++  "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law.  If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++  When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it.  (Additional permissions may be written to require their own+removal in certain cases when you modify the work.)  You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++  Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++    a) Disclaiming warranty or limiting liability differently from the+    terms of sections 15 and 16 of this License; or++    b) Requiring preservation of specified reasonable legal notices or+    author attributions in that material or in the Appropriate Legal+    Notices displayed by works containing it; or++    c) Prohibiting misrepresentation of the origin of that material, or+    requiring that modified versions of such material be marked in+    reasonable ways as different from the original version; or++    d) Limiting the use for publicity purposes of names of licensors or+    authors of the material; or++    e) Declining to grant rights under trademark law for use of some+    trade names, trademarks, or service marks; or++    f) Requiring indemnification of licensors and authors of that+    material by anyone who conveys the material (or modified versions of+    it) with contractual assumptions of liability to the recipient, for+    any liability that these contractual assumptions directly impose on+    those licensors and authors.++  All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10.  If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term.  If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++  If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++  Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++  8. Termination.++  You may not propagate or modify a covered work except as expressly+provided under this License.  Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++  However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++  Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++  Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License.  If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++  9. Acceptance Not Required for Having Copies.++  You are not required to accept this License in order to receive or+run a copy of the Program.  Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance.  However,+nothing other than this License grants you permission to propagate or+modify any covered work.  These actions infringe copyright if you do+not accept this License.  Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++  10. Automatic Licensing of Downstream Recipients.++  Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License.  You are not responsible+for enforcing compliance by third parties with this License.++  An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations.  If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++  You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License.  For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++  11. Patents.++  A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based.  The+work thus licensed is called the contributor's "contributor version".++  A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version.  For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++  Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++  In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement).  To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++  If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients.  "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.+  +  If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++  A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License.  You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++  Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++  12. No Surrender of Others' Freedom.++  If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License.  If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all.  For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++  13. Use with the GNU Affero General Public License.++  Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work.  The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++  14. Revised Versions of this License.++  The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time.  Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++  Each version is given a distinguishing version number.  If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation.  If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++  If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++  Later license versions may give you additional or different+permissions.  However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++  15. Disclaimer of Warranty.++  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++  16. Limitation of Liability.++  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++  17. Interpretation of Sections 15 and 16.++  If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++              END OF TERMS AND CONDITIONS++     How to Apply These Terms to Your New Programs++  If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++  To do so, attach the following notices to the program.  It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++    <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 General Public License as published by+    the Free Software Foundation, either version 3 of the License, or+    (at your option) any later version.++    This program is distributed in the hope that it will be useful,+    but WITHOUT ANY WARRANTY; without even the implied warranty of+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+    GNU General Public License for more details.++    You should have received a copy of the GNU General Public License+    along with this program.  If not, see <http://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++  If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++    <program>  Copyright (C) <year>  <name of author>+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+    This is free software, and you are welcome to redistribute it+    under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License.  Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++  You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<http://www.gnu.org/licenses/>.++  The GNU General Public License does not permit incorporating your program+into proprietary programs.  If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library.  If this is what you want to do, use the GNU Lesser General+Public License instead of this License.  But first, please read+<http://www.gnu.org/philosophy/why-not-lgpl.html>.++
+ Main.hs view
@@ -0,0 +1,31 @@+-- Author:     Andy Stewart <lazycat.manatee@gmail.com>+-- Maintainer: Andy Stewart <lazycat.manatee@gmail.com>+-- +-- Copyright (C) 2010 Andy Stewart, all rights reserved.+-- +-- This program is free software: you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation, either version 3 of the License, or+-- any later version.+-- +-- This program is distributed in the hope that it will be useful,+-- but WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+-- GNU General Public License for more details.+-- +-- You should have received a copy of the GNU General Public License+-- along with this program.  If not, see <http://www.gnu.org/licenses/>.++{-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables #-}+{-# LANGUAGE OverloadedStrings #-}+module Main where++import Control.Applicative hiding (empty)+import Manatee.Core.Render+import Manatee.Core.Types+import Manatee.Extension.IrcClient++-- | Irc client render process.+main :: IO ()+main = +    startupRender (\ pagePath client pageId -> PageBufferWrap <$> ircBufferNew pagePath client pageId)
+ Manatee/Extension/IrcClient.hs view
@@ -0,0 +1,26 @@+-- Author:     Andy Stewart <lazycat.manatee@gmail.com>+-- Maintainer: Andy Stewart <lazycat.manatee@gmail.com>+-- +-- Copyright (C) 2010 Andy Stewart, all rights reserved.+-- +-- This program is free software: you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation, either version 3 of the License, or+-- any later version.+-- +-- This program is distributed in the hope that it will be useful,+-- but WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+-- GNU General Public License for more details.+-- +-- You should have received a copy of the GNU General Public License+-- along with this program.  If not, see <http://www.gnu.org/licenses/>.++{-# LANGUAGE OverloadedStrings #-}+module Manatee.Extension.IrcClient (+  module Manatee.Extension.IrcClient.IrcBuffer,+  module Manatee.Extension.IrcClient.IrcView,+) where++import Manatee.Extension.IrcClient.IrcBuffer+import Manatee.Extension.IrcClient.IrcView
+ Manatee/Extension/IrcClient/DBus.hs view
@@ -0,0 +1,200 @@+-- Author:     Andy Stewart <lazycat.manatee@gmail.com>+-- Maintainer: Andy Stewart <lazycat.manatee@gmail.com>+-- +-- Copyright (C) 2010 Andy Stewart, all rights reserved.+-- +-- This program is free software: you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation, either version 3 of the License, or+-- any later version.+-- +-- This program is distributed in the hope that it will be useful,+-- but WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+-- GNU General Public License for more details.+-- +-- You should have received a copy of the GNU General Public License+-- along with this program.  If not, see <http://www.gnu.org/licenses/>.++{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE ScopedTypeVariables #-}+module Manatee.Extension.IrcClient.DBus where++import DBus.Client hiding (Signal)+import DBus.MatchRule+import DBus.Message (Signal, signalBody)+import DBus.Types+import Data.Maybe (fromMaybe)+import Data.Text.Lazy (Text, empty)+import Graphics.UI.Gtk.General.General+import Language.Haskell.TH+import Manatee.Core.DBus+import Manatee.Core.TH+import Manatee.Extension.IrcClient.Types+import Manatee.Toolkit.General.DBus+import Manatee.Toolkit.General.Misc+import Network.FastIRC.Types+import System.Posix.Process +import System.Posix.Types (ProcessID)++import qualified Data.ByteString.Char8 as B++data IrcDaemonMember = Join+                     | Part+                     | SendMessage+                       deriving (Show, Eq, Ord)++data IrcDaemonSignalArgs = JoinArgs Server Port Channel Nick ProcessID+                         | PartArgs Server Channel ProcessID+                         | SendMessageArgs Server B.ByteString+                           deriving (Show, Eq, Ord)++data IrcClientMember = ReceivePrivate+                     | ReceiveJoin+                     | ReceiveTopicReply+                     | ReceiveTopicWhoTime+                     | ReceiveChannelUrl+                     | ReceiveNames+                     | ReceiveQuit+                     | ReceivePart+                     | DaemonProcessStartup+                       deriving (Show, Eq, Ord)++data IrcClientSignalArgs = ReceivePrivateArgs NickName CommandArg+                         | ReceiveJoinArgs NickName UserName HostName+                         | ReceiveTopicReplyArgs CommandArg+                         | ReceiveTopicWhoTimeArgs NickName Integer+                         | ReceiveChannelUrlArgs B.ByteString+                         | ReceiveNamesArgs B.ByteString+                         | ReceiveQuitArgs NickName UserName HostName CommandArg+                         | ReceivePartArgs NickName UserName HostName CommandArg+                         | DaemonProcessStartupArgs+                           deriving (Show, Eq, Ord)++-- | Irc daemon bus name.+ircDaemonBusName :: Text+ircDaemonBusName = "org.manatee.extension.irc.daemon"++ircDaemonInterfaceName :: Text +ircDaemonInterfaceName = "org.manatee.daemon.interface"++-- | The daemon path name.+ircDaemonPathName :: Text +ircDaemonPathName = "/path"++-- | Check daemon signal argument.+-- Return False if mismatch.+mkFunDec "checkIrcDaemonSignalArgs" (checkSignalArgs ''IrcDaemonMember ''IrcDaemonSignalArgs)++-- | Unpack daemon signal from Variant list.+-- unpackIrcDaemonSignalArgs_ :: IrcDaemonMember -> [Variant] -> Maybe IrcDaemonSignalArgs                 +mkFunDec "unpackIrcDaemonSignalArgs_" (unpackVariantList ''IrcDaemonMember ''IrcDaemonSignalArgs)++-- | Pack daemon signal argument to Variant list.+-- packIrcDaemonSignalArgs :: IrcDaemonSignalArgs -> [Variant]+$(packVariantList "packIrcDaemonSignalArgs" ''IrcDaemonSignalArgs)++-- | Check client signal argument.+-- Return False if mismatch.+mkFunDec "checkIrcClientSignalArgs" (checkSignalArgs ''IrcClientMember ''IrcClientSignalArgs)++-- | Unpack client signal from Variant list.+-- unpackIrcClientSignalArgs_ :: IrcClientMember -> [Variant] -> Maybe IrcClientSignalArgs                 +mkFunDec "unpackIrcClientSignalArgs_" (unpackVariantList ''IrcClientMember ''IrcClientSignalArgs)++-- | Pack client signal argument to Variant list.+-- packIrcClientSignalArgs :: IrcClientSignalArgs -> [Variant]+$(packVariantList "packIrcClientSignalArgs" ''IrcClientSignalArgs)++-- | Build daemon signal.+-- If signal argument not match daemon member name.+mkIrcDaemonSignal :: Client -> IrcDaemonMember -> IrcDaemonSignalArgs -> IO ()+mkIrcDaemonSignal client memberName args +    | checkIrcDaemonSignalArgs memberName args -- check signal argument before emit signal.+        = emitSignal client signal+    | otherwise+        = putStrLn $ "mkIrcDaemonSignal CRITICAL: Invalid argument for dbus daemon member: " ++ show memberName+          where signal = mkMessageSignal +                         ircDaemonPathName+                         (showText memberName)+                         ircDaemonInterfaceName+                         ircDaemonBusName+                         (packIrcDaemonSignalArgs args)++-- | Build daemon match rule.+mkIrcDaemonMatchRule :: Client -> (IrcDaemonMember, IrcDaemonSignalArgs -> IO ()) -> IO ()+mkIrcDaemonMatchRule client (member, fun) = +    onSignal client matchRule $ \_ signal -> +        fun $ pickIrcDaemonSignalArgs member signal+        where matchRule = mkMatchRule+                          (Just Signal) +                          empty +                          ircDaemonInterfaceName+                          (showText member)+                          ircDaemonPathName+                          ircDaemonBusName+                          []++-- | Build daemon match rule list.+mkIrcDaemonMatchRules :: Client -> [(IrcDaemonMember, IrcDaemonSignalArgs -> IO ())] -> IO ()              +mkIrcDaemonMatchRules client = mapM_ (mkIrcDaemonMatchRule client)++-- | Pick IrcDaemonSignalArgs.+pickIrcDaemonSignalArgs :: IrcDaemonMember -> Signal -> IrcDaemonSignalArgs          +pickIrcDaemonSignalArgs member signal = unpackIrcDaemonSignalArgs member $ signalBody signal++-- | Unpack daemon signal from Variant list.+-- Report error if mismatch.+unpackIrcDaemonSignalArgs member args = +    fromMaybe +      (error $ "unpackIrcDaemonSignalArgs: Miss pattern for " ++ show member)+      (unpackIrcDaemonSignalArgs_ member args)++-- | Pick IrcClientSignalArgs.+pickIrcClientSignalArgs :: IrcClientMember -> Signal -> IrcClientSignalArgs          +pickIrcClientSignalArgs member signal = unpackIrcClientSignalArgs member $ signalBody signal++-- | Unpack client signal from Variant list.+-- Report error if mismatch.+unpackIrcClientSignalArgs member args = +    fromMaybe +      (error $ "unpackIrcClientSignalArgs: Miss pattern for " ++ show member)+      (unpackIrcClientSignalArgs_ member args)++-- | Build render signal.+-- If signal argument not match render member name.+mkIrcClientSignal :: Client -> ProcessID -> IrcClientMember -> IrcClientSignalArgs -> IO ()+mkIrcClientSignal client processId memberName args +    | checkIrcClientSignalArgs memberName args -- check signal argument before emit signal.+        = emitSignal client signal+    | otherwise+        = putStrLn $ "mkIrcClientSignal CRITICAL: Invalid argument for dbus render member: " ++ show memberName+          where signal = mkMessageSignal +                         renderPathName+                         (showText memberName)+                         renderInterfaceName+                         (mkRenderClientName processId)+                         (packIrcClientSignalArgs args)++-- | Build render process match rule for catch signal.+mkIrcClientMatchRule :: Client -> (IrcClientMember, IrcClientSignalArgs -> IO ()) -> IO ()+mkIrcClientMatchRule client (member, fun) = do+    processId <- getProcessID+    let matchRule = mkMatchRule +                          (Just Signal) +                          empty +                          renderInterfaceName +                          (showText member)+                          renderPathName+                          (mkRenderClientName processId)+                          []+    -- Use postGUIAsync wrap DBus action to protect gtk+ main thread. +    onSignal client matchRule $ \_ signal -> +        postGUIAsync $ fun $ pickIrcClientSignalArgs member signal++-- | Build irc client match rule for catch signal.+mkIrcClientMatchRules :: Client -> [(IrcClientMember, IrcClientSignalArgs -> IO ())] -> IO ()+mkIrcClientMatchRules client = mapM_ (mkIrcClientMatchRule client)++deriveVariable (conT ''Integer)
+ Manatee/Extension/IrcClient/Daemon.hs view
@@ -0,0 +1,312 @@+-- Author:     Andy Stewart <lazycat.manatee@gmail.com>+-- Maintainer: Andy Stewart <lazycat.manatee@gmail.com>+-- +-- Copyright (C) 2010 Andy Stewart, all rights reserved.+-- +-- This program is free software: you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation, either version 3 of the License, or+-- any later version.+-- +-- This program is distributed in the hope that it will be useful,+-- but WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+-- GNU General Public License for more details.+-- +-- You should have received a copy of the GNU General Public License+-- along with this program.  If not, see <http://www.gnu.org/licenses/>.++{-# LANGUAGE TypeSynonymInstances #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE OverloadedStrings #-}+module Manatee.Extension.IrcClient.Daemon where++import Control.Applicative hiding (empty)+import Control.Concurrent+import Control.Concurrent.STM+import Control.Monad+import DBus.Client hiding (Signal)+import Data.List (delete)+import Data.Map (Map)+import Data.Maybe (fromMaybe)+import Manatee.Extension.IrcClient.DBus+import Manatee.Extension.IrcClient.Types+import Manatee.Toolkit.General.DBus+import Manatee.Toolkit.General.Map+import Manatee.Toolkit.General.Maybe+import Manatee.Toolkit.General.STM+import Network+import Network.FastIRC.IO+import Network.FastIRC.Messages+import Network.FastIRC.Users+import System.IO+import System.Posix.Types (ProcessID)+import Text.Groom++import qualified Control.Exception as Exc+import qualified Data.ByteString.Char8 as B+import qualified Data.Map as M+import qualified Data.Set as S++type HasConnected = Bool++type IrcConnect = +    -- "MVar Handle" as lock for avoid multithreading request to connect same server.+    Map Server+    -- Use processId list can broadcast irc message to multiple clients.+        (MVar Handle, Map Channel [ProcessID])++data IrcStatus =+    IrcStatus {ircConnect       :: TVar IrcConnect+              ,ircClient        :: Client+              ,ircExitSignal    :: MVar String}++-- | Initial status.+ircInitStatus :: IO IrcStatus+ircInitStatus =+  IrcStatus <$> newTVarIO M.empty+            <*> mkSessionClient+            <*> newEmptyMVar++-- | Send irc message.+ircSendMessage :: IrcStatus -> IrcDaemonSignalArgs -> IO ()+ircSendMessage IrcStatus {ircConnect    = connect} +               (SendMessageArgs server message) = do+  connectStatus <- readTVarIO connect+  case findMinMatch connectStatus (\ serverName _ -> serverName == server) of+    Just (_, (handle, _)) -> do+      isEmpty <- isEmptyMVar handle+      if isEmpty+         -- Socket is not activated.+         then putStrLn $ "Server " ++ server ++ "'s handle is not activated."+         -- Send message.+         else do+           h <- readMVar handle+           write h message+    -- Server is not connected.+    Nothing -> putStrLn $ "Server " ++ server ++ " is not connected."++-- | Part channel.+ircPart :: IrcStatus -> IrcDaemonSignalArgs -> IO ()    +ircPart (IrcStatus {ircConnect   = connect+                   ,ircExitSignal= exitSignal})+        (PartArgs server channel processId) = do+  -- Debug.+  -- putStrLn $ "ircPart : part command " ++ show (server, channel, processId)+  +  -- Part channel.+  connectStatus <- readTVarIO connect+  findMinMatch connectStatus (\ serverName _ -> serverName == server) +    ?>= \ (_, (handle, channelMap)) -> do+      let newChannelMap = +              case findMinMatch channelMap (\ channelName _ -> channelName == channel) of+                Just (_, processIdList) -> +                    -- Delete process id from list.+                    case delete processId processIdList of+                      -- Delete channel from map if no client process exit. +                      [] -> M.delete channel channelMap+                      -- Otherwise, just delete process from process list.+                      x  -> M.insert channel x channelMap+                Nothing -> channelMap++      if M.null newChannelMap+         -- Close socket when no channel exit in with server.+         then do+           -- Close socket.+           tryTakeMVar handle >?>= \h -> +                -- putStrLn $ "ircPart : Close irc server " ++ server ++ " connect."+                hClose h                                      ++           -- Whether quit daemon process.+           let newConnect = M.delete server connectStatus+           if M.null newConnect+              -- Quit daemon process when no server exit.+              then putMVar exitSignal "Exit"+              -- Otherwise, delete server from map.+              else +                -- putStrLn $ "ircPart : Delete irc server " ++ server+                writeTVarIO connect newConnect+         -- Otherwise, just update channel's process list.+         else +           -- putStrLn $ "ircPart : Part channel " ++ channel+           modifyTVarIO connect $ \c ->+             M.insert server (handle, newChannelMap) c++-- | Join channel.+ircJoin :: IrcStatus -> IrcDaemonSignalArgs -> IO ()+ircJoin status@(IrcStatus {ircConnect   = connect})+        (JoinArgs server port channel nick processId) = do+  -- Debug.+  -- putStrLn $ "Join command : " ++ show (server, port, channel, nick, processId)++  connectStatus <- readTVarIO connect+  let connectMatch = findMinMatch connectStatus (\ serverName _ -> serverName == server)+  (connectHandle, firstJoin) <- +    case connectMatch of+      -- Add client information if server has connected.+      Just (serverName, (handle, channelMap)) -> do+        let newConnectStatus = +              M.insert serverName +                   (handle,+                    case findMinMatch channelMap (\ channelName _ -> channelName == channel) of+                      Just (channelName, processList) -> +                          if processId `elem` processList+                             -- Keep no touch if channel and processId has exist+                             then channelMap+                             -- Otherwise add current processId in map.+                             else M.insert channelName (processList ++ [processId]) channelMap+                      Nothing -> +                          -- Or create new processid channel.+                          M.insert channel [processId] channelMap) +                   connectStatus+        writeTVarIO connect newConnectStatus+        return (handle, False)+      -- Otherwise connect server.+      Nothing -> do+        -- Create socket lock avoid multiple connect *race condition*.+        handle <- newEmptyMVar+        let newConnectStatus = +              M.insert server +                       (handle, M.fromList [(channel, [processId])])+                       connectStatus+        writeTVarIO connect newConnectStatus++        -- Connect server.+        h <- connectTo server (PortNumber (fromIntegral port))+        hSetBuffering h NoBuffering+        isSucess <- tryPutMVar handle h+        if isSucess +           then putStrLn $ "ircJoin : connect server " ++ server ++ " successful."+           else putStrLn "### ircJoin : Impossible! Multiple threads trying to connect to same server."+      +        -- Listen server.+        forkIO $ ircListenServerMessage status (server, h)+      +        return (handle, True)++  -- All threads for same socket will block here until first thread connect socket successful.+  h <- readMVar connectHandle++  -- Feed Nick and User message when first connect to server.+  when firstJoin $ do+    hPutCommand h (NickCmd (B.pack nick) Nothing)+    hPutCommand h (UserCmd tempUser "0" tempRealname "0")++  -- Feed join message.+  hPutCommand h (JoinCmd $ M.fromList [(B.pack channel, Nothing)])+  +-- | Listen server message.+ircListenServerMessage :: IrcStatus -> (Server, Handle) -> IO ()+ircListenServerMessage status@(IrcStatus {ircConnect = connect+                                         ,ircClient  = client})+                       (server, handle) = +  Exc.catch +     (do +       -- Get irc message.+       Message {msgOrigin  = origin+               ,msgCommand = command} <- hGetMessage handle++       -- Get nick.+       let (nick, user, host) = +               case origin of+                 Just spec -> +                     case spec of+                       Nick n -> (n, "", "")+                       User n u h -> (n, u, h)+                 Nothing -> ("", "", "")+       +       -- Parse command.+       connectStatus <- readTVarIO connect+       let sendToChannel command channelMap channel action = +               case findMinMatch channelMap (\ channelName _ -> B.pack channelName == channel) of+                 Just (_, processIdList) -> +                     -- Broadcast message to all irc client.+                     forM_ processIdList action+                 Nothing -> putStrLn $ "ircListenServerMessage : " ++ groom command+       case findMinMatch connectStatus (\ serverName _ -> serverName == server) of+         Just (_, (_, channelMap)) -> +           case command of+             PrivMsgCmd targetNameSet commandArg -> +                 mapM_ (\ target -> +                            sendToChannel command channelMap target $ \processId -> +                                mkIrcClientSignal client processId ReceivePrivate (ReceivePrivateArgs nick commandArg)+                       ) $ S.toList targetNameSet+             PingCmd server str -> +                          -- putStrLn $ "ircListenServerMessage : Pong server " ++ show (showCommand command)+                          hPutCommand handle $ PongCmd server str+             JoinCmd channels -> +               when enableJoinMessage $ +                    mapM_ (\ (channel, _) -> +                               sendToChannel command channelMap channel $ \processId -> +                                   mkIrcClientSignal client processId ReceiveJoin (ReceiveJoinArgs nick user host)+                          ) $ M.toList channels+             QuitCmd reason -> +                 when enableQuitMessage $ +                     -- Broadcast quit message to all channel process.+                     mapM_ (\ (_, processIdList) -> +                                forM_ processIdList $ \processId -> +                                    mkIrcClientSignal client processId +                                                      ReceiveQuit +                                                      (ReceiveQuitArgs nick user host (fromMaybe "" reason))+                           ) $ M.toList channelMap+             PartCmd targetNameSet commandArg -> +                 mapM_ (\ target -> +                            sendToChannel command channelMap target $ \processId -> +                                mkIrcClientSignal client processId +                                                  ReceivePart +                                                  (ReceivePartArgs nick user host (fromMaybe "" commandArg))+                       ) $ S.toList targetNameSet+             NumericCmd number messages -> +                 case number of+                   332 -> +                     when (length messages >= 3) $ do+                       let channel = messages !! 1+                           msg     = B.concat $ drop 2 messages+                       sendToChannel command channelMap channel $ \processId -> +                           mkIrcClientSignal +                               client processId +                               ReceiveTopicReply +                               (ReceiveTopicReplyArgs msg)+                   333 -> +                       when (length messages >= 4) $ do+                         let channel = messages !! 1+                             nick    = messages !! 2+                             seconds = read (B.unpack (messages !! 3)) :: Integer+                         sendToChannel command channelMap channel $ \processId -> +                             mkIrcClientSignal +                                 client processId +                                 ReceiveTopicWhoTime +                                 (ReceiveTopicWhoTimeArgs nick seconds)+                   328 -> +                       when (length messages >= 3) $ do+                         let channel = messages !! 1+                             url     = messages !! 2+                         sendToChannel command channelMap channel $ \processId -> +                             mkIrcClientSignal +                                 client processId +                                 ReceiveChannelUrl+                                 (ReceiveChannelUrlArgs url)+                   353 -> +                       when (length messages >= 4) $ do+                         let channel = messages !! 2+                             nicks   = messages !! 3+                         sendToChannel command channelMap channel $ \processId ->+                             mkIrcClientSignal +                                 client processId+                                 ReceiveNames+                                 (ReceiveNamesArgs nicks)+                   _ -> putStrLn $ "Numeric <" ++ show number ++ "> " ++ show messages+             _ -> putStrLn $ groom $ showCommand command+         Nothing -> putStrLn $ "### Impossible! ircListenServerMessage : Unknown server " ++ server+       +       -- Loop.+       ircListenServerMessage status (server, handle))+     -- Print debug information when catch server socket exception.+     (\ (_ :: Exc.IOException) -> putStrLn $ "ircListenServerMessage : Catch server " ++ server ++ " socket exception\n.")++-- | Flush message to socket.+write :: Handle -> B.ByteString -> IO ()+write handle msg = do+  B.hPutStr handle (msg `B.append` "\r\n")+  B.putStrLn msg+
+ Manatee/Extension/IrcClient/HighlightNick.hs view
@@ -0,0 +1,68 @@+-- Author:     Andy Stewart <lazycat.manatee@gmail.com>+-- Maintainer: Andy Stewart <lazycat.manatee@gmail.com>+-- +-- Copyright (C) 2010 Andy Stewart, all rights reserved.+-- +-- This program is free software: you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation, either version 3 of the License, or+-- any later version.+-- +-- This program is distributed in the hope that it will be useful,+-- but WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+-- GNU General Public License for more details.+-- +-- You should have received a copy of the GNU General Public License+-- along with this program.  If not, see <http://www.gnu.org/licenses/>.++module Manatee.Extension.IrcClient.HighlightNick where++import Data.Digest.OpenSSL.MD5+import Data.List.Split+import Graphics.UI.Gtk+import Manatee.Toolkit.General.String++import qualified Data.ByteString.Char8 as B++type NickColor = (Int, Int , Int)++-- | Background color.+backgroundColor :: NickColor+backgroundColor = (65335, 65335, 65335)+-- backgroundColor = (0, 0, 0)++-- | Returns the luminance of color. +-- Luminance is a value of 0.299 red + 0.587 green + 0.114 blue +-- and is always between 0 and 255.+colorLuminance :: NickColor -> Int+colorLuminance (r, g, b) = +    floor ((fromIntegral r * 0.299 + fromIntegral g * 0.587 + fromIntegral b * 0.114) / 256)++-- | Returns the inverted color.+invertColor :: NickColor -> NickColor+invertColor (r, g, b) =+  (65535 - r, 65535 - g, 65535 - b)++-- | Get unique color of nick. +nickColor :: B.ByteString -> NickColor+nickColor nick+    -- Invert color if too dark or too bright.+    | abs (luminance - backgroundLuminance) < 85+        = invertColor color+    | otherwise +        = color+  where hash      = take 12 $ md5sum nick +        [r, g, b] = splitEvery 4 hash+        color     = (hexStringToInt r+                    ,hexStringToInt g+                    ,hexStringToInt b)+        luminance = colorLuminance color+        backgroundLuminance = colorLuminance backgroundColor++-- | Convert nick color to color.+nickColorToColor :: NickColor -> Color        +nickColorToColor (r, g, b) =+  Color (fromIntegral r)+        (fromIntegral g)+        (fromIntegral b)
+ Manatee/Extension/IrcClient/IrcBuffer.hs view
@@ -0,0 +1,594 @@+-- Author:     Andy Stewart <lazycat.manatee@gmail.com>+-- Maintainer: Andy Stewart <lazycat.manatee@gmail.com>+-- +-- Copyright (C) 2010 Andy Stewart, all rights reserved.+-- +-- This program is free software: you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation, either version 3 of the License, or+-- any later version.+-- +-- This program is distributed in the hope that it will be useful,+-- but WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+-- GNU General Public License for more details.+-- +-- You should have received a copy of the GNU General Public License+-- along with this program.  If not, see <http://www.gnu.org/licenses/>.++{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}+module Manatee.Extension.IrcClient.IrcBuffer where++import Control.Concurrent.STM+import Control.Monad+import DBus.Client hiding (Signal)+import Data.Array+import Data.Map (Map)+import Data.Maybe+import Data.Set (Set)+import Data.Typeable+import Graphics.UI.Gtk hiding (Language, eventButton, eventClick)+import Graphics.UI.Gtk.Gdk.Events+import Graphics.UI.Gtk.SourceView.SourceBuffer+import Language.Translate.Google+import Manatee.Core.DBus+import Manatee.Core.Types+import Manatee.Extension.IrcClient.DBus+import Manatee.Extension.IrcClient.HighlightNick+import Manatee.Extension.IrcClient.PageMode+import Manatee.Extension.IrcClient.Smile+import Manatee.Extension.IrcClient.Types+import Manatee.Toolkit.General.Basic+import Manatee.Toolkit.General.ByteString+import Manatee.Toolkit.General.DBus+import Manatee.Toolkit.General.List+import Manatee.Toolkit.General.Map+import Manatee.Toolkit.General.Maybe+import Manatee.Toolkit.General.Process+import Manatee.Toolkit.General.STM+import Manatee.Toolkit.General.Set+import Manatee.Toolkit.General.Time+import Manatee.Toolkit.Gtk.Multiline+import Network.FastIRC.Types+import Network.URI+import System.Posix.Process+import Text.Regex.Posix hiding (after)++import qualified Data.ByteString.Char8 as B+import qualified Data.ByteString.UTF8 as UTF8+import qualified Data.Map as M+import qualified Data.Set as S++data IrcBuffer = +    IrcBuffer {ircBufferServer            :: Server+              ,ircBufferPort              :: Port+              ,ircBufferChannel           :: Channel+              ,ircBufferClient            :: Client+              ,ircBufferPageId            :: PageId+              ,ircBufferMode              :: PageMode+              ,ircBufferBuffer            :: SourceBuffer+              ,ircBufferInsertMark        :: TextMark+              ,ircBufferPromptMark        :: TextMark+              ,ircBufferScrollMark        :: TVar (Maybe TextMark)+              ,ircBufferEditableTag       :: TextTag+              ,ircBufferMessageTag        :: TextTag+              ,ircBufferServerColorTag    :: TextTag+              ,ircBufferSelfColorTag      :: TextTag+              ,ircBufferOtherColorTag     :: TextTag+              ,ircBufferJoinColorTag      :: TextTag+              ,ircBufferQuitColorTag      :: TextTag+              ,ircBufferPartColorTag      :: TextTag+              ,ircBufferActionColorTag    :: TextTag+              ,ircBufferUrlColorTag       :: TextTag+              ,ircBufferTimeStamp         :: TVar (Map Int (String, Color))+              ,ircBufferNick              :: TVar Nick+              ,ircBufferNickSet           :: TVar (Set NickName)+              ,ircBufferNickColorMap      :: TVar (Map NickName TextTag)+              ,ircBufferTranslateLanguage :: TVar Language+              ,ircBufferBroadcastChannel  :: TChan IrcBufferSignal+              ,ircBufferSmilePixbufs      :: Map String Pixbuf+              }+    deriving Typeable++data IrcBufferSignal = SwitchTranslateLanguage +                     | BufferChanged+                       deriving (Show, Eq, Ord)++-- | Create buffer new.+ircBufferNew :: String -> Client -> PageId -> IO IrcBuffer+ircBufferNew info client pageId = do+  -- Get server port channel information.+  let (mynick, server, port, channel) = ircParseInfo info+  putStrLn ("Buffer create (server, port, channel) : " ++ show (server, port, channel))++  -- Create source buffer and text mark.+  sourceBuffer <- sourceBufferNew Nothing+  ircBufferInsertPromptStr sourceBuffer+  insertMark <- ircBufferCreateInsertMark sourceBuffer+  promptMark <- ircBufferCreatePromptMark sourceBuffer+  scrollMark <- newTVarIO Nothing++  -- Create editable tag.+  textTag <- textTagNew Nothing+  set textTag [textTagEditable := False]+  tagTable <- textBufferGetTagTable sourceBuffer+  textTagTableAdd tagTable textTag++  -- Create message tag.+  messageTag <- textTagNew Nothing+  set messageTag [textTagEditable := False]+  textTagTableAdd tagTable messageTag++  -- Create color tag.+  serverColorTag <- ircBufferCreateColorTag sourceBuffer serverMsgColor+  selfColorTag   <- ircBufferCreateColorTag sourceBuffer selfMsgColor+  otherColorTag  <- ircBufferCreateColorTag sourceBuffer otherMsgColor+  joinColorTag   <- ircBufferCreateColorTag sourceBuffer joinMsgColor+  quitColorTag   <- ircBufferCreateColorTag sourceBuffer quitMsgColor+  partColorTag   <- ircBufferCreateColorTag sourceBuffer partMsgColor+  actionColorTag <- ircBufferCreateColorTag sourceBuffer actionMsgColor+  urlColorTag    <- ircBufferCreateColorTag sourceBuffer urlColor+  set urlColorTag [textTagUnderline := UnderlineSingle]++  -- Open url when click.+  urlColorTag `onTextTagEvent` \ event iter -> +      case event of+        Button {eventClick  = click+               ,eventButton = button} -> +          when (button == LeftButton && click == SingleClick) $ +            textBufferGetTagTextWithIter sourceBuffer iter urlColorTag +              >?>= \ url ->+                mkDaemonSignal client NewTab (NewTabArgs "PageBrowser" url)+        _ -> return ()++  -- Apply text tag.+  startIter <- textBufferGetStartIter sourceBuffer+  endIter   <- textBufferGetIterAtMark sourceBuffer promptMark+  textBufferApplyTag sourceBuffer textTag startIter endIter++  -- Time stamp.+  timeStamp <- newTVarIO M.empty++  -- Nick set.+  nick <- newTVarIO mynick++  -- Nick set.+  nickSet <- newTVarIO S.empty++  -- Nick color map.+  nickColorMap <- newTVarIO M.empty++  -- Target language.+  lang <- newTVarIO targetLanguage++  -- Broadcast channel.+  broadcastChannel <- newTChanIO :: IO (TChan IrcBufferSignal)++  -- Get smile pixbufs.+  smilePixbufs <- createSmilePixbufs++  -- Create buffer.+  let buffer = IrcBuffer server port channel+                         client pageId ircMode+                         sourceBuffer insertMark promptMark scrollMark +                         textTag messageTag serverColorTag selfColorTag otherColorTag +                         joinColorTag quitColorTag partColorTag actionColorTag urlColorTag+                         timeStamp nick nickSet nickColorMap lang+                         broadcastChannel smilePixbufs++  -- Add self in nick map.+  ircBufferAddNick buffer (B.pack mynick)++  -- Build DBus match rule.+  processId <- getProcessID+  mkIrcClientMatchRules client+    [(ReceivePrivate,+      \ (ReceivePrivateArgs nick msg) -> +          ircBufferReceivePrivate buffer nick msg)+    ,(ReceiveJoin,+     \ (ReceiveJoinArgs nick user host) ->+          ircBufferReceiveJoin buffer nick user host)+    ,(ReceiveTopicReply,+      \ (ReceiveTopicReplyArgs msg) ->+          ircBufferReceiveTopicReply buffer msg)+    ,(ReceiveTopicWhoTime,+      \ (ReceiveTopicWhoTimeArgs nick seconds) ->+          ircBufferReceiveTopicWhoTime buffer nick seconds)+    ,(ReceiveChannelUrl,+      \ (ReceiveChannelUrlArgs url) ->+          ircBufferReceiveChannelUrl buffer url)+    ,(ReceiveNames,+      \ (ReceiveNamesArgs nicks) -> +          ircBufferReceiveNames buffer nicks)+    ,(ReceiveQuit,+      \ (ReceiveQuitArgs nick user host reason) ->+          ircBufferReceiveQuit buffer nick user host reason)+    ,(ReceivePart,+      \ (ReceivePartArgs nick user host reason) ->+          ircBufferReceivePart buffer nick user host reason)+    ,(DaemonProcessStartup,+     \_ -> mkIrcDaemonSignal client Join (JoinArgs server port channel mynick processId))]+    +  -- Check whether daemon process has startup.+  ifM (isBusNameExist ircDaemonBusName)+      -- Send join signal if daemon process has startup.+      (mkIrcDaemonSignal client Join (JoinArgs server port channel mynick processId))+      -- Otherwise startup daemon process, send join signal after daemon process startup complete.+      (do+         putStrLn "No irc daemon process, starting one."+         runProcess_ "manatee-irc-daemon" [show processId])++  -- Add function when main loop left.+  -- Send part signal to daemon process if tab closed.+  quitAdd 0 (do+              putStrLn $ "Irc process "  ++ show processId ++ " quit."+              mkIrcDaemonSignal client Part (PartArgs server channel processId)+              return False)++  -- Record scroll mark before change buffer.+  -- Then we can restore scroll mark position after buffer changed.+  sourceBuffer `on` bufferChanged $ do+    cursorMark <- textBufferGetInsert sourceBuffer+    promptIter <- textBufferGetIterAtMark sourceBuffer promptMark+    insertIter <- textBufferGetInsertIter sourceBuffer+    order <- textIterCompare insertIter promptIter+    case order of+      GT -> writeTVarIO scrollMark (Just cursorMark)+      EQ -> writeTVarIO scrollMark (Just cursorMark)+      _  -> writeTVarIO scrollMark Nothing++  -- Broadcast signal when buffer changed.+  sourceBuffer `after` bufferChanged $+     writeTChanIO broadcastChannel BufferChanged ++  return buffer++-- | Parse "irc:[//[user@][server[:port]][/]][#channel]".+ircParseInfo :: String -> (Nick, Server, Port, Channel)+ircParseInfo str = +    if null matchTextList+       then (defaultNick, defaultServer, defaultPort, defaultChannel)+       else +           let (_ : (nickStr, _) : (serverStr, _) : (portStr, _) : (channelStr, _) : _) = elems $ head matchTextList+               nick = if null nickStr then defaultNick else init nickStr+               server = if null serverStr then defaultServer else serverStr+               port = if null portStr then defaultPort else read $ tail portStr :: Int+               channel = (\x -> case x of+                                 ('/':c) -> c +                                 _ -> x+                         ) $ if null channelStr then defaultChannel else channelStr+           in (nick, server, port, channel)+    where matchTextList =+              matchAllText +                  (makeRegex ("irc://([^<> \t\n'@:]+@)*([a-zA-Z.]+)*(:[0-9]+)*(/*[$#+!].[^ \t\n,]+)*" :: String) :: Regex) +                  str+          ++-- | Receive private message.+ircBufferReceivePrivate :: IrcBuffer -> NickName -> CommandArg -> IO ()+ircBufferReceivePrivate buffer@(IrcBuffer {ircBufferClient           = client+                                          ,ircBufferPageId           = pageId+                                          ,ircBufferSelfColorTag     = selfColorTag+                                          ,ircBufferOtherColorTag    = otherColorTag+                                          ,ircBufferActionColorTag   = actionColorTag+                                          ,ircBufferNick = mynick}) +                        nick content = do+  -- Format private message.+  let ((msg, msgHeadLen), isAction) = +        if B.pack "\SOHACTION " `B.isPrefixOf` content +               && B.pack "\SOH" `B.isSuffixOf` content+           then +               let prefixLen  = B.length (B.pack "\SOHACTION ")+                   suffixLen  = B.length (B.pack "\SOH")+                   takeLen    = B.length content - prefixLen - suffixLen+                   newContent = B.take takeLen $ B.drop prefixLen content+               in (ircBufferIndentMessage newContent (B.concat ["* ", nick, " "]), True)+           else +               (ircBufferIndentMessage content (B.concat ["<", nick, "> "]), False)++  -- Get color with the type of private message.+  mynickname <- readTVarIO mynick+  let messageColor +          -- Use selfColorTag when it's self message.+          | B.unpack nick == mynickname+              = selfColorTag+          -- User actionColorTag when print action message.+          | isAction +              = actionColorTag+          -- Otherwise use otherColorTag.+          | otherwise +              = otherColorTag++  -- Insert private message.+  ircBufferReceiveMsg buffer msg msgHeadLen messageColor++  -- Notify user when some call. +  let myNickName = B.pack mynickname+  unless (nick == myNickName) $ +    when (B.isInfixOf myNickName msg) $+      mkDaemonSignal client +                     ShowTooltip +                     (ShowTooltipArgs (init_ (UTF8.toString msg)) Nothing 8000 Nothing Nothing False (Just pageId))++-- | Receive quit message.+ircBufferReceiveQuit :: IrcBuffer -> NickName -> UserName -> HostName -> B.ByteString -> IO ()+ircBufferReceiveQuit buffer@(IrcBuffer {ircBufferNickSet = nickSet+                                       ,ircBufferQuitColorTag = quitColorTag}) +                     nick user host reason = do+  -- Quit nick map.+  set <- readTVarIO nickSet+  case maybeFindMin set (== nick) of+    Just _ -> do+      -- Remove from set.+      modifyTVarIO nickSet $ \ set ->+          S.delete nick set++      -- Format quit message.+      let adjustMsg = B.pack "*** "+          content   = B.concat [nick, " (", user, "@", host, ") has quit: ", reason]+          (msg, msgHeadLen) = ircBufferIndentMessage content adjustMsg+      +      -- Insert quit message.+      ircBufferReceiveMsg buffer msg msgHeadLen quitColorTag+    Nothing -> return ()++-- | Receive part message.+ircBufferReceivePart :: IrcBuffer -> NickName -> UserName -> HostName -> B.ByteString -> IO ()+ircBufferReceivePart buffer@(IrcBuffer {ircBufferNickSet        = nickSet+                                       ,ircBufferPartColorTag   = partColorTag}) +                     nick user host reason = do+  -- Remove from set.+  modifyTVarIO nickSet $ \ set ->+      S.delete nick set++  -- Format part message.+  let adjustMsg = B.pack "*** "+      content   = B.concat [nick, " (", user, "@", host, ") has part: ", reason]+      (msg, msgHeadLen) = ircBufferIndentMessage content adjustMsg+  +  -- Insert part message.+  ircBufferReceiveMsg buffer msg msgHeadLen partColorTag++-- | Receive topic replay message.+ircBufferReceiveNames :: IrcBuffer -> B.ByteString -> IO ()+ircBufferReceiveNames buffer nicks = +  -- Add nick to color map.+  forM_ (B.words nicks) $ \nick -> +    ircBufferAddNick buffer nick++-- | Receive topic replay message.+ircBufferReceiveChannelUrl :: IrcBuffer -> B.ByteString -> IO ()+ircBufferReceiveChannelUrl buffer@(IrcBuffer {ircBufferChannel          = channel+                                             ,ircBufferServerColorTag   = serverColorTag})+                           url = do+  -- Format channel url message.+  let adjustMsg = B.pack "*** "+      content   = B.concat [B.pack channel, " URL: ", url]+      (msg, msgHeadLen) = ircBufferIndentMessage content adjustMsg+      +  -- Insert channel url message.+  ircBufferReceiveMsg buffer msg msgHeadLen serverColorTag++-- | Receive topic replay message.+ircBufferReceiveTopicReply :: IrcBuffer -> CommandArg -> IO ()+ircBufferReceiveTopicReply buffer@(IrcBuffer {ircBufferChannel          = channel+                                             ,ircBufferServerColorTag   = serverColorTag})+                           message = do+  -- Format topic replay message.+  let adjustMsg = B.pack "*** "+      content   = B.concat ["Topic for ", B.pack channel, ": ", message]+      (msg, msgHeadLen) = ircBufferIndentMessage content adjustMsg+      +  -- Insert topic replay message.+  ircBufferReceiveMsg buffer msg msgHeadLen serverColorTag++-- | Receive topic replay message.+ircBufferReceiveTopicWhoTime :: IrcBuffer -> NickName -> Integer -> IO ()+ircBufferReceiveTopicWhoTime buffer@(IrcBuffer {ircBufferChannel        = channel+                                               ,ircBufferServerColorTag = serverColorTag})+                                nick seconds = do+  -- Format topic who time message.+  time <- getSecondsTimeStamp seconds "%H:%M:%S %Y/%m/%d"+  let adjustMsg = B.pack "*** "+      content   = B.concat [B.pack channel, ": topic set by ", nick, ", ", B.pack time]+      (msg, msgHeadLen) = ircBufferIndentMessage content adjustMsg+      +  -- Insert topic who time message.+  ircBufferReceiveMsg buffer msg msgHeadLen serverColorTag++-- | Receive join message.+ircBufferReceiveJoin :: IrcBuffer -> NickName -> UserName -> HostName -> IO ()+ircBufferReceiveJoin buffer@(IrcBuffer {ircBufferChannel        = channel+                                       ,ircBufferJoinColorTag   = joinColorTag+                                       ,ircBufferNick           = mynick}) +                        nick user host = do+  nickname <- readTVarIO mynick+  -- Don't print self join message.+  when (B.unpack nick /= nickname) $ do+    -- Add nick to set.+    ircBufferAddNick buffer nick++    -- Format join message.+    let adjustMsg = B.pack "*** " +        content   = B.concat [nick, " (", user, "@", host, ") has joined channel ", B.pack channel]+        (msg, msgHeadLen) = ircBufferIndentMessage content adjustMsg ++    -- Insert join message.+    ircBufferReceiveMsg buffer msg msgHeadLen joinColorTag+  +-- | Receive irc message.+ircBufferReceiveMsg :: IrcBuffer -> B.ByteString -> Int -> TextTag -> IO ()+ircBufferReceiveMsg IrcBuffer {ircBufferBuffer       = buffer+                              ,ircBufferInsertMark   = insertMark+                              ,ircBufferPromptMark   = promptMark+                              ,ircBufferEditableTag  = tag+                              ,ircBufferMessageTag   = messageTag+                              ,ircBufferTimeStamp    = stamp+                              ,ircBufferNickColorMap = nickColorMap+                              ,ircBufferUrlColorTag  = urlColorTag+                              ,ircBufferSmilePixbufs = smilePixbufs+                              } +                    message msgHeadLen colorTag = do+  -- Make editable tag can edit temporary for insert irc message.+  set tag [textTagEditable := True]++  -- Update time stamp before insert message.+  insertIter<- textBufferGetIterAtMark buffer insertMark+  line      <- textIterGetLine insertIter+  timeStamp <- getTimeStamp "[%H:%M:%S]"+  color <- get colorTag textTagForegroundGdk+  modifyTVarIO stamp $ \s -> +      M.insert line (timeStamp, color) s++  -- Create new mark to save insert iter position.+  -- To apply color tag after insert message.+  saveMark <- textBufferCreateMark buffer Nothing insertIter True++  -- Filter smile string from message.+  (msg, smileIndex) <- smileMessage message smilePixbufs++  -- Insert irc message before insertMark.+  textBufferInsertByteString buffer insertIter msg++  -- Apply base color tag.+  saveIter   <- textBufferGetIterAtMark buffer saveMark+  insertIter <- textBufferGetIterAtMark buffer insertMark+  textBufferApplyTag buffer colorTag saveIter insertIter++  -- Apply nick color tag.+  colorMap <- readTVarIO nickColorMap+  unless (null $ map fst $ M.toList colorMap) $ +    -- Regex "[^<> \t\n\'@,.:]+" works fine,+    -- don't build regex match all nickname, +    -- too big regex will make matchAllText *failed*.+    forM_ (matchAllText (makeRegex (B.pack "[^<> \t\n\'@,.:]+") :: Regex) msg)+        $ \ x -> do+          let ((word, (matchOffset, matchLength)) : _) = elems x+          case findMinMatch colorMap (\ nickName _ -> nickName == word) of+            Just (_, colorTag) -> do+                  matchStartIter <- textIterCopy saveIter+                  matchEndIter   <- textIterCopy saveIter+                  textIterForwardChars matchStartIter matchOffset+                  textIterForwardChars matchEndIter (matchOffset + matchLength)+                  textBufferApplyTag buffer colorTag matchStartIter matchEndIter+            Nothing -> return ()++  -- Apply URL color tag.+  forM_ (matchAllText (makeRegex (B.pack "[^]\\ \t\n`\\[\"^]+") :: Regex) msg)+      $ \ x -> do+        let ((word, (matchOffset, matchLength)) : _) = elems x+        parseURI (UTF8.toString word) ?>= \ uri -> +          when (isJust $ uriAuthority uri) $ do +            matchStartIter <- textIterCopy saveIter+            matchEndIter   <- textIterCopy saveIter+            textIterForwardChars matchStartIter matchOffset+            textIterForwardChars matchEndIter (matchOffset + matchLength)+            textBufferApplyTag buffer urlColorTag matchStartIter matchEndIter++  -- Insert smile pixbuf.+  forM_ smileIndex $ \ (offset, pixbuf) -> do+    iter <- textBufferGetIterAtMark buffer saveMark+    textIterForwardChars iter offset+    textBufferInsertPixbuf buffer iter pixbuf++  -- We should apply message tag after all INSERT action.+  -- Otherwise will get rang bound.+  msgStartIter <- textBufferGetIterAtMark buffer saveMark+  msgEndIter   <- textBufferGetIterAtMark buffer insertMark+  textIterForwardChars msgStartIter msgHeadLen -- skip message head (e.g. nick name)+  textIterBackwardChar msgEndIter              -- skip '\n' at last+  textBufferApplyTag buffer messageTag msgStartIter msgEndIter++  -- Apply editable tag to new rang (from start to insertMark).+  startIter <- textBufferGetStartIter buffer+  endIter   <- textBufferGetIterAtMark buffer promptMark+  textBufferApplyTag buffer tag startIter endIter++  -- Make irc message read-only again.+  set tag [textTagEditable := False]++-- | Add nick to nick set.+ircBufferAddNick :: IrcBuffer -> NickName -> IO ()+ircBufferAddNick buffer@(IrcBuffer {ircBufferNickSet = nickSet})+                 nick = do+    -- Add nick to list.+    set <- readTVarIO nickSet+    case maybeFindMin set (== nick) of+      Just _  -> +          -- Debug.+          -- putStrLn $ "Nick " ++ B.unpack nick ++ " already in nick set."+          return ()+      Nothing -> +        -- Debug.+        -- putStrLn $ "Nick " ++ B.unpack nick ++ " added to nick set."+        modifyTVarIO nickSet $ \ set -> +            S.insert nick set++    -- Update nick color.+    ircBufferUpdateNickColor buffer nick++-- | Update nick color to  map.+ircBufferUpdateNickColor :: IrcBuffer -> NickName -> IO ()+ircBufferUpdateNickColor (IrcBuffer {ircBufferBuffer       = buffer+                                    ,ircBufferNickColorMap = nickColorMap})+                         nick = do+  colorMap <- readTVarIO nickColorMap+  case findMinMatch colorMap (\ nickName _ -> nickName == nick) of+    Just _  -> +      -- Debug+      -- putStrLn $ "Have build color for nick : " ++ B.unpack nick+      return ()+    Nothing -> do+      -- Get color nick.+      let color = nickColorToColor $ nickColor nick++      -- Create color tag.+      textTag <- textTagNew Nothing+      set textTag [textTagForegroundGdk := color+                  ,textTagWeight        := fromEnum WeightBold]++      -- Add color tag to table.+      tagTable <- textBufferGetTagTable buffer+      textTagTableAdd tagTable textTag++      -- Update color map.+      modifyTVarIO nickColorMap $ \map ->+          M.insert nick textTag map+      +-- | Create color tag.+ircBufferCreateColorTag :: TextBufferClass buffer => buffer -> Color -> IO TextTag+ircBufferCreateColorTag buffer color = do+  tagTable <- textBufferGetTagTable buffer+  colorTag <- textTagNew Nothing+  set colorTag [textTagForegroundGdk := color]+  textTagTableAdd tagTable colorTag+  return colorTag++-- | Insert prompt string.+ircBufferInsertPromptStr :: TextBufferClass buffer => buffer -> IO ()+ircBufferInsertPromptStr buffer = +    textBufferSetText buffer promptStr++-- | Create insert mark.+ircBufferCreateInsertMark :: TextBufferClass buffer => buffer -> IO TextMark+ircBufferCreateInsertMark buffer = do+  textIter <- textBufferGetStartIter buffer+  textBufferCreateMark buffer Nothing textIter False++-- | Create prompt mark.+ircBufferCreatePromptMark :: TextBufferClass buffer => buffer -> IO TextMark+ircBufferCreatePromptMark buffer = do+  textIter <- textBufferGetIterAtOffset buffer (length promptStr)+  textBufferCreateMark buffer Nothing textIter True+          +-- | Indent message.+ircBufferIndentMessage :: B.ByteString -> B.ByteString -> (B.ByteString, Int)+ircBufferIndentMessage content adjustMsg = (concatMsg msgLines, B.length adjustMsg)+  where indentMsg = B.replicate (B.length adjustMsg) ' '+        msgLines  = map B.unwords $ wrapLine (wrapColumn - B.length adjustMsg) (splitWords content)+        concatMsg []     = B.concat [adjustMsg, "\n"]+        concatMsg [x]    = B.concat [adjustMsg, x, "\n"]+        concatMsg (x:xs) = B.concat [B.concat [adjustMsg, x, "\n"]+                                    ,B.concat $ map (\ xx -> B.concat [indentMsg, xx, "\n"]) xs]+
+ Manatee/Extension/IrcClient/IrcView.hs view
@@ -0,0 +1,592 @@+-- Author:     Andy Stewart <lazycat.manatee@gmail.com>+-- Maintainer: Andy Stewart <lazycat.manatee@gmail.com>+-- +-- Copyright (C) 2010 Andy Stewart, all rights reserved.+-- +-- This program is free software: you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation, either version 3 of the License, or+-- any later version.+-- +-- This program is distributed in the hope that it will be useful,+-- but WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+-- GNU General Public License for more details.+-- +-- You should have received a copy of the GNU General Public License+-- along with this program.  If not, see <http://www.gnu.org/licenses/>.++{-# LANGUAGE ExistentialQuantification, RankNTypes, DeriveDataTypeable, ScopedTypeVariables #-}+{-# LANGUAGE OverloadedStrings #-}+module Manatee.Extension.IrcClient.IrcView where++import Control.Applicative+import Control.Concurrent.STM+import Control.Monad+import Data.Map (Map)+import Data.ByteString (ByteString)+import Data.Text.Lazy (Text)+import Data.Typeable+import Graphics.UI.Gtk hiding (Statusbar, statusbarNew, get, Language)+import Graphics.UI.Gtk.Gdk.SerializedEvent+import Graphics.UI.Gtk.SourceView+import Language.Translate.Google+import Manatee.Core.DBus+import Manatee.Core.PageView+import Manatee.Core.Types+import Manatee.Extension.IrcClient.DBus+import Manatee.Extension.IrcClient.HighlightNick+import Manatee.Extension.IrcClient.IrcBuffer+import Manatee.Extension.IrcClient.Types+import Manatee.Toolkit.General.Basic+import Manatee.Toolkit.General.ByteString+import Manatee.Toolkit.General.Map+import Manatee.Toolkit.General.Maybe+import Manatee.Toolkit.General.Process+import Manatee.Toolkit.General.STM+import Manatee.Toolkit.General.String+import Manatee.Toolkit.Gtk.Concurrent+import Manatee.Toolkit.Gtk.Gtk+import Manatee.Toolkit.Gtk.Multiline+import Manatee.Toolkit.Gtk.ScrolledWindow+import Network.FastIRC.Messages+import Text.Morse++import qualified Data.ByteString.Char8 as B+import qualified Data.Map as M+import qualified Data.Set as S+import qualified Data.ByteString.UTF8 as UTF8++data IrcView =+    IrcView {ircViewPlugId            :: TVar PagePlugId+            ,ircViewScrolledWindow    :: ScrolledWindow+            ,ircViewView              :: SourceView+            ,ircViewBuffer            :: IrcBuffer+            ,ircViewBroadcastChannel  :: ViewChannel IrcBufferSignal+            }+    deriving Typeable++instance PageBuffer IrcBuffer where+    pageBufferGetName           = return . ircBufferChannel+    pageBufferSetName _ _       = return ()+    pageBufferClient            = ircBufferClient+    pageBufferCreateView a pId  = PageViewWrap <$> ircViewNew a pId+    pageBufferMode              = ircBufferMode++instance PageView IrcView where+    pageViewBuffer              = PageBufferWrap . ircViewBuffer+    pageViewPlugId              = ircViewPlugId+    pageViewFocus               = widgetGrabFocus . ircViewView+    pageViewCut                 = ircViewCut+    pageViewCopy                = ircViewCopy+    pageViewPaste               = ircViewPaste+    pageViewScrolledWindow      = ircViewScrolledWindow+    pageViewHandleKeyAction     = ircViewHandleKeyAction+    pageViewScrollToTop         = ircViewScrollToTop+    pageViewScrollToBottom      = ircViewScrollToBottom+    pageViewScrollVerticalPage  = ircViewScrollVerticalPage+    pageViewScrollVerticalStep  = ircViewScrollVerticalStep++-- | Create new irc view.+ircViewNew :: IrcBuffer -> PagePlugId -> IO IrcView+ircViewNew sb plugId = do+  -- Create plug id.+  pId <- newTVarIO plugId++  -- Create UI frame.+  scrolledWindow <- scrolledWindowNew_++  -- Create source view.+  ircView <- sourceViewNewWithBuffer (ircBufferBuffer sb)+  scrolledWindow `containerAdd` ircView+  forM_ [StateNormal, StateActive, StatePrelight, StateSelected, StateInsensitive] +    $ \state -> widgetModifyBg ircView state (nickColorToColor backgroundColor)++  -- Broadcast channel.+  channel <- createViewChannel (ircBufferBroadcastChannel sb) ircView++  let sv = IrcView pId scrolledWindow ircView sb channel++  -- Customize setup.+  sourceViewSetHighlightCurrentLine ircView True      -- highlight current line.+  sourceViewSetInsertSpacesInsteadOfTabs ircView True -- use space instead tabs+  sourceViewSetShowLineNumbers ircView showLineNumber -- show line number+  textViewSetCursorVisible ircView True               -- make cursor visible+  textViewSetWrapMode ircView WrapWord                -- auto wrap text++  -- Set fixed-width font, otherwise wrap mode can't work.+  fontDescr <- fontDescriptionFromString "Monospace"+  widgetModifyFont ircView (Just fontDescr)++  -- Update time stamp at right.+  gutter <- sourceViewGetGutter ircView timeStampPosition+  cell   <- cellRendererTextNew+  sourceGutterInsert gutter cell 0++  -- Set gutter data.+  sourceGutterSetCellDataFunc gutter cell $ \ c l _ -> do+         -- Display time stamp.+         timeStampMap <- readTVarIO $ ircBufferTimeStamp sb+         let (timeStamp, timeColor) = +                 case findMinMatch timeStampMap (\ line _ -> line == l) of+                   Just x  -> snd x+                   Nothing -> (defaultTimeStamp, Color 0 0 0)+         set (castToCellRendererText c) [cellText := timeStamp]+         set (castToCellRendererText c) [cellTextForegroundColor := timeColor]++  -- Set gutter size.+  sourceGutterSetCellSizeFunc gutter cell $ \ c -> +      -- -1 mean cell renderer will adjust width with chars dynamically.+      set (castToCellRendererText c) [cellTextWidthChars := (-1)]++  -- Read channel.+  ircViewListenChannel sv++  return sv++-- | Listen broadcast channel for draw view synchronous.+ircViewListenChannel :: IrcView -> IO ()+ircViewListenChannel view = +  listenViewChannel (ircViewBroadcastChannel view) $ \ signal -> +      case signal of+        SwitchTranslateLanguage -> do+          -- Update language status+          lang <- readTVarIO $ ircBufferTranslateLanguage $ ircViewBuffer view+          pageViewUpdateInfoStatus view "Translate" ("Translate to (" ++ show lang ++ ")")+        BufferChanged -> do+          -- Scroll screen if prompt mark at left of insert mark.+          -- Otherwise don't screen, because user screen download to read old messages.+          let buffer = ircViewBuffer view+              textBuffer = ircBufferBuffer buffer+              ircView = ircViewView view+          readTVarIO (ircBufferScrollMark buffer)+              >?>= \ mark -> do+                  iter   <- textBufferGetIterAtMark textBuffer mark+                  (y, _) <- textViewGetLineYrange ircView iter+                  (Rectangle _ vy _ vh) <- textViewGetVisibleRect ircView+                  when (y >= vy + vh) $ +                       textViewScrollMarkOnscreen ircView mark++-- | Swtich translate language.+ircViewSwitchTranslateLanguage :: IrcView -> IO ()+ircViewSwitchTranslateLanguage IrcView {ircViewBuffer           = buffer+                                       ,ircViewBroadcastChannel = channel} = do+  modifyTVarIO (ircBufferTranslateLanguage buffer) +      $ \lang -> if lang == targetLanguage+                    then sourceLanguage+                    else targetLanguage+  writeTChanIO (viewChannel channel) SwitchTranslateLanguage++-- | Handle key action.+ircViewHandleKeyAction :: IrcView -> Text -> SerializedEvent -> IO ()+ircViewHandleKeyAction view keystoke sEvent = +  case M.lookup keystoke ircViewKeymap of+    -- Execute action when found in keymap.+    Just action -> action view+    -- Otherwise propagate event.+    Nothing -> widgetPropagateEvent (ircViewView view) sEvent ++-- | Begin.+ircViewScrollToTop :: IrcView -> IO ()+ircViewScrollToTop a = do+  textViewBegin (ircViewView a) (ircViewScrolledWindow a)+  ircViewApplySelectionMark a++-- | End.+ircViewScrollToBottom :: IrcView -> IO ()+ircViewScrollToBottom a = do+  textViewEnd (ircViewView a) (ircViewScrolledWindow a)+  ircViewApplySelectionMark a++-- | Scroll page vertically.+ircViewScrollVerticalPage :: Bool -> IrcView -> IO ()+ircViewScrollVerticalPage isDown a = do+  let sw = ircViewScrolledWindow a+      tv = ircViewView a+  pageInc <- (<=<) adjustmentGetPageIncrement scrolledWindowGetVAdjustment sw+  textViewScrollVertical tv sw (if isDown then pageInc else (- pageInc))+  ircViewApplySelectionMark a++-- | Scroll step vertically.+ircViewScrollVerticalStep :: Bool -> IrcView -> IO ()+ircViewScrollVerticalStep isDown a = do+  let sw = ircViewScrolledWindow a+      tv = ircViewView a+  ti <- textViewGetTextIter tv+  (_, lineHeight) <- textViewGetLineYrange tv ti+  let stepInc = integralToDouble lineHeight+  textViewScrollVertical tv sw (if isDown then stepInc else (- stepInc))+  ircViewApplySelectionMark a++-- | Send morse code.+ircViewSendMorse :: IrcView -> IO ()+ircViewSendMorse view@(IrcView {ircViewBuffer = buffer+                               ,ircViewView   = vView}) = do+  -- Scroll mark on screen visible area.+  let textBuffer = ircBufferBuffer buffer+      promptMark = ircBufferPromptMark buffer+  textViewScrollMarkOnscreen vView promptMark++  -- Get input string.+  startIter <- textBufferGetIterAtMark textBuffer promptMark+  endIter   <- textBufferGetEndIter textBuffer+  text      <- textBufferGetText textBuffer startIter endIter True++  -- Clean input.+  ircViewCleanInput view ++  if isBlankString text+     -- Avoid send blank string, server will ignore blank message.+     then pageViewUpdateOutputStatus view "Ignored blank ..." Nothing+     -- Otherwise send message to server.+     else ircViewSend view (UTF8.fromString $ encodeMorse text)++-- | Send irc message.+ircViewSendMessage :: Bool -> IrcView -> IO ()+ircViewSendMessage isTranslate+                   view@(IrcView {ircViewBuffer = buffer+                                 ,ircViewView   = vView}) = do+  -- Scroll mark on screen visible area.+  let promptMark = ircBufferPromptMark buffer+  textViewScrollMarkOnscreen vView promptMark++  -- Get input string.+  text <- ircViewGetInput view++  -- Clean input.+  ircViewCleanInput view++  if isBlankByteString text+     -- Avoid send blank string, server will ignore blank message.+     then pageViewUpdateOutputStatus view "Ignored blank ..." Nothing+     -- Otherwise send message to server.+     else +       if isTranslate +          -- Try get translation.+          then +            forkGuiIO_ (do+                         pageViewUpdateOutputStatus view "Translation ..." Nothing+                         lang <- readTVarIO $ ircBufferTranslateLanguage buffer+                         translate text Nothing lang)+                       $ \result -> +                           case result of+                             -- Send original message if translate failed.+                             Left _ -> do+                               pageViewUpdateOutputStatus view "Get translation failed, send original message." Nothing+                               ircViewSend view text+                             -- Otherwise send translation.+                             Right translation -> do+                                 pageViewUpdateOutputStatus view "Translation ... completed." Nothing+                                 ircViewSend view translation+          -- Send original message.+          else ircViewSend view text++-- | Select all.+ircViewSelectAll :: IrcView -> IO ()+ircViewSelectAll = textViewSelectAll . ircViewView++-- | Wrap delete action.+ircViewWrapDeleteAction :: IrcView -> IO Bool -> IO ()+ircViewWrapDeleteAction view action =+  unlessM action $ +    pageViewUpdateOutputStatus view "Can't delete uneditable area." Nothing++-- | Delete lines.+ircViewDelLines :: IrcView -> IO ()+ircViewDelLines view =+  ircViewWrapDeleteAction view (textViewDelLines (ircViewView view))++-- | Delete.+ircViewDelete :: IrcView -> IO ()+ircViewDelete view = +  textViewDelete (ircViewView view) True True >> return ()++-- | Delete forward char.+ircViewDeleteForwardChar :: IrcView -> IO ()+ircViewDeleteForwardChar view = +  ircViewWrapDeleteAction view (textViewDeleteForwardChar (ircViewView view) True)++-- | Backward char.+ircViewDeleteBackwardChar :: IrcView -> IO ()+ircViewDeleteBackwardChar view = +  ircViewWrapDeleteAction view (textViewDeleteBackwardChar (ircViewView view) True)++-- | Forward word.+ircViewDeleteForwardWord :: IrcView -> IO ()+ircViewDeleteForwardWord view = +  ircViewWrapDeleteAction view (textViewDeleteForwardWord (ircViewView view) True)++-- | Backward word.+ircViewDeleteBackwardWord :: IrcView -> IO ()+ircViewDeleteBackwardWord view = +  ircViewWrapDeleteAction view (textViewDeleteBackwardWord (ircViewView view) True)++-- | Delete to line end.+ircViewDeleteToLineEnd :: IrcView -> IO ()+ircViewDeleteToLineEnd view = +  ircViewWrapDeleteAction view (textViewDeleteToLineEnd (ircViewView view) True)++-- | Delete to line start.+ircViewDeleteToLineStart :: IrcView -> IO ()+ircViewDeleteToLineStart view = +  ircViewWrapDeleteAction view (textViewDeleteToLineStart (ircViewView view) True)++-- | Cut.+ircViewCut :: IrcView -> IO Bool+ircViewCut view = do+  textViewCut $ ircViewView view+  return True++-- | Copy.+ircViewCopy :: IrcView -> IO Bool+ircViewCopy view = do+  textViewCopy $ ircViewView view+  return True++-- | Paste.+ircViewPaste :: IrcView -> IO Bool+ircViewPaste view = do+  textViewPaste $ ircViewView view+  return True++-- | Forward line.+ircViewForwardLine :: IrcView -> IO ()+ircViewForwardLine a = do+    textViewForwardLine (ircViewView a) (ircViewScrolledWindow a)+    ircViewApplySelectionMark a++-- | Backward line.+ircViewBackwardLine :: IrcView -> IO ()+ircViewBackwardLine a = do+    textViewBackwardLine (ircViewView a) (ircViewScrolledWindow a)+    ircViewApplySelectionMark a++-- | Forward char.+ircViewForwardChar :: IrcView -> IO ()+ircViewForwardChar a = do+    textViewForwardChar (ircViewView a) (ircViewScrolledWindow a)+    ircViewApplySelectionMark a++-- | Backward char.+ircViewBackwardChar :: IrcView -> IO ()+ircViewBackwardChar a = do+    textViewBackwardChar (ircViewView a) (ircViewScrolledWindow a)+    ircViewApplySelectionMark a++-- | Forward word.+ircViewForwardWord :: IrcView -> IO ()+ircViewForwardWord a = do+    textViewForwardWord (ircViewView a) (ircViewScrolledWindow a)+    ircViewApplySelectionMark a++-- | Backward word.+ircViewBackwardWord :: IrcView -> IO ()+ircViewBackwardWord a = do+    textViewBackwardWord (ircViewView a) (ircViewScrolledWindow a)+    ircViewApplySelectionMark a++-- | Smart home.+ircViewSmartHome :: IrcView -> IO ()+ircViewSmartHome a = do+    textViewSmartHome $ ircViewView a+    ircViewApplySelectionMark a++-- | Smart end.+ircViewSmartEnd :: IrcView -> IO ()+ircViewSmartEnd a = do+    textViewSmartEnd $ ircViewView a+    ircViewApplySelectionMark a++-- | Set selection mark.+ircViewToggleSelectionMark :: IrcView -> IO ()+ircViewToggleSelectionMark = textViewToggleSelectionMark . ircViewView ++-- | Exchange selection mark.+ircViewExchangeSelectionMark :: IrcView -> IO ()+ircViewExchangeSelectionMark = textViewExchangeSelectionMark . ircViewView ++-- | Show selection mark.+ircViewApplySelectionMark :: IrcView -> IO ()+ircViewApplySelectionMark = textViewApplySelectionMark . ircViewView++-- | Newline.+ircViewNewline :: IrcView -> IO ()  +ircViewNewline = textViewNewLine . ircViewView++-- | Get text buffer.+ircViewGetTextBuffer :: IrcView -> IO TextBuffer +ircViewGetTextBuffer = textViewGetBuffer . ircViewView++-- | Get source buffer.+ircViewGetSourceBuffer :: IrcView -> IO SourceBuffer+ircViewGetSourceBuffer sb = +    castToSourceBuffer <$> ircViewGetTextBuffer sb++-- | Move to prompt position.+ircViewMoveToPrompt :: IrcView -> IO ()+ircViewMoveToPrompt IrcView {ircViewBuffer = buffer+                            ,ircViewView   = view} = +  textViewPlaceCursorWithMark view (ircBufferPromptMark buffer)++-- | Clean input.+ircViewCleanInput :: IrcView -> IO ()+ircViewCleanInput IrcView {ircViewBuffer = buffer} = do+  -- Get iter range.+  let textBuffer = ircBufferBuffer buffer+      promptMark = ircBufferPromptMark buffer+  promptIter <- textBufferGetIterAtMark textBuffer promptMark +  endIter    <- textBufferGetEndIter textBuffer++  -- Clean input.+  textBufferDelete textBuffer promptIter endIter++-- | Get input message.+ircViewGetInput :: IrcView -> IO ByteString+ircViewGetInput IrcView {ircViewBuffer = buffer} = do+  -- Get iter range.+  let textBuffer = ircBufferBuffer buffer+      promptMark = ircBufferPromptMark buffer+  promptIter <- textBufferGetIterAtMark textBuffer promptMark +  endIter    <- textBufferGetEndIter textBuffer++  -- Return input message.+  textBufferGetByteString textBuffer promptIter endIter True++-- | Send message.+ircViewSend :: IrcView -> ByteString -> IO ()+ircViewSend view@(IrcView {ircViewBuffer = buffer}) +            message = do+    nick <- readTVarIO $ ircBufferNick buffer+    -- Push message to buffer.+    ircBufferReceivePrivate buffer (B.pack nick) message+    -- Send message to server.+    let msg = showCommand $ PrivMsgCmd (S.singleton (B.pack $ ircBufferChannel buffer)) message+    mkIrcDaemonSignal (pageViewClient view) SendMessage (SendMessageArgs (ircBufferServer buffer) msg)++-- | Open url around pointer.+ircViewOpenUrl :: IrcView -> IO ()+ircViewOpenUrl view@(IrcView {ircViewBuffer = buffer}) = +  textBufferGetTagText (ircBufferBuffer buffer) (ircBufferUrlColorTag buffer)+     >?>= \ url ->        +         mkDaemonSignal (pageViewClient view) NewTab (NewTabArgs "PageBrowser" url)++-- | Translate message around pointer.+ircViewTranslateMessage :: IrcView -> IO ()+ircViewTranslateMessage view@(IrcView {ircViewBuffer = +                                                 IrcBuffer {ircBufferBuffer             = buffer+                                                           ,ircBufferMessageTag         = messageTag+                                                           ,ircBufferTranslateLanguage  = language}}) = do+  -- Use end line iter to match messageTag content (skip message head).+  iter <- textBufferGetCurrentLineEndIter_ buffer+  textIterBackwardChar iter+  textBufferGetTagByteStringWithIter buffer iter messageTag+     >?>= \ text -> +         forkGuiIO_ (do+                      pageViewUpdateOutputStatus view "Fetch translation ..." Nothing+                      -- Translate reverse. :)+                      lang <- readTVarIO language+                      translate text Nothing (if lang == targetLanguage +                                              then sourceLanguage+                                              else targetLanguage))+                     $ \result -> +                         case result of+                           Left _ -> +                               pageViewUpdateOutputStatus view "Fetch translation ... failed." Nothing+                           Right translation -> do+                               pageViewUpdateOutputStatus view "Fetch translation ... completed." Nothing+                               -- Get rectangle around cursor.+                               point <- ircViewGetTooltipPoint view+                               -- Show translation with tooltip.+                               mkDaemonSignal (pageViewClient view)+                                              ShowTooltip +                                              (ShowTooltipArgs (UTF8.toString translation) +                                                               (Just point) 10000+                                                               Nothing (Just (Color 0 65535 0)) +                                                               True Nothing)++-- | Translate morse code.+ircViewTranslateMorse :: IrcView -> IO ()+ircViewTranslateMorse view@(IrcView {ircViewBuffer = +                                                 IrcBuffer {ircBufferBuffer     = buffer+                                                           ,ircBufferMessageTag = messageTag}}) = do+  -- Use end line iter to match messageTag content (skip message head).+  iter <- textBufferGetCurrentLineEndIter_ buffer +  textIterBackwardChar iter+  textBufferGetTagTextWithIter buffer iter messageTag+       >?>= \ text -> do+           -- Get rectangle around cursor.+           point <- ircViewGetTooltipPoint view+           mkDaemonSignal (pageViewClient view)+                          ShowTooltip+                          (ShowTooltipArgs (decodeMorse text)+                                           (Just point) 10000+                                           Nothing (Just (Color 65535 65535 0)) +                                           True Nothing)+                          +-- | Read message around pointer.+ircViewReadMessage :: IrcView -> IO ()+ircViewReadMessage view@(IrcView {ircViewBuffer = +                                      IrcBuffer {ircBufferBuffer     = buffer+                                                ,ircBufferMessageTag = messageTag}}) = do+  -- Use end line iter to match messageTag content (skip message head).+  iter <- textBufferGetCurrentLineEndIter_ buffer +  textIterBackwardChar iter+  textBufferGetTagTextWithIter buffer iter messageTag+       >?>= \ text -> ircViewReadText view text++-- | Read irc message.+ircViewReadText :: IrcView -> String -> IO ()+ircViewReadText view text = +  execute "festival" ("echo " ++ show text ++ " | %s --tts") True+          >?>= \ failedReason ->+              pageViewUpdateOutputStatus view failedReason Nothing++-- | Get tooltip coordinate.+ircViewGetTooltipPoint :: IrcView -> IO Point+ircViewGetTooltipPoint IrcView {ircViewView = textView} = do+  textIter <- textViewGetTextIter textView+  (Rectangle x y width height) <- textViewGetIterLocation textView textIter+  (wx, wy) <- textViewBufferToWindowCoords textView TextWindowWidget (x, y)+  return (wx + width, wy + height)+++-- | Keymap.+ircViewKeymap :: Map Text (IrcView -> IO ())+ircViewKeymap = +    M.fromList [("Return",   ircViewSendMessage False)+               ,("M-m",      ircViewSendMessage False)+               ,("C-m",      ircViewSendMessage True)+               ,("C-n",      ircViewSwitchTranslateLanguage)+               ,("C-N",      ircViewSendMorse)+               ,("M-M",      ircViewMoveToPrompt)+               ,("M-N",      ircViewCleanInput)+               ,("M-a",      ircViewSelectAll)+               ,("M-d",      ircViewDelLines)+               ,("M-D",      ircViewDelete)+               ,("M-,",      ircViewDeleteBackwardChar)+               ,("M-.",      ircViewDeleteForwardChar)+               ,("M-<",      ircViewDeleteBackwardWord)+               ,("M->",      ircViewDeleteForwardWord)+               ,("M-C-,",    ircViewDeleteToLineStart)+               ,("M-C-.",    ircViewDeleteToLineEnd)+               ,("M-j",      ircViewForwardLine)+               ,("M-k",      ircViewBackwardLine)+               ,("M-l",      ircViewForwardChar)+               ,("M-h",      ircViewBackwardChar)+               ,("Down",     ircViewForwardLine)+               ,("Up",       ircViewBackwardLine)+               ,("Right",    ircViewForwardChar)+               ,("Left",     ircViewBackwardChar)+               ,("S-Return", ircViewNewline)+               ,("M-L",      ircViewForwardWord)+               ,("M-H",      ircViewBackwardWord)+               ,("M-P-h",    ircViewSmartHome)+               ,("M-P-l",    ircViewSmartEnd)+               ,("C-c",      ircViewToggleSelectionMark)+               ,("C-C",      ircViewExchangeSelectionMark)+               ,("C-o",      ircViewOpenUrl)+               ,("C-j",      ircViewTranslateMessage)+               ,("C-J",      ircViewTranslateMorse)+               ,("C-k",      ircViewReadMessage)+               ]+
+ Manatee/Extension/IrcClient/PageMode.hs view
@@ -0,0 +1,32 @@+-- Author:     Andy Stewart <lazycat.manatee@gmail.com>+-- Maintainer: Andy Stewart <lazycat.manatee@gmail.com>+-- +-- Copyright (C) 2010 Andy Stewart, all rights reserved.+-- +-- This program is free software: you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation, either version 3 of the License, or+-- any later version.+-- +-- This program is distributed in the hope that it will be useful,+-- but WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+-- GNU General Public License for more details.+-- +-- You should have received a copy of the GNU General Public License+-- along with this program.  If not, see <http://www.gnu.org/licenses/>.++module Manatee.Extension.IrcClient.PageMode where++import Manatee.Core.Types++import qualified Data.Map as M++-- | Irc+ircMode :: PageMode+ircMode =+  PageMode {pageModeName   = "Irc"+           ,pageModeRegexp = ""+           ,pageModeKeymap = M.empty+           ,pageModeLoad   = \_ -> return ()}+
+ Manatee/Extension/IrcClient/Smile.hs view
@@ -0,0 +1,119 @@+-- Author:     Andy Stewart <lazycat.manatee@gmail.com>+-- Maintainer: Andy Stewart <lazycat.manatee@gmail.com>+-- +-- Copyright (C) 2010 Andy Stewart, all rights reserved.+-- +-- This program is free software: you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation, either version 3 of the License, or+-- any later version.+-- +-- This program is distributed in the hope that it will be useful,+-- but WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+-- GNU General Public License for more details.+-- +-- You should have received a copy of the GNU General Public License+-- along with this program.  If not, see <http://www.gnu.org/licenses/>.++{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}+module Manatee.Extension.IrcClient.Smile where++import Control.Arrow+import Control.Monad+import Data.Array+import Data.ByteString (ByteString)+import Data.Map (Map)+import Graphics.UI.Gtk hiding (Statusbar, statusbarNew, get, Language)+import Manatee.Toolkit.General.String+import Manatee.Toolkit.General.Map+import Manatee.Toolkit.General.Maybe+import Paths_manatee_ircclient+import System.FilePath+import Text.Regex.Posix hiding (after)++import qualified Data.ByteString.UTF8 as UTF8+import qualified Data.Map as M++-- | The size of smile.+smileSize :: Int+smileSize = 16++-- | Replace smile string with pixbuf, and return insert offset of pixbuf. +smileMessage :: ByteString -> Map String Pixbuf -> IO (ByteString, [(Int, Pixbuf)])+smileMessage msg pixbufMap = do+    let -- Get UTF8 string, because insert offset use Unicode char width and not byte char.+        -- so we need convert ByteString to UTF8 string first.+        -- Otherwise we will get wrong insert offset when display UTF8 string (e.g. Chinese).+        msgString = UTF8.toString msg+        -- Get regexp matches.+        stringMatches = +          -- Filter blank match.+          filter (\ (word, _) -> not $ isBlankString word)+          -- Get match.+          $ map (\x -> +                     let (_ : (word, (matchOffset, matchLength)) : _) = elems x+                     in (word, (matchOffset, matchLength))) +                (matchAllText +                  (makeRegex ("\\s(x\\(|;\\)|:/|:'|:>|:x|:\\*|:z|:\\(|:D|:\\)|:o|:I|;p|:O|)" :: String) :: Regex) +                  msgString)          +        -- Smile pixbuf.+        smilePixbuf str = +          let (_, pixbuf) = maybeError+                            (findMinMatch pixbufMap (\ name _ -> name == str))+                            ("smileMessage : can't match smile " ++ str) +          in pixbuf+        -- Get insert offset.+        getInsertOffset [] _ _ = []+        getInsertOffset [(_, (offset, _))] deleteLen pixbufNum =+          [offset - deleteLen + pixbufNum]+        getInsertOffset ((_, (offset, length)) : xs) deleteLen pixbufNum = +          (offset - deleteLen + pixbufNum) : getInsertOffset xs (deleteLen + length) (pixbufNum + 1)+        -- Get new message.+        getNewMessage [] _ _ = ""+        getNewMessage [(_, (matchOffset, matchLen))] str deleteOffset = +            let (fstStr, sndStr) = splitAt (matchOffset - deleteOffset) str+                (_, restStr) = splitAt matchLen sndStr+            in fstStr ++ restStr+        getNewMessage ((_, (matchOffset, matchLen)) : xs) str deleteOffset = +            let (fstStr, sndStr) = splitAt (matchOffset - deleteOffset) str+                (_, restStr) = splitAt matchLen sndStr+            in fstStr ++ getNewMessage xs restStr (matchOffset + matchLen)+            +    if null stringMatches  +       -- Don't convert anything if no regexp match.+       then return (msg, [])+       else do+         let pixbufs    = map (\ (str, _) -> smilePixbuf str) stringMatches+             offsets    = getInsertOffset stringMatches 0 0+             newMessage = UTF8.fromString $ getNewMessage stringMatches msgString 0++         return (newMessage, zip offsets pixbufs)+    +-- | Create smile pixbufs.+createSmilePixbufs :: IO (Map String Pixbuf)+createSmilePixbufs = do+  dir <- getDataDir+  let imagePath imageName = dir </> (imageName ++ ".png")+      paths = map (second imagePath) +              [("x(", "angry")+              ,(":/", "confused")+              ,(":'", "crying")+              ,(":>", "embarrassed")+              ,(":x", "inlove")+              ,(":*", "kiss")+              ,(":z", "sleepy")+              ,(":(", "sad")+              ,(":D", "laugh")+              ,(":)", "smile")+              ,(":o", "surprised")+              ,(":I", "tired")+              ,(";p", "tongue")+              ,(":O", "whistling")+              ,(";)", "wink")]  +  pixbufs <- +    forM paths $ \ (smileStr, path) -> do+         pixbuf <- pixbufNewFromFileAtScale path smileSize smileSize True+         return (smileStr, pixbuf)+  return $ M.fromList pixbufs
+ Manatee/Extension/IrcClient/Types.hs view
@@ -0,0 +1,132 @@+-- Author:     Andy Stewart <lazycat.manatee@gmail.com>+-- Maintainer: Andy Stewart <lazycat.manatee@gmail.com>+-- +-- Copyright (C) 2010 Andy Stewart, all rights reserved.+-- +-- This program is free software: you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation, either version 3 of the License, or+-- any later version.+-- +-- This program is distributed in the hope that it will be useful,+-- but WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+-- GNU General Public License for more details.+-- +-- You should have received a copy of the GNU General Public License+-- along with this program.  If not, see <http://www.gnu.org/licenses/>.++{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE DeriveDataTypeable #-}+module Manatee.Extension.IrcClient.Types where++import Graphics.UI.Gtk hiding (Statusbar, statusbarNew, get, Language)+import Language.Translate.Google++import qualified Data.ByteString.Char8 as B++type Server     = String+type Channel    = String+type Port       = Int+type Nick       = String+type Password   = String++-- | Temporary user name for test.+tempUser :: B.ByteString+tempUser = "Irc client for Manatee ( http://www.flickr.com/photos/48809572@N02/ )."++-- | Temporary real name for test.+tempRealname :: B.ByteString+tempRealname = "Andy Stewart"++-- | Default user nick.+defaultNick :: String+defaultNick = "manateeUser"++-- | Default server.+defaultServer :: String+defaultServer = "irc.freenode.net"++-- | Default port.+defaultPort :: Int+defaultPort = 6667++-- | Default channel+defaultChannel :: String+defaultChannel = "#haskell"++-- | Enable join message.+enableJoinMessage :: Bool+enableJoinMessage = True++-- | Enable quit message.+enableQuitMessage :: Bool+enableQuitMessage = True++-- | Target language to translate.+targetLanguage :: Language+targetLanguage = English++-- | Source language.+sourceLanguage :: Language+sourceLanguage = ChineseSimplified++-- | Show line number.+showLineNumber :: Bool+showLineNumber = False++-- | Time stamp position.+timeStampPosition :: TextWindowType+timeStampPosition = TextWindowLeft++-- | The prompt string.+promptStr :: String+promptStr = "> "++-- | The column limit to wrap irc message.+wrapColumn :: Int+wrapColumn = 100++-- | The default time stamp : [00:00:00]+defaultTimeStamp :: String+defaultTimeStamp = +    "          "++-- | Server message color.+serverMsgColor :: Color+serverMsgColor = Color 30000 30000 0++-- | Self message color.+selfMsgColor :: Color+selfMsgColor = Color 7710 37008 65535+-- selfMsgColor = Color 12850 52685 12850++-- | Other message color.+otherMsgColor :: Color+otherMsgColor = Color 0 0 0+-- otherMsgColor = Color 8738 35723 8738++-- | Join message color.+joinMsgColor :: Color+joinMsgColor = Color 12850 52685 12850 +-- joinMsgColor = Color 26985 26985 26985++-- | Quit message color.+quitMsgColor :: Color+quitMsgColor = Color 52685 14135 0+-- quitMsgColor = Color 26985 26985 26985++-- | Part message color.+partMsgColor :: Color+partMsgColor = Color 52685 14135 0+-- partMsgColor = Color 26985 26985 26985++-- | Action message color.+actionMsgColor :: Color+actionMsgColor = Color 41120 8224 61680+-- actionMsgColor = Color 48830 48830 48830++-- | Url color.+urlColor :: Color+urlColor = Color 38036 0 54227+
+ Setup.hs view
@@ -0,0 +1,18 @@+import Distribution.Simple+import Manatee.Core.Config+import Manatee.Core.Types+import Manatee.Extension.IrcClient.PageMode++import qualified Data.Map as M++main = defaultMainWithHooks +       simpleUserHooks {+         -- Update PageTypeRule after install successful.+         postInst = \ _ _ _ _ -> do+             (PageTypeRule rule) <- readConfig pageTypeRulePath (PageTypeRule M.empty)+             writeConfig pageTypeRulePath (PageTypeRule (M.insert "PageIrc" "manatee-ircclient" rule))+             -- Update PageModeRule.+             (PageModeRule modeRule) <- readConfig pageModeRulePath (PageModeRule M.empty)+             writeConfig pageModeRulePath (PageModeRule +                                                (M.insert "PageIrc" (Left $ pageModeName ircMode) modeRule))+       }
+ icons/angry.png view

binary file changed (absent → 670 bytes)

+ icons/confused.png view

binary file changed (absent → 689 bytes)

+ icons/crying.png view

binary file changed (absent → 760 bytes)

+ icons/embarrassed.png view

binary file changed (absent → 677 bytes)

+ icons/inlove.png view

binary file changed (absent → 756 bytes)

+ icons/kiss.png view

binary file changed (absent → 699 bytes)

+ icons/laugh.png view

binary file changed (absent → 726 bytes)

+ icons/sad.png view

binary file changed (absent → 648 bytes)

+ icons/sleepy.png view

binary file changed (absent → 625 bytes)

+ icons/smile.png view

binary file changed (absent → 655 bytes)

+ icons/surprised.png view

binary file changed (absent → 664 bytes)

+ icons/tired.png view

binary file changed (absent → 632 bytes)

+ icons/tongue.png view

binary file changed (absent → 702 bytes)

+ icons/whistling.png view

binary file changed (absent → 664 bytes)

+ icons/wink.png view

binary file changed (absent → 657 bytes)

+ manatee-ircclient.cabal view
@@ -0,0 +1,68 @@+name:			manatee-ircclient+version:		0.0.1+Cabal-Version:	>= 1.6+license:		GPL-3+license-file:	LICENSE+copyright:		(c) 2009 ~ 2010 Andy Stewart+synopsis:		IRC client extension for Manatee.+description:    manatee-ircclient is IRC client extension for Manatee (Haskell/Gtk+ Integrated Live Environment)+author:			Andy Stewart+maintainer:		Andy Stewart <lazycat.manatee@gmail.com>+stability:		provisional+category:		Manatee, IRC Client, IRC++tested-with:	GHC==6.12.3+build-type:		Custom++data-dir: icons+data-files: angry.png+            confused.png+            crying.png+            embarrassed.png+            inlove.png+            kiss.png+            sleepy.png+            sad.png+            laugh.png+            smile.png+            surprised.png+            tired.png+            tongue.png+            whistling.png+            wink.png++Source-Repository head+  type:         darcs+  location:     http://patch-tag.com/r/AndyStewart/manatee-ircclient+  +Library+     build-depends: base >= 4 && < 5, manatee-core >= 0.0.1, dbus-client >= 0.3 && < 0.4, stm >= 2.1.2.0,+                    containers >= 0.3.0.0, gtk-serialized-event >= 0.12.0, gtk >= 0.12.0, +                    text >= 0.7.1.0, bytestring >= 0.9.1.5,+                    dbus-core, template-haskell, gtksourceview2 >= 0.12.0, unix >= 2.4.0.0,+                    network, groom, fastirc >= 0.2.0, split >= 0.1.2, nano-md5 >= 0.1.2, filepath,+                    regex-posix >= 0.94.1, array >= 0.3.0.0, GoogleTranslate >= 0.0.3, utf8-string, mtl, Cabal, +                    MorseCode >= 0.0.4+     exposed-modules:+       Manatee.Extension.IrcClient+       Manatee.Extension.IrcClient.Types+       Manatee.Extension.IrcClient.DBus+       Manatee.Extension.IrcClient.Daemon+       Manatee.Extension.IrcClient.HighlightNick+       Manatee.Extension.IrcClient.IrcBuffer+       Manatee.Extension.IrcClient.IrcView+       Manatee.Extension.IrcClient.PageMode+       Manatee.Extension.IrcClient.Smile+     other-modules: Paths_manatee_ircclient+     extensions:+     ghc-options: -fwarn-unused-matches -fwarn-unused-binds -fwarn-unused-imports -fwarn-overlapping-patterns -fwarn-duplicate-exports -fwarn-unrecognised-pragmas -fwarn-hi-shadowing +     +Executable manatee-irc-daemon+     main-is: Daemon.hs++     ghc-options: -threaded ++Executable manatee-ircclient+     main-is: Main.hs++     ghc-options: -threaded