+
+
+
+
+
+
+
+
+
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 000000000..5e1c8e218
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,674 @@
+GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. {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:
+
+ {{project}} Copyright (C) {{year}} {{fullname}}
+ 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}.
diff --git a/_locales/de/messages.json b/_locales/de/messages.json
new file mode 100644
index 000000000..6b36759c5
--- /dev/null
+++ b/_locales/de/messages.json
@@ -0,0 +1,130 @@
+{
+ "extName": {
+ "message": "µBlock",
+ "description": "extension name."
+ },
+ "extShortDesc": {
+ "message": "Finally, an efficient blocker for Chromium-based browsers. Easy on CPU and memory.",
+ "description": "this will in chrome web store: must be 132 characters or less"
+ },
+ "3pPageName" : {
+ "message": "3rd-party filters",
+ "description": "appears as tab name in dashboard"
+ },
+ "1pPageName" : {
+ "message": "Your filters",
+ "description": "appears as tab name in dashboard."
+ },
+ "aboutPageName": {
+ "message": "Über",
+ "description": "appears as tab name in dashboard"
+ },
+
+
+ "3pListsOfBlockedHostsPrompt2" : {
+ "message": "{{ubiquitousBlacklistCount}} eindeutig blockierte Hostnamen aus:",
+ "description": "English: {{ubiquitousBlacklistCount}} distinct blocked hostnames from:"
+ },
+ "3pListsOfBlockedHostsPerListStats" : {
+ "message": "{{used}} benutzt aus {{total}}",
+ "description": "English: {{used}} used out of {{total}}"
+ },
+ "3pParseAllABPHideFiltersPrompt1" : {
+ "message": "Adblock+ Filter zum Verstecken von Elementen analysieren und anwenden.",
+ "description": "English: Parse and enforce Adblock+ element hiding filters."
+ },
+ "3pParseAllABPHideFiltersPrompt2" : {
+ "message": "{{abpHideFilterCount}} Filter zum Verstecken von Elementen genutzt.",
+ "description": "English: {{abpHideFilterCount}} element hiding filters used."
+ },
+ "3pParseAllABPHideFiltersInfo" : {
+ "message": "
Diese Option ermöglicht die Analyse und Anwendung von Adblock Plus-kompatiblen Filtern zum “Verstecken von Elementen” . Diese Filter sind in erster Linie kosmetischer Natur und dienen zum Verstecken von Elementen auf einer Webseite, die als optische Belästigung wahrgenommen werden und nicht von der Matrix oder normalen ABP-Filtern geblockt werden können.
Das Aktivieren dieser Option erhöht den Speicherbedarf von µBlock.
",
+ "description": "English: see English messages.json"
+ },
+ "3pListsOfBlockedHostsHeader" : {
+ "message": "Listen blockierter Hostnamen",
+ "description": "English: Lists of blocked hosts"
+ },
+ "3pApplyChanges" : {
+ "message": "Änderungen anwenden",
+ "description": "English: Apply changes"
+ },
+
+
+ "1pFormatHint" : {
+ "message": "Eine Regel pro Zeile. Eine Regel kann ein einfacher Hostname sein oder ein Adblock Plus-kompatibler Filter. Zeilen mit vorangestelltem ‘!’ werden ignoriert.",
+ "description": "English: One filter per line. A filter can be a plain hostname, or an Adblock Plus-compatible filter. Lines prefixed with ‘!’ will be ignored."
+ },
+ "1pImport" : {
+ "message": "Importieren und anfügen",
+ "description": "English: Import and append"
+ },
+ "1pExport" : {
+ "message": "Exportieren",
+ "description": "English: Export"
+ },
+ "1pApplyChanges" : {
+ "message": "Änderungen anwenden",
+ "description": "English: Apply changes"
+ },
+
+
+ "aboutChangelog" : {
+ "message": "Changelog",
+ "description": "English: Change log"
+ },
+ "aboutCode" : {
+ "message": "Quellcode (GPLv3)",
+ "description": "English: Source code (GPLv3)"
+ },
+ "aboutExtensionDataHeader" : {
+ "message": "Externe Ressourcen dieser Erweiterung",
+ "description": "English: Extension data"
+ },
+ "aboutAssetsUpdatePrompt" : {
+ "message": "Von µBlock benutzte externe Ressourcen können hier upgedatet werden, ohne auf eine neue Version dieser Erweiterung warten zu müssen. Diese Ressourcen werden bezogen vom Github Repository dieses Projekts.",
+ "description": "Short descriptive text of the update feature"
+ },
+ "aboutAssetsUpdateColPath" : {
+ "message": "Pfad",
+ "description": "Path column header"
+ },
+ "aboutAssetsUpdateColStatus" : {
+ "message": "Status",
+ "description": "Status column header"
+ },
+ "aboutAssetsUpdateGetListError" : {
+ "message": "Ein Fehler ist aufgetreten. Ist XHR blockiert für raw2.github.com?",
+ "description": "Successful outcome of clicking 'update' button"
+ },
+ "aboutAssetsUpdateStatusAdded" : {
+ "message": "Hinzufügen",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateStatusChanged" : {
+ "message": "Neue Version verfügbar",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateStatusUnchanged" : {
+ "message": "Up-to-date",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateStatusRemoved" : {
+ "message": "Entfernen",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateButton" : {
+ "message": "Update",
+ "description": "Update button"
+ },
+ "aboutAssetsUpdatingButton" : {
+ "message": "Updating...",
+ "description": "Updating..."
+ },
+
+
+ "dummy": {
+ "message": "This entry must be the last one",
+ "description": "so we dont need to deal with comma for last entry"
+ }
+}
diff --git a/_locales/en/messages.json b/_locales/en/messages.json
new file mode 100644
index 000000000..1bc6bdd9e
--- /dev/null
+++ b/_locales/en/messages.json
@@ -0,0 +1,130 @@
+{
+ "extName": {
+ "message": "µBlock",
+ "description": "extension name."
+ },
+ "extShortDesc": {
+ "message": "Finally, an efficient blocker for Chromium-based browsers. Easy on CPU and memory.",
+ "description": "this will be in the chrome web store: must be 132 characters or less"
+ },
+ "3pPageName" : {
+ "message": "3rd-party filters",
+ "description": "appears as tab name in dashboard."
+ },
+ "1pPageName" : {
+ "message": "Your filters",
+ "description": "appears as tab name in dashboard."
+ },
+ "aboutPageName": {
+ "message": "About",
+ "description": "appears as tab name in dashboard."
+ },
+
+
+ "3pListsOfBlockedHostsPrompt2" : {
+ "message": "{{ubiquitousBlacklistCount}} network filters from:",
+ "description": "English: {{ubiquitousBlacklistCount}} distinct blocked hostnames from:"
+ },
+ "3pListsOfBlockedHostsPerListStats" : {
+ "message": "{{used}} used out of {{total}}",
+ "description": "English: {{used}} used out of {{total}}"
+ },
+ "3pParseAllABPHideFiltersPrompt1" : {
+ "message": "Parse and enforce Adblock+ element hiding filters.",
+ "description": "English: Parse and enforce Adblock+ element hiding filters."
+ },
+ "3pParseAllABPHideFiltersPrompt2" : {
+ "message": "{{abpHideFilterCount}} element hiding filters used.",
+ "description": "English: {{abpHideFilterCount}} element hiding filters used."
+ },
+ "3pParseAllABPHideFiltersInfo" : {
+ "message": "
This option enables the parsing and enforcing of Adblock Plus-compatible “element hiding” filters. These filters are essentially cosmetic, they serve to hide elements in a web page which are deemed to be a visual nuisance, and which can't be blocked by the matrix- or ABP-filtering engines.
Enabling this feature increases µBlock's memory footprint.
",
+ "description": "English: see English messages.json"
+ },
+ "3pListsOfBlockedHostsHeader" : {
+ "message": "Lists of blocked hosts",
+ "description": "English: Lists of blocked hosts"
+ },
+ "3pApplyChanges" : {
+ "message": "Apply changes",
+ "description": "English: Apply changes"
+ },
+
+
+ "1pFormatHint" : {
+ "message": "One filter per line. A filter can be a plain hostname, or an Adblock Plus-compatible filter. Lines prefixed with ‘!’ will be ignored.",
+ "description": "English: One filter per line. A filter can be a plain hostname, or an Adblock Plus-compatible filter. Lines prefixed with ‘!’ will be ignored."
+ },
+ "1pImport" : {
+ "message": "Import and append",
+ "description": "English: Import and append"
+ },
+ "1pExport" : {
+ "message": "Export",
+ "description": "English: Export"
+ },
+ "1pApplyChanges" : {
+ "message": "Apply changes",
+ "description": "English: Apply changes"
+ },
+
+
+ "aboutChangelog" : {
+ "message": "Change log",
+ "description": "English: Change log"
+ },
+ "aboutCode" : {
+ "message": "Source code (GPLv3)",
+ "description": "English: Source code (GPLv3)"
+ },
+ "aboutExtensionDataHeader" : {
+ "message": "Extension data",
+ "description": "English: Extension data"
+ },
+ "aboutAssetsUpdatePrompt" : {
+ "message": "µBlock assets can be updated here without having to wait for the next release of the extension. These assets are pulled from the project's Github repository.",
+ "description": "Short descriptive text of the update feature"
+ },
+ "aboutAssetsUpdateColPath" : {
+ "message": "Path",
+ "description": "Path column header"
+ },
+ "aboutAssetsUpdateColStatus" : {
+ "message": "Status",
+ "description": "Status column header"
+ },
+ "aboutAssetsUpdateGetListError" : {
+ "message": "An error occurred. Is XHR blocked for raw2.github.com?",
+ "description": "Successful outcome of clicking 'update' button"
+ },
+ "aboutAssetsUpdateStatusAdded" : {
+ "message": "To add",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateStatusChanged" : {
+ "message": "New version available",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateStatusUnchanged" : {
+ "message": "Up to date",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateStatusRemoved" : {
+ "message": "To remove",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateButton" : {
+ "message": "Update",
+ "description": "Update button"
+ },
+ "aboutAssetsUpdatingButton" : {
+ "message": "Updating...",
+ "description": "Updating..."
+ },
+
+
+ "dummy": {
+ "message": "This entry must be the last one",
+ "description": "so we dont need to deal with comma for last entry"
+ }
+}
diff --git a/_locales/fr/messages.json b/_locales/fr/messages.json
new file mode 100644
index 000000000..456d002a6
--- /dev/null
+++ b/_locales/fr/messages.json
@@ -0,0 +1,130 @@
+{
+ "extName": {
+ "message": "µBlock",
+ "description": "extension name."
+ },
+ "extShortDesc": {
+ "message": "Finally, an efficient blocker for Chromium-based browsers. Easy on CPU and memory.",
+ "description": "this will in chrome web store: must be 132 characters or less"
+ },
+ "3pPageName" : {
+ "message": "Listes de filtres",
+ "description": "appears as tab name in dashboard"
+ },
+ "1pPageName" : {
+ "message": "Vos règles",
+ "description": "appears as tab name in dashboard."
+ },
+ "aboutPageName": {
+ "message": "À propos",
+ "description": "appears as tab name in dashboard"
+ },
+
+
+ "3pListsOfBlockedHostsPrompt2" : {
+ "message": "{{ubiquitousBlacklistCount}} hôtes actuellement bloqués :",
+ "description": "English: {{ubiquitousBlacklistCount}} distinct blocked hostnames from:"
+ },
+ "3pListsOfBlockedHostsPerListStats" : {
+ "message": "{{used}} utilisés sur un total de {{total}}",
+ "description": "English: {{used}} used out of {{total}}"
+ },
+ "3pParseAllABPHideFiltersPrompt1" : {
+ "message": "Utiliser en plus les règles Adblock Plus esthétiques",
+ "description": "English: Parse and enforce Adblock+ element hiding filters."
+ },
+ "3pParseAllABPHideFiltersPrompt2" : {
+ "message": "{{abpHideFilterCount}} règles Adblock Plus esthétiques utilisées",
+ "description": "English: {{abpHideFilterCount}} element hiding filters used."
+ },
+ "3pParseAllABPHideFiltersInfo" : {
+ "message": "
Cette option permet de prendre en charge les filtres AdblockPlus de type “element hiding”. Ces filtres ont principalement un impact visuel, servant à dissimuler des éléments nuisibles d'une page Web et qui ne sont blocables ni par la matrice, ni par le filtrage type Adblock Plus.
L'activation de cette fonctionnalité augmente l'empreinte mémoire de µBlock
",
+ "description": "English: see English messages.json"
+ },
+ "3pListsOfBlockedHostsHeader" : {
+ "message": "Listes d'hôtes à bloquer",
+ "description": "English: Lists of blocked hosts"
+ },
+ "3pApplyChanges" : {
+ "message": "Appliquer",
+ "description": "English: Apply changes"
+ },
+
+
+ "1pFormatHint" : {
+ "message": "Une règle par ligne. Une règle peut être un simple nom d'hôte, ou encore un filtre respectant la syntaxe des filtres Adblock Plus. Les lignes débutant par ‘!’ seront ignorées.",
+ "description": "English: One filter per line. A filter can be a plain hostname, or an Adblock Plus-compatible filter. Lines prefixed with ‘!’ will be ignored."
+ },
+ "1pImport" : {
+ "message": "Importer",
+ "description": "English: Import and append"
+ },
+ "1pExport" : {
+ "message": "Exporter",
+ "description": "English: Export"
+ },
+ "1pApplyChanges" : {
+ "message": "Appliquer",
+ "description": "English: Apply changes"
+ },
+
+
+ "aboutChangelog" : {
+ "message": "Journal des changements (en Anglais)",
+ "description": "English: Change log"
+ },
+ "aboutCode" : {
+ "message": "Code Source (Licence GPLv3, en Anglais)",
+ "description": "English: Source code (GPLv3)"
+ },
+ "aboutExtensionDataHeader" : {
+ "message": "Données de l'extension",
+ "description": "English: Extension data"
+ },
+ "aboutAssetsUpdatePrompt" : {
+ "message": "Les éléments dynamiques, comprenant entre autres listes d'hôtes à bloquer et recettes prédéfinies, peuvent être mis à jour ici sans avoir à attendre la prochaine version de µBlock. Le processus s'effectue à partir de la page du projet sur Github.",
+ "description": "Short descriptive text of the update feature"
+ },
+ "aboutAssetsUpdateColPath" : {
+ "message": "Élément dynamique",
+ "description": "Path column header"
+ },
+ "aboutAssetsUpdateColStatus" : {
+ "message": "État",
+ "description": "Status column header"
+ },
+ "aboutAssetsUpdateGetListError" : {
+ "message": "Une erreur est survenue. Veuillez vous assurer que les requêtes de type XHR ne soient pas bloquées pour raw2.github.com",
+ "description": "Successful outcome of clicking 'update' button"
+ },
+ "aboutAssetsUpdateStatusAdded" : {
+ "message": "À ajouter",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateStatusChanged" : {
+ "message": "Nouvelle version disponible",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateStatusUnchanged" : {
+ "message": "À jour",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateStatusRemoved" : {
+ "message": "À supprimer",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateButton" : {
+ "message": "Mettre à jour",
+ "description": "Update button"
+ },
+ "aboutAssetsUpdatingButton" : {
+ "message": "Mise à jour en cours...",
+ "description": "Updating..."
+ },
+
+
+ "dummy": {
+ "message": "This entry must be the last one",
+ "description": "so we dont need to deal with comma for last entry"
+ }
+}
diff --git a/_locales/ru/messages.json b/_locales/ru/messages.json
new file mode 100644
index 000000000..a6ef13076
--- /dev/null
+++ b/_locales/ru/messages.json
@@ -0,0 +1,130 @@
+{
+ "extName": {
+ "message": "µBlock",
+ "description": "название расширения"
+ },
+ "extShortDesc": {
+ "message": "Finally, an efficient blocker for Chromium-based browsers. Easy on CPU and memory.",
+ "description": "this will in chrome web store: must be 132 characters or less"
+ },
+ "3pPageName" : {
+ "message": "Third-party filters",
+ "description": "appears as tab name in dashboard"
+ },
+ "1pPageName" : {
+ "message": "Your filters",
+ "description": "appears as tab name in dashboard."
+ },
+ "aboutPageName": {
+ "message": "О расширении",
+ "description": "appears as tab name in dashboard."
+ },
+
+
+ "3pListsOfBlockedHostsPrompt2" : {
+ "message": "{{ubiquitousBlacklistCount}} блокируется хостов, помимо:",
+ "description": "English: {{ubiquitousBlacklistCount}} distinct blocked hostnames from:"
+ },
+ "3pListsOfBlockedHostsPerListStats" : {
+ "message": "{{used}} используется из {{total}}",
+ "description": "English: {{used}} used out of {{total}}"
+ },
+ "3pParseAllABPHideFiltersPrompt1" : {
+ "message": "Разбор и применение Adblock+ фильтров скрытия элементов.",
+ "description": "English: Parse and enforce Adblock+ element hiding filters."
+ },
+ "3pParseAllABPHideFiltersPrompt2" : {
+ "message": "{{abpHideFilterCount}} element hiding filters used.",
+ "description": "English: {{abpHideFilterCount}} element hiding filters used."
+ },
+ "3pParseAllABPHideFiltersInfo" : {
+ "message": "
Эта опция включает разбор и применение Adblock Plus-совместимых “element hiding” фильтров. Эти фильтры по сути только визуальные, они позволяют скрыть элементы страницы, которые не могут быть заблокированы матрицей фильтров или ABP-фильтрами.
Включение этой опции увеличивает использование памяти для µBlock.
",
+ "description": "English: see English messages.json"
+ },
+ "3pListsOfBlockedHostsHeader" : {
+ "message": "Список блокируемых хостов",
+ "description": "English: Lists of blocked hosts"
+ },
+ "3pApplyChanges" : {
+ "message": "Применить изменения",
+ "description": "English: Apply changes"
+ },
+
+
+ "1pFormatHint" : {
+ "message": "Одно правило на строку. Правилом может быть обычное имя сайти, или Adblock Plus-совместимый фильтр. Линии начинающиеся с ‘!’ будут пропущены.",
+ "description": "English: One filter per line. A filter can be a plain hostname, or an Adblock Plus-compatible filter. Lines prefixed with ‘!’ will be ignored."
+ },
+ "1pImport" : {
+ "message": "Импортировать и добавить",
+ "description": "English: Import and append"
+ },
+ "1pExport" : {
+ "message": "Экспортировать",
+ "description": "English: Export"
+ },
+ "1pApplyChanges" : {
+ "message": "Применить изменения",
+ "description": "English: Apply changes"
+ },
+
+
+ "aboutChangelog" : {
+ "message": "Список изменений",
+ "description": "English: Change log"
+ },
+ "aboutCode" : {
+ "message": "Исходный код (GPLv3)",
+ "description": "English: Source code (GPLv3)"
+ },
+ "aboutExtensionDataHeader" : {
+ "message": "Данные расширения",
+ "description": "English: Extension data"
+ },
+ "aboutAssetsUpdatePrompt" : {
+ "message": "µBlock подписки могут быть обновлены здесь вручную, если не хотите ждать новой версии расширения. Они загружаются из Github хранилища.",
+ "description": "Short descriptive text of the update feature"
+ },
+ "aboutAssetsUpdateColPath" : {
+ "message": "Путь",
+ "description": "Path column header"
+ },
+ "aboutAssetsUpdateColStatus" : {
+ "message": "Состояние",
+ "description": "Status column header"
+ },
+ "aboutAssetsUpdateGetListError" : {
+ "message": "Произошла ошибка. XHR заблокирован для raw2.github.com?",
+ "description": "Successful outcome of clicking 'update' button"
+ },
+ "aboutAssetsUpdateStatusAdded" : {
+ "message": "Добавить",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateStatusChanged" : {
+ "message": "Доступно обновление",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateStatusUnchanged" : {
+ "message": "Обновлений не найдено",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateStatusRemoved" : {
+ "message": "Для удаления",
+ "description": "Displayed in the status column for each entry"
+ },
+ "aboutAssetsUpdateButton" : {
+ "message": "Обновить",
+ "description": "Update button"
+ },
+ "aboutAssetsUpdatingButton" : {
+ "message": "Обновление...",
+ "description": "Updating..."
+ },
+
+
+ "dummy": {
+ "message": "Эта запись должна быть последней",
+ "description": "so we dont need to deal with comma for last entry"
+ }
+}
diff --git a/_locales/zh_CN/messages.json b/_locales/zh_CN/messages.json
new file mode 100644
index 000000000..9ae7f2e9a
--- /dev/null
+++ b/_locales/zh_CN/messages.json
@@ -0,0 +1,130 @@
+{
+ "extName": {
+ "message": "µBlock",
+ "description": "extension name."
+ },
+ "extShortDesc": {
+ "message": "Finally, an efficient blocker for Chromium-based browsers. Easy on CPU and memory.",
+ "description": "this will be in the chrome web store: must be 132 characters or less"
+ },
+ "1pPageName" : {
+ "message": "Your filters",
+ "description": "appears as tab name in dashboard."
+ },
+ "3pPageName" : {
+ "message": "Third-party filters",
+ "description": "appears as tab name in dashboard."
+ },
+ "aboutPageName": {
+ "message": "关于",
+ "description": "appears as tab name in dashboard."
+ },
+
+
+ "3pListsOfBlockedHostsPrompt2" : {
+ "message": "共{{ubiquitousBlacklistCount}}个不同的屏蔽站点名,来自:",
+ "description": "English: {{ubiquitousBlacklistCount}} distinct blocked hostnames from:"
+ },
+ "3pListsOfBlockedHostsPerListStats" : {
+ "message": "{{total}}中使用{{used}}",
+ "description": "English: {{used}} used out of {{total}}"
+ },
+ "3pParseAllABPHideFiltersPrompt1" : {
+ "message": "解析并应用Adblock+元素隐藏过滤规则。",
+ "description": "English: Parse and enforce Adblock+ element hiding filters."
+ },
+ "3pParseAllABPHideFiltersPrompt2" : {
+ "message": "{{abpHideFilterCount}}条元素隐藏过滤规则被使用。",
+ "description": "English: {{abpHideFilterCount}} element hiding filters used."
+ },
+ "3pParseAllABPHideFiltersInfo" : {
+ "message": "
+
+
+
+
+
+
+
+
diff --git a/dist/README.md b/dist/README.md
new file mode 100644
index 000000000..ca2fd1216
--- /dev/null
+++ b/dist/README.md
@@ -0,0 +1,11 @@
+## INSTALL
+
+- Download and unzip `ublock_{version}.zip` (latest version desirable).
+- Go to chromium/chrome *Extensions*.
+- Click to check *Developer mode*.
+- Click *Load unpacked extension...*.
+- In the file selector dialog:
+ - Select the directory `ublock` which was created when you unzipped `ublock.zip`.
+ - Click *Open*.
+
+The extension will now be available in your chromium/chrome browser.
diff --git a/img/browsericons/icon19-off.png b/img/browsericons/icon19-off.png
new file mode 100644
index 000000000..6a495a622
Binary files /dev/null and b/img/browsericons/icon19-off.png differ
diff --git a/img/browsericons/icon19.png b/img/browsericons/icon19.png
new file mode 100644
index 000000000..f91c8ee5e
Binary files /dev/null and b/img/browsericons/icon19.png differ
diff --git a/img/browsericons/icon38-off.png b/img/browsericons/icon38-off.png
new file mode 100644
index 000000000..7666c6b99
Binary files /dev/null and b/img/browsericons/icon38-off.png differ
diff --git a/img/browsericons/icon38.png b/img/browsericons/icon38.png
new file mode 100644
index 000000000..f8b5108e8
Binary files /dev/null and b/img/browsericons/icon38.png differ
diff --git a/img/help16.png b/img/help16.png
new file mode 100644
index 000000000..4bfac0b94
Binary files /dev/null and b/img/help16.png differ
diff --git a/img/icon_128.png b/img/icon_128.png
new file mode 100644
index 000000000..9b6fbfa0a
Binary files /dev/null and b/img/icon_128.png differ
diff --git a/img/icon_16.png b/img/icon_16.png
new file mode 100644
index 000000000..6f8e53385
Binary files /dev/null and b/img/icon_16.png differ
diff --git a/js/1p-filters.js b/js/1p-filters.js
new file mode 100644
index 000000000..bcc1f10d8
--- /dev/null
+++ b/js/1p-filters.js
@@ -0,0 +1,141 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global chrome, $ */
+
+/******************************************************************************/
+
+(function() {
+
+/******************************************************************************/
+
+var cachedUserFilters = '';
+
+/******************************************************************************/
+
+messaging.start('1p-filters.js');
+
+/******************************************************************************/
+
+// This is to give a visual hint that the content of user blacklist has changed.
+
+function userFiltersChanged() {
+ $('#userFiltersApply')
+ .attr(
+ 'disabled',
+ $('#userFilters').val().trim() === cachedUserFilters
+ );
+}
+
+/******************************************************************************/
+
+function renderUserFilters() {
+ var onRead = function(details) {
+ if ( details.error ) {
+ return;
+ }
+ cachedUserFilters = details.content.trim();
+ $('#userFilters').val(details.content);
+ };
+ messaging.ask({ what: 'readUserFilters' }, onRead);
+}
+
+/******************************************************************************/
+
+function allFiltersApplyHandler() {
+ messaging.tell({ what: 'reloadAllFilters' });
+ $('#userFiltersApply').attr('disabled', true );
+}
+
+/******************************************************************************/
+
+function appendToUserFiltersFromFile() {
+ var input = $('').attr({
+ type: 'file',
+ accept: 'text/plain'
+ });
+ var fileReaderOnLoadHandler = function() {
+ var textarea = $('#userFilters');
+ textarea.val(textarea.val() + '\n' + this.result);
+ userFiltersChanged();
+ };
+ var filePickerOnChangeHandler = function() {
+ $(this).off('change', filePickerOnChangeHandler);
+ var file = this.files[0];
+ if ( !file ) {
+ return;
+ }
+ if ( file.type.indexOf('text') !== 0 ) {
+ return;
+ }
+ var fr = new FileReader();
+ fr.onload = fileReaderOnLoadHandler;
+ fr.readAsText(file);
+ input.off('change', filePickerOnChangeHandler);
+ };
+ input.on('change', filePickerOnChangeHandler);
+ input.trigger('click');
+}
+
+/******************************************************************************/
+
+function exportUserFiltersToFile() {
+ chrome.downloads.download({
+ 'url': 'data:text/plain,' + encodeURIComponent($('#userFilters').val()),
+ 'filename': 'my-ublock-filters.txt',
+ 'saveAs': true
+ });
+}
+
+/******************************************************************************/
+
+function userFiltersApplyHandler() {
+ var onWritten = function(details) {
+ if ( details.error ) {
+ return;
+ }
+ cachedUserFilters = details.content.trim();
+ userFiltersChanged();
+ allFiltersApplyHandler();
+ };
+ var request = {
+ what: 'writeUserFilters',
+ content: $('#userFilters').val()
+ };
+ messaging.ask(request, onWritten);
+}
+
+/******************************************************************************/
+
+$(function() {
+ // Handle user interaction
+ $('#importUserFiltersFromFile').on('click', appendToUserFiltersFromFile);
+ $('#exportUserFiltersToFile').on('click', exportUserFiltersToFile);
+ $('#userFilters').on('input propertychange', userFiltersChanged);
+ $('#userFiltersApply').on('click', userFiltersApplyHandler);
+
+ renderUserFilters();
+});
+
+/******************************************************************************/
+
+})();
+
diff --git a/js/3p-filters.js b/js/3p-filters.js
new file mode 100644
index 000000000..5dc1eb7e8
--- /dev/null
+++ b/js/3p-filters.js
@@ -0,0 +1,235 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global chrome, $ */
+
+/******************************************************************************/
+
+(function() {
+
+/******************************************************************************/
+
+var userListName = chrome.i18n.getMessage('1pPageName');
+var cachedUserUbiquitousBlacklistedHosts = '';
+var cachedUserUbiquitousWhitelistedHosts = '';
+var selectedBlacklistsHash = '';
+
+/******************************************************************************/
+
+messaging.start('lists.js');
+
+var onMessage = function(msg) {
+ switch ( msg.what ) {
+ case 'loadUbiquitousBlacklistCompleted':
+ renderBlacklists();
+ selectedBlacklistsChanged();
+ break;
+
+ default:
+ break;
+ }
+};
+
+messaging.listen(onMessage);
+
+/******************************************************************************/
+
+function getµb() {
+ return chrome.extension.getBackgroundPage().µBlock;
+}
+
+/******************************************************************************/
+
+function renderNumber(value) {
+ // TODO: localization
+ if ( +value > 1000 ) {
+ value = value.toString();
+ var i = value.length - 3;
+ while ( i > 0 ) {
+ value = value.slice(0, i) + ',' + value.slice(i);
+ i -= 3;
+ }
+ }
+ return value;
+}
+
+/******************************************************************************/
+
+// TODO: get rid of background page dependencies
+
+function renderBlacklists() {
+ // empty list first
+ $('#blacklists .blacklistDetails').remove();
+
+ var µb = getµb();
+
+ $('#3pListsOfBlockedHostsPrompt2').text(
+ chrome.i18n.getMessage('3pListsOfBlockedHostsPrompt2')
+ .replace('{{ubiquitousBlacklistCount}}', renderNumber(µb.abpFilters.getFilterCount()))
+ );
+
+ // Assemble a pretty blacklist name if possible
+ var prettifyListName = function(blacklistTitle, blacklistHref) {
+ if ( blacklistHref === µb.userFiltersPath ) {
+ return userListName;
+ }
+ if ( !blacklistTitle ) {
+ return blacklistHref;
+ }
+ if ( blacklistHref.indexOf('assets/thirdparties/') !== 0 ) {
+ return blacklistTitle;
+ }
+ var matches = blacklistHref.match(/^assets\/thirdparties\/([^\/]+)/);
+ if ( matches === null || matches.length !== 2 ) {
+ return blacklistTitle;
+ }
+ var hostname = matches[1];
+ var domain = µb.URI.domainFromHostname(hostname);
+ if ( domain === '' ) {
+ return blacklistTitle;
+ }
+ var html = [
+ blacklistTitle,
+ ' (',
+ domain,
+ ')'
+ ];
+ return html.join('');
+ };
+
+ var blacklists = µb.remoteBlacklists;
+ var ul = $('#blacklists');
+ var keys = Object.keys(blacklists);
+ var i = keys.length;
+ var blacklist, blacklistHref;
+ var liTemplate = $('#blacklistTemplate .blacklistDetails').first();
+ var li, child, text;
+ while ( i-- ) {
+ blacklistHref = keys[i];
+ blacklist = blacklists[blacklistHref];
+ li = liTemplate.clone();
+ child = $('input', li);
+ child.prop('checked', !blacklist.off);
+ child = $('a', li);
+ child.attr('href', encodeURI(blacklistHref));
+ child.html(prettifyListName(blacklist.title, blacklistHref));
+ child = $('span', li);
+ text = child.text()
+ .replace('{{used}}', !blacklist.off && !isNaN(+blacklist.entryUsedCount) ? renderNumber(blacklist.entryUsedCount) : '0')
+ .replace('{{total}}', !isNaN(+blacklist.entryCount) ? renderNumber(blacklist.entryCount) : '?')
+ ;
+ child.text(text);
+ ul.prepend(li);
+ }
+ $('#parseAllABPHideFilters').attr('checked', µb.userSettings.parseAllABPHideFilters === true);
+ $('#ubiquitousParseAllABPHideFiltersPrompt2').text(
+ chrome.i18n.getMessage("listsParseAllABPHideFiltersPrompt2")
+ .replace('{{abpHideFilterCount}}', renderNumber(µb.abpHideFilters.getFilterCount()))
+ );
+
+ selectedBlacklistsHash = getSelectedBlacklistsHash();
+}
+
+/******************************************************************************/
+
+// Create a hash so that we know whether the selection of preset blacklists
+// has changed.
+
+function getSelectedBlacklistsHash() {
+ var hash = '';
+ var inputs = $('#blacklists .blacklistDetails > input');
+ var i = inputs.length;
+ var entryHash;
+ while ( i-- ) {
+ entryHash = $(inputs[i]).prop('checked').toString();
+ hash += entryHash;
+ }
+ // Factor in whether ABP filters are to be processed
+ hash += $('#parseAllABPHideFilters').prop('checked').toString();
+
+ return hash;
+}
+
+/******************************************************************************/
+
+// This is to give a visual hint that the selection of blacklists has changed.
+
+function selectedBlacklistsChanged() {
+ $('#blacklistsApply').attr(
+ 'disabled',
+ getSelectedBlacklistsHash() === selectedBlacklistsHash
+ );
+}
+
+/******************************************************************************/
+
+function blacklistsApplyHandler() {
+ var newHash = getSelectedBlacklistsHash();
+ if ( newHash === selectedBlacklistsHash ) {
+ return;
+ }
+ // Reload blacklists
+ var switches = [];
+ var lis = $('#blacklists .blacklistDetails');
+ var i = lis.length;
+ var path;
+ while ( i-- ) {
+ path = $(lis[i]).children('a').attr('href');
+ switches.push({
+ location: path,
+ off: $(lis[i]).children('input').prop('checked') === false
+ });
+ }
+ messaging.tell({
+ what: 'reloadAllFilters',
+ switches: switches
+ });
+ $('#blacklistsApply').attr('disabled', true );
+}
+
+/******************************************************************************/
+
+function abpHideFiltersCheckboxChanged() {
+ messaging.tell({
+ what: 'userSettings',
+ name: 'parseAllABPHideFilters',
+ value: $(this).is(':checked')
+ });
+ selectedBlacklistsChanged();
+}
+
+/******************************************************************************/
+
+$(function() {
+ // Handle user interaction
+ $('#blacklists').on('change', '.blacklistDetails', selectedBlacklistsChanged);
+ $('#blacklistsApply').on('click', blacklistsApplyHandler);
+ $('#parseAllABPHideFilters').on('change', abpHideFiltersCheckboxChanged);
+
+ renderBlacklists();
+});
+
+/******************************************************************************/
+
+})();
+
diff --git a/js/about.js b/js/about.js
new file mode 100644
index 000000000..a89bc202d
--- /dev/null
+++ b/js/about.js
@@ -0,0 +1,122 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global chrome, $ */
+
+/******************************************************************************/
+
+$(function() {
+
+/******************************************************************************/
+
+var updateList = {};
+var assetListSwitches = ['o', 'o', 'o'];
+var commitHistoryURLPrefix = 'https://github.com/gorhill/ublock/commits/master/';
+
+/******************************************************************************/
+
+var setAssetListClassBit = function(bit, state) {
+ assetListSwitches[assetListSwitches.length-1-bit] = !state ? 'o' : 'x';
+ $('#assetList')
+ .removeClass()
+ .addClass(assetListSwitches.join(''));
+};
+
+/******************************************************************************/
+
+var renderAssetList = function(details) {
+ var dirty = false;
+ var paths = Object.keys(details.list).sort();
+ if ( paths.length > 0 ) {
+ $('#assetList .assetEntry').remove();
+ var assetTable = $('#assetList table');
+ var i = 0;
+ var path, status, html;
+ while ( path = paths[i++] ) {
+ status = details.list[path].status;
+ dirty = dirty || status !== 'Unchanged';
+ html = [];
+ html.push('
');
+ html.push(chrome.i18n.getMessage('aboutAssetsUpdateStatus' + status));
+ assetTable.append(html.join(''));
+ }
+ $('#assetList a').attr('target', '_blank');
+ updateList = details.list;
+ }
+ setAssetListClassBit(0, paths.length !== 0);
+ setAssetListClassBit(1, dirty);
+ setAssetListClassBit(2, false);
+};
+
+/******************************************************************************/
+
+var updateAssets = function() {
+ setAssetListClassBit(2, true);
+ var onDone = function(details) {
+ if ( details.changedCount !== 0 ) {
+ messaging.tell({ what: 'loadUpdatableAssets' });
+ }
+ };
+ messaging.ask({ what: 'launchAssetUpdater', list: updateList }, onDone);
+};
+
+/******************************************************************************/
+
+var updateAssetsList = function() {
+ messaging.ask({ what: 'getAssetUpdaterList' }, renderAssetList);
+};
+
+/******************************************************************************/
+
+// Updating all assets could be done from elsewhere and if so the
+// list here needs to be updated.
+
+var onAnnounce = function(msg) {
+ switch ( msg.what ) {
+ case 'allLocalAssetsUpdated':
+ updateAssetsList();
+ break;
+
+ default:
+ break;
+ }
+};
+
+messaging.start('about.js');
+messaging.listen(onAnnounce);
+
+/******************************************************************************/
+
+$('#aboutVersion').html(chrome.runtime.getManifest().version);
+$('#aboutAssetsUpdateButton').on('click', updateAssets);
+
+/******************************************************************************/
+
+updateAssetsList();
+
+/******************************************************************************/
+
+});
diff --git a/js/abp-filters.js b/js/abp-filters.js
new file mode 100644
index 000000000..c1e9d238a
--- /dev/null
+++ b/js/abp-filters.js
@@ -0,0 +1,1466 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* jshint esnext: true, bitwise: false */
+/* global µBlock */
+
+/******************************************************************************/
+
+µBlock.abpFilters = (function(){
+
+/******************************************************************************/
+
+const BlockAction = 0 << 15;
+const AllowAction = 1 << 15;
+
+const AnyType = 1 << 11;
+
+const AnyParty = 0 << 8;
+const FirstParty = 1 << 8;
+const ThirdParty = 2 << 8;
+const SpecificParty = 3 << 8;
+const SpecificNotParty = 4 << 8;
+
+const BlockAnyTypeAnyParty = BlockAction | AnyType | AnyParty;
+const BlockAnyType1stParty = BlockAction | AnyType | FirstParty;
+const BlockAnyType3rdParty = BlockAction | AnyType | ThirdParty;
+const BlockAnyTypeOneParty = BlockAction | AnyType | SpecificParty;
+const BlockAnyTypeOtherParties = BlockAction | AnyType | SpecificNotParty;
+const BlockAnyType = BlockAction | AnyType;
+const BlockAnyParty = BlockAction | AnyParty;
+const BlockOneParty = BlockAction | SpecificParty;
+const BlockOtherParties = BlockAction | SpecificNotParty;
+
+const AllowAnyTypeAnyParty = AllowAction | AnyType | AnyParty;
+const AllowAnyType1stParty = AllowAction | AnyType | FirstParty;
+const AllowAnyType3rdParty = AllowAction | AnyType | ThirdParty;
+const AllowAnyTypeOneParty = AllowAction | AnyType | SpecificParty;
+const AllowAnyTypeOtherParties = AllowAction | AnyType | SpecificNotParty;
+const AllowAnyType = AllowAction | AnyType;
+const AllowAnyParty = AllowAction | AnyParty;
+const AllowOneParty = AllowAction | SpecificParty;
+const AllowOtherParties = AllowAction | SpecificNotParty;
+
+var pageHostname = '';
+
+var reIgnoreEmpty = /^\s+$/;
+var reIgnoreComment = /^\[|^!/;
+var reHostnameRule = /^[0-9a-z][0-9a-z.-]+[0-9a-z]$/;
+var reHostnameToken = /^[0-9a-z]+/g;
+var reGoodToken = /[%0-9a-z]{2,}/g;
+
+var typeNameToTypeValue = {
+ 'stylesheet': 2 << 11,
+ 'image': 3 << 11,
+ 'object': 4 << 11,
+ 'script': 5 << 11,
+ 'xmlhttprequest': 6 << 11,
+ 'sub_frame': 7 << 11,
+ 'other': 8 << 11
+};
+
+// ABP filters: https://adblockplus.org/en/filters
+// regex tester: http://regex101.com/
+
+/******************************************************************************/
+/*
+var histogram = function(label, categories) {
+ var h = [],
+ categoryBucket;
+ for ( var k in categories ) {
+ if ( categories.hasOwnProperty(k) === false ) {
+ continue;
+ }
+ categoryBucket = categories[k];
+ for ( var kk in categoryBucket ) {
+ if ( categoryBucket.hasOwnProperty(kk) === false ) {
+ continue;
+ }
+ filterBucket = categoryBucket[kk];
+ h.push({
+ k: k + ' ' + kk,
+ n: filterBucket instanceof FilterBucket ? filterBucket.filters.length : 1
+ });
+ }
+ }
+
+ console.log('Histogram %s', label);
+
+ var total = h.length;
+ h.sort(function(a, b) { return b.n - a.n; });
+
+ // Find indices of entries of interest
+ var target = 2;
+ for ( var i = 0; i < total; i++ ) {
+ if ( h[i].n === target ) {
+ console.log('\tEntries with only %d filter(s) start at index %s (key = "%s")', target, i, h[i].k);
+ target -= 1;
+ }
+ }
+
+ h = h.slice(0, 50);
+
+ h.forEach(function(v) {
+ console.log('\tkey=%s count=%d', v.k, v.n);
+ });
+ console.log('\tTotal buckets count: %d', total);
+};
+*/
+/*
+var adbProfiler = {
+ testCount: 0,
+ urlCount: 0,
+ dumpEach: 200,
+ countUrl: function() {
+ this.urlCount += 1;
+ if ( (this.urlCount % this.dumpEach) === 0 ) {
+ this.dump();
+ }
+ },
+ countTest: function() {
+ this.testCount += 1;
+ },
+ dump: function() {
+ console.log('µBlock.adbProfiler> number or filters tested per URL: %d (sample: %d URLs)', this.testCount / this.urlCount, this.urlCount);
+ },
+ reset: function() {
+ this.testCount = 0;
+ this.urlCount = 0;
+ },
+ dummy: 0
+};
+*/
+
+/*******************************************************************************
+
+Filters family tree:
+
+- plain (no wildcard)
+ - anywhere
+ - no hostname
+ - specific hostname
+ - specific not hostname
+ - anchored at start
+ - no hostname
+ - specific hostname
+ - specific not hostname
+ - anchored at end
+ - no hostname
+ - specific hostname
+ - specific not hostname
+
+- one wildcard
+ - anywhere
+ - no hostname
+ - specific hostname
+ - specific not hostname
+ - anchored at start
+ - no hostname
+ - specific hostname
+ - specific not hostname
+ - anchored at end
+ - no hostname
+ - specific hostname
+ - specific not hostname
+
+- more than one wildcard
+ - anywhere
+ - no hostname
+ - specific hostname
+ - specific not hostname
+ - anchored at start
+ - no hostname
+ - specific hostname
+ - specific not hostname
+ - anchored at end
+ - no hostname
+ - specific hostname
+ - specific not hostname
+
+*/
+
+/******************************************************************************/
+
+var FilterPlain = function(s, tokenBeg) {
+ this.s = s;
+ this.tokenBeg = tokenBeg;
+};
+
+FilterPlain.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return url.substr(tokenBeg - this.tokenBeg, this.s.length) === this.s;
+};
+
+var FilterPlainHostname = function(s, tokenBeg, hostname) {
+ this.s = s;
+ this.tokenBeg = tokenBeg;
+ this.hostname = hostname;
+};
+
+FilterPlainHostname.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) === this.hostname &&
+ url.substr(tokenBeg - this.tokenBeg, this.s.length) === this.s;
+};
+
+var FilterPlainNotHostname = function(s, tokenBeg, hostname) {
+ this.s = s;
+ this.tokenBeg = tokenBeg;
+ this.hostname = hostname;
+};
+
+FilterPlainNotHostname.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) !== this.hostname &&
+ url.substr(tokenBeg - this.tokenBeg, this.s.length) === this.s;
+};
+
+/******************************************************************************/
+
+var FilterPlainPrefix0 = function(s) {
+ this.s = s;
+};
+
+FilterPlainPrefix0.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return url.substr(tokenBeg, this.s.length) === this.s;
+};
+
+var FilterPlainPrefix0Hostname = function(s, hostname) {
+ this.s = s;
+ this.hostname = hostname;
+};
+
+FilterPlainPrefix0Hostname.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) === this.hostname &&
+ url.substr(tokenBeg, this.s.length) === this.s;
+};
+
+var FilterPlainPrefix0NotHostname = function(s, hostname) {
+ this.s = s;
+ this.hostname = hostname;
+};
+
+FilterPlainPrefix0NotHostname.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) !== this.hostname &&
+ url.substr(tokenBeg, this.s.length) === this.s;
+};
+
+/******************************************************************************/
+
+var FilterPlainPrefix1 = function(s) {
+ this.s = s;
+};
+
+FilterPlainPrefix1.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return url.substr(tokenBeg - 1, this.s.length) === this.s;
+};
+
+var FilterPlainPrefix1Hostname = function(s, hostname) {
+ this.s = s;
+ this.hostname = hostname;
+};
+
+FilterPlainPrefix1Hostname.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) === this.hostname &&
+ url.substr(tokenBeg - 1, this.s.length) === this.s;
+};
+
+var FilterPlainPrefix1NotHostname = function(s, hostname) {
+ this.s = s;
+ this.hostname = hostname;
+};
+
+FilterPlainPrefix1NotHostname.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) !== this.hostname &&
+ url.substr(tokenBeg - 1, this.s.length) === this.s;
+};
+
+/******************************************************************************/
+
+var FilterPlainLeftAnchored = function(s) {
+ this.s = s;
+};
+
+FilterPlainLeftAnchored.prototype.match = function(url) {
+ // adbProfiler.countTest();
+ return url.slice(0, this.s.length) === this.s;
+};
+
+var FilterPlainLeftAnchoredHostname = function(s, hostname) {
+ this.s = s;
+ this.hostname = hostname;
+};
+
+FilterPlainLeftAnchoredHostname.prototype.match = function(url) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) === this.hostname &&
+ url.slice(0, this.s.length) === this.s;
+};
+
+var FilterPlainLeftAnchoredNotHostname = function(s, hostname) {
+ this.s = s;
+ this.hostname = hostname;
+};
+
+FilterPlainLeftAnchoredNotHostname.prototype.match = function(url) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) !== this.hostname &&
+ url.slice(0, this.s.length) === this.s;
+};
+
+/******************************************************************************/
+
+var FilterPlainRightAnchored = function(s) {
+ this.s = s;
+};
+
+FilterPlainRightAnchored.prototype.match = function(url) {
+ // adbProfiler.countTest();
+ return url.slice(-this.s.length) === this.s;
+};
+
+var FilterPlainRightAnchoredHostname = function(s, hostname) {
+ this.s = s;
+ this.hostname = hostname;
+};
+
+FilterPlainRightAnchoredHostname.prototype.match = function(url) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) === this.hostname &&
+ url.slice(-this.s.length) === this.s;
+};
+
+var FilterPlainRightAnchoredNotHostname = function(s, hostname) {
+ this.s = s;
+ this.hostname = hostname;
+};
+
+FilterPlainRightAnchoredNotHostname.prototype.match = function(url) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) !== this.hostname &&
+ url.slice(-this.s.length) === this.s;
+};
+
+/******************************************************************************/
+
+// With a single wildcard, regex is not optimal.
+// See:
+// http://jsperf.com/regexp-vs-indexof-abp-miss/3
+// http://jsperf.com/regexp-vs-indexof-abp-hit/3
+
+var FilterSingleWildcard = function(s, tokenBeg) {
+ this.s = s;
+ this.tokenBeg = tokenBeg;
+ var wcOffset = s.indexOf('*');
+ this.lSegment = s.slice(0, wcOffset);
+ this.rSegment = s.slice(wcOffset + 1);
+};
+
+FilterSingleWildcard.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ tokenBeg -= this.tokenBeg;
+ return url.substr(tokenBeg, this.lSegment.length) === this.lSegment &&
+ url.indexOf(this.rSegment, tokenBeg + this.lSegment.length) > 0;
+};
+
+var FilterSingleWildcardHostname = function(s, tokenBeg, hostname) {
+ this.s = s;
+ this.tokenBeg = tokenBeg;
+ var wcOffset = s.indexOf('*');
+ this.lSegment = s.slice(0, wcOffset);
+ this.rSegment = s.slice(wcOffset + 1);
+ this.hostname = hostname;
+};
+
+FilterSingleWildcardHostname.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ tokenBeg -= this.tokenBeg;
+ return pageHostname.slice(-this.hostname.length) === this.hostname &&
+ url.substr(tokenBeg, this.lSegment.length) === this.lSegment &&
+ url.indexOf(this.rSegment, tokenBeg + this.lSegment.length) > 0;
+};
+
+var FilterSingleWildcardNotHostname = function(s, tokenBeg, hostname) {
+ this.s = s;
+ this.tokenBeg = tokenBeg;
+ var wcOffset = s.indexOf('*');
+ this.lSegment = s.slice(0, wcOffset);
+ this.rSegment = s.slice(wcOffset + 1);
+ this.hostname = hostname;
+};
+
+FilterSingleWildcardNotHostname.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ tokenBeg -= this.tokenBeg;
+ return pageHostname.slice(-this.hostname.length) !== this.hostname &&
+ url.substr(tokenBeg, this.lSegment.length) === this.lSegment &&
+ url.indexOf(this.rSegment, tokenBeg + this.lSegment.length) > 0;
+};
+
+/******************************************************************************/
+
+var FilterSingleWildcardPrefix0 = function(s) {
+ this.s = s;
+ var wcOffset = s.indexOf('*');
+ this.lSegment = s.slice(0, wcOffset);
+ this.rSegment = s.slice(wcOffset + 1);
+};
+
+FilterSingleWildcardPrefix0.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return url.substr(tokenBeg, this.lSegment.length) === this.lSegment &&
+ url.indexOf(this.rSegment, tokenBeg + this.lSegment.length) > 0;
+};
+
+var FilterSingleWildcardPrefix0Hostname = function(s, hostname) {
+ this.s = s;
+ var wcOffset = s.indexOf('*');
+ this.lSegment = s.slice(0, wcOffset);
+ this.rSegment = s.slice(wcOffset + 1);
+ this.hostname = hostname;
+};
+
+FilterSingleWildcardPrefix0Hostname.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) === this.hostname &&
+ url.substr(tokenBeg, this.lSegment.length) === this.lSegment &&
+ url.indexOf(this.rSegment, tokenBeg + this.lSegment.length) > 0;
+};
+
+var FilterSingleWildcardPrefix0NotHostname = function(s, hostname) {
+ this.s = s;
+ var wcOffset = s.indexOf('*');
+ this.lSegment = s.slice(0, wcOffset);
+ this.rSegment = s.slice(wcOffset + 1);
+ this.hostname = hostname;
+};
+
+FilterSingleWildcardPrefix0NotHostname.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) !== this.hostname &&
+ url.substr(tokenBeg, this.lSegment.length) === this.lSegment &&
+ url.indexOf(this.rSegment, tokenBeg + this.lSegment.length) > 0;
+};
+
+/******************************************************************************/
+
+// With a single wildcard, regex is not optimal.
+// See:
+// http://jsperf.com/regexp-vs-indexof-abp-miss/3
+// http://jsperf.com/regexp-vs-indexof-abp-hit/3
+
+var FilterSingleWildcardLeftAnchored = function(s) {
+ this.s = s;
+ var wcOffset = s.indexOf('*');
+ this.lSegment = s.slice(0, wcOffset);
+ this.rSegment = s.slice(wcOffset + 1);
+};
+
+FilterSingleWildcardLeftAnchored.prototype.match = function(url) {
+ // adbProfiler.countTest();
+ return url.slice(0, this.lSegment.length) === this.lSegment &&
+ url.indexOf(this.rSegment, this.lSegment.length) > 0;
+};
+
+var FilterSingleWildcardLeftAnchoredHostname = function(s, hostname) {
+ this.s = s;
+ var wcOffset = s.indexOf('*');
+ this.lSegment = s.slice(0, wcOffset);
+ this.rSegment = s.slice(wcOffset + 1);
+ this.hostname = hostname;
+};
+
+FilterSingleWildcardLeftAnchoredHostname.prototype.match = function(url) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) === this.hostname &&
+ url.slice(0, this.lSegment.length) === this.lSegment &&
+ url.indexOf(this.rSegment, this.lSegment.length) > 0;
+};
+
+var FilterSingleWildcardLeftAnchoredNotHostname = function(s, hostname) {
+ this.s = s;
+ var wcOffset = s.indexOf('*');
+ this.lSegment = s.slice(0, wcOffset);
+ this.rSegment = s.slice(wcOffset + 1);
+ this.hostname = hostname;
+};
+
+FilterSingleWildcardLeftAnchoredNotHostname.prototype.match = function(url) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) !== this.hostname &&
+ url.slice(0, this.lSegment.length) === this.lSegment &&
+ url.indexOf(this.rSegment, this.lSegment.length) > 0;
+};
+
+/******************************************************************************/
+
+// With a single wildcard, regex is not optimal.
+// See:
+// http://jsperf.com/regexp-vs-indexof-abp-miss/3
+// http://jsperf.com/regexp-vs-indexof-abp-hit/3
+
+var FilterSingleWildcardRightAnchored = function(s) {
+ this.s = s;
+ var wcOffset = s.indexOf('*');
+ this.lSegment = s.slice(0, wcOffset);
+ this.rSegment = s.slice(wcOffset + 1);
+};
+
+FilterSingleWildcardRightAnchored.prototype.match = function(url) {
+ // adbProfiler.countTest();
+ return url.slice(-this.rSegment.length) === this.rSegment &&
+ url.lastIndexOf(this.lSegment, url.length - this.rSegment.length - this.lSegment.length) >= 0;
+};
+
+var FilterSingleWildcardRightAnchoredHostname = function(s, hostname) {
+ this.s = s;
+ var wcOffset = s.indexOf('*');
+ this.lSegment = s.slice(0, wcOffset);
+ this.rSegment = s.slice(wcOffset + 1);
+ this.hostname = hostname;
+};
+
+FilterSingleWildcardRightAnchoredHostname.prototype.match = function(url) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) === this.hostname &&
+ url.slice(-this.rSegment.length) === this.rSegment &&
+ url.lastIndexOf(this.lSegment, url.length - this.rSegment.length - this.lSegment.length) >= 0;
+};
+
+var FilterSingleWildcardRightAnchoredNotHostname = function(s, hostname) {
+ this.s = s;
+ var wcOffset = s.indexOf('*');
+ this.lSegment = s.slice(0, wcOffset);
+ this.rSegment = s.slice(wcOffset + 1);
+ this.hostname = hostname;
+};
+
+FilterSingleWildcardRightAnchoredNotHostname.prototype.match = function(url) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) !== this.hostname &&
+ url.slice(-this.rSegment.length) === this.rSegment &&
+ url.lastIndexOf(this.lSegment, url.length - this.rSegment.length - this.lSegment.length) >= 0;
+};
+
+/******************************************************************************/
+
+// With many wildcards, a regex is best.
+
+// Ref: regex escaper taken from:
+// https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
+// modified for the purpose here.
+
+var FilterManyWildcards = function(s, tokenBeg) {
+ this.s = s;
+ this.tokenBeg = tokenBeg;
+ this.re = new RegExp('^' + s.replace(/([.+?^=!:${}()|\[\]\/\\])/g, '\\$1').replace(/\*/g, '.*'));
+};
+
+FilterManyWildcards.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return this.re.test(url.slice(tokenBeg - this.tokenBeg));
+};
+
+var FilterManyWildcardsHostname = function(s, tokenBeg, hostname) {
+ this.s = s;
+ this.tokenBeg = tokenBeg;
+ this.re = new RegExp('^' + s.replace(/([.+?^=!:${}()|\[\]\/\\])/g, '\\$1').replace(/\*/g, '.*'));
+ this.hostname = hostname;
+};
+
+FilterManyWildcardsHostname.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) === this.hostname &&
+ this.re.test(url.slice(tokenBeg - this.tokenBeg));
+};
+
+var FilterManyWildcardsNotHostname = function(s, tokenBeg, hostname) {
+ this.s = s;
+ this.tokenBeg = tokenBeg;
+ this.re = new RegExp('^' + s.replace(/([.+?^=!:${}()|\[\]\/\\])/g, '\\$1').replace(/\*/g, '.*'));
+ this.hostname = hostname;
+};
+
+FilterManyWildcardsNotHostname.prototype.match = function(url, tokenBeg) {
+ // adbProfiler.countTest();
+ return pageHostname.slice(-this.hostname.length) !== this.hostname &&
+ this.re.test(url.slice(tokenBeg - this.tokenBeg));
+};
+
+/******************************************************************************/
+
+var makeFilter = function(details, tokenBeg) {
+ var s = details.f;
+ var wcOffset = s.indexOf('*');
+ if ( wcOffset > 0 ) {
+ if ( (/\*[^*]\*/).test(s) ) {
+ return details.anchor === 0 ? new FilterManyWildcards(s, tokenBeg) : null;
+ }
+ if ( details.anchor < 0 ) {
+ return new FilterSingleWildcardLeftAnchored(s);
+ }
+ if ( details.anchor > 0 ) {
+ return new FilterSingleWildcardRightAnchored(s);
+ }
+ if ( tokenBeg === 0 ) {
+ return new FilterSingleWildcardPrefix0(s);
+ }
+ return new FilterSingleWildcard(s, tokenBeg);
+ }
+ if ( details.anchor < 0 ) {
+ return new FilterPlainLeftAnchored(s);
+ }
+ if ( details.anchor > 0 ) {
+ return new FilterPlainRightAnchored(s);
+ }
+ if ( tokenBeg === 0 ) {
+ return new FilterPlainPrefix0(s);
+ }
+ if ( tokenBeg === 1 ) {
+ return new FilterPlainPrefix1(s);
+ }
+ return new FilterPlain(s, tokenBeg);
+};
+
+/******************************************************************************/
+
+var makeHostnameFilter = function(details, tokenBeg, hostname) {
+ var s = details.f;
+ var wcOffset = s.indexOf('*');
+ if ( wcOffset > 0 ) {
+ if ( (/\*[^*]\*/).test(s) ) {
+ return details.anchor === 0 ? new FilterManyWildcardsHostname(s, tokenBeg, hostname) : null;
+ }
+ if ( details.anchor < 0 ) {
+ return new FilterSingleWildcardLeftAnchoredHostname(s, hostname);
+ }
+ if ( details.anchor > 0 ) {
+ return new FilterSingleWildcardRightAnchoredHostname(s, hostname);
+ }
+ if ( tokenBeg === 0 ) {
+ return new FilterSingleWildcardPrefix0Hostname(s, hostname);
+ }
+ return new FilterSingleWildcardHostname(s, tokenBeg, hostname);
+ }
+ if ( details.anchor < 0 ) {
+ return new FilterPlainLeftAnchoredHostname(s, hostname);
+ }
+ if ( details.anchor > 0 ) {
+ return new FilterPlainRightAnchoredHostname(s, hostname);
+ }
+ if ( tokenBeg === 0 ) {
+ return new FilterPlainPrefix0Hostname(s, hostname);
+ }
+ if ( tokenBeg === 1 ) {
+ return new FilterPlainPrefix1Hostname(s, hostname);
+ }
+ return new FilterPlainHostname(s, tokenBeg, hostname);
+};
+
+/******************************************************************************/
+
+var makeNotHostnameFilter = function(details, tokenBeg, hostname) {
+ var s = details.f;
+ var wcOffset = s.indexOf('*');
+ if ( wcOffset > 0 ) {
+ if ( (/\*[^*]\*/).test(s) ) {
+ return details.anchor === 0 ? new FilterManyWildcardsNotHostname(s, tokenBeg, hostname) : null;
+ }
+ if ( details.anchor < 0 ) {
+ return new FilterSingleWildcardLeftAnchoredNotHostname(s, hostname);
+ }
+ if ( details.anchor > 0 ) {
+ return new FilterSingleWildcardRightAnchoredNotHostname(s, hostname);
+ }
+ if ( tokenBeg === 0 ) {
+ return new FilterSingleWildcardPrefix0NotHostname(s, hostname);
+ }
+ return new FilterSingleWildcardNotHostname(s, tokenBeg, hostname);
+ }
+ if ( details.anchor < 0 ) {
+ return new FilterPlainLeftAnchoredNotHostname(s, hostname);
+ }
+ if ( details.anchor > 0 ) {
+ return new FilterPlainRightAnchoredNotHostname(s, hostname);
+ }
+ if ( tokenBeg === 0 ) {
+ return new FilterPlainPrefix0NotHostname(s, hostname);
+ }
+ if ( tokenBeg === 1 ) {
+ return new FilterPlainPrefix1NotHostname(s, hostname);
+ }
+ return new FilterPlainNotHostname(s, tokenBeg, hostname);
+};
+
+/******************************************************************************/
+
+// Given a string, find a good token. Tokens which are too generic, i.e. very
+// common with a high probability of ending up as a miss, are not
+// good. Avoid if possible. This has a *significant* positive impact on
+// performance.
+// These "bad tokens" are collated manually.
+
+var badTokens = {
+ 'com': true,
+ 'http': true,
+ 'https': true,
+ 'images': true,
+ 'img': true,
+ 'js': true,
+ 'news': true,
+ 'www': true
+};
+
+var findFirstGoodToken = function(s) {
+ reGoodToken.lastIndex = 0;
+ var matches;
+ while ( matches = reGoodToken.exec(s) ) {
+ if ( badTokens[matches[0]] === undefined ) {
+ return matches;
+ }
+ }
+ // No good token found, just return the first token from left
+ reGoodToken.lastIndex = 0;
+ return reGoodToken.exec(s);
+};
+
+/******************************************************************************/
+
+var findHostnameToken = function(s) {
+ reHostnameToken.lastIndex = 0;
+ return reHostnameToken.exec(s);
+};
+
+/******************************************************************************/
+
+// Trim leading/trailing char "c"
+
+var trimChar = function(s, c) {
+ // Remove leading and trailing wildcards
+ var pos = 0;
+ while ( s.charAt(pos) === c ) {
+ pos += 1;
+ }
+ s = s.slice(pos);
+ if ( pos = s.length ) {
+ while ( s.charAt(pos-1) === c ) {
+ pos -= 1;
+ }
+ s = s.slice(0, pos);
+ }
+ return s;
+};
+
+/******************************************************************************/
+
+var FilterParser = function() {
+ this.action = BlockAction;
+ this.anchor = 0;
+ this.domains = [];
+ this.elemHiding = false;
+ this.f = '';
+ this.firstParty = false;
+ this.fopts = '';
+ this.hostname = false;
+ this.hostnames = [];
+ this.notDomains = [];
+ this.notHostnames = [];
+ this.thirdParty = false;
+ this.types = [];
+ this.unsupported = false;
+};
+
+/******************************************************************************/
+
+FilterParser.prototype.toNormalizedType = {
+ 'stylesheet': 'stylesheet',
+ 'image': 'image',
+ 'object': 'object',
+ 'object-subrequest': 'object',
+ 'script': 'script',
+ 'xmlhttprequest': 'xmlhttprequest',
+ 'subdocument': 'sub_frame',
+ 'other': 'other'
+};
+
+/******************************************************************************/
+
+FilterParser.prototype.reset = function() {
+ this.action = BlockAction;
+ this.anchor = 0;
+ this.domains = [];
+ this.elemHiding = false;
+ this.f = '';
+ this.firstParty = false;
+ this.fopts = '';
+ this.hostname = false;
+ this.hostnames = [];
+ this.notDomains = [];
+ this.notHostnames = [];
+ this.thirdParty = false;
+ this.types = [];
+ this.unsupported = false;
+ return this;
+};
+
+/******************************************************************************/
+
+FilterParser.prototype.parseOptType = function(raw, not) {
+ var type = this.toNormalizedType[raw];
+ if ( not ) {
+ for ( var k in typeNameToTypeValue ) {
+ if ( k === type ) {
+ continue;
+ }
+ this.types.push(typeNameToTypeValue[k]);
+ }
+ } else {
+ this.types.push(typeNameToTypeValue[type]);
+ }
+};
+
+/******************************************************************************/
+
+FilterParser.prototype.parseOptParty = function(not) {
+ if ( not ) {
+ this.firstParty = true;
+ } else {
+ this.thirdParty = true;
+ }
+};
+
+/******************************************************************************/
+
+FilterParser.prototype.parseOptHostnames = function(raw) {
+ var µburi = µBlock.URI;
+ var hostnames = raw.split('|');
+ var hostname, not, domain;
+ for ( var i = 0; i < hostnames.length; i++ ) {
+ hostname = hostnames[i];
+ not = hostname.charAt(0) === '~';
+ if ( not ) {
+ hostname = hostname.slice(1);
+ }
+ domain = µburi.domainFromHostname(hostname);
+ if ( not ) {
+ this.notHostnames.push(hostname);
+ this.notDomains.push(domain);
+ } else {
+ this.hostnames.push(hostname);
+ this.domains.push(domain);
+ }
+ }
+};
+
+/******************************************************************************/
+
+FilterParser.prototype.parse = function(s) {
+ // important!
+ this.reset();
+
+ // element hiding filter?
+ if ( s.indexOf('##') >= 0 || s.indexOf('#@') >= 0 ) {
+ this.elemHiding = true;
+ return this;
+ }
+
+ // block or allow filter?
+ if ( s.slice(0, 2) === '@@' ) {
+ this.action = AllowAction;
+ s = s.slice(2);
+ }
+
+ // hostname anchoring
+ if ( s.slice(0, 2) === '||' ) {
+ this.hostname = true;
+ s = s.slice(2);
+ }
+
+ // left-anchored
+ if ( s.charAt(0) === '|' ) {
+ this.anchor = -1;
+ s = s.slice(1);
+ }
+
+ // options
+ var pos = s.indexOf('$');
+ if ( pos > 0 ) {
+ this.fopts = s.slice(pos + 1);
+ s = s.slice(0, pos);
+ }
+
+ // right-anchored
+ if ( s.slice(-1) === '|' ) {
+ this.anchor = 1;
+ s = s.slice(0, -1);
+ }
+
+ // normalize placeholders
+ // TODO: transforming `^` into `*` is not a strict interpretation of
+ // ABP syntax.
+ s = s.replace(/\^/g, '*');
+ s = s.replace(/\*\*+/g, '*');
+
+ // remove leading and trailing wildcards
+ this.f = trimChar(s, '*');
+
+ if ( !this.fopts ) {
+ return this;
+ }
+
+ // parse options
+ var opts = this.fopts.split(',');
+ var opt, not;
+ for ( var i = 0; i < opts.length; i++ ) {
+ opt = opts[i];
+ not = opt.charAt(0) === '~';
+ if ( not ) {
+ opt = opt.slice(1);
+ }
+ if ( opt === 'third-party' ) {
+ this.parseOptParty(not);
+ continue;
+ }
+ if ( this.toNormalizedType.hasOwnProperty(opt) ) {
+ this.parseOptType(opt, not);
+ continue;
+ }
+ if ( opt.slice(0,7) === 'domain=' ) {
+ this.parseOptHostnames(opt.slice(7));
+ continue;
+ }
+ if ( opt === 'popup' ) {
+ this.elemHiding = true;
+ break;
+ }
+ this.unsupported = true;
+ }
+ return this;
+};
+
+/******************************************************************************/
+/******************************************************************************/
+
+var FilterBucket = function(a, b) {
+ this.filters = [a, b];
+ this.s = '';
+};
+
+/******************************************************************************/
+
+FilterBucket.prototype.add = function(a) {
+ this.filters.push(a);
+};
+
+/******************************************************************************/
+
+FilterBucket.prototype.match = function(url, tokenBeg) {
+ var filters = this.filters;
+ var i = filters.length;
+ while ( i-- ) {
+ if ( filters[i].match(url, tokenBeg) !== false ) {
+ this.s = filters[i].s;
+ return true;
+ }
+ }
+ return false;
+};
+
+/******************************************************************************/
+/******************************************************************************/
+
+var FilterContainer = function() {
+ this.categories = {};
+ this.duplicates = {};
+ this.url = '';
+ this.tokenBeg = 0;
+ this.tokenEnd = 0;
+ this.filterParser = new FilterParser();
+ this.processedFilterCount = 0;
+ this.supportedFilterCount = 0;
+ this.allowFilterCount = 0;
+ this.blockFilterCount = 0;
+
+ // This is for hostname-based-any-request filters
+ this.blockedAnyPartyHostnames = new µBlock.LiquidDict();
+ this.blocked3rdPartyHostnames = new µBlock.LiquidDict();
+
+ // Used during URL matching
+ this.reAnyToken = /[%0-9a-z]+/g;
+ this.matches = null;
+ this.bucket0 = undefined;
+ this.bucket1 = undefined;
+ this.bucket2 = undefined;
+ this.bucket3 = undefined;
+ this.bucket4 = undefined;
+ this.bucket5 = undefined;
+ this.bucket6 = undefined;
+ this.bucket7 = undefined;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.toDomainBits = function(domain) {
+ if ( domain === undefined ) {
+ return 0;
+ }
+ var i = domain.length >> 2;
+ return (domain.charCodeAt( 0) & 0x01) << 3 |
+ (domain.charCodeAt( i) & 0x01) << 2 |
+ (domain.charCodeAt( i+i) & 0x01) << 1 |
+ (domain.charCodeAt(i+i+i) & 0x01) << 0;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.makeCategoryKey = function(category) {
+ return String.fromCharCode(category);
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.addAnyPartyHostname = function(hostname) {
+ if ( this.blockedAnyPartyHostnames.add(hostname) ) {
+ this.blockFilterCount += 1;
+ return true;
+ }
+ return false;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.add3rdPartyHostname = function(hostname) {
+ if ( this.blocked3rdPartyHostnames.add(hostname) ) {
+ this.blockFilterCount += 1;
+ return true;
+ }
+ return false;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.add = function(s) {
+ // ORDER OF TESTS IS IMPORTANT!
+
+ // Ignore empty lines
+ if ( reIgnoreEmpty.test(s) ) {
+ return false;
+ }
+
+ // Ignore comments
+ if ( reIgnoreComment.test(s) ) {
+ return false;
+ }
+
+ var parsed = this.filterParser.parse(s);
+
+ // Ignore element-hiding filters
+ if ( parsed.elemHiding ) {
+ return false;
+ }
+
+ if ( this.duplicates[s] ) {
+ return false;
+ }
+ this.duplicates[s] = true;
+
+ this.processedFilterCount += 1;
+
+ // Ignore rules with other conditions for now
+ if ( parsed.unsupported ) {
+ // console.log('µBlock> abp-filter.js/FilterContainer.add(): unsupported filter "%s"', s);
+ return false;
+ }
+
+ this.supportedFilterCount += 1;
+
+ // Ignore optionless hostname rules, these will be taken care of by µBlock.
+ if ( parsed.hostname && parsed.fopts === '' && parsed.action === BlockAction && reHostnameRule.test(parsed.f) ) {
+ return false;
+ }
+
+ // Pure third-party hostnames, use more efficient liquid dict
+ if ( reHostnameRule.test(parsed.f) && parsed.hostname && parsed.action === BlockAction ) {
+ if ( parsed.fopts === 'third-party' ) {
+ return this.blocked3rdPartyHostnames.add(parsed.f);
+ }
+ if ( parsed.fopts === '' ) {
+ return this.blockedAnyPartyHostnames.add(parsed.f);
+ }
+ }
+
+ var r = this.addFilter(parsed);
+ if ( r === false ) {
+ return false;
+ }
+
+ if ( parsed.action ) {
+ this.allowFilterCount += 1;
+ } else {
+ this.blockFilterCount += 1;
+ }
+ return true;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.addFilter = function(parsed) {
+ // TODO: avoid duplicates
+
+ var matches = parsed.hostname ? findHostnameToken(parsed.f) : findFirstGoodToken(parsed.f);
+ if ( !matches || !matches[0].length ) {
+ return false;
+ }
+ var tokenBeg = matches.index;
+ var tokenEnd = parsed.hostname ? reHostnameToken.lastIndex : reGoodToken.lastIndex;
+ var i, n, filter;
+
+ if ( parsed.hostnames.length || parsed.notHostnames.length ) {
+ n = parsed.hostnames.length;
+ for ( i = 0; i < n; i++ ) {
+ filter = makeHostnameFilter(parsed, tokenBeg, parsed.hostnames[i]);
+ if ( !filter ) {
+ return false;
+ }
+ this.addFilterEntry(
+ filter,
+ parsed,
+ SpecificParty | this.toDomainBits(parsed.domains[i]),
+ tokenBeg,
+ tokenEnd
+ );
+ }
+ n = parsed.notHostnames.length;
+ for ( i = 0; i < n; i++ ) {
+ filter = makeNotHostnameFilter(parsed, tokenBeg, parsed.notHostnames[i]);
+ if ( !filter ) {
+ return false;
+ }
+ this.addFilterEntry(
+ filter,
+ parsed,
+ SpecificNotParty | this.toDomainBits(parsed.notDomains[i]),
+ tokenBeg,
+ tokenEnd
+ );
+ }
+ } else {
+ filter = makeFilter(parsed, tokenBeg);
+ if ( !filter ) {
+ return false;
+ }
+ if ( parsed.firstParty ) {
+ this.addFilterEntry(filter, parsed, FirstParty, tokenBeg, tokenEnd);
+ } else if ( parsed.thirdParty ) {
+ this.addFilterEntry(filter, parsed, ThirdParty, tokenBeg, tokenEnd);
+ } else {
+ this.addFilterEntry(filter, parsed, AnyParty, tokenBeg, tokenEnd);
+ }
+ }
+ return true;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.addFilterEntry = function(filter, parsed, party, tokenBeg, tokenEnd) {
+ var s = parsed.f;
+ var prefixKey = trimChar(s.substring(tokenBeg - 1, tokenBeg), '*');
+ var suffixKey = trimChar(s.substring(tokenEnd, tokenEnd + 1), '*');
+ var tokenKey = prefixKey + s.slice(tokenBeg, tokenEnd) + suffixKey;
+ if ( parsed.types.length === 0 ) {
+ this.addToCategory(parsed.action | AnyType | party, tokenKey, filter);
+ return;
+ }
+ var n = parsed.types.length;
+ for ( var i = 0; i < n; i++ ) {
+ this.addToCategory(parsed.action | parsed.types[i] | party, tokenKey, filter);
+ }
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.addToCategory = function(category, tokenKey, filter) {
+ var categoryKey = this.makeCategoryKey(category);
+ var categoryBucket = this.categories[categoryKey];
+ if ( !categoryBucket ) {
+ categoryBucket = this.categories[categoryKey] = {};
+ }
+ var filterEntry = categoryBucket[tokenKey];
+ if ( filterEntry === undefined ) {
+ categoryBucket[tokenKey] = filter;
+ return;
+ }
+ if ( filterEntry instanceof FilterBucket ) {
+ filterEntry.add(filter);
+ return;
+ }
+ categoryBucket[tokenKey] = new FilterBucket(filterEntry, filter);
+};
+
+/******************************************************************************/
+
+// Reset all, thus reducing to a minimum memory footprint of the context.
+
+FilterContainer.prototype.reset = function() {
+ this.processedFilterCount = 0;
+ this.supportedFilterCount = 0;
+ this.allowFilterCount = 0;
+ this.blockFilterCount = 0;
+ this.categories = {};
+ this.blockedAnyPartyHostnames.reset();
+ this.blocked3rdPartyHostnames.reset();
+ this.duplicates = {};
+ this.filterParser.reset();
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.freeze = function() {
+ // histogram('allFilters', this.categories);
+ this.blockedAnyPartyHostnames.freeze();
+ this.blocked3rdPartyHostnames.freeze();
+ this.duplicates = {};
+ this.filterParser.reset();
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.matchToken = function(bucket) {
+ var url = this.url;
+ var beg = this.matches.index;
+ var end = this.reAnyToken.lastIndex;
+ var f;
+ if ( end !== url.length ) {
+ if ( beg !== 0 ) {
+ f = bucket[url.slice(beg-1, end+1)];
+ if ( f !== undefined && f.match(url, beg) !== false ) {
+ return f.s;
+ }
+ }
+ f = bucket[url.slice(beg, end+1)];
+ if ( f !== undefined && f.match(url, beg) !== false ) {
+ return f.s;
+ }
+ }
+ if ( beg !== 0 ) {
+ f = bucket[url.slice(beg-1, end)];
+ if ( f !== undefined && f.match(url, beg) !== false ) {
+ return f.s;
+ }
+ }
+ f = bucket[url.slice(beg, end)];
+ if ( f !== undefined && f.match(url, beg) !== false ) {
+ return f.s;
+ }
+ return false;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.matchTokens = function() {
+ var url = this.url;
+ var re = this.reAnyToken;
+ var r;
+
+ re.lastIndex = 0;
+ while ( this.matches = re.exec(url) ) {
+ if ( this.bucket0 ) {
+ r = this.matchToken(this.bucket0);
+ if ( r !== false ) { return r; }
+ }
+ if ( this.bucket1 ) {
+ r = this.matchToken(this.bucket1);
+ if ( r !== false ) { return r; }
+ }
+ if ( this.bucket2 ) {
+ r = this.matchToken(this.bucket2);
+ if ( r !== false ) { return r; }
+ }
+ if ( this.bucket3 ) {
+ r = this.matchToken(this.bucket3);
+ if ( r !== false ) { return r; }
+ }
+ if ( this.bucket4 ) {
+ r = this.matchToken(this.bucket4);
+ if ( r !== false ) { return r; }
+ }
+ if ( this.bucket5 ) {
+ r = this.matchToken(this.bucket5);
+ if ( r !== false ) { return r; }
+ }
+ if ( this.bucket6 ) {
+ r = this.matchToken(this.bucket6);
+ if ( r !== false ) { return r; }
+ }
+ if ( this.bucket7 ) {
+ r = this.matchToken(this.bucket7);
+ if ( r !== false ) { return r; }
+ }
+ }
+ return false;
+};
+
+/******************************************************************************/
+
+// This is where we test filters which have the form:
+//
+// `||www.example.com^`
+//
+// Because LiquidDict is well optimized to deal with plain hostname, we gain
+// reusing it here for these sort of filters rather than using filters
+// specialized to deal with other complex filters.
+
+FilterContainer.prototype.matchAnyPartyHostname = function(requestHostname) {
+ // Quick test first
+ if ( this.blockedAnyPartyHostnames.test(requestHostname) ) {
+ return '||' + requestHostname + '^';
+ }
+ // Check parent hostnames if quick test failed
+ var hostnames = µBlock.URI.parentHostnamesFromHostname(requestHostname);
+ for ( var i = 0, n = hostnames.length; i < n; i++ ) {
+ if ( this.blockedAnyPartyHostnames.test(hostnames[i]) ) {
+ return '||' + hostnames[i] + '^';
+ }
+ }
+ return false;
+};
+
+/******************************************************************************/
+
+// This is where we test filters which have the form:
+//
+// `||www.example.com^$third-party`
+//
+// Because LiquidDict is well optimized to deal with plain hostname, we gain
+// reusing it here for these sort of filters rather than using filters
+// specialized to deal with other complex filters.
+
+FilterContainer.prototype.match3rdPartyHostname = function(requestHostname) {
+ // Quick test first
+ if ( this.blocked3rdPartyHostnames.test(requestHostname) ) {
+ return '||' + requestHostname + '^$third-party';
+ }
+ // Check parent hostnames if quick test failed
+ var hostnames = µBlock.URI.parentHostnamesFromHostname(requestHostname);
+ for ( var i = 0, n = hostnames.length; i < n; i++ ) {
+ if ( this.blocked3rdPartyHostnames.test(hostnames[i]) ) {
+ return '||' + hostnames[i] + '^$third-party';
+ }
+ }
+ return false;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.matchString = function(pageStore, url, requestType, requestHostname) {
+ // adbProfiler.countUrl();
+
+ // https://github.com/gorhill/httpswitchboard/issues/239
+ // Convert url to lower case:
+ // `match-case` option not supported, but then, I saw only one
+ // occurrence of it in all the supported lists (bulgaria list).
+ this.url = url.toLowerCase();
+
+ // The logic here is simple:
+ //
+ // block = !whitelisted && blacklisted
+ // or equivalent
+ // allow = whitelisted || !blacklisted
+
+ // Since statistically a hit on a block filter is more likely than a hit
+ // on an allow filter, we test block filters first, and then if and only
+ // if there is a hit on a block filter do we test against allow filters.
+ // This helps performance compared to testing against both classes of
+ // filters in the same loop.
+
+ var pageDomain = pageStore.pageDomain || '';
+ var party = requestHostname.slice(-pageDomain.length) === pageDomain ?
+ FirstParty :
+ ThirdParty;
+ var domainParty = this.toDomainBits(pageDomain);
+ var type = typeNameToTypeValue[requestType];
+ var categories = this.categories;
+
+ // This will be used by hostname-based filters
+ pageHostname = pageStore.pageHostname || '';
+
+ // Test hostname-based block filters
+ var bf = false;
+ bf = this.matchAnyPartyHostname(requestHostname);
+ if ( bf === false && party === ThirdParty ) {
+ bf = this.match3rdPartyHostname(requestHostname);
+ }
+
+ // Test against block filters
+ if ( bf === false ) {
+ this.bucket0 = categories[this.makeCategoryKey(BlockAnyTypeAnyParty)];
+ this.bucket1 = categories[this.makeCategoryKey(BlockAnyType | party)];
+ this.bucket2 = categories[this.makeCategoryKey(BlockAnyTypeOneParty | domainParty)];
+ this.bucket3 = categories[this.makeCategoryKey(BlockAnyTypeOtherParties | domainParty)];
+ this.bucket4 = categories[this.makeCategoryKey(BlockAnyParty | type)];
+ this.bucket5 = categories[this.makeCategoryKey(BlockAction | type | party)];
+ this.bucket6 = categories[this.makeCategoryKey(BlockOneParty | type | domainParty)];
+ this.bucket7 = categories[this.makeCategoryKey(BlockOtherParties | type | domainParty)];
+
+ bf = this.matchTokens();
+ }
+
+ // If there is no block filter, no need to test against allow filters
+ if ( bf === false ) {
+ return false;
+ }
+
+ // Test against allow filters
+ this.bucket0 = categories[this.makeCategoryKey(AllowAnyTypeAnyParty)];
+ this.bucket1 = categories[this.makeCategoryKey(AllowAnyType | party)];
+ this.bucket2 = categories[this.makeCategoryKey(AllowAnyTypeOneParty | domainParty)];
+ this.bucket3 = categories[this.makeCategoryKey(AllowAnyTypeOtherParties | domainParty)];
+ this.bucket4 = categories[this.makeCategoryKey(AllowAnyParty | type)];
+ this.bucket5 = categories[this.makeCategoryKey(AllowAction | type | party)];
+ this.bucket6 = categories[this.makeCategoryKey(AllowOneParty | type | domainParty)];
+ this.bucket7 = categories[this.makeCategoryKey(AllowOtherParties | type | domainParty)];
+
+ if ( this.matchTokens() !== false ) {
+ return false;
+ }
+
+ return bf;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.getFilterCount = function() {
+ return this.blockFilterCount + this.allowFilterCount;
+};
+
+/******************************************************************************/
+
+return new FilterContainer();
+
+/******************************************************************************/
+
+})();
diff --git a/js/abp-hide-filters.js b/js/abp-hide-filters.js
new file mode 100644
index 000000000..3f4bfdde5
--- /dev/null
+++ b/js/abp-hide-filters.js
@@ -0,0 +1,681 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* jshint bitwise: false */
+/* global µBlock */
+
+/******************************************************************************/
+
+µBlock.abpHideFilters = (function(){
+
+
+/******************************************************************************/
+
+var µb = µBlock;
+var pageHostname = '';
+//var filterTestCount = 0;
+//var bucketTestCount = 0;
+
+/******************************************************************************/
+/*
+var histogram = function(label, buckets) {
+ var h = [],
+ bucket;
+ for ( var k in buckets ) {
+ if ( buckets.hasOwnProperty(k) === false ) {
+ continue;
+ }
+ bucket = buckets[k];
+ h.push({
+ k: k,
+ n: bucket instanceof FilterBucket ? bucket.filters.length : 1
+ });
+ }
+
+ console.log('Histogram %s', label);
+
+ var total = h.length;
+ h.sort(function(a, b) { return b.n - a.n; });
+
+ // Find indices of entries of interest
+ var target = 3;
+ for ( var i = 0; i < total; i++ ) {
+ if ( h[i].n === target ) {
+ console.log('\tEntries with only %d filter(s) start at index %s (key = "%s")', target, i, h[i].k);
+ target -= 1;
+ }
+ }
+
+ h = h.slice(0, 50);
+
+ h.forEach(function(v) {
+ console.log('\tkey="%s" count=%d', v.k, v.n);
+ });
+ console.log('\tTotal buckets count: %d', total);
+};
+*/
+/******************************************************************************/
+
+// Pure id- and class-based filters
+// Examples:
+// #A9AdsMiddleBoxTop
+// .AD-POST
+
+var FilterPlain = function(s) {
+ this.s = s;
+};
+
+FilterPlain.prototype.retrieve = function(s, out) {
+ if ( s === this.s ) {
+ out.push(this.s);
+ }
+};
+
+/******************************************************************************/
+
+// Id- and class-based filters with extra selector stuff following.
+// Examples:
+// #center_col > div[style="font-size:14px;margin-right:0;min-height:5px"] ...
+// #adframe:not(frameset)
+// .l-container > #fishtank
+
+var FilterPlainMore = function(s) {
+ this.s = s;
+};
+
+FilterPlainMore.prototype.retrieve = function(s, out) {
+ if ( s === this.s.slice(0, s.length) ) {
+ out.push(this.s);
+ }
+};
+
+/******************************************************************************/
+
+// Any selector specific to a hostname
+// Examples:
+// search.snapdo.com###ABottomD
+// facebook.com##.-cx-PRIVATE-fbAdUnit__root
+// sltrib.com###BLContainer + div[style="height:90px;"]
+// myps3.com.au##.Boxer[style="height: 250px;"]
+// lindaikeji.blogspot.com##a > img[height="600"]
+// japantimes.co.jp##table[align="right"][width="250"]
+// mobilephonetalk.com##[align="center"] > b > a[href^="http://tinyurl.com/"]
+
+var FilterHostname = function(s, hostname) {
+ this.s = s;
+ this.hostname = hostname;
+};
+
+FilterHostname.prototype.retrieve = function(s, out) {
+ if ( pageHostname.slice(-this.hostname.length) === this.hostname ) {
+ out.push(this.s);
+ }
+};
+
+/******************************************************************************/
+/******************************************************************************/
+
+// TODO: evaluate the gain (if any) from avoiding the use of an array for when
+// there are only two filters (or three, etc.). I suppose there is a specific
+// number of filters below which using an array is more of an overhead than
+// using a couple of property members.
+// i.e. FilterBucket2, FilterBucket3, FilterBucketN.
+
+var FilterBucket = function(a, b) {
+ this.filters = [a, b];
+};
+
+FilterBucket.prototype.add = function(a) {
+ this.filters.push(a);
+};
+
+FilterBucket.prototype.retrieve = function(s, out) {
+ var i = this.filters.length;
+ //filterTestCount += i - 1;
+ while ( i-- ) {
+ this.filters[i].retrieve(s, out);
+ }
+};
+
+/******************************************************************************/
+/******************************************************************************/
+
+var FilterParser = function() {
+ this.s = '';
+ this.prefix = '';
+ this.suffix = '';
+ this.anchor = 0;
+ this.filterType = '#';
+ this.hostnames = [];
+ this.invalid = false;
+ this.unsupported = false;
+ this.reParser = /^\s*([^#]*)(##|#@#)(.+)\s*$/;
+ this.rePlain = /^([#.][\w-]+)/;
+ this.rePlainMore = /^[#.][\w-]+[^\w-]/;
+ this.reElement = /^[a-z]/i;
+};
+
+/******************************************************************************/
+
+FilterParser.prototype.reset = function() {
+ this.s = '';
+ this.prefix = '';
+ this.suffix = '';
+ this.anchor = '';
+ this.filterType = '#';
+ this.hostnames = [];
+ this.invalid = false;
+ return this;
+};
+
+/******************************************************************************/
+
+FilterParser.prototype.parse = function(s) {
+ // important!
+ this.reset();
+
+ var matches = this.reParser.exec(s);
+ if ( matches === null || matches.length !== 4 ) {
+ this.invalid = true;
+ return this;
+ }
+
+ // Remember original string
+ this.s = s;
+ this.prefix = matches[1];
+ this.anchor = matches[2];
+ this.suffix = matches[3];
+
+ // 2014-05-23:
+ // https://github.com/gorhill/httpswitchboard/issues/260
+ // Any sequence of `#` longer than one means the line is not a valid
+ // cosmetic filter.
+ if ( this.suffix.indexOf('##') >= 0 ) {
+ this.invalid = true;
+ return this;
+ }
+
+ this.filterType = this.anchor.charAt(1);
+ if ( this.prefix !== '' ) {
+ this.hostnames = this.prefix.split(/\s*,\s*/);
+ }
+ return this;
+};
+
+/******************************************************************************/
+
+FilterParser.prototype.isPlainMore = function() {
+ return this.rePlainMore.test(this.suffix);
+};
+
+/******************************************************************************/
+
+FilterParser.prototype.isElement = function() {
+ return this.reElement.test(this.suffix);
+};
+
+/******************************************************************************/
+
+FilterParser.prototype.extractPlain = function() {
+ var matches = this.rePlain.exec(this.suffix);
+ if ( matches && matches.length === 2 ) {
+ return matches[1];
+ }
+ return '';
+};
+
+/******************************************************************************/
+/******************************************************************************/
+
+var FilterContainer = function() {
+ this.filterParser = new FilterParser();
+ this.acceptedCount = 0;
+ this.processedCount = 0;
+ this.filters = {};
+ this.hideUnfiltered = [];
+ this.donthideUnfiltered = [];
+ this.rejected = [];
+};
+
+/******************************************************************************/
+
+// Reset all, thus reducing to a minimum memory footprint of the context.
+
+FilterContainer.prototype.reset = function() {
+ this.filterParser.reset();
+ this.acceptedCount = 0;
+ this.processedCount = 0;
+ this.filters = {};
+ this.hideUnfiltered = [];
+ this.donthideUnfiltered = [];
+ this.rejected = [];
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.add = function(s) {
+ var parsed = this.filterParser.parse(s);
+ if ( parsed.invalid ) {
+ return false;
+ }
+
+ this.processedCount += 1;
+
+ //if ( s === 'mail.google.com##.nH.adC > .nH > .nH > .u5 > .azN' ) {
+ // debugger;
+ //}
+
+ // hostname-based filters: with a hostname, narrowing is good enough, no
+ // need to further narrow.
+ if ( parsed.hostnames.length ) {
+ return this.addHostnameFilter(parsed);
+ }
+
+ // no specific hostname, narrow using class or id.
+ var selectorType = parsed.suffix.charAt(0);
+ if ( selectorType === '#' || selectorType === '.' ) {
+ return this.addPlainFilter(parsed);
+ }
+
+ // no specific hostname, no class, no id.
+ // TO IMPLEMENT
+ // My idea of implementation so far is to return a pre-built container
+ // of these very generic filter, and let the content script sort out
+ // what it needs from it. Filters in that category are mostly
+ // `a[href^="..."]` kind of filters.
+ // Content script side, the unsorted container of selectors could be used
+ // in a querySelectorAll() to figure which rules apply (if any), or they
+ // could just all be injected undiscriminately (not good).
+ if ( parsed.filterType === '#' ) {
+ this.hideUnfiltered.push(parsed.suffix);
+ } else {
+ this.donthideUnfiltered.push(parsed.suffix);
+ }
+ this.acceptedCount += 1;
+
+ return true;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.chunkify = function(selectors) {
+ var chunkified = [], chunk;
+ for (;;) {
+ chunk = selectors.splice(0, 10);
+ if ( chunk.length === 0 ) {
+ break;
+ }
+ chunkified.push(chunk.join(','));
+ }
+ return chunkified;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.freeze = function() {
+ this.hideUnfiltered = this.chunkify(this.hideUnfiltered);
+ this.donthideUnfiltered = this.chunkify(this.donthideUnfiltered);
+
+ this.filterParser.reset();
+
+ //console.log('µBlock> adp-hide-filters.js: %d filters accepted', this.acceptedCount);
+ //console.log('µBlock> adp-hide-filters.js: %d filters processed', this.processedCount);
+ //console.log('µBlock> adp-hide-filters.js: coverage is %s%', (this.acceptedCount * 100 / this.processedCount).toFixed(1));
+ //console.log('µBlock> adp-hide-filters.js: unfiltered hide selectors:', this.hideUnfiltered);
+ //console.log('µBlock> adp-hide-filters.js: unfiltered dont hide selectors:', this.donthideUnfiltered);
+ //console.log('µBlock> adp-hide-filters.js: rejected selectors:', this.rejected);
+
+ // histogram('allFilters', this.filters);
+};
+
+/******************************************************************************/
+
+// Is
+// 3 unicode chars
+// | | | |
+//
+// 00000000 TTTTTTTT PP PP PP PP PP PP PP PP SS SS SS SS SS SS SS SS
+// | | |
+// | | |
+// | | |
+// | | ls 2-bit of 8 suffix chars
+// | |
+// | +-- ls 2-bit of 8 prefix chars
+// |
+// |
+// +-- filter type ('#'=hide '@'=unhide)
+//
+
+var makePrefixHash = function(type, prefix) {
+ // Ref: Given a URL, returns a unique 4-character long hash string
+ // Based on: FNV32a
+ // http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-reference-source
+ // The rest is custom, suited for µBlock.
+ var len = prefix.length;
+ var i2 = len >> 1;
+ var i4 = len >> 2;
+ var i8 = len >> 3;
+ var hint = (0x811c9dc5 ^ prefix.charCodeAt(0)) >>> 0;
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= prefix.charCodeAt(i8);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= prefix.charCodeAt(i4);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= prefix.charCodeAt(i4+i8);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= prefix.charCodeAt(i2);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= prefix.charCodeAt(i2+i8);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= prefix.charCodeAt(i2+i4);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= prefix.charCodeAt(len-1);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ return String.fromCharCode(type.charCodeAt(0), hint & 0xFFFF, 0);
+};
+
+var makeSuffixHash = function(type, suffix) {
+ var len = suffix.length;
+ var i2 = len >> 1;
+ var i4 = len >> 2;
+ var i8 = len >> 3;
+ var hint = (0x811c9dc5 ^ suffix.charCodeAt(0)) >>> 0;
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= suffix.charCodeAt(i8);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= suffix.charCodeAt(i4);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= suffix.charCodeAt(i4+i8);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= suffix.charCodeAt(i2);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= suffix.charCodeAt(i2+i8);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= suffix.charCodeAt(i2+i4);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ hint ^= suffix.charCodeAt(len-1);
+ hint += (hint<<1) + (hint<<4) + (hint<<7) + (hint<<8) + (hint<<24);
+ hint >>>= 0;
+ return String.fromCharCode(type.charCodeAt(0), 0, hint & 0x0FFF);
+};
+
+/**
+Histogram for above hash generator:
+
+Histogram allFilters
+ Entries with only 3 filter(s) start at index 2706 (key = "#ꍵ")
+ Entries with only 2 filter(s) start at index 4349 (key = "#냶")
+ Entries with only 1 filter(s) start at index 6896 (key = "#퀛")
+ key="#싣" count=141
+ key="#隁" count=57
+ key="#Ꚇ" count=48
+ key="#" count=45
+ key="#캃" count=36
+ key="#력" count=33
+ key="#끻" count=30
+ key="#u" count=26
+ key="#" count=25
+ key="#Ꮳ" count=24
+ key="#鵲" count=23
+ key="#䙇" count=20
+ key="#ḇ" count=19
+ key="#睅" count=19
+ key="#㔽" count=19
+ key="#뻧" count=18
+ key="#䕀" count=18
+ key="#퉫" count=17
+ key="#筙" count=17
+ key="#㮰" count=17
+ key="#鯛" count=16
+ key="#" count=16
+ key="#꣱" count=16
+ key="#ü" count=16
+ key="#告" count=16
+ key="#╡" count=16
+ key="#㰁" count=16
+ key="#৹" count=16
+ key="#镳" count=15
+ key="#碇" count=15
+ key="#৾" count=15
+ key="#貿" count=15
+ key="#š" count=15
+ key="#" count=15
+ key="#" count=14
+ key="#ຏ" count=14
+ key="#낶" count=14
+ key="#瑻" count=14
+ key="#ৡ" count=14
+ key="#" count=13
+ key="#ᯋ" count=13
+ key="#⼒" count=13
+ key="#腫" count=13
+ key="#겚" count=13
+ key="#耏" count=13
+ key="#匋" count=13
+ key="#튦" count=13
+ key="#ﰹ" count=13
+ key="#㭴" count=13
+ key="#" count=13
+ Total buckets count: 12098
+*/
+
+/******************************************************************************/
+
+FilterContainer.prototype.addPlainFilter = function(parsed) {
+ // Verify whether the plain selector is followed by extra selector stuff
+ if ( parsed.isPlainMore() ) {
+ return this.addPlainMoreFilter(parsed);
+ }
+ var f = new FilterPlain(parsed.suffix);
+ var hash = makeSuffixHash(parsed.filterType, parsed.suffix);
+ this.addFilterEntry(hash, f);
+ this.acceptedCount += 1;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.addPlainMoreFilter = function(parsed) {
+ var selectorSuffix = parsed.extractPlain();
+ if ( selectorSuffix === '' ) {
+ return;
+ }
+ var f = new FilterPlainMore(parsed.suffix);
+ var hash = makeSuffixHash(parsed.filterType, selectorSuffix);
+ this.addFilterEntry(hash, f);
+ this.acceptedCount += 1;
+};
+
+/******************************************************************************/
+
+// rhill 2014-05-20: When a domain exists, just specify a generic selector.
+
+FilterContainer.prototype.addHostnameFilter = function(parsed) {
+ var µburi = µBlock.URI;
+ var f, hash;
+ var hostnames = parsed.hostnames;
+ var i = hostnames.length, hostname;
+ while ( i-- ) {
+ hostname = hostnames[i];
+ if ( !hostname ) {
+ continue;
+ }
+ f = new FilterHostname(parsed.suffix, hostname);
+ hash = makePrefixHash(parsed.filterType, µburi.domainFromHostname(hostname));
+ this.addFilterEntry(hash, f);
+ }
+ this.acceptedCount += 1;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.addFilterEntry = function(hash, f) {
+ var bucket = this.filters[hash];
+ if ( bucket === undefined ) {
+ this.filters[hash] = f;
+ } else if ( bucket instanceof FilterBucket ) {
+ bucket.add(f);
+ } else {
+ this.filters[hash] = new FilterBucket(bucket, f);
+ }
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.retrieveGenericSelectors = function(request) {
+ if ( µb.userSettings.parseAllABPHideFilters !== true ) {
+ return;
+ }
+
+ if ( !request.selectors ) {
+ return;
+ }
+
+ //quickProfiler.start('FilterContainer.retrieve()');
+
+ //filterTestCount = 0;
+ //bucketTestCount = 0;
+
+ var r = {
+ hide: [],
+ donthide: [],
+ hideUnfiltered: [],
+ donthideUnfiltered: []
+ };
+
+ var hash, bucket;
+ var hideSelectors = r.hide;
+ var selectors = request.selectors;
+ var i = selectors.length;
+ var selector;
+ while ( i-- ) {
+ selector = selectors[i];
+ if ( !selector ) {
+ continue;
+ }
+ hash = makeSuffixHash('#', selector);
+ if ( bucket = this.filters[hash] ) {
+ //bucketTestCount += 1;
+ //filterTestCount += 1;
+ bucket.retrieve(selector, hideSelectors);
+ }
+ }
+
+ r.hideUnfiltered = this.hideUnfiltered;
+ r.donthideUnfiltered = this.donthideUnfiltered;
+
+ //quickProfiler.stop();
+
+/*
+ console.log(
+ 'µBlock> abp-hide-filters.js: "%s"\n\t%d selectors in => %d/%d filters/buckets tested => %d selectors out',
+ url,
+ inSelectors.length,
+ //filterTestCount,
+ //bucketTestCount,
+ hideSelectors.length + donthideSelectors.length
+ );
+*/
+
+ return r;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.retrieveDomainSelectors = function(request) {
+ if ( µb.userSettings.parseAllABPHideFilters !== true ) {
+ return;
+ }
+
+ if ( !request.locationURL ) {
+ return;
+ }
+
+ //quickProfiler.start('FilterContainer.retrieve()');
+
+ //filterTestCount = 0;
+ //bucketTestCount = 0;
+
+ var hostname = pageHostname = µb.URI.hostnameFromURI(request.locationURL);
+ var r = {
+ domain: µb.URI.domainFromHostname(hostname),
+ hide: [],
+ donthide: []
+ };
+ var bucket;
+ var hash = makePrefixHash('#', r.domain);
+ if ( bucket = this.filters[hash] ) {
+ //bucketTestCount += 1;
+ //filterTestCount += 1;
+ bucket.retrieve(null, r.hide);
+ }
+ hash = makePrefixHash('@', r.domain);
+ if ( bucket = this.filters[hash] ) {
+ //bucketTestCount += 1;
+ //filterTestCount += 1;
+ bucket.retrieve(null, r.donthide);
+ }
+
+ //quickProfiler.stop();
+
+/*
+ console.log(
+ 'µBlock> abp-hide-filters.js: "%s"\n\t%d selectors in => %d/%d filters/buckets tested => %d selectors out',
+ url,
+ inSelectors.length,
+ //filterTestCount,
+ //bucketTestCount,
+ hideSelectors.length + donthideSelectors.length
+ );
+*/
+
+ return r;
+};
+
+/******************************************************************************/
+
+FilterContainer.prototype.getFilterCount = function() {
+ return this.acceptedCount;
+};
+
+/******************************************************************************/
+
+return new FilterContainer();
+
+/******************************************************************************/
+
+})();
+
+/******************************************************************************/
diff --git a/js/asset-updater.js b/js/asset-updater.js
new file mode 100644
index 000000000..5ce68031c
--- /dev/null
+++ b/js/asset-updater.js
@@ -0,0 +1,224 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global chrome, µBlock */
+
+/******************************************************************************/
+
+// Asset update manager
+
+µBlock.assetUpdater = (function() {
+
+/******************************************************************************/
+
+var getUpdateList = function(callback) {
+ var localChecksumsText = '';
+ var remoteChecksumsText = '';
+
+ var compareChecksums = function() {
+ var parseChecksumsText = function(text) {
+ var result = {};
+ var lines = text.split(/\n+/);
+ var i = lines.length;
+ var fields;
+ while ( i-- ) {
+ fields = lines[i].trim().split(/\s+/);
+ if ( fields.length !== 2 ) {
+ continue;
+ }
+ result[fields[1]] = fields[0];
+ }
+ return result;
+ };
+ if ( remoteChecksumsText === 'Error' || localChecksumsText === 'Error' ) {
+ remoteChecksumsText = localChecksumsText = '';
+ }
+ var localAssetChecksums = parseChecksumsText(localChecksumsText);
+ var remoteAssetChecksums = parseChecksumsText(remoteChecksumsText);
+
+ var toUpdate = {};
+ var path;
+ for ( path in remoteAssetChecksums ) {
+ if ( !remoteAssetChecksums.hasOwnProperty(path) ) {
+ continue;
+ }
+ if ( localAssetChecksums[path] === undefined ) {
+ toUpdate[path] = {
+ status: 'Added',
+ remoteChecksum: remoteAssetChecksums[path],
+ localChecksum: ''
+ };
+ continue;
+ }
+ if ( localAssetChecksums[path] === remoteAssetChecksums[path] ) {
+ toUpdate[path] = {
+ status: 'Unchanged',
+ remoteChecksum: remoteAssetChecksums[path],
+ localChecksum: localAssetChecksums[path]
+ };
+ continue;
+ }
+ toUpdate[path] = {
+ status: 'Changed',
+ remoteChecksum: remoteAssetChecksums[path],
+ localChecksum: localAssetChecksums[path]
+ };
+ }
+ for ( path in localAssetChecksums ) {
+ if ( !localAssetChecksums.hasOwnProperty(path) ) {
+ continue;
+ }
+ if ( remoteAssetChecksums[path] === undefined ) {
+ toUpdate[path] = {
+ status: 'Removed',
+ remoteChecksum: '',
+ localChecksum: localAssetChecksums[path]
+ };
+ }
+ }
+
+ callback({ 'list': toUpdate });
+ };
+
+ var validateChecksums = function(details) {
+ if ( details.error || details.content === '' ) {
+ return 'Error';
+ }
+ if ( /^(?:[0-9a-f]{32}\s+\S+(\s+|$))+/.test(details.content) ) {
+ return details.content;
+ }
+ return 'Error';
+ };
+
+ var onLocalChecksumsLoaded = function(details) {
+ localChecksumsText = validateChecksums(details);
+ if ( remoteChecksumsText !== '' ) {
+ compareChecksums();
+ }
+ };
+
+ var onRemoteChecksumsLoaded = function(details) {
+ remoteChecksumsText = validateChecksums(details);
+ if ( localChecksumsText !== '' ) {
+ compareChecksums();
+ }
+ };
+
+ µBlock.assets.getRemote('assets/checksums.txt', onRemoteChecksumsLoaded);
+ µBlock.assets.get('assets/checksums.txt', onLocalChecksumsLoaded);
+};
+
+/******************************************************************************/
+
+// If `list` is null, it will be fetched internally.
+
+var update = function(list, callback) {
+ var assetChangedCount = 0;
+ var assetProcessedCount;
+ var updatedAssetChecksums = [];
+
+ var onCompleted = function() {
+ var details = {
+ what: 'allLocalAssetsUpdated',
+ changedCount: assetChangedCount
+ };
+ callback(details);
+ µBlock.messaging.announce(details);
+ };
+
+ var doCountdown = function() {
+ assetProcessedCount -= 1;
+ if ( assetProcessedCount > 0 ) {
+ return;
+ }
+ µBlock.assets.put(
+ 'assets/checksums.txt',
+ updatedAssetChecksums.join('\n'),
+ onCompleted
+ );
+ chrome.storage.local.set({ 'assetsUpdateTimestamp': Date.now() });
+ };
+
+ var assetUpdated = function(details) {
+ var path = details.path;
+ var entry = list[path];
+ if ( details.error ) {
+ updatedAssetChecksums.push(entry.localChecksum + ' ' + path);
+ } else {
+ updatedAssetChecksums.push(entry.remoteChecksum + ' ' + path);
+ assetChangedCount += 1;
+ }
+ doCountdown();
+ };
+
+ var processList = function() {
+ assetProcessedCount = Object.keys(list).length;
+ if ( assetProcessedCount === 0 ) {
+ onCompleted();
+ return;
+ }
+ var entry;
+ var details = { path: '', md5: '' };
+ for ( var path in list ) {
+ if ( list.hasOwnProperty(path) === false ) {
+ continue;
+ }
+ entry = list[path];
+ if ( entry.status === 'Added' || entry.status === 'Changed' ) {
+ details.path = path;
+ details.md5 = entry.remoteChecksum;
+ µBlock.assets.update(details, assetUpdated);
+ continue;
+ }
+ if ( entry.status === 'Unchanged' ) {
+ updatedAssetChecksums.push(entry.localChecksum + ' ' + path);
+ }
+ doCountdown();
+ }
+ };
+
+ var listLoaded = function(details) {
+ list = details.list;
+ processList();
+ };
+
+ if ( list ) {
+ processList();
+ } else {
+ getUpdateList(listLoaded);
+ }
+};
+
+/******************************************************************************/
+
+// Export API
+
+return {
+ 'getList': getUpdateList,
+ 'update': update
+};
+
+/******************************************************************************/
+
+})();
+
+/******************************************************************************/
+
diff --git a/js/assets.js b/js/assets.js
new file mode 100644
index 000000000..195fa2861
--- /dev/null
+++ b/js/assets.js
@@ -0,0 +1,415 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global chrome, µBlock */
+
+/*******************************************************************************
+
+Assets
+ Read:
+ If in cache
+ Use cache
+ If not in cache
+ Use local
+ Update:
+ Use remote
+ Save in cache
+
+ Import:
+ Use textarea
+ Save in cache [user directory]
+
+File system structure:
+ assets
+ ublock
+ ...
+ thirdparties
+ ...
+ user
+ blacklisted-hosts.txt
+ ...
+
+*/
+
+// Ref: http://www.w3.org/TR/2012/WD-file-system-api-20120417/
+// Ref: http://www.html5rocks.com/en/tutorials/file/filesystem/
+
+/******************************************************************************/
+
+// Low-level asset files manager
+
+µBlock.assets = (function() {
+
+/******************************************************************************/
+
+var fileSystem;
+var fileSystemQuota = 40 * 1024 * 1024;
+var remoteRoot = µBlock.projectServerRoot;
+
+/******************************************************************************/
+
+var nullFunc = function() { };
+
+/******************************************************************************/
+
+var getTextFileFromURL = function(url, onLoad, onError) {
+ // console.log('µBlock> getTextFileFromURL("%s"):', url);
+ var xhr = new XMLHttpRequest();
+ xhr.responseType = 'text';
+ xhr.onload = onLoad;
+ xhr.onerror = onError;
+ xhr.ontimeout = onError;
+ xhr.open('get', url, true);
+ xhr.send();
+};
+
+/******************************************************************************/
+
+// Useful to avoid having to manage a directory tree
+
+var cachePathFromPath = function(path) {
+ return path.replace(/\//g, '___');
+};
+
+var pathFromCachePath = function(path) {
+ return path.replace(/___/g, '/');
+};
+
+/******************************************************************************/
+
+var requestFileSystem = function(onSuccess, onError) {
+ if ( fileSystem ) {
+ onSuccess(fileSystem);
+ return;
+ }
+
+ var onRequestFileSystem = function(fs) {
+ fileSystem = fs;
+ onSuccess(fs);
+ };
+
+ var onRequestQuota = function(grantedBytes) {
+ window.webkitRequestFileSystem(window.PERSISTENT, grantedBytes, onRequestFileSystem, onError);
+ };
+
+ navigator.webkitPersistentStorage.requestQuota(fileSystemQuota, onRequestQuota, onError);
+};
+
+/******************************************************************************/
+
+// Flush cached non-user assets if these are from a prior version.
+// https://github.com/gorhill/httpswitchboard/issues/212
+
+var cacheSynchronized = false;
+
+var synchronizeCache = function() {
+ if ( cacheSynchronized ) {
+ return;
+ }
+ cacheSynchronized = true;
+
+ var directoryReader;
+ var done = function() {
+ directoryReader = null;
+ };
+
+ var onReadEntries = function(entries) {
+ var n = entries.length;
+ if ( !n ) {
+ return done();
+ }
+ var entry;
+ for ( var i = 0; i < n; i++ ) {
+ entry = entries[i];
+ // Ignore whatever is in 'user' folder: these are NOT cached entries.
+ if ( pathFromCachePath(entry.fullPath).indexOf('/assets/user/') >= 0 ) {
+ continue;
+ }
+ entry.remove(nullFunc);
+ }
+ directoryReader.readEntries(onReadEntries, onReadEntriesError);
+ };
+
+ var onReadEntriesError = function(err) {
+ console.error('µBlock> synchronizeCache() / onReadEntriesError("%s"):', err.name);
+ done();
+ };
+
+ var onRequestFileSystemSuccess = function(fs) {
+ directoryReader = fs.root.createReader();
+ directoryReader.readEntries(onReadEntries, onReadEntriesError);
+ };
+
+ var onRequestFileSystemError = function(err) {
+ console.error('µBlock> synchronizeCache() / onRequestFileSystemError():', err.name);
+ done();
+ };
+
+ var onLastVersionRead = function(store) {
+ var currentVersion = chrome.runtime.getManifest().version;
+ var lastVersion = store.extensionLastVersion || '0.0.0.0';
+ if ( currentVersion === lastVersion ) {
+ return done();
+ }
+ chrome.storage.local.set({ 'extensionLastVersion': currentVersion });
+ requestFileSystem(onRequestFileSystemSuccess, onRequestFileSystemError);
+ };
+
+ chrome.storage.local.get('extensionLastVersion', onLastVersionRead);
+};
+
+/******************************************************************************/
+
+var readLocalFile = function(path, callback) {
+ var reportBack = function(content, err) {
+ var details = {
+ 'path': path,
+ 'content': content,
+ 'error': err
+ };
+ callback(details);
+ };
+
+ var onLocalFileLoaded = function() {
+ // console.log('µBlock> onLocalFileLoaded()');
+ reportBack(this.responseText);
+ this.onload = this.onerror = null;
+ };
+
+ var onLocalFileError = function(ev) {
+ console.error('µBlock> readLocalFile() / onLocalFileError("%s")', path);
+ reportBack('', 'Error');
+ this.onload = this.onerror = null;
+ };
+
+ var onCacheFileLoaded = function() {
+ // console.log('µBlock> readLocalFile() / onCacheFileLoaded()');
+ reportBack(this.responseText);
+ this.onload = this.onerror = null;
+ };
+
+ var onCacheFileError = function(ev) {
+ // This handler may be called under normal circumstances: it appears
+ // the entry may still be present even after the file was removed.
+ // console.error('µBlock> readLocalFile() / onCacheFileError("%s")', path);
+ getTextFileFromURL(chrome.runtime.getURL(path), onLocalFileLoaded, onLocalFileError);
+ this.onload = this.onerror = null;
+ };
+
+ var onCacheEntryFound = function(entry) {
+ // console.log('µBlock> readLocalFile() / onCacheEntryFound():', entry.toURL());
+ // rhill 2014-04-18: `ublock` query parameter is added to ensure
+ // the browser cache is bypassed.
+ getTextFileFromURL(entry.toURL() + '?ublock=' + Date.now(), onCacheFileLoaded, onCacheFileError);
+ };
+
+ var onCacheEntryError = function(err) {
+ if ( err.name !== 'NotFoundError' ) {
+ console.error('µBlock> readLocalFile() / onCacheEntryError("%s"):', path, err.name);
+ }
+ getTextFileFromURL(chrome.runtime.getURL(path), onLocalFileLoaded, onLocalFileError);
+ };
+
+ var onRequestFileSystemSuccess = function(fs) {
+ fs.root.getFile(cachePathFromPath(path), null, onCacheEntryFound, onCacheEntryError);
+ };
+
+ var onRequestFileSystemError = function(err) {
+ console.error('µBlock> readLocalFile() / onRequestFileSystemError():', err.name);
+ getTextFileFromURL(chrome.runtime.getURL(path), onLocalFileLoaded, onLocalFileError);
+ };
+
+ requestFileSystem(onRequestFileSystemSuccess, onRequestFileSystemError);
+};
+
+/******************************************************************************/
+
+var readRemoteFile = function(path, callback) {
+ var reportBack = function(content, err) {
+ var details = {
+ 'path': path,
+ 'content': content,
+ 'error': err
+ };
+ callback(details);
+ };
+
+ var onRemoteFileLoaded = function() {
+ // console.log('µBlock> readRemoteFile() / onRemoteFileLoaded()');
+ // https://github.com/gorhill/httpswitchboard/issues/263
+ if ( this.status === 200 ) {
+ reportBack(this.responseText);
+ } else {
+ reportBack('', 'Error ' + this.statusText);
+ }
+ this.onload = this.onerror = null;
+ };
+
+ var onRemoteFileError = function(ev) {
+ console.error('µBlock> readRemoteFile() / onRemoteFileError("%s")', path);
+ reportBack('', 'Error');
+ this.onload = this.onerror = null;
+ };
+
+ // 'ublock=...' is to skip browser cache
+ getTextFileFromURL(
+ remoteRoot + path + '?ublock=' + Date.now(),
+ onRemoteFileLoaded,
+ onRemoteFileError
+ );
+};
+
+/******************************************************************************/
+
+var writeLocalFile = function(path, content, callback) {
+ var reportBack = function(err) {
+ var details = {
+ 'path': path,
+ 'content': content,
+ 'error': err
+ };
+ callback(details);
+ };
+
+ var onFileWriteSuccess = function() {
+ // console.log('µBlock> writeLocalFile() / onFileWriteSuccess("%s")', path);
+ reportBack();
+ };
+
+ var onFileWriteError = function(err) {
+ console.error('µBlock> writeLocalFile() / onFileWriteError("%s"):', path, err.name);
+ reportBack(err.name);
+ };
+
+ var onFileTruncateSuccess = function() {
+ // console.log('µBlock> writeLocalFile() / onFileTruncateSuccess("%s")', path);
+ this.onwriteend = onFileWriteSuccess;
+ this.onerror = onFileWriteError;
+ var blob = new Blob([content], { type: 'text/plain' });
+ this.write(blob);
+ };
+
+ var onFileTruncateError = function(err) {
+ console.error('µBlock> writeLocalFile() / onFileTruncateError("%s"):', path, err.name);
+ reportBack(err.name);
+ };
+
+ var onCreateFileWriterSuccess = function(fwriter) {
+ fwriter.onwriteend = onFileTruncateSuccess;
+ fwriter.onerror = onFileTruncateError;
+ fwriter.truncate(0);
+ };
+
+ var onCreateFileWriterError = function(err) {
+ console.error('µBlock> writeLocalFile() / onCreateFileWriterError("%s"):', path, err.name);
+ reportBack(err.name);
+ };
+
+ var onCacheEntryFound = function(file) {
+ // console.log('µBlock> writeLocalFile() / onCacheEntryFound():', file.toURL());
+ file.createWriter(onCreateFileWriterSuccess, onCreateFileWriterError);
+ };
+
+ var onCacheEntryError = function(err) {
+ console.error('µBlock> writeLocalFile() / onCacheEntryError("%s"):', path, err.name);
+ reportBack(err.name);
+ };
+
+ var onRequestFileSystemError = function(err) {
+ console.error('µBlock> writeLocalFile() / onRequestFileSystemError():', err.name);
+ reportBack(err.name);
+ };
+
+ var onRequestFileSystem = function(fs) {
+ fs.root.getFile(cachePathFromPath(path), { create: true }, onCacheEntryFound, onCacheEntryError);
+ };
+
+ requestFileSystem(onRequestFileSystem, onRequestFileSystemError);
+};
+
+/******************************************************************************/
+
+var updateFromRemote = function(details, callback) {
+ // 'ublock=...' is to skip browser cache
+ var remoteURL = remoteRoot + details.path + '?ublock=' + Date.now();
+ var targetPath = details.path;
+ var targetMd5 = details.md5 || '';
+
+ var reportBackError = function() {
+ callback({
+ 'path': targetPath,
+ 'error': 'Error'
+ });
+ };
+
+ var onRemoteFileLoaded = function() {
+ this.onload = this.onerror = null;
+ if ( typeof this.responseText !== 'string' ) {
+ console.error('µBlock> updateFromRemote("%s") / onRemoteFileLoaded(): no response', remoteURL);
+ reportBackError();
+ return;
+ }
+ if ( YaMD5.hashStr(this.responseText) !== targetMd5 ) {
+ console.error('µBlock> updateFromRemote("%s") / onRemoteFileLoaded(): bad md5 checksum', remoteURL);
+ reportBackError();
+ return;
+ }
+ // console.debug('µBlock> updateFromRemote("%s") / onRemoteFileLoaded()', remoteURL);
+ writeLocalFile(targetPath, this.responseText, callback);
+ };
+
+ var onRemoteFileError = function(ev) {
+ this.onload = this.onerror = null;
+ console.error('µBlock> updateFromRemote() / onRemoteFileError("%s"):', remoteURL, this.statusText);
+ reportBackError();
+ };
+
+ getTextFileFromURL(
+ remoteURL,
+ onRemoteFileLoaded,
+ onRemoteFileError
+ );
+};
+
+/******************************************************************************/
+
+// Flush cached assets if cache content is from an older version: the extension
+// always ships with the most up-to-date assets.
+
+synchronizeCache();
+
+/******************************************************************************/
+
+// Export API
+
+return {
+ 'get': readLocalFile,
+ 'getRemote': readRemoteFile,
+ 'put': writeLocalFile,
+ 'update': updateFromRemote
+};
+
+/******************************************************************************/
+
+})();
+
+/******************************************************************************/
+
diff --git a/js/async.js b/js/async.js
new file mode 100644
index 000000000..fa0d680ec
--- /dev/null
+++ b/js/async.js
@@ -0,0 +1,149 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global chrome, µBlock */
+
+/******************************************************************************/
+
+// Async job queue module
+
+µBlock.asyncJobs = (function() {
+
+var processJobs = function() {
+ asyncJobManager.process();
+};
+
+var AsyncJobEntry = function(name) {
+ this.name = name;
+ this.data = null;
+ this.callback = null;
+ this.when = 0;
+ this.period = 0;
+};
+
+AsyncJobEntry.prototype.destroy = function() {
+ this.name = '';
+ this.data = null;
+ this.callback = null;
+};
+
+var AsyncJobManager = function() {
+ this.timeResolution = 200;
+ this.jobs = {};
+ this.jobCount = 0;
+ this.jobJunkyard = [];
+ this.timerId = null;
+ this.timerWhen = Number.MAX_VALUE;
+};
+
+AsyncJobManager.prototype.restartTimer = function() {
+ var when = Number.MAX_VALUE;
+ var jobs = this.jobs, job;
+ for ( var jobName in jobs ) {
+ job = jobs[jobName];
+ if ( job instanceof AsyncJobEntry ) {
+ if ( job.when < when ) {
+ when = job.when;
+ }
+ }
+ }
+ // Quantize time value
+ when = Math.floor((when + this.timeResolution - 1) / this.timeResolution) * this.timeResolution;
+
+ if ( when < this.timerWhen ) {
+ clearTimeout(this.timerId);
+ this.timerWhen = when;
+ this.timerId = setTimeout(processJobs, Math.max(when - Date.now(), 10));
+ }
+};
+
+AsyncJobManager.prototype.add = function(name, data, callback, delay, recurrent) {
+ var job = this.jobs[name];
+ if ( !job ) {
+ job = this.jobJunkyard.pop();
+ if ( !job ) {
+ job = new AsyncJobEntry(name);
+ } else {
+ job.name = name;
+ }
+ this.jobs[name] = job;
+ this.jobCount++;
+ }
+ job.data = data;
+ job.callback = callback;
+ job.when = Date.now() + delay;
+ job.period = recurrent ? delay : 0;
+ this.restartTimer();
+};
+
+AsyncJobManager.prototype.process = function() {
+ this.timerId = null;
+ this.timerWhen = Number.MAX_VALUE;
+ var now = Date.now();
+ var job;
+ for ( var jobName in this.jobs ) {
+ if ( this.jobs.hasOwnProperty(jobName) === false ) {
+ continue;
+ }
+ job = this.jobs[jobName];
+ if ( job.when > now ) {
+ continue;
+ }
+ job.callback(job.data);
+ if ( job.period ) {
+ job.when = now + job.period;
+ } else {
+ delete this.jobs[jobName];
+ job.destroy();
+ this.jobCount--;
+ this.jobJunkyard.push(job);
+ }
+ }
+ this.restartTimer();
+};
+
+// Only one instance
+var asyncJobManager = new AsyncJobManager();
+
+// Publish
+return asyncJobManager;
+
+})();
+
+/******************************************************************************/
+
+// Update visual of extension icon.
+// A time out is used to coalesce adjacent requests to update badge.
+
+µBlock.updateBadge = function(tabId) {
+ if ( tabId < 0 ) {
+ return;
+ }
+ var updateBadgeCallback = function(tabId) {
+ var pageStore = µBlock.pageStoreFromTabId(tabId);
+ if ( pageStore ) {
+ pageStore.updateBadge();
+ } else {
+ chrome.browserAction.setIcon({ tabId: tabId, path: 'img/browsericons/icon19-off.png' });
+ }
+ };
+ this.asyncJobs.add('updateBadge-' + tabId, tabId, updateBadgeCallback, 200);
+};
diff --git a/js/background.js b/js/background.js
new file mode 100644
index 000000000..b9b602364
--- /dev/null
+++ b/js/background.js
@@ -0,0 +1,76 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global chrome */
+
+/******************************************************************************/
+
+var µBlock = (function() {
+
+/******************************************************************************/
+
+return {
+ manifest: chrome.runtime.getManifest(),
+
+ userSettings: {
+ showIconBadge: true,
+ parseAllABPHideFilters: true,
+ exceptionList: {}
+ },
+ localSettings: {
+ blockedRequestCount: 0,
+ allowedRequestCount: 0
+ },
+
+ updateAssetsEvery: 5 * 24 * 60 * 60 * 1000,
+ projectServerRoot: 'https://raw2.github.com/gorhill/ublock/master/',
+
+ // list of remote blacklist locations
+ remoteBlacklists: {
+ // User
+ 'assets/user/filters.txt': {},
+
+ // 3rd-party lists fetched dynamically
+ },
+
+ // urls stats are kept on the back burner while waiting to be reactivated
+ // in a tab or another.
+ pageStores: {},
+ pageStoreDump: {},
+
+ // Power switch to disengage µBlock
+ off: false,
+
+ userFiltersPath: 'assets/user/filters.txt',
+
+ storageQuota: chrome.storage.local.QUOTA_BYTES,
+ storageUsed: 0,
+
+ // so that I don't have to care for last comma
+ dummy: 0
+};
+
+/******************************************************************************/
+
+})();
+
+/******************************************************************************/
+
diff --git a/js/contentscript-end.js b/js/contentscript-end.js
new file mode 100644
index 000000000..3e15e04a7
--- /dev/null
+++ b/js/contentscript-end.js
@@ -0,0 +1,371 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* jshint multistr: true */
+/* global chrome */
+
+// Injected into content pages
+
+/******************************************************************************/
+/******************************************************************************/
+
+// https://github.com/gorhill/httpswitchboard/issues/345
+
+var messaging = (function(name){
+ var port = null;
+ var dangling = false;
+ var requestId = 1;
+ var requestIdToCallbackMap = {};
+ var listenCallback = null;
+
+ var onPortMessage = function(details) {
+ if ( typeof details.id !== 'number' ) {
+ return;
+ }
+ // Announcement?
+ if ( details.id < 0 ) {
+ if ( listenCallback ) {
+ listenCallback(details.msg);
+ }
+ return;
+ }
+ var callback = requestIdToCallbackMap[details.id];
+ if ( !callback ) {
+ return;
+ }
+ callback(details.msg);
+ delete requestIdToCallbackMap[details.id];
+ checkDisconnect();
+ };
+
+ var start = function(name) {
+ port = chrome.runtime.connect({
+ name: name +
+ '/' +
+ String.fromCharCode(
+ Math.random() * 0x7FFF | 0,
+ Math.random() * 0x7FFF | 0,
+ Math.random() * 0x7FFF | 0,
+ Math.random() * 0x7FFF | 0
+ )
+ });
+ port.onMessage.addListener(onPortMessage);
+ };
+
+ if ( typeof name === 'string' && name.length > 0 ) {
+ start(name);
+ }
+
+ var stop = function() {
+ listenCallback = null;
+ dangling = true;
+ checkDisconnect();
+ };
+
+ var ask = function(msg, callback) {
+ if ( !callback ) {
+ tell(msg);
+ return;
+ }
+ var id = requestId++;
+ port.postMessage({ id: id, msg: msg });
+ requestIdToCallbackMap[id] = callback;
+ };
+
+ var tell = function(msg) {
+ port.postMessage({ id: 0, msg: msg });
+ };
+
+ var listen = function(callback) {
+ listenCallback = callback;
+ };
+
+ var checkDisconnect = function() {
+ if ( !dangling ) {
+ return;
+ }
+ if ( Object.keys(requestIdToCallbackMap).length ) {
+ return;
+ }
+ port.disconnect();
+ port = null;
+ };
+
+ return {
+ start: start,
+ stop: stop,
+ ask: ask,
+ tell: tell,
+ listen: listen
+ };
+})('contentscript-end.js');
+
+/******************************************************************************/
+/******************************************************************************/
+
+(function() {
+
+/******************************************************************************/
+
+// ABP cosmetic filters
+
+var CosmeticFiltering = function() {
+ this.queriedSelectors = {};
+ this.injectedSelectors = {};
+ this.classSelectors = null;
+ this.idSelectors = null;
+};
+
+CosmeticFiltering.prototype.onDOMContentLoaded = function() {
+ this.classesFromNodeList(document.querySelectorAll('*[class]'));
+ this.idsFromNodeList(document.querySelectorAll('*[id]'));
+ this.retrieveGenericSelectors();
+};
+
+CosmeticFiltering.prototype.retrieveGenericSelectors = function() {
+ var selectors = this.classSelectors !== null ? Object.keys(this.classSelectors) : [];
+ if ( this.idSelectors !== null ) {
+ selectors = selectors.concat(this.idSelectors);
+ }
+ if ( selectors.length > 0 ) {
+ //console.log('µBlock> ABP cosmetic filters: retrieving CSS rules using %d selectors', selectors.length);
+ messaging.ask({
+ what: 'retrieveGenericCosmeticSelectors',
+ pageURL: window.location.href,
+ selectors: selectors
+ },
+ this.retrieveHandler.bind(this)
+ );
+ }
+ this.idSelectors = null;
+ this.classSelectors = null;
+};
+
+CosmeticFiltering.prototype.retrieveHandler = function(selectors) {
+ if ( !selectors ) {
+ return;
+ }
+ var styleText = [];
+ this.filterUnfiltered(selectors.hideUnfiltered, selectors.hide);
+ this.reduce(selectors.hide, this.injectedSelectors);
+ if ( selectors.hide.length ) {
+ var hideStyleText = '{{hideSelectors}} {display:none !important;}'
+ .replace('{{hideSelectors}}', selectors.hide.join(','));
+ styleText.push(hideStyleText);
+ this.applyCSS(selectors.hide, 'display', 'none');
+ //console.debug('µBlock> generic cosmetic filters: injecting %d CSS rules:', selectors.hide.length, hideStyleText);
+ }
+ this.filterUnfiltered(selectors.donthideUnfiltered, selectors.donthide);
+ this.reduce(selectors.donthide, this.injectedSelectors);
+ if ( selectors.donthide.length ) {
+ var dontHideStyleText = '{{donthideSelectors}} {display:initial !important;}'
+ .replace('{{donthideSelectors}}', selectors.donthide.join(','));
+ styleText.push(dontHideStyleText);
+ this.applyCSS(selectors.donthide, 'display', 'initial');
+ //console.debug('µBlock> generic cosmetic filters: injecting %d CSS rules:', selectors.donthide.length, dontHideStyleText);
+ }
+ if ( styleText.length > 0 ) {
+ var style = document.createElement('style');
+ style.appendChild(document.createTextNode(styleText.join('\n')));
+ var parent = document.body || document.documentElement;
+ if ( parent ) {
+ parent.appendChild(style);
+ }
+ }
+};
+
+CosmeticFiltering.prototype.applyCSS = function(selectors, prop, value) {
+ if ( document.body === null ) {
+ return;
+ }
+ var elems = document.querySelectorAll(selectors);
+ var i = elems.length;
+ while ( i-- ) {
+ elems[i].style[prop] = value;
+ }
+};
+
+CosmeticFiltering.prototype.filterUnfiltered = function(inSelectors, outSelectors) {
+ var i = inSelectors.length;
+ var selector;
+ while ( i-- ) {
+ selector = inSelectors[i];
+ if ( this.injectedSelectors[selector] ) {
+ continue;
+ }
+ if ( document.querySelector(selector) !== null ) {
+ outSelectors.push(selector);
+ }
+ }
+};
+
+CosmeticFiltering.prototype.reduce = function(selectors, dict) {
+ var first = dict.µb === undefined;
+ var i = selectors.length, selector, end;
+ while ( i-- ) {
+ selector = selectors[i];
+ if ( first || !dict[selector] ) {
+ if ( end !== undefined ) {
+ selectors.splice(i+1, end-i);
+ end = undefined;
+ }
+ dict[selector] = true;
+ } else if ( end === undefined ) {
+ end = i;
+ }
+ }
+ if ( end !== undefined ) {
+ selectors.splice(0, end+1);
+ }
+ dict.µb = true;
+};
+
+CosmeticFiltering.prototype.classesFromNodeList = function(nodes) {
+ if ( !nodes ) {
+ return;
+ }
+ if ( this.classSelectors === null ) {
+ this.classSelectors = {};
+ }
+ var classNames, className, j;
+ var i = nodes.length;
+ while ( i-- ) {
+ className = nodes[i].className;
+ if ( typeof className !== 'string' ) {
+ continue;
+ }
+ className = className.trim();
+ if ( className === '' ) {
+ continue;
+ }
+ if ( className.indexOf(' ') < 0 ) {
+ className = '.' + className;
+ if ( this.queriedSelectors[className] ) {
+ continue;
+ }
+ this.classSelectors[className] = true;
+ this.queriedSelectors[className] = true;
+ continue;
+ }
+ classNames = className.trim().split(/\s+/);
+ j = classNames.length;
+ while ( j-- ) {
+ className = classNames[j];
+ if ( className === '' ) {
+ continue;
+ }
+ className = '.' + className;
+ if ( this.queriedSelectors[className] ) {
+ continue;
+ }
+ this.classSelectors[className] = true;
+ this.queriedSelectors[className] = true;
+ }
+ }
+};
+
+CosmeticFiltering.prototype.idsFromNodeList = function(nodes) {
+ if ( !nodes ) {
+ return;
+ }
+ if ( this.idSelectors === null ) {
+ this.idSelectors = [];
+ }
+ var id;
+ var i = nodes.length;
+ while ( i-- ) {
+ id = nodes[i].id;
+ if ( typeof id !== 'string' ) {
+ continue;
+ }
+ id = id.trim();
+ if ( id === '' ) {
+ continue;
+ }
+ id = '#' + id;
+ if ( this.queriedSelectors[id] ) {
+ continue;
+ }
+ this.idSelectors.push(id);
+ this.queriedSelectors[id] = true;
+ }
+};
+
+CosmeticFiltering.prototype.allFromNodeList = function(nodes) {
+ this.classesFromNodeList(nodes);
+ this.idsFromNodeList(nodes);
+};
+
+var cosmeticFiltering = new CosmeticFiltering();
+
+/******************************************************************************/
+
+var mutationObservedHandler = function(mutations) {
+ var iMutation = mutations.length;
+ var mutation;
+ while ( iMutation-- ) {
+ mutation = mutations[iMutation];
+ if ( !mutation.addedNodes || !mutation.addedNodes.length ) {
+ // TODO: attr changes also must be dealth with, but then, how
+ // likely is it...
+ continue;
+ }
+ cosmeticFiltering.allFromNodeList(mutation.addedNodes);
+ }
+
+ cosmeticFiltering.retrieveGenericSelectors();
+};
+
+/******************************************************************************/
+
+// rhill 2013-11-09: Weird... This code is executed from µBlock
+// context first time extension is launched. Avoid this.
+// TODO: Investigate if this was a fluke or if it can really happen.
+// I suspect this could only happen when I was using chrome.tabs.executeScript(),
+// because now a delarative content script is used, along with "http{s}" URL
+// pattern matching.
+
+// console.debug('µBlock> window.location.href = "%s"', window.location.href);
+
+if ( /^https?:\/\/./.test(window.location.href) === false ) {
+ console.debug("Huh?");
+ return;
+}
+
+cosmeticFiltering.onDOMContentLoaded();
+
+// Observe changes in the DOM
+
+// This fixes http://acid3.acidtests.org/
+if ( document.body ) {
+ // https://github.com/gorhill/httpswitchboard/issues/176
+ var observer = new MutationObserver(mutationObservedHandler);
+ observer.observe(document.body, {
+ attributes: false,
+ childList: true,
+ characterData: false,
+ subtree: true
+ });
+}
+
+/******************************************************************************/
+
+})();
diff --git a/js/contentscript-start.js b/js/contentscript-start.js
new file mode 100644
index 000000000..b50503ff5
--- /dev/null
+++ b/js/contentscript-start.js
@@ -0,0 +1,198 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* jshint multistr: true */
+/* global chrome */
+
+// Injected into content pages
+
+/******************************************************************************/
+
+// OK, I keep changing my mind whether a closure should be used or not. This
+// will be the rule: if there are any variables directly accessed on a regular
+// basis, use a closure so that they are cached. Otherwise I don't think the
+// overhead of a closure is worth it. That's my understanding.
+
+(function() {
+
+/******************************************************************************/
+/******************************************************************************/
+
+// https://github.com/gorhill/httpswitchboard/issues/345
+
+var messaging = (function(name){
+ var port = null;
+ var dangling = false;
+ var requestId = 1;
+ var requestIdToCallbackMap = {};
+ var listenCallback = null;
+
+ var onPortMessage = function(details) {
+ if ( typeof details.id !== 'number' ) {
+ return;
+ }
+ // Announcement?
+ if ( details.id < 0 ) {
+ if ( listenCallback ) {
+ listenCallback(details.msg);
+ }
+ return;
+ }
+ var callback = requestIdToCallbackMap[details.id];
+ if ( !callback ) {
+ return;
+ }
+ callback(details.msg);
+ delete requestIdToCallbackMap[details.id];
+ checkDisconnect();
+ };
+
+ var start = function(name) {
+ port = chrome.runtime.connect({
+ name: name +
+ '/' +
+ String.fromCharCode(
+ Math.random() * 0x7FFF | 0,
+ Math.random() * 0x7FFF | 0,
+ Math.random() * 0x7FFF | 0,
+ Math.random() * 0x7FFF | 0
+ )
+ });
+ port.onMessage.addListener(onPortMessage);
+ };
+
+ if ( typeof name === 'string' && name.length > 0 ) {
+ start(name);
+ }
+
+ var stop = function() {
+ listenCallback = null;
+ dangling = true;
+ checkDisconnect();
+ };
+
+ var ask = function(msg, callback) {
+ if ( !callback ) {
+ tell(msg);
+ return;
+ }
+ var id = requestId++;
+ port.postMessage({ id: id, msg: msg });
+ requestIdToCallbackMap[id] = callback;
+ };
+
+ var tell = function(msg) {
+ port.postMessage({ id: 0, msg: msg });
+ };
+
+ var listen = function(callback) {
+ listenCallback = callback;
+ };
+
+ var checkDisconnect = function() {
+ if ( !dangling ) {
+ return;
+ }
+ if ( Object.keys(requestIdToCallbackMap).length ) {
+ return;
+ }
+ port.disconnect();
+ port = null;
+ };
+
+ return {
+ start: start,
+ stop: stop,
+ ask: ask,
+ tell: tell,
+ listen: listen
+ };
+})('contentscript-start.js');
+
+/******************************************************************************/
+/******************************************************************************/
+
+// Domain-based ABP cosmetic filters.
+// These can be inserted before the DOM is loaded.
+
+var domainCosmeticFilteringHandler = function(selectors) {
+ if ( !selectors ) {
+ return;
+ }
+ var styleText = [];
+ if ( selectors.hide.length ) {
+ var hideStyleText = '{{hideSelectors}} {display:none !important;}'
+ .replace('{{hideSelectors}}', selectors.hide.join(','));
+ styleText.push(hideStyleText);
+ domainCosmeticFilteringApplyCSS(selectors.hide, 'display', 'none');
+ //console.debug('µBlock> "%s" cosmetic filters: injecting %d CSS rules:', selectors.domain, selectors.hide.length, hideStyleText);
+ }
+ if ( selectors.donthide.length ) {
+ var dontHideStyleText = '{{donthideSelectors}} {display:initial !important;}'
+ .replace('{{donthideSelectors}}', selectors.donthide.join(','));
+ styleText.push(dontHideStyleText);
+ domainCosmeticFilteringApplyCSS(selectors.donthide, 'display', 'initial');
+ //console.debug('µBlock> "%s" cosmetic filters: injecting %d CSS rules:', selectors.domain, selectors.donthide.length, dontHideStyleText);
+ }
+ if ( styleText.length > 0 ) {
+ var style = document.createElement('style');
+ style.appendChild(document.createTextNode(styleText.join('\n')));
+ var parent = document.head || document.documentElement;
+ if ( parent ) {
+ parent.appendChild(style);
+ }
+ }
+};
+
+var domainCosmeticFilteringApplyCSS = function(selectors, prop, value) {
+ if ( document.body === null ) {
+ return;
+ }
+ var elems = document.querySelectorAll(selectors);
+ var i = elems.length;
+ while ( i-- ) {
+ elems[i].style[prop] = value;
+ }
+};
+
+messaging.ask(
+ {
+ what: 'retrieveDomainCosmeticSelectors',
+ pageURL: window.location.href,
+ locationURL: window.location.href
+ },
+ domainCosmeticFilteringHandler
+);
+
+/******************************************************************************/
+/******************************************************************************/
+
+// The port will never be used again at this point, disconnecting allows
+// the browser to flush this script from memory.
+
+messaging.stop();
+
+/******************************************************************************/
+/******************************************************************************/
+
+})();
+
+/******************************************************************************/
diff --git a/js/dashboard-common.js b/js/dashboard-common.js
new file mode 100644
index 000000000..fabc7e413
--- /dev/null
+++ b/js/dashboard-common.js
@@ -0,0 +1,41 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/******************************************************************************/
+
+$(function() {
+
+/******************************************************************************/
+
+// Open links in the proper window
+$('a').attr('target', '_blank');
+$('a[href*="dashboard.html"]').attr('target', '_parent');
+
+$('.whatisthis').on('click', function() {
+ $(this).parent()
+ .find('.whatisthis-expandable')
+ .toggleClass('whatisthis-expanded');
+});
+
+
+/******************************************************************************/
+
+});
diff --git a/js/dashboard.js b/js/dashboard.js
new file mode 100644
index 000000000..7caac69de
--- /dev/null
+++ b/js/dashboard.js
@@ -0,0 +1,55 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/******************************************************************************/
+
+(function() {
+
+var loadDashboardPanel = function(hash) {
+ var button = $(hash);
+ var url = button.data('dashboardPanelUrl');
+ $('iframe')[0].src = url;
+ $('.tabButton').each(function(){
+ var button = $(this);
+ button.toggleClass('selected', button.data('dashboardPanelUrl') === url);
+ });
+}
+
+/******************************************************************************/
+
+var onTabClickHandler = function() {
+ loadDashboardPanel(window.location.hash);
+}
+
+/******************************************************************************/
+
+$(function() {
+ $(window).on('hashchange', onTabClickHandler);
+ var hash = window.location.hash;
+ if ( hash.length < 2 ) {
+ hash = '#thirdparty-filters';
+ }
+ loadDashboardPanel(hash);
+});
+
+/******************************************************************************/
+
+})();
diff --git a/js/i18n.js b/js/i18n.js
new file mode 100644
index 000000000..c7d48bcd4
--- /dev/null
+++ b/js/i18n.js
@@ -0,0 +1,40 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+// Helper to deal with the i18n'ing of HTML files.
+// jQuery must be present at this point.
+
+$(function() {
+ $('[data-i18n]').each(function() {
+ var me = $(this);
+ var key = me.data('i18n');
+ me.html(chrome.i18n.getMessage(key));
+ });
+ // copy text of
if any to document title
+ document.title = $('h1').first().text();
+
+ // Tool tips
+ $('[data-i18n-tip]').each(function() {
+ var me = $(this);
+ var key = me.data('i18nTip');
+ me.attr('data-tip', chrome.i18n.getMessage(key));
+ });
+});
diff --git a/js/liquid-dict.js b/js/liquid-dict.js
new file mode 100644
index 000000000..1ce408884
--- /dev/null
+++ b/js/liquid-dict.js
@@ -0,0 +1,196 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/******************************************************************************/
+
+µBlock.LiquidDict = (function() {
+
+/******************************************************************************/
+
+var LiquidDict = function() {
+ this.dict = {};
+ this.count = 0;
+ this.bucketCount = 0;
+ this.frozenBucketCount = 0;
+
+ // Somewhat arbitrary: I need to come up with hard data to know at which
+ // point binary search is better than indexOf.
+ this.cutoff = 500;
+};
+
+/******************************************************************************/
+
+var meltBucket = function(ldict, len, bucket) {
+ ldict.frozenBucketCount -= 1;
+ var map = {};
+ if ( bucket.charAt(0) === ' ' ) {
+ bucket.trim().split(' ').map(function(k) {
+ map[k] = true;
+ });
+ } else {
+ var offset = 0;
+ while ( offset < bucket.length ) {
+ map[bucket.substring(offset, len)] = true;
+ offset += len;
+ }
+ }
+ return map;
+};
+
+/******************************************************************************/
+
+var melt = function(ldict) {
+ var buckets = ldict.dict;
+ var bucket;
+ for ( var key in buckets ) {
+ bucket = buckets[key];
+ if ( typeof bucket === 'string' ) {
+ buckets[key] = meltBucket(ldict, key.charCodeAt(0) & 0xFF, bucket);
+ }
+ }
+};
+
+/******************************************************************************/
+
+var freezeBucket = function(ldict, bucket) {
+ ldict.frozenBucketCount += 1;
+ var words = Object.keys(bucket);
+ var wordLen = words[0].length;
+ if ( wordLen * words.length < ldict.cutoff ) {
+ return ' ' + words.join(' ') + ' ';
+ }
+ return words.sort().join('');
+};
+
+/******************************************************************************/
+
+// How the key is derived dictates the number and size of buckets.
+//
+// http://jsperf.com/makekey-concat-vs-join/3
+//
+// Question: Why is using a prototyped function better than a standalone
+// helper function?
+
+LiquidDict.prototype.makeKey = function(word) {
+ var len = word.length;
+ if ( len > 255 ) {
+ len = 255;
+ }
+ var i = len >> 2;
+ return String.fromCharCode(
+ (word.charCodeAt( 0) & 0x03) << 14 |
+ (word.charCodeAt( i) & 0x03) << 12 |
+ (word.charCodeAt( i+i) & 0x03) << 10 |
+ (word.charCodeAt(i+i+i) & 0x03) << 8 |
+ len
+ );
+};
+
+/******************************************************************************/
+
+LiquidDict.prototype.test = function(word) {
+ var key = this.makeKey(word);
+ var bucket = this.dict[key];
+ if ( bucket === undefined ) {
+ return false;
+ }
+ if ( typeof bucket === 'object' ) {
+ return bucket[word] !== undefined;
+ }
+ if ( bucket.charAt(0) === ' ' ) {
+ return bucket.indexOf(' ' + word + ' ') >= 0;
+ }
+ // binary search
+ var len = word.length;
+ var left = 0;
+ // http://jsperf.com/or-vs-floor/3
+ var right = ~~(bucket.length / len + 0.5);
+ var i, needle;
+ while ( left < right ) {
+ i = left + right >> 1;
+ needle = bucket.substr( len * i, len );
+ if ( word < needle ) {
+ right = i;
+ } else if ( word > needle ) {
+ left = i + 1;
+ } else {
+ return true;
+ }
+ }
+ return false;
+};
+
+/******************************************************************************/
+
+LiquidDict.prototype.add = function(word) {
+ var key = this.makeKey(word);
+ if ( key === undefined ) {
+ return false;
+ }
+ var bucket = this.dict[key];
+ if ( bucket === undefined ) {
+ this.dict[key] = bucket = {};
+ this.bucketCount += 1;
+ bucket[word] = true;
+ this.count += 1;
+ return true;
+ } else if ( typeof bucket === 'string' ) {
+ this.dict[key] = bucket = meltBucket(this, word.len, bucket);
+ }
+ if ( bucket[word] === undefined ) {
+ bucket[word] = true;
+ this.count += 1;
+ return true;
+ }
+ return false;
+};
+
+/******************************************************************************/
+
+LiquidDict.prototype.freeze = function() {
+ var buckets = this.dict;
+ var bucket;
+ for ( var key in buckets ) {
+ bucket = buckets[key];
+ if ( typeof bucket === 'object' ) {
+ buckets[key] = freezeBucket(this, bucket);
+ }
+ }
+};
+
+/******************************************************************************/
+
+LiquidDict.prototype.reset = function() {
+ this.dict = {};
+ this.count = 0;
+ this.bucketCount = 0;
+ this.frozenBucketCount = 0;
+};
+
+/******************************************************************************/
+
+return LiquidDict;
+
+/******************************************************************************/
+
+})();
+
+/******************************************************************************/
diff --git a/js/messaging-client.js b/js/messaging-client.js
new file mode 100644
index 000000000..740c53a5b
--- /dev/null
+++ b/js/messaging-client.js
@@ -0,0 +1,130 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+// This is the reference client-side implementation of µBlock's messaging
+// infrastructure. The "server"-side implementation is in messaging.js.
+
+// The client-side implementation creates a port in order to connect to
+// µBlock's background page. With this port we can "ask", "tell" or "announce":
+//
+// "ask": send a request and expect an answer using a callback.
+// "tell": send a request with no expectation of an answer.
+// "announce": send a request to be relayed to all connections -- no answer
+// expected.
+//
+// The tricky part in this implementation is to ensure all the requests are
+// uniquely identified, so that the background-page can keep track of these
+// until it is ready to send back an answer, which will be tagged with the
+// same id. The uniqueness must be true for all ports which connect to the
+// background page at any given time.
+//
+// Currently using Math.random() to generate this id... I don't know about the
+// implementation of Math.random(), but as long as I have a good expectation
+// of uniqueness, it's ok, we are not dealing with critical stuff here.
+
+var messaging = (function(name){
+ var port = null;
+ var dangling = false;
+ var requestId = 1;
+ var requestIdToCallbackMap = {};
+ var listenCallback = null;
+
+ var onPortMessage = function(details) {
+ if ( typeof details.id !== 'number' ) {
+ return;
+ }
+ // Announcement?
+ if ( details.id < 0 ) {
+ if ( listenCallback ) {
+ listenCallback(details.msg);
+ }
+ return;
+ }
+ var callback = requestIdToCallbackMap[details.id];
+ if ( !callback ) {
+ return;
+ }
+ callback(details.msg);
+ delete requestIdToCallbackMap[details.id];
+ checkDisconnect();
+ };
+
+ var start = function(name) {
+ port = chrome.runtime.connect({
+ name: name +
+ '/' +
+ String.fromCharCode(
+ Math.random() * 0x7FFF | 0,
+ Math.random() * 0x7FFF | 0,
+ Math.random() * 0x7FFF | 0,
+ Math.random() * 0x7FFF | 0
+ )
+ });
+ port.onMessage.addListener(onPortMessage);
+ };
+
+ if ( typeof name === 'string' && name.length > 0 ) {
+ start(name);
+ }
+
+ var stop = function() {
+ listenCallback = null;
+ dangling = true;
+ checkDisconnect();
+ };
+
+ var ask = function(msg, callback) {
+ if ( !callback ) {
+ tell(msg);
+ return;
+ }
+ var id = requestId++;
+ port.postMessage({ id: id, msg: msg });
+ requestIdToCallbackMap[id] = callback;
+ };
+
+ var tell = function(msg) {
+ port.postMessage({ id: 0, msg: msg });
+ };
+
+ var listen = function(callback) {
+ listenCallback = callback;
+ };
+
+ var checkDisconnect = function() {
+ if ( !dangling ) {
+ return;
+ }
+ if ( Object.keys(requestIdToCallbackMap).length ) {
+ return;
+ }
+ port.disconnect();
+ port = null;
+ };
+
+ return {
+ start: start,
+ stop: stop,
+ ask: ask,
+ tell: tell,
+ listen: listen
+ };
+})();
diff --git a/js/messaging-handlers.js b/js/messaging-handlers.js
new file mode 100644
index 000000000..30c39b33d
--- /dev/null
+++ b/js/messaging-handlers.js
@@ -0,0 +1,260 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global chrome, µBlock */
+
+/******************************************************************************/
+
+(function() {
+
+// popup.js
+
+/******************************************************************************/
+
+var getStats = function(request, callback) {
+ var µb = µBlock;
+ var r = {
+ globalBlockedRequestCount: µb.localSettings.blockedRequestCount,
+ globalAllowedRequestCount: µb.localSettings.allowedRequestCount,
+ tabId: request.tabId,
+ pageURL: '',
+ pageBlockedRequestCount: 0,
+ pageAllowedRequestCount: 0,
+ netFilteringSwitch: false,
+ cosmeticFilteringSwitch: false
+ };
+ var pageStore = µb.pageStoreFromTabId(request.tabId);
+ if ( pageStore ) {
+ r.pageURL = pageStore.pageURL;
+ r.pageHostname = pageStore.pageHostname;
+ r.pageBlockedRequestCount = pageStore.perLoadBlockedRequestCount;
+ r.pageAllowedRequestCount = pageStore.perLoadAllowedRequestCount;
+ r.netFilteringSwitch = µb.getNetFilteringSwitch(pageStore.pageHostname);
+ }
+ return r;
+};
+
+/******************************************************************************/
+
+var onMessage = function(request, sender, callback) {
+ // Async
+ switch ( request.what ) {
+ default:
+ break;
+ }
+
+ // Sync
+ var response;
+
+ switch ( request.what ) {
+ case 'stats':
+ response = getStats(request);
+ break;
+
+ case 'toggleNetFiltering':
+ µBlock.toggleNetFilteringSwitch(
+ request.hostname,
+ request.state
+ );
+ µBlock.updateBadge(request.tabId);
+ break;
+
+ default:
+ return µBlock.messaging.defaultHandler(request, sender, callback);
+ }
+
+ callback(response);
+};
+
+µBlock.messaging.listen('popup.js', onMessage);
+
+})();
+
+/******************************************************************************/
+
+// content scripts
+
+(function() {
+
+var onMessage = function(request, sender, callback) {
+ // Async
+ switch ( request.what ) {
+ default:
+ break;
+ }
+
+ // Sync
+ var response;
+
+ switch ( request.what ) {
+ case 'retrieveDomainCosmeticSelectors':
+ response = µBlock.abpHideFilters.retrieveDomainSelectors(request);
+ break;
+
+ case 'retrieveGenericCosmeticSelectors':
+ response = µBlock.abpHideFilters.retrieveGenericSelectors(request);
+ break;
+
+ default:
+ return µBlock.messaging.defaultHandler(request, sender, callback);
+ }
+
+ callback(response);
+};
+
+µBlock.messaging.listen('contentscript-start.js', onMessage);
+µBlock.messaging.listen('contentscript-end.js', onMessage);
+
+})();
+
+/******************************************************************************/
+
+// 3p-filters.js
+
+(function() {
+
+var onMessage = function(request, sender, callback) {
+ var µb = µBlock;
+
+ // Async
+ switch ( request.what ) {
+ case 'readUserUbiquitousBlockRules':
+ return µb.assets.get(µb.userFiltersPath, callback);
+
+ case 'writeUserUbiquitousBlockRules':
+ return µb.assets.put(µb.userFiltersPath, request.content, callback);
+
+ default:
+ break;
+ }
+
+ // Sync
+ var response;
+
+ switch ( request.what ) {
+ default:
+ return µb.messaging.defaultHandler(request, sender, callback);
+ }
+
+ callback(response);
+};
+
+µBlock.messaging.listen('3p-filters.js', onMessage);
+
+})();
+
+/******************************************************************************/
+
+// 1p-filters.js
+
+(function() {
+
+var onMessage = function(request, sender, callback) {
+ var µb = µBlock;
+
+ // Async
+ switch ( request.what ) {
+ case 'readUserFilters':
+ return µb.assets.get(µb.userFiltersPath, callback);
+
+ case 'writeUserFilters':
+ return µb.assets.put(µb.userFiltersPath, request.content, callback);
+
+ default:
+ break;
+ }
+
+ // Sync
+ var response;
+
+ switch ( request.what ) {
+ default:
+ return µb.messaging.defaultHandler(request, sender, callback);
+ }
+
+ callback(response);
+};
+
+µBlock.messaging.listen('1p-filters.js', onMessage);
+
+})();
+
+/******************************************************************************/
+
+// about.js
+
+(function() {
+
+var onMessage = function(request, sender, callback) {
+ var µb = µBlock;
+
+ // Async
+ switch ( request.what ) {
+ case 'getAssetUpdaterList':
+ return µb.assetUpdater.getList(callback);
+
+ case 'launchAssetUpdater':
+ return µb.assetUpdater.update(request.list, callback);
+
+ case 'readUserSettings':
+ return chrome.storage.local.get(µb.userSettings, callback);
+
+ case 'readUserFilters':
+ return µb.assets.get(µb.userFiltersPath, callback);
+
+ case 'writeUserFilters':
+ return µb.assets.put(µb.userFiltersPath, request.content, callback);
+
+ default:
+ break;
+ }
+
+ // Sync
+ var response;
+
+ switch ( request.what ) {
+ case 'loadUpdatableAssets':
+ response = µb.loadUpdatableAssets();
+ break;
+
+ case 'readFilterListSelection':
+ response = µb.remoteBlacklists;
+ break;
+
+ case 'getSomeStats':
+ response = {
+ storageQuota: µb.storageQuota,
+ storageUsed: µb.storageUsed
+ };
+ break;
+
+ default:
+ return µb.messaging.defaultHandler(request, sender, callback);
+ }
+
+ callback(response);
+};
+
+µBlock.messaging.listen('about.js', onMessage);
+
+})();
+
+/******************************************************************************/
diff --git a/js/messaging.js b/js/messaging.js
new file mode 100644
index 000000000..14cb53116
--- /dev/null
+++ b/js/messaging.js
@@ -0,0 +1,240 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+// So there might be memory leaks related to the direct use of sendMessage(),
+// as per https://code.google.com/p/chromium/issues/detail?id=320723. The issue
+// is not marked as resolved, and the last message from chromium dev is:
+//
+// "You can construct Port objects (runtime.connect) and emulate sendMessage
+// "behaviour. The bug is that sendMessage doesn't clean up its Ports."
+//
+// So the point here is to have an infrastructure which allows relying more on
+// direct use of Port objects rather than going through sendMessage().
+
+/******************************************************************************/
+/*******************************************************************************
+
+// Here this is the "server"-side implementation.
+//
+// Reference client-side implementation is found in:
+//
+// messaging-client.js
+//
+// For instance, it needs to be cut & pasted for content scripts since
+// I can not include in a simple way js file content from another js file.
+
+*******************************************************************************/
+/******************************************************************************/
+
+µBlock.messaging = (function() {
+
+/******************************************************************************/
+
+var nameToPortMap = {};
+var nameToListenerMap = {};
+var nullFunc = function(){};
+
+/******************************************************************************/
+
+var listenerNameFromPortName = function(portName) {
+ var pos = portName.indexOf('/');
+ if ( pos <= 0 ) {
+ return '';
+ }
+ return portName.slice(0, pos);
+};
+
+var listenerFromPortName = function(portName) {
+ return nameToListenerMap[listenerNameFromPortName(portName)];
+};
+
+/******************************************************************************/
+
+var listen = function(portName, callback) {
+ var listener = nameToListenerMap[portName];
+ if ( listener && listener !== callback ) {
+ throw 'Only one listener allowed';
+ }
+ nameToListenerMap[portName] = callback;
+};
+
+/******************************************************************************/
+
+var tell = function(target, msg) {
+ target += '/';
+ for ( var portName in nameToPortMap ) {
+ if ( nameToPortMap.hasOwnProperty(portName) === false ) {
+ continue;
+ }
+ if ( portName.indexOf(target) === 0 ) {
+ nameToPortMap[portName].postMessage({ id: -1, msg: msg });
+ }
+ }
+};
+
+/******************************************************************************/
+
+var announce = function(msg) {
+ // Background page handler
+ defaultHandler(msg, null, nullFunc);
+
+ // Extension pages & content scripts handlers
+ var port;
+ for ( var portName in nameToPortMap ) {
+ if ( nameToPortMap.hasOwnProperty(portName) === false ) {
+ continue;
+ }
+ nameToPortMap[portName].postMessage({ id: -1, msg: msg });
+ }
+};
+
+/******************************************************************************/
+
+var onMessage = function(request, port) {
+ // Annoucement: dispatch everywhere.
+ if ( request.id < 0 ) {
+ announce(request.msg);
+ return;
+ }
+ var listener = listenerFromPortName(port.name) || defaultHandler;
+ var reqId = request.id;
+ // Being told
+ if ( reqId <= 0 ) {
+ listener(request.msg, port.sender, nullFunc);
+ return;
+ }
+ // Being asked
+ listener(request.msg, port.sender, function(response) {
+ port.postMessage({
+ id: reqId,
+ msg: response !== undefined ? response : null
+ });
+ });
+};
+
+/******************************************************************************/
+
+// Default is for commonly used message.
+
+function defaultHandler(request, sender, callback) {
+ // Async
+ switch ( request.what ) {
+ case 'loadUbiquitousAllowRules':
+ return µBlock.loadUbiquitousWhitelists();
+
+ default:
+ break;
+ }
+
+ // Sync
+ var response;
+
+ switch ( request.what ) {
+ case 'forceReloadTab':
+ µBlock.forceReload(request.pageURL);
+ break;
+
+ case 'getUserSettings':
+ response = µBlock.userSettings;
+ break;
+
+ case 'gotoExtensionURL':
+ µBlock.utils.gotoExtensionURL(request.url);
+ break;
+
+ case 'gotoURL':
+ µBlock.utils.gotoURL(request);
+ break;
+
+ case 'reloadAllFilters':
+ µBlock.reloadPresetBlacklists(request.switches);
+ break;
+
+ case 'userSettings':
+ response = µBlock.changeUserSettings(request.name, request.value);
+ break;
+
+ default:
+ // console.error('µBlock> messaging.js / defaultHandler > unknown request: %o', request);
+ break;
+ }
+
+ callback(response);
+}
+
+/******************************************************************************/
+
+// Port disconnected, relay this information to apropriate listener.
+
+var onDisconnect = function(port) {
+ // Notify listener of the disconnection -- using a reserved message id.
+ var listener = listenerFromPortName(port.name) || defaultHandler;
+ var msg = {
+ 'what': 'disconnected',
+ 'which': listenerNameFromPortName(port.name)
+ };
+ listener(msg, port.sender, nullFunc);
+
+ // Cleanup port if no longer in use.
+ var port = nameToPortMap[port.name];
+ if ( port ) {
+ delete nameToPortMap[port.name];
+ port.onMessage.removeListener(onMessage);
+ port.onDisconnect.removeListener(onDisconnect);
+ }
+};
+
+/******************************************************************************/
+
+var onConnect = function(port) {
+ // We must have a port name.
+ if ( !port.name ) {
+ throw 'µBlock> messaging.js / onConnectHandler(): no port name!';
+ }
+
+ // Port should not already exist.
+ if ( nameToPortMap[port.name] ) {
+ throw 'µBlock> messaging.js / onConnectHandler(): port already exists!';
+ }
+
+ nameToPortMap[port.name] = port;
+ port.onMessage.addListener(onMessage);
+ port.onDisconnect.addListener(onDisconnect);
+};
+
+/******************************************************************************/
+
+chrome.runtime.onConnect.addListener(onConnect);
+
+/******************************************************************************/
+
+return {
+ listen: listen,
+ tell: tell,
+ announce: announce,
+ defaultHandler: defaultHandler
+};
+
+/******************************************************************************/
+
+})();
+
+/******************************************************************************/
diff --git a/js/pagestore.js b/js/pagestore.js
new file mode 100644
index 000000000..823f3b987
--- /dev/null
+++ b/js/pagestore.js
@@ -0,0 +1,150 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global chrome, µBlock */
+
+/*******************************************************************************
+
+A PageRequestStore object is used to store net requests in two ways:
+
+To record distinct net requests
+To create a log of net requests
+
+**/
+
+/******************************************************************************/
+/******************************************************************************/
+
+µBlock.PageStore = (function() {
+
+/******************************************************************************/
+
+var µb = µBlock;
+var pageStoreJunkyard = [];
+
+/******************************************************************************/
+
+var pageStoreFactory = function(tabId, pageURL) {
+ var entry = pageStoreJunkyard.pop();
+ if ( entry ) {
+ return entry.init(tabId, pageURL);
+ }
+ return new PageStore(tabId, pageURL);
+};
+
+/******************************************************************************/
+
+function PageStore(tabId, pageURL) {
+ this.tabId = -1;
+ this.pageURL = '';
+ this.pageHostname = '';
+ this.pageDomain = '';
+ this.perLoadBlockedRequestCount = 0;
+ this.perLoadAllowedRequestCount = 0;
+ this.disposeTime = 0;
+ this.init(tabId, pageURL);
+}
+
+/******************************************************************************/
+
+PageStore.prototype.init = function(tabId, pageURL) {
+ this.tabId = tabId;
+ this.pageURL = pageURL;
+ this.pageHostname = µb.URI.hostnameFromURI(pageURL);
+ this.pageDomain = µb.URI.domainFromHostname(this.pageHostname);
+ this.perLoadBlockedRequestCount = 0;
+ this.perLoadAllowedRequestCount = 0;
+ this.disposeTime = 0;
+ return this;
+};
+
+/******************************************************************************/
+
+PageStore.prototype.dispose = function() {
+ // rhill 2013-11-07: Even though at init time these are reset, I still
+ // need to release the memory taken by these, which can amount to
+ // sizeable enough chunks (especially requests, through the request URL
+ // used as a key).
+ this.pageURL = '';
+ this.pageHostname = '';
+ this.pageDomain = '';
+ if ( pageStoreJunkyard.length < 32 ) {
+ pageStoreJunkyard.push(this);
+ }
+};
+
+/******************************************************************************/
+
+PageStore.prototype.recordRequest = function(type, url, block) {
+ // rhill 2013-10-26: This needs to be called even if the request is
+ // already logged, since the request stats are cached for a while after
+ // the page is no longer visible in a browser tab.
+ µb.updateBadge(this.tabId);
+
+ if ( block !== false ) {
+ this.perLoadBlockedRequestCount++;
+ µb.localSettings.blockedRequestCount++;
+ } else {
+ this.perLoadAllowedRequestCount++;
+ µb.localSettings.allowedRequestCount++;
+ }
+};
+
+/******************************************************************************/
+
+// Update badge, incrementally
+
+// rhill 2013-11-09: well this sucks, I can't update icon/badge
+// incrementally, as chromium overwrite the icon at some point without
+// notifying me, and this causes internal cached state to be out of sync.
+
+PageStore.prototype.updateBadge = function() {
+ var netFilteringSwitch = µBlock.getNetFilteringSwitch(this.pageHostname);
+ var iconPath = netFilteringSwitch ? 'img/browsericons/icon19.png' : 'img/browsericons/icon19-off.png';
+
+ chrome.browserAction.setIcon({ tabId: this.tabId, path: iconPath });
+
+ var iconStr = '';
+ if ( netFilteringSwitch && this.perLoadBlockedRequestCount ) {
+ iconStr = µb.formatCount(this.perLoadBlockedRequestCount);
+ }
+ chrome.browserAction.setBadgeText({
+ tabId: this.tabId,
+ text: iconStr
+ });
+
+ if ( iconStr !== '' ) {
+ chrome.browserAction.setBadgeBackgroundColor({
+ tabId: this.tabId,
+ color: '#666'
+ });
+ }
+};
+
+/******************************************************************************/
+
+return {
+ factory: pageStoreFactory
+};
+
+})();
+
+/******************************************************************************/
diff --git a/js/popup.js b/js/popup.js
new file mode 100644
index 000000000..1e104208c
--- /dev/null
+++ b/js/popup.js
@@ -0,0 +1,169 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/******************************************************************************/
+/******************************************************************************/
+
+(function() {
+
+/******************************************************************************/
+/******************************************************************************/
+
+var stats;
+
+/******************************************************************************/
+/******************************************************************************/
+
+// https://github.com/gorhill/httpswitchboard/issues/345
+
+messaging.start('popup.js');
+
+/******************************************************************************/
+
+var hasClassName = function(elem, className) {
+ var re = new RegExp('(^| )' + className + '( |$)', 'g');
+ return re.test(elem.className);
+};
+
+var toggleClassName = function(elem, className, newState) {
+ var re = new RegExp('(^| )' + className + '( |$)', 'g');
+ var currentState = re.test(elem.className);
+ if ( newState === undefined ) {
+ newState = !currentState;
+ }
+ if ( newState !== currentState ) {
+ if ( newState ) {
+ elem.className += ' ' + className;
+ } else {
+ elem.className = elem.className.replace(re, '').trim();
+ }
+ }
+};
+
+/******************************************************************************/
+
+var renderStats = function() {
+ if ( !stats || !document.getElementById('switch') ) {
+ return;
+ }
+ var blocked = stats.pageBlockedRequestCount;
+ var total = stats.pageAllowedRequestCount + blocked;
+ var elem = document.getElementById('page-blocked');
+ if ( total === 0 ) {
+ elem.innerHTML = '0';
+ } else {
+ elem.innerHTML = [
+ blocked,
+ ' / ',
+ total,
+ ' \u21D2 ',
+ (blocked * 100 / total).toFixed(0),
+ '%'
+ ].join('');
+ }
+
+ blocked = stats.globalBlockedRequestCount;
+ total = stats.globalAllowedRequestCount + blocked;
+ elem = document.getElementById('total-blocked');
+ if ( total === 0 ) {
+ elem.innerHTML = '0';
+ } else {
+ elem.innerHTML = [
+ blocked,
+ ' / ',
+ total,
+ ' \u21D2 ',
+ (blocked * 100 / total).toFixed(0),
+ '%'
+ ].join('');
+ }
+
+ toggleClassName(
+ document.querySelector('#switch .fa'),
+ 'off',
+ stats.pageURL === '' || !stats.netFilteringSwitch
+ );
+};
+
+/******************************************************************************/
+
+var onStatsReceived = function(details) {
+ stats = details;
+ renderStats();
+};
+
+/******************************************************************************/
+
+var onTabsReceived = function(tabs) {
+ if ( tabs.length === 0 ) {
+ return;
+ }
+ var q = {
+ what: 'stats',
+ tabId: tabs[0].id
+ };
+ messaging.ask( q, onStatsReceived );
+};
+
+chrome.tabs.query({ active: true }, onTabsReceived);
+
+/******************************************************************************/
+
+var handleNetFilteringSwitch = function() {
+ if ( !stats || !stats.pageURL ) {
+ return;
+ }
+ toggleClassName(this, 'off');
+ messaging.tell({
+ what: 'toggleNetFiltering',
+ hostname: stats.pageHostname,
+ state: !hasClassName(this, 'off'),
+ tabId: stats.tabId
+ });
+};
+
+/******************************************************************************/
+
+var renderHeader = function() {
+ var hdr = document.querySelector('h1,h2,h3,h4');
+ hdr.innerHTML = hdr.innerHTML + ' v' + chrome.runtime.getManifest().version;
+};
+
+
+/******************************************************************************/
+
+var installEventHandlers = function() {
+ document.querySelector('#switch .fa').addEventListener('click', handleNetFilteringSwitch);
+};
+
+/******************************************************************************/
+
+// Make menu only when popup html is fully loaded
+
+window.addEventListener('load', function() {
+ renderHeader();
+ renderStats();
+ installEventHandlers();
+});
+
+/******************************************************************************/
+
+})();
diff --git a/js/profiler.js b/js/profiler.js
new file mode 100644
index 000000000..8eeecc84a
--- /dev/null
+++ b/js/profiler.js
@@ -0,0 +1,82 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/******************************************************************************/
+
+var quickProfiler = (function() {
+
+/******************************************************************************/
+
+var timer = performance;
+var time = 0;
+var count = -3;
+var tstart = 0;
+var lastlog = timer.now();
+var prompt = '';
+
+/******************************************************************************/
+
+var reset = function() {
+ time = 0;
+ count = -3;
+ tstart = 0;
+};
+
+/******************************************************************************/
+
+var avg = function() {
+ return count > 0 ? time / count : 0;
+};
+
+/******************************************************************************/
+
+var start = function(s) {
+ prompt = s || '';
+ tstart = timer.now();
+};
+
+/******************************************************************************/
+
+var stop = function() {
+ count += 1;
+ if ( count > 0 ) {
+ var now = timer.now();
+ time += (now - tstart);
+ if ( (now - lastlog) > 10000 ) {
+ console.log('µBlock() > %s: %s ms', prompt, avg().toFixed(3));
+ lastlog = now;
+ }
+ }
+};
+
+/******************************************************************************/
+
+return {
+ reset: reset,
+ start: start,
+ stop: stop
+};
+
+/******************************************************************************/
+
+})();
+
+/******************************************************************************/
diff --git a/js/start.js b/js/start.js
new file mode 100644
index 000000000..2ab08ba39
--- /dev/null
+++ b/js/start.js
@@ -0,0 +1,52 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+// ORDER IS IMPORTANT
+
+/******************************************************************************/
+
+// Load everything
+
+µBlock.load();
+
+/******************************************************************************/
+
+// Automatic update of non-user assets
+// https://github.com/gorhill/httpswitchboard/issues/334
+
+(function() {
+ var µb = µBlock;
+
+ var jobDone = function(details) {
+ if ( details.changedCount === 0 ) {
+ return;
+ }
+ µb.loadUpdatableAssets();
+ };
+
+ var jobCallback = function() {
+ µb.assetUpdater.update(null, jobDone);
+ };
+
+ µb.asyncJobs.add('autoUpdateAssets', null, jobCallback, µb.updateAssetsEvery, true);
+})();
+
+/******************************************************************************/
diff --git a/js/storage.js b/js/storage.js
new file mode 100644
index 000000000..5dc5c3d3d
--- /dev/null
+++ b/js/storage.js
@@ -0,0 +1,380 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global chrome, µBlock, punycode, publicSuffixList */
+
+/******************************************************************************/
+
+µBlock.getBytesInUse = function() {
+ var getBytesInUseHandler = function(bytesInUse) {
+ µBlock.storageUsed = bytesInUse;
+ };
+ chrome.storage.local.getBytesInUse(null, getBytesInUseHandler);
+};
+
+/******************************************************************************/
+
+µBlock.saveLocalSettings = function() {
+ chrome.storage.local.set(this.localSettings, function() {
+ µBlock.getBytesInUse();
+ });
+};
+
+/******************************************************************************/
+
+µBlock.loadLocalSettings = function() {
+ var settingsLoaded = function(store) {
+ µBlock.localSettings = store;
+ };
+
+ chrome.storage.local.get(this.localSettings, settingsLoaded);
+};
+
+/******************************************************************************/
+
+// Save local settings regularly. Not critical.
+
+µBlock.asyncJobs.add(
+ 'autoSaveLocalSettings',
+ null,
+ µBlock.saveLocalSettings.bind(µBlock),
+ 2 * 60 * 1000,
+ true
+);
+
+/******************************************************************************/
+
+µBlock.saveUserSettings = function() {
+ chrome.storage.local.set(this.userSettings, function() {
+ µBlock.getBytesInUse();
+ });
+};
+
+/******************************************************************************/
+
+µBlock.loadUserSettings = function() {
+ var settingsLoaded = function(store) {
+ µBlock.userSettings = store;
+ };
+
+ chrome.storage.local.get(this.userSettings, settingsLoaded);
+};
+
+/******************************************************************************/
+
+µBlock.loadUbiquitousBlacklists = function() {
+ var blacklists;
+ var blacklistLoadCount;
+ var obsoleteBlacklists = [];
+
+ var removeObsoleteBlacklistsHandler = function(store) {
+ if ( !store.remoteBlacklists ) {
+ return;
+ }
+ var location;
+ while ( location = obsoleteBlacklists.pop() ) {
+ delete store.remoteBlacklists[location];
+ }
+ chrome.storage.local.set(store);
+ };
+
+ var removeObsoleteBlacklists = function() {
+ if ( obsoleteBlacklists.length === 0 ) {
+ return;
+ }
+ chrome.storage.local.get(
+ { 'remoteBlacklists': µBlock.remoteBlacklists },
+ removeObsoleteBlacklistsHandler
+ );
+ };
+
+ var mergeBlacklist = function(details) {
+ var µb = µBlock;
+ µb.mergeUbiquitousBlacklist(details);
+ blacklistLoadCount -= 1;
+ if ( blacklistLoadCount === 0 ) {
+ loadBlacklistsEnd();
+ }
+ };
+
+ var loadBlacklistsEnd = function() {
+ µBlock.abpFilters.freeze();
+ µBlock.abpHideFilters.freeze();
+ removeObsoleteBlacklists();
+ µBlock.messaging.announce({ what: 'loadUbiquitousBlacklistCompleted' });
+ };
+
+ var loadBlacklistsStart = function(store) {
+ var µb = µBlock;
+ // rhill 2013-12-10: set all existing entries to `false`.
+ µb.abpFilters.reset();
+ µb.abpHideFilters.reset();
+ blacklists = store.remoteBlacklists;
+ var blacklistLocations = Object.keys(store.remoteBlacklists);
+
+ blacklistLoadCount = blacklistLocations.length;
+ if ( blacklistLoadCount === 0 ) {
+ loadBlacklistsEnd();
+ return;
+ }
+
+ // Load each preset blacklist which is not disabled.
+ var location;
+ while ( location = blacklistLocations.pop() ) {
+ // If loaded list location is not part of default list locations,
+ // remove its entry from local storage.
+ if ( !µb.remoteBlacklists[location] ) {
+ obsoleteBlacklists.push(location);
+ blacklistLoadCount -= 1;
+ continue;
+ }
+ // https://github.com/gorhill/httpswitchboard/issues/218
+ // Transfer potentially existing list title into restored list data.
+ if ( store.remoteBlacklists[location].title !== µb.remoteBlacklists[location].title ) {
+ store.remoteBlacklists[location].title = µb.remoteBlacklists[location].title;
+ }
+ // Store details of this preset blacklist
+ µb.remoteBlacklists[location] = store.remoteBlacklists[location];
+ // rhill 2013-12-09:
+ // Ignore list if disabled
+ // https://github.com/gorhill/httpswitchboard/issues/78
+ if ( store.remoteBlacklists[location].off ) {
+ blacklistLoadCount -= 1;
+ continue;
+ }
+ µb.assets.get(location, mergeBlacklist);
+ }
+ };
+
+ var onListOfBlockListsLoaded = function(details) {
+ var µb = µBlock;
+ // Initialize built-in list of 3rd-party block lists.
+ var lists = JSON.parse(details.content);
+ for ( var location in lists ) {
+ if ( lists.hasOwnProperty(location) === false ) {
+ continue;
+ }
+ µb.remoteBlacklists['assets/thirdparties/' + location] = lists[location];
+ }
+ // Now get user's selection of list of block lists.
+ chrome.storage.local.get(
+ { 'remoteBlacklists': µb.remoteBlacklists },
+ loadBlacklistsStart
+ );
+ };
+
+ // Reset list of 3rd-party block lists.
+ for ( var location in this.remoteBlacklists ) {
+ if ( location.indexOf('assets/thirdparties/') === 0 ) {
+ delete this.remoteBlacklists[location];
+ }
+ }
+
+ // Get new list of 3rd-party block lists.
+ this.assets.get('assets/ublock/filter-lists.json', onListOfBlockListsLoaded);
+};
+
+/******************************************************************************/
+
+µBlock.mergeUbiquitousBlacklist = function(details) {
+ // console.log('µBlock > mergeUbiquitousBlacklist from "%s": "%s..."', details.path, details.content.slice(0, 40));
+
+ var rawText = details.content;
+ var rawEnd = rawText.length;
+
+ // rhill 2013-10-21: No need to prefix with '* ', the hostname is just what
+ // we need for preset blacklists. The prefix '* ' is ONLY needed when
+ // used as a filter in temporary blacklist.
+
+ // rhill 2014-01-22: Transpose possible Adblock Plus-filter syntax
+ // into a plain hostname if possible.
+ // Useful references:
+ // https://adblockplus.org/en/filter-cheatsheet
+ // https://adblockplus.org/en/filters
+ var abpFilters = this.abpFilters;
+ var abpHideFilters = this.userSettings.parseAllABPHideFilters ? this.abpHideFilters : null;
+ var thisListCount = 0;
+ var thisListUsedCount = 0;
+ var reLocalhost = /(^|\s)(localhost\.localdomain|localhost|local|broadcasthost|0\.0\.0\.0|127\.0\.0\.1|::1|fe80::1%lo0)(?=\s|$)/g;
+ var reAdblockFilter = /^[^a-z0-9:]|[^a-z0-9]$|[^a-z0-9_:.-]/;
+ var reAdblockHostFilter = /^\|\|([a-z0-9.-]+[a-z0-9])\^?$/;
+ var reAsciiSegment = /^[\x21-\x7e]+$/;
+ var matches;
+ var lineBeg = 0, lineEnd, currentLineBeg;
+ var line, c;
+
+ while ( lineBeg < rawEnd ) {
+ lineEnd = rawText.indexOf('\n', lineBeg);
+ if ( lineEnd < 0 ) {
+ lineEnd = rawText.indexOf('\r', lineBeg);
+ if ( lineEnd < 0 ) {
+ lineEnd = rawEnd;
+ }
+ }
+
+ // rhill 2014-04-18: The trim is important here, as without it there
+ // could be a lingering `\r` which would cause problems in the
+ // following parsing code.
+ line = rawText.slice(lineBeg, lineEnd).trim();
+ currentLineBeg = lineBeg;
+ lineBeg = lineEnd + 1;
+
+ // Strip comments
+ c = line.charAt(0);
+ if ( c === '!' || c === '[' ) {
+ continue;
+ }
+
+ // 2014-05-18: ABP element hide filters are allowed to contain space
+ // characters
+ if ( abpHideFilters !== null ) {
+ if ( abpHideFilters.add(line) ) {
+ continue;
+ }
+ }
+
+ if ( c === '#' ) {
+ continue;
+ }
+
+ // https://github.com/gorhill/httpswitchboard/issues/15
+ // Ensure localhost et al. don't end up in the ubiquitous blacklist.
+ line = line
+ .replace(/\s+#.*$/, '')
+ .toLowerCase()
+ .replace(reLocalhost, '')
+ .trim();
+
+ // The filter is whatever sequence of printable ascii character without
+ // whitespaces
+ matches = reAsciiSegment.exec(line);
+ if ( !matches || matches.length === 0 ) {
+ continue;
+ }
+
+ // Bypass anomalies
+ // For example, when a filter contains whitespace characters, or
+ // whatever else outside the range of printable ascii characters.
+ if ( matches[0] !== line ) {
+ // console.error('"%s": "%s" !== "%s"', details.path, matches[0], line);
+ continue;
+ }
+
+ line = matches[0];
+
+ // Likely an ABP net filter?
+ if ( reAdblockFilter.test(line) ) {
+ if ( abpFilters !== null ) {
+ if ( abpFilters.add(line) ) {
+ continue;
+ }
+ }
+ // rhill 2014-01-22: Transpose possible Adblock Plus-filter syntax
+ // into a plain hostname if possible.
+ matches = reAdblockHostFilter.exec(line);
+ if ( !matches || matches.length < 2 ) {
+ continue;
+ }
+ line = matches[1];
+ }
+
+ if ( line === '' ) {
+ continue;
+ }
+
+ thisListCount++;
+ if ( abpFilters.addAnyPartyHostname(line) ) {
+ thisListUsedCount++;
+ }
+ }
+
+ // For convenience, store the number of entries for this
+ // blacklist, user might be happy to know this information.
+ this.remoteBlacklists[details.path].entryCount = thisListCount;
+ this.remoteBlacklists[details.path].entryUsedCount = thisListUsedCount;
+};
+
+/******************************************************************************/
+
+// `switches` contains the preset blacklists for which the switch must be
+// revisited.
+
+µBlock.reloadPresetBlacklists = function(switches) {
+ var presetBlacklists = this.remoteBlacklists;
+
+ // Toggle switches, if any
+ if ( switches !== undefined ) {
+ var i = switches.length;
+ while ( i-- ) {
+ if ( !presetBlacklists[switches[i].location] ) {
+ continue;
+ }
+ presetBlacklists[switches[i].location].off = !!switches[i].off;
+ }
+
+ // Save switch states
+ chrome.storage.local.set({ 'remoteBlacklists': presetBlacklists }, function() {
+ µBlock.getBytesInUse();
+ });
+ }
+
+ // Now force reload
+ this.loadUbiquitousBlacklists();
+};
+
+/******************************************************************************/
+
+µBlock.loadPublicSuffixList = function() {
+ var applyPublicSuffixList = function(details) {
+ // TODO: Not getting proper suffix list is a bit serious, I think
+ // the extension should be force-restarted if it occurs..
+ if ( !details.error ) {
+ publicSuffixList.parse(details.content, punycode.toASCII);
+ }
+ };
+ this.assets.get(
+ 'assets/thirdparties/publicsuffix.org/list/effective_tld_names.dat',
+ applyPublicSuffixList
+ );
+};
+
+/******************************************************************************/
+
+// Load updatable assets
+
+µBlock.loadUpdatableAssets = function() {
+ this.loadUbiquitousBlacklists();
+ this.loadPublicSuffixList();
+};
+
+/******************************************************************************/
+
+// Load all
+
+µBlock.load = function() {
+ this.loadLocalSettings();
+ this.loadUserSettings();
+
+ // load updatable assets -- after updating them if needed
+ this.assetUpdater.update(null, this.loadUpdatableAssets.bind(this));
+
+ this.getBytesInUse();
+};
diff --git a/js/tab.js b/js/tab.js
new file mode 100644
index 000000000..b218ecce9
--- /dev/null
+++ b/js/tab.js
@@ -0,0 +1,166 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global chrome, µBlock */
+
+/******************************************************************************/
+
+(function(){
+ function onTabCreated(tab) {
+ // Can this happen?
+ if ( tab.id < 0 || !tab.url || tab.url === '' ) {
+ return;
+ }
+ µBlock.bindTabToPageStats(tab.id, tab.url);
+ }
+ chrome.tabs.onCreated.addListener(onTabCreated);
+
+ function onTabUpdated(tabId, changeInfo, tab) {
+ // Can this happen?
+ if ( !tab.url || tab.url === '' ) {
+ return;
+ }
+ if ( changeInfo.url ) {
+ µBlock.bindTabToPageStats(tabId, tab.url);
+ µBlock.updateBadge(tabId);
+ }
+ }
+ chrome.tabs.onUpdated.addListener(onTabUpdated);
+
+ function onTabRemoved(tabId) {
+ if ( tabId < 0 ) {
+ return;
+ }
+ µBlock.unbindTabFromPageStats(tabId);
+ }
+ chrome.tabs.onRemoved.addListener(onTabRemoved);
+
+ function onBeforeNavigateCallback(details) {
+ if ( details.frameId > 0 ) {
+ return;
+ }
+ µBlock.bindTabToPageStats(details.tabId, details.url);
+ }
+ chrome.webNavigation.onBeforeNavigate.addListener(onBeforeNavigateCallback);
+
+ // Initialize internal state with maybe already existing tabs
+ chrome.tabs.query({ url: '' }, function(tabs) {
+ var i = tabs.length;
+ while ( i-- ) {
+ µBlock.bindTabToPageStats(tabs[i].id, tabs[i].url);
+ }
+ });
+})();
+
+/******************************************************************************/
+/******************************************************************************/
+
+// https://github.com/gorhill/httpswitchboard/issues/303
+// Some kind of trick going on here:
+// Any scheme other than 'http' and 'https' is remapped into a fake
+// URL which trick the rest of µBlock into being able to process an
+// otherwise unmanageable scheme. µBlock needs web page to have a proper
+// hostname to work properly, so just like the 'chromium-behind-the-scene'
+// fake domain name, we map unknown schemes into a fake '{scheme}-scheme'
+// hostname. This way, for a specific scheme you can create scope with
+// rules which will apply only to that scheme.
+
+µBlock.normalizePageURL = function(pageURL) {
+ var uri = this.URI.set(pageURL);
+ if ( uri.scheme === 'https' || uri.scheme === 'http' ) {
+ return uri.normalizedURI();
+ }
+ return '';
+}
+
+/******************************************************************************/
+
+// Create an entry for the tab if it doesn't exist.
+
+µBlock.bindTabToPageStats = function(tabId, pageURL) {
+ // First unbind whatever page store is bound to the tab id.
+ this.unbindTabFromPageStats(tabId);
+
+ // https://github.com/gorhill/httpswitchboard/issues/303
+ // Normalize to a page-URL.
+ pageURL = this.normalizePageURL(pageURL);
+
+ // do not create stats store for urls which are of no interests
+ if ( pageURL === '' ) {
+ return null;
+ }
+
+ // Bring back existing page store or create new one.
+ var pageStore = this.pageStores[tabId];
+ if ( !pageStore ) {
+ var k = pageURL + ' ' + tabId;
+ pageStore = this.pageStoreDump[k];
+ if ( pageStore ) {
+ delete this.pageStoreDump[k];
+ }
+ }
+
+ if ( !pageStore ) {
+ pageStore = this.PageStore.factory(tabId, pageURL);
+ pageStore.perLoadAllowedRequestCount =
+ pageStore.perLoadBlockedRequestCount = 0;
+ }
+
+ this.pageStores[tabId] = pageStore;
+
+ return pageStore;
+};
+
+µBlock.unbindTabFromPageStats = function(tabId) {
+ var pageStore = this.pageStores[tabId];
+ if ( pageStore ) {
+ //pageStore.disposeTime = Date.now();
+ //this.pageStoreDump[pageStore.pageURL + ' ' + tabId] = pageStore;
+ }
+ delete this.pageStores[tabId];
+};
+
+/******************************************************************************/
+
+µBlock.pageUrlFromTabId = function(tabId) {
+ var pageStore = this.pageStores[tabId];
+ return pageStore ? pageStore.pageURL : '';
+};
+
+µBlock.pageUrlFromPageStats = function(pageStats) {
+ if ( pageStats ) {
+ return pageStats.pageURL;
+ }
+ return '';
+};
+
+µBlock.pageStoreFromTabId = function(tabId) {
+ return this.pageStores[tabId];
+};
+
+/******************************************************************************/
+
+µBlock.forceReload = function(pageURL) {
+ var tabId = this.tabIdFromPageUrl(pageURL);
+ if ( tabId ) {
+ chrome.tabs.reload(tabId, { bypassCache: true });
+ }
+};
diff --git a/js/traffic.js b/js/traffic.js
new file mode 100644
index 000000000..b931a48a0
--- /dev/null
+++ b/js/traffic.js
@@ -0,0 +1,137 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* jshint multistr: true */
+/* global chrome, µBlock */
+
+/******************************************************************************/
+
+// Start isolation from global scope
+
+µBlock.webRequest = (function() {
+
+/******************************************************************************/
+
+// Intercept and filter web requests according to white and black lists.
+
+var onBeforeRequestHandler = function(details) {
+ var requestType = details.type;
+
+ // console.debug('onBeforeRequestHandler()> "%s": %o', details.url, details);
+
+ // Do not block behind the scene requests.
+ if ( details.tabId < 0 ) {
+ return;
+ }
+
+ // Never block root main doc.
+ if ( requestType === 'main_frame' && details.parentFrameId < 0 ) {
+ return;
+ }
+
+ var µb = µBlock;
+ var µburi = µb.URI;
+ var requestURL = µburi.set(details.url).normalizedURI();
+ var requestScheme = µburi.scheme;
+ var requestHostname = µburi.hostname;
+ var requestPath = µburi.path;
+
+ // Ignore non-http schemes
+ if ( requestScheme.indexOf('http') !== 0 ) {
+ return;
+ }
+
+ // Do not block myself from updating assets
+ if ( requestType === 'xmlhttprequest' && requestURL.slice(0, µb.projectServerRoot.length) === µb.projectServerRoot ) {
+ return;
+ }
+
+ // rhill 2013-12-15:
+ // Try to transpose generic `other` category into something more
+ // meaningful.
+ if ( requestType === 'other' ) {
+ requestType = µb.transposeType(requestType, requestPath);
+ }
+
+ // Lookup the page store associated with this tab id.
+ var pageStore = µb.pageStoreFromTabId(details.tabId) || {};
+
+ var reason = false;
+ if ( µb.getNetFilteringSwitch(pageStore.pageHostname) ) {
+ reason = µb.abpFilters.matchString(pageStore, requestURL, requestType, requestHostname);
+ }
+
+ // Block using ABP filters?
+ pageStore.recordRequest(requestType, requestURL, reason);
+
+ // whitelisted?
+ if ( reason === false ) {
+ return;
+ }
+
+ // blacklisted
+ // console.debug('onBeforeRequestHandler()> BLOCK "%s": %o', details.url, details);
+
+ // If it's a blacklisted frame, redirect to something harmless.
+ if ( requestType === 'sub_frame' ) {
+ return { 'redirectUrl': 'about:blank' };
+ }
+
+ return { 'cancel': true };
+};
+
+/******************************************************************************/
+
+chrome.webRequest.onBeforeRequest.addListener(
+ //function(details) {
+ // quickProfiler.start('onBeforeRequest');
+ // var r = onBeforeRequestHandler(details);
+ // quickProfiler.stop();
+ // return r;
+ //},
+ onBeforeRequestHandler,
+ {
+ "urls": [
+ "http://*/*",
+ "https://*/*",
+ ],
+ "types": [
+ "main_frame",
+ "sub_frame",
+ 'stylesheet',
+ "script",
+ "image",
+ "object",
+ "xmlhttprequest",
+ "other"
+ ]
+ },
+ [ "blocking" ]
+);
+
+console.log('µBlock> Beginning to intercept net requests at %s', (new Date()).toISOString());
+
+/******************************************************************************/
+
+})();
+
+/******************************************************************************/
+
diff --git a/js/ublock.js b/js/ublock.js
new file mode 100644
index 000000000..a9ee20178
--- /dev/null
+++ b/js/ublock.js
@@ -0,0 +1,158 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global chrome, µBlock */
+
+/******************************************************************************/
+
+µBlock.getNetFilteringSwitch = function(hostname) {
+ var exceptionList = this.userSettings.exceptionList;
+ if ( exceptionList[hostname] !== undefined ) {
+ return false;
+ }
+ var hostnames = this.URI.parentHostnamesFromHostname(hostname);
+ while ( hostname = hostnames.shift() ) {
+ if ( exceptionList[hostname] !== undefined ) {
+ return false;
+ }
+ }
+ return true;
+};
+
+/******************************************************************************/
+
+µBlock.toggleNetFilteringSwitch = function(hostname, newState) {
+ var currentState = this.getNetFilteringSwitch(hostname);
+ if ( newState === undefined ) {
+ newState = !currentState;
+ }
+ if ( newState === currentState ) {
+ return currentState;
+ }
+ var exceptionList = this.userSettings.exceptionList;
+
+ // Add to exception list
+ if ( !newState ) {
+ exceptionList[hostname] = true;
+ this.saveExceptionList();
+ return true;
+ }
+
+ // Remove from exception list
+ if ( newState ) {
+ var hostnames = this.URI.allHostnamesFromHostname(hostname);
+ while ( hostname = hostnames.shift() ) {
+ if ( exceptionList[hostname] !== undefined ) {
+ delete exceptionList[hostname];
+ }
+ }
+ this.saveExceptionList();
+ return false;
+ }
+};
+
+/******************************************************************************/
+
+µBlock.saveExceptionList = function() {
+ chrome.storage.local.set({
+ 'exceptionList': this.userSettings.exceptionList
+ });
+};
+
+/******************************************************************************/
+
+µBlock.changeUserSettings = function(name, value) {
+ if ( typeof name !== 'string' || name === '' ) {
+ return;
+ }
+
+ var µb = µBlock;
+
+ // Do not allow an unknown user setting to be created
+ if ( µb.userSettings[name] === undefined ) {
+ return;
+ }
+
+ if ( value === undefined ) {
+ return µb.userSettings[name];
+ }
+
+ // Pre-change
+ switch ( name ) {
+
+ default:
+ break;
+ }
+
+ // Change
+ µb.userSettings[name] = value;
+
+ // Post-change
+ switch ( name ) {
+
+ default:
+ break;
+ }
+
+ µb.saveUserSettings();
+};
+
+/******************************************************************************/
+
+µBlock.transposeType = function(type, path) {
+ if ( type === 'other' ) {
+ var pos = path.lastIndexOf('.');
+ if ( pos > 0 ) {
+ var ext = path.slice(pos);
+ if ( '.eot.ttf.otf.svg.woff'.indexOf(ext) >= 0 ) {
+ return 'stylesheet';
+ }
+ if ( '.ico.png'.indexOf(ext) >= 0 ) {
+ return 'image';
+ }
+ }
+ }
+ return type;
+};
+
+/******************************************************************************/
+
+µBlock.formatCount = function(count) {
+ if ( typeof count !== 'number' ) {
+ return '';
+ }
+ var s = count.toFixed(0);
+ if ( count >= 1000 ) {
+ if ( count < 10000 ) {
+ s = '>' + s.slice(0,1) + 'K';
+ } else if ( count < 100000 ) {
+ s = s.slice(0,2) + 'K';
+ } else if ( count < 1000000 ) {
+ s = s.slice(0,3) + 'K';
+ } else if ( count < 10000000 ) {
+ s = s.slice(0,1) + 'M';
+ } else {
+ s = s.slice(0,-6) + 'M';
+ }
+ }
+ return s;
+};
+
diff --git a/js/uritools.js b/js/uritools.js
new file mode 100644
index 000000000..92ab43668
--- /dev/null
+++ b/js/uritools.js
@@ -0,0 +1,416 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global µBlock, publicSuffixList */
+
+/*******************************************************************************
+
+RFC 3986 as reference: http://tools.ietf.org/html/rfc3986#appendix-A
+
+Naming convention from https://en.wikipedia.org/wiki/URI_scheme#Examples
+
+*/
+
+/******************************************************************************/
+
+// This will inserted as a module in the µBlock object.
+
+µBlock.URI = (function() {
+
+/******************************************************************************/
+
+// Favorite regex tool: http://regex101.com/
+
+// Ref:
+// I removed redundant capture groups: capture less = peform faster. See
+//
+// Performance improvements welcomed.
+// jsperf:
+var reRFC3986 = /^([^:\/?#]+:)?(\/\/[^\/?#]*)?([^?#]*)(\?[^#]*)?(#.*)?/;
+
+// Derived
+var reSchemeFromURI = /^[^:\/?#]+:/;
+var reAuthorityFromURI = /^(?:[^:\/?#]+:)?(\/\/[^\/?#]+)/;
+
+// These are to parse authority field, not parsed by above official regex
+// IPv6 is seen as an exception: a non-compatible IPv6 is first tried, and
+// if it fails, the IPv6 compatible regex istr used. This helps
+// peformance by avoiding the use of a too complicated regex first.
+
+// https://github.com/gorhill/httpswitchboard/issues/211
+// "While a hostname may not contain other characters, such as the
+// "underscore character (_), other DNS names may contain the underscore"
+var reHostPortFromAuthority = /^(?:[^@]*@)?([0-9a-z._-]*)(:\d*)?$/i;
+var reIPv6PortFromAuthority = /^(?:[^@]*@)?(\[[0-9a-f:]*\])(:\d*)?$/i;
+
+var reHostFromNakedAuthority = /^[0-9a-z._-]+[0-9a-z]$/i;
+var reHostFromAuthority = /^(?:[^@]*@)?([0-9a-z._-]+)(?::\d*)?$/i;
+var reIPv6FromAuthority = /^(?:[^@]*@)?(\[[0-9a-f:]+\])(?::\d*)?$/i;
+
+// Coarse (but fast) tests
+var reValidHostname = /^([a-z\d]+(-*[a-z\d]+)*)(\.[a-z\d]+(-*[a-z\d])*)*$/;
+var reIPAddressNaive = /^\d+\.\d+\.\d+\.\d+$|^\[[\da-zA-Z:]+\]$/;
+
+// Accurate tests
+// Source.: http://stackoverflow.com/questions/5284147/validating-ipv4-addresses-with-regexp/5284410#5284410
+var reIPv4 = /^((25[0-5]|2[0-4]\d|[01]?\d\d?)(\.|$)){4}/;
+
+// Source: http://forums.intermapper.com/viewtopic.php?p=1096#1096
+var reIPv6 = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
+
+/******************************************************************************/
+
+var reset = function(o) {
+ o.scheme = '';
+ o.hostname = '';
+ o._ipv4 = undefined;
+ o._ipv6 = undefined;
+ o.port = '';
+ o.path = '';
+ o.query = '';
+ o.fragment = '';
+ return o;
+};
+
+var resetAuthority = function(o) {
+ o.hostname = '';
+ o._ipv4 = undefined;
+ o._ipv6 = undefined;
+ o.port = '';
+ return o;
+};
+
+/******************************************************************************/
+
+// This will be exported
+
+var URI = {
+ scheme: '',
+ authority: '',
+ hostname: '',
+ _ipv4: undefined,
+ _ipv6: undefined,
+ port: '',
+ domain: undefined,
+ path: '',
+ query: '',
+ fragment: '',
+ schemeBit: (1 << 0),
+ userBit: (1 << 1),
+ passwordBit: (1 << 2),
+ hostnameBit: (1 << 3),
+ portBit: (1 << 4),
+ pathBit: (1 << 5),
+ queryBit: (1 << 6),
+ fragmentBit: (1 << 7),
+ allBits: (0xFFFF)
+};
+
+URI.authorityBit = (URI.userBit | URI.passwordBit | URI.hostnameBit | URI.portBit);
+URI.normalizeBits = (URI.schemeBit | URI.hostnameBit | URI.pathBit | URI.queryBit);
+
+/******************************************************************************/
+
+// See: https://en.wikipedia.org/wiki/URI_scheme#Examples
+// URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
+//
+// foo://example.com:8042/over/there?name=ferret#nose
+// \_/ \______________/\_________/ \_________/ \__/
+// | | | | |
+// scheme authority path query fragment
+// | _____________________|__
+// / \ / \
+// urn:example:animal:ferret:nose
+
+URI.set = function(uri) {
+ if ( uri === undefined ) {
+ return reset(URI);
+ }
+ var matches = reRFC3986.exec(uri);
+ if ( !matches ) {
+ return reset(URI);
+ }
+ this.scheme = matches[1] !== undefined ? matches[1].slice(0, -1) : '';
+ this.authority = matches[2] !== undefined ? matches[2].slice(2).toLowerCase() : '';
+ this.path = matches[3] !== undefined ? matches[3] : '';
+
+ //
+ // "In general, a URI that uses the generic syntax for authority
+ // "with an empty path should be normalized to a path of '/'."
+ if ( this.authority !== '' && this.path === '' ) {
+ this.path = '/';
+ }
+ this.query = matches[4] !== undefined ? matches[4].slice(1) : '';
+ this.fragment = matches[5] !== undefined ? matches[5].slice(1) : '';
+
+ // Assume very simple authority, i.e. just a hostname (highest likelihood
+ // case for µBlock)
+ if ( reHostFromNakedAuthority.test(this.authority) ) {
+ this.hostname = this.authority;
+ this.port = '';
+ return this;
+ }
+ // Authority contains more than just a hostname
+ matches = reHostPortFromAuthority.exec(this.authority);
+ if ( !matches ) {
+ matches = reIPv6PortFromAuthority.exec(this.authority);
+ if ( !matches ) {
+ return resetAuthority(URI);
+ }
+ }
+ this.hostname = matches[1] !== undefined ? matches[1] : '';
+ // http://en.wikipedia.org/wiki/FQDN
+ if ( this.hostname.slice(-1) === '.' ) {
+ this.hostname = this.hostname.slice(0, -1);
+ }
+ this.port = matches[2] !== undefined ? matches[2].slice(1) : '';
+ return this;
+};
+
+/******************************************************************************/
+
+// URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
+//
+// foo://example.com:8042/over/there?name=ferret#nose
+// \_/ \______________/\_________/ \_________/ \__/
+// | | | | |
+// scheme authority path query fragment
+// | _____________________|__
+// / \ / \
+// urn:example:animal:ferret:nose
+
+URI.assemble = function(bits) {
+ if ( bits === undefined ) {
+ bits = this.allBits;
+ }
+ var s = [];
+ if ( this.scheme && (bits & this.schemeBit) ) {
+ s.push(this.scheme, ':');
+ }
+ if ( this.hostname && (bits & this.hostnameBit) ) {
+ s.push('//', this.hostname);
+ }
+ if ( this.port && (bits & this.portBit) ) {
+ s.push(':', this.port);
+ }
+ if ( this.path && (bits & this.pathBit) ) {
+ s.push(this.path);
+ }
+ if ( this.query && (bits & this.queryBit) ) {
+ s.push('?', this.query);
+ }
+ if ( this.fragment && (bits & this.fragmentBit) ) {
+ s.push('#', this.fragment);
+ }
+ return s.join('');
+};
+
+/******************************************************************************/
+
+URI.schemeFromURI = function(uri) {
+ var matches = reSchemeFromURI.exec(uri);
+ if ( !matches ) {
+ return '';
+ }
+ return matches[0].slice(0, -1).toLowerCase();
+};
+
+/******************************************************************************/
+
+URI.authorityFromURI = function(uri) {
+ var matches = reAuthorityFromURI.exec(uri);
+ if ( !matches ) {
+ return '';
+ }
+ return matches[1].slice(2).toLowerCase();
+};
+
+/******************************************************************************/
+
+// The most used function, so it better be fast.
+
+URI.hostnameFromURI = function(uri) {
+ var matches = reAuthorityFromURI.exec(uri);
+ if ( !matches ) {
+ return '';
+ }
+ var authority = matches[1].slice(2);
+ // Assume very simple authority (most common case for µBlock)
+ if ( reHostFromNakedAuthority.test(authority) ) {
+ return authority.toLowerCase();
+ }
+ matches = reHostFromAuthority.exec(authority);
+ if ( !matches ) {
+ matches = reIPv6FromAuthority.exec(authority);
+ if ( !matches ) {
+ return '';
+ }
+ }
+ // http://en.wikipedia.org/wiki/FQDN
+ var hostname = matches[1];
+ if ( hostname.slice(-1) === '.' ) {
+ hostname = hostname.slice(0, -1);
+ }
+ return hostname.toLowerCase();
+};
+
+/******************************************************************************/
+
+// It is expected that there is higher-scoped `publicSuffixList` lingering
+// somewhere. Cache it. See .
+var psl = publicSuffixList;
+
+URI.domainFromHostname = function(hostname) {
+ if ( !reIPAddressNaive.test(hostname) ) {
+ return psl.getDomain(hostname);
+ }
+ return hostname;
+};
+
+URI.domain = function() {
+ return this.domainFromHostname(this.hostname);
+};
+
+/******************************************************************************/
+
+URI.domainFromURI = function(uri) {
+ if ( !uri ) {
+ return '';
+ }
+ return this.domainFromHostname(this.hostnameFromURI(uri));
+};
+
+/******************************************************************************/
+
+// Normalize the way µBlock expects it
+
+URI.normalizedURI = function() {
+ // Will be removed:
+ // - port
+ // - user id/password
+ // - fragment
+ return this.assemble(this.normalizeBits);
+};
+
+/******************************************************************************/
+
+URI.rootURL = function() {
+ if ( !this.hostname ) {
+ return '';
+ }
+ return this.assemble(this.schemeBit | this.hostnameBit);
+};
+
+/******************************************************************************/
+
+URI.isValidHostname = function(hostname) {
+ var r;
+ try {
+ r = reValidHostname.test(hostname);
+ }
+ catch (e) {
+ return false;
+ }
+ return r;
+};
+
+/******************************************************************************/
+
+// Return the parent domain. For IP address, there is no parent domain.
+
+URI.parentHostnameFromHostname = function(hostname) {
+ // `locahost` => ``
+ // `example.org` => `example.org`
+ // `www.example.org` => `example.org`
+ // `tomato.www.example.org` => `example.org`
+ var domain = this.domainFromHostname(hostname);
+
+ // `locahost` === `` => bye
+ // `example.org` === `example.org` => bye
+ // `www.example.org` !== `example.org` => stay
+ // `tomato.www.example.org` !== `example.org` => stay
+ if ( domain === '' || domain === hostname ) {
+ return undefined;
+ }
+
+ // Parent is hostname minus first label
+ return hostname.slice(hostname.indexOf('.') + 1);
+};
+
+/******************************************************************************/
+
+// Return all possible parent hostnames which can be derived from `hostname`,
+// ordered from direct parent up to domain inclusively.
+
+URI.parentHostnamesFromHostname = function(hostname) {
+ // TODO: I should create an object which is optimized to receive
+ // the list of hostnames by making it reusable (junkyard etc.) and which
+ // has its own element counter property in order to avoid memory
+ // alloc/dealloc.
+ var domain = this.domainFromHostname(hostname);
+ if ( domain === '' || domain === hostname ) {
+ return [];
+ }
+ var nodes = [];
+ var pos;
+ for (;;) {
+ pos = hostname.indexOf('.');
+ if ( pos < 0 ) {
+ break;
+ }
+ hostname = hostname.slice(pos + 1);
+ nodes.push(hostname);
+ if ( hostname === domain ) {
+ break;
+ }
+ }
+ return nodes;
+};
+
+/******************************************************************************/
+
+// Return all possible hostnames which can be derived from `hostname`,
+// ordered from self up to domain inclusively.
+
+URI.allHostnamesFromHostname = function(hostname) {
+ var nodes = this.parentHostnamesFromHostname(hostname);
+ nodes.unshift(hostname);
+ return nodes;
+};
+
+/******************************************************************************/
+
+URI.toString = function() {
+ return this.assemble();
+};
+
+/******************************************************************************/
+
+// Export
+
+return URI;
+
+/******************************************************************************/
+
+})();
+
+/******************************************************************************/
+
diff --git a/js/utils.js b/js/utils.js
new file mode 100644
index 000000000..78509ea79
--- /dev/null
+++ b/js/utils.js
@@ -0,0 +1,109 @@
+/*******************************************************************************
+
+ µBlock - a Chromium browser extension to block requests.
+ Copyright (C) 2014 Raymond Hill
+
+ 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/}.
+
+ Home: https://github.com/gorhill/uBlock
+*/
+
+/* global chrome, µBlock */
+
+/******************************************************************************/
+
+// This will inserted as a module in the µBlock object.
+
+µBlock.utils = (function() {
+
+/******************************************************************************/
+
+var gotoURL = function(details) {
+ if ( details.tabId ) {
+ chrome.tabs.update(details.tabId, { url: details.url });
+ } else {
+ chrome.tabs.create({ url: details.url });
+ }
+};
+
+/******************************************************************************/
+
+var gotoExtensionURL = function(url) {
+ var hasFragment = function(url) {
+ return url.indexOf('#') >= 0;
+ };
+
+ var removeFragment = function(url) {
+ var pos = url.indexOf('#');
+ if ( pos < 0 ) {
+ return url;
+ }
+ return url.slice(0, pos);
+ };
+
+ var tabIndex = 9999;
+ var targetUrl = chrome.extension.getURL(url);
+ var urlToFind = removeFragment(targetUrl);
+
+ var currentWindow = function(tabs) {
+ var updateProperties = { active: true };
+ var i = tabs.length;
+ while ( i-- ) {
+ if ( removeFragment(tabs[i].url) !== urlToFind ) {
+ continue;
+ }
+ // If current tab in dashboard is different, force the new one, if
+ // there is one, to be activated.
+ if ( tabs[i].url !== targetUrl ) {
+ if ( hasFragment(targetUrl) ) {
+ updateProperties.url = targetUrl;
+ }
+ }
+ // Activate found matching tab
+ // Commented out as per:
+ // https://github.com/gorhill/httpswitchboard/issues/150#issuecomment-32683726
+ // chrome.tabs.move(tabs[0].id, { index: index + 1 });
+ chrome.tabs.update(tabs[i].id, updateProperties);
+ return;
+ }
+ chrome.tabs.create({ 'url': targetUrl, index: tabIndex + 1 });
+ };
+
+ var currentTab = function(tabs) {
+ if ( tabs.length ) {
+ tabIndex = tabs[0].index;
+ }
+ chrome.tabs.query({ currentWindow: true }, currentWindow);
+ };
+
+ // https://github.com/gorhill/httpswitchboard/issues/150
+ // Logic:
+ // - If URL is already opened in a tab, just activate tab
+ // - Otherwise find the current active tab and open in a tab immediately
+ // to the right of the active tab
+ chrome.tabs.query({ active: true }, currentTab);
+};
+
+/******************************************************************************/
+
+return {
+ gotoURL: gotoURL,
+ gotoExtensionURL: gotoExtensionURL
+};
+
+/******************************************************************************/
+
+})();
+
+/******************************************************************************/
diff --git a/lib/jquery-2.min.js b/lib/jquery-2.min.js
new file mode 100644
index 000000000..cbe6abe59
--- /dev/null
+++ b/lib/jquery-2.min.js
@@ -0,0 +1,4 @@
+/*! jQuery v2.1.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
+!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m=a.document,n="2.1.0",o=function(a,b){return new o.fn.init(a,b)},p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};o.fn=o.prototype={jquery:n,constructor:o,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=o.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return o.each(this,a,b)},map:function(a){return this.pushStack(o.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},o.extend=o.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||o.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(o.isPlainObject(d)||(e=o.isArray(d)))?(e?(e=!1,f=c&&o.isArray(c)?c:[]):f=c&&o.isPlainObject(c)?c:{},g[b]=o.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},o.extend({expando:"jQuery"+(n+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===o.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isPlainObject:function(a){if("object"!==o.type(a)||a.nodeType||o.isWindow(a))return!1;try{if(a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(b){return!1}return!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=o.trim(a),a&&(1===a.indexOf("use strict")?(b=m.createElement("script"),b.text=a,m.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":k.call(a)},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?o.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),o.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||o.guid++,f):void 0},now:Date.now,support:l}),o.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=o.type(a);return"function"===c||o.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);o.find=t,o.expr=t.selectors,o.expr[":"]=o.expr.pseudos,o.unique=t.uniqueSort,o.text=t.getText,o.isXMLDoc=t.isXML,o.contains=t.contains;var u=o.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(o.isFunction(b))return o.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return o.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return o.filter(b,a,c);b=o.filter(b,a)}return o.grep(a,function(a){return g.call(b,a)>=0!==c})}o.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?o.find.matchesSelector(d,a)?[d]:[]:o.find.matches(a,o.grep(b,function(a){return 1===a.nodeType}))},o.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(o(a).filter(function(){for(b=0;c>b;b++)if(o.contains(e[b],this))return!0}));for(b=0;c>b;b++)o.find(a,e[b],d);return d=this.pushStack(c>1?o.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?o(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=o.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof o?b[0]:b,o.merge(this,o.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:m,!0)),v.test(c[1])&&o.isPlainObject(b))for(c in b)o.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=m.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=m,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):o.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(o):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),o.makeArray(a,this))};A.prototype=o.fn,y=o(m);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};o.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&o(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),o.fn.extend({has:function(a){var b=o(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(o.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?o(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&o.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?o.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(o(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(o.unique(o.merge(this.get(),o(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}o.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return o.dir(a,"parentNode")},parentsUntil:function(a,b,c){return o.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return o.dir(a,"nextSibling")},prevAll:function(a){return o.dir(a,"previousSibling")},nextUntil:function(a,b,c){return o.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return o.dir(a,"previousSibling",c)},siblings:function(a){return o.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return o.sibling(a.firstChild)},contents:function(a){return a.contentDocument||o.merge([],a.childNodes)}},function(a,b){o.fn[a]=function(c,d){var e=o.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=o.filter(d,e)),this.length>1&&(C[a]||o.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return o.each(a.match(E)||[],function(a,c){b[c]=!0}),b}o.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):o.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){o.each(b,function(b,c){var d=o.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&o.each(arguments,function(a,b){var c;while((c=o.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?o.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},o.extend({Deferred:function(a){var b=[["resolve","done",o.Callbacks("once memory"),"resolved"],["reject","fail",o.Callbacks("once memory"),"rejected"],["notify","progress",o.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return o.Deferred(function(c){o.each(b,function(b,f){var g=o.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&o.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?o.extend(a,d):d}},e={};return d.pipe=d.then,o.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&o.isFunction(a.promise)?e:0,g=1===f?a:o.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&o.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;o.fn.ready=function(a){return o.ready.promise().done(a),this},o.extend({isReady:!1,readyWait:1,holdReady:function(a){a?o.readyWait++:o.ready(!0)},ready:function(a){(a===!0?--o.readyWait:o.isReady)||(o.isReady=!0,a!==!0&&--o.readyWait>0||(H.resolveWith(m,[o]),o.fn.trigger&&o(m).trigger("ready").off("ready")))}});function I(){m.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),o.ready()}o.ready.promise=function(b){return H||(H=o.Deferred(),"complete"===m.readyState?setTimeout(o.ready):(m.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},o.ready.promise();var J=o.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===o.type(c)){e=!0;for(h in c)o.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,o.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(o(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};o.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=o.expando+Math.random()}K.uid=1,K.accepts=o.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,o.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(o.isEmptyObject(f))o.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,o.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{o.isArray(b)?d=b.concat(b.map(o.camelCase)):(e=o.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!o.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?o.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}o.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),o.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;
+while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=o.camelCase(d.slice(5)),P(f,d,e[d]));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=o.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),o.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||o.isArray(c)?d=L.access(a,b,o.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=o.queue(a,b),d=c.length,e=c.shift(),f=o._queueHooks(a,b),g=function(){o.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:o.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),o.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";l.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return m.activeElement}catch(a){}}o.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=o.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof o!==U&&o.event.triggered!==b.type?o.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],n=q=h[1],p=(h[2]||"").split(".").sort(),n&&(l=o.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=o.event.special[n]||{},k=o.extend({type:n,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&o.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(n,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),o.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],n=q=h[1],p=(h[2]||"").split(".").sort(),n){l=o.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||o.removeEvent(a,n,r.handle),delete i[n])}else for(n in i)o.event.remove(a,n+b[j],c,d,!0);o.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,p=[d||m],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||m,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+o.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[o.expando]?b:new o.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:o.makeArray(c,[b]),n=o.event.special[q]||{},e||!n.trigger||n.trigger.apply(d,c)!==!1)){if(!e&&!n.noBubble&&!o.isWindow(d)){for(i=n.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||m)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:n.bindType||q,l=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),l&&l.apply(g,c),l=k&&g[k],l&&l.apply&&o.acceptData(g)&&(b.result=l.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||n._default&&n._default.apply(p.pop(),c)!==!1||!o.acceptData(d)||k&&o.isFunction(d[q])&&!o.isWindow(d)&&(h=d[k],h&&(d[k]=null),o.event.triggered=q,d[q](),o.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=o.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=o.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=o.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((o.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?o(e,this).index(i)>=0:o.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,bb=/<([\w:]+)/,cb=/<|?\w+;/,db=/<(?:script|style|link)/i,eb=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/^$|\/(?:java|ecma)script/i,gb=/^true\/(.*)/,hb=/^\s*\s*$/g,ib={option:[1,""],thead:[1,"