├── .gitmodules
├── LICENSE
├── Makefile
├── README.md
├── bootstrap.js
├── chrome.manifest
├── content
├── minidactyl.jsm
├── pterosaur.js
├── pterosaur.png
├── subprocess.jsm
└── subprocess_worker_unix.js
└── install.rdf
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "content/vimbed"]
2 | path = content/vimbed
3 | url = https://github.com/ardagnir/vimbed
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | pterosaur.xpi: chrome.manifest install.rdf content/minidactyl.jsm content/subprocess_worker_unix.js content/subprocess.jsm content/pterosaur.js bootstrap.js content/vimbed/plugin/vimbed.vim
2 | git submodule update
3 | zip pterosaur.xpi chrome.manifest install.rdf content/minidactyl.jsm content/subprocess_worker_unix.js content/subprocess.jsm content/pterosaur.js content/pterosaur.png bootstrap.js content/vimbed/plugin/vimbed.vim
4 |
5 | content/vimbed/plugin/vimbed.vim:
6 | git submodule update --init
7 |
8 | install:
9 | firefox pterosaur.xpi
10 |
11 | clean:
12 | rm pterosaur.xpi
13 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | **Note: THIS PROJECT IS NO LONGER MAINTAINED**
2 |
3 | **Due to the rules of my new employer, I likely won't be able to continue contributing to or maintaining Pterosaur as a Firefox addon for the foreseeable future. Pterosaur works through Firefox 38, which should be in ESR until mid-2016. Hopefully, I will have made a Chromium version well before then. I apologize to everybody whose workflow will be disrupted. Pterosaur is free software. There is nothing stopping you from forking it.**
4 |
5 | Pterosaur
6 | =========
7 |
8 | Pterosaur gives you the full power of Vim and your vimrc in each Firefox text field.
9 |
10 | 
11 |
12 | *Pterosaur supports most vim plugins. This demo uses Pterosaur v1.0 with the [vim-surround](http://github.com/tpope/vim-surround) plugin and a mod of the [invader-vim](http://github.com/mattn/invader-vim) script.*
13 |
14 | ## Requirements
15 | - Pterosaur requires [Vim](http://www.vim.org).
16 | - Your vim version needs to have [+clientserver](#vim-info) support compiled in. Run `vim --version | grep clientserver` to check. (You want a plus sign)
17 | - Pterosaur works best in GNU/Linux.
18 | - Pterosaur also works in OSX [(but read the OSX section first)](#mac-osx-notes)
19 |
20 | ## Installing
21 | ### The Easy Way:
22 | Click [here](http://ardagnir.github.io/pterosaur.xpi)
23 |
24 | ### The Normal Way:
25 | **Step 1:** Clone pterosaur. (If you're updating from a pre-1.0 version, just move pterosuar *out* of the Pentadactyl plugins directory and `git pull`)
26 |
27 | git clone --recursive http://github.com/ardagnir/pterosaur
28 |
29 | **Step 2:** Make and install pterosaur.
30 |
31 | cd pterosaur
32 | make
33 | make install
34 |
35 | *`make install` won't work for Mac users. Manually install the xpi after the `make` or use "The Easy Way" above.*
36 |
37 | ## How it works
38 | Pterosaur uses [vimbed](http://github.com/ardagnir/vimbed) to run an actual vim instance in the background and routes keystrokes through vim.
39 |
40 | Pterosaur attempts to be unobtrusive, so even though it edits every non-password textbox with vim, it starts out in vim's insert mode and enters vim's select mode when you select text with the mouse. This allows you to use traditional firefox mouse behavior, while still being able to leave insert mode and use anything you want from vim.
41 |
42 | ## Pentadactyl/Vimperator Integration
43 | Pterosaur integrates well with both Pentadactyl and Vimperator.
44 |
45 | While Pterosaur allows you to edit text with vim, Pentadactyl and Vimperator will give you vim like control over the rest of your browser. If you haven't already, you should consider installing one of them. (IMO Pentadactyl is better, but you have to [build it yourself](http://5digits.org/coding) for newer versions of Firefox.)
46 |
47 | ## Configuration
48 | Pterosaur can be configured by editing various configuration options. These can be edited in Firefox through the **about:config** or in Pentadactyl/Vimperator using the **:set!** command. All the following extensions begin with **extensions.pterosaur.**
49 |
50 | **enabled**: set to false to disable Pterosaur
51 |
52 | **contentonly**: When set to false, Pterosaur uses vim in the chrome areas of the browser window (like the awesomebar and firebug). When set to true, only web content uses vim. Defaults to true.
53 |
54 | **allowprivate**: By default, Pterosaur will *not* send keys typed in private browsing mode to vim. If you set this to true, it will not treat private browsing any differently than normal browsing.
55 |
56 | **autorestart**: Defaults to true. If you quit vim with autorestart enabled, vim will start back up automatically. Otherwise, typing :q in normal mode will make Pterosaur unusable.
57 |
58 | **verbose**: Causes pterosaur to display extra information to the browser console.
59 |
60 | **restartnow**: Set this to true to restart Pterosaur's vim instance. Especially useful if you don't have autorestart enabled or if you switched vimbinaries and don't want to restart Firefox. This automatically sets back to false after half a second so that it can be used again.
61 |
62 | Pentadactyl and Vimperator users can also restart vim using the :pterosaurrestart command.
63 |
64 | **vimbinary**: Set this to the path of the vim binary you want Pterosaur to use. Pick a [terminal vim binary with +clientserver enabled](#vim-info).
65 |
66 | **debugtty**: Set this to a tty to display Pterosaur's running vim process on that tty. Type `tty` in any terminal window to get the string you'll need to type. It should look something like `/dev/pts/0`
67 |
68 | **rcfile**: Set this to a file (default: ~/.pterosaurrc) to have Pterosaur's vim load that file on startup. This is useful for Pterosaur-specific vim settings.
69 |
70 | **exitkey**: Pressing this key will cause the textbox to lose focus if pressed in normal mode or immediately following an Escape press. The default value is ``. Control values can be used in the form `` or `` (case sensitive).
71 |
72 | **envoverrides**: A space seperated list of environment variables with values used to to override the defaults when calling vim. For example, you might set this value to something like "DISPLAY=:0 XAUTHORITY=/home/me/.Xauthority" if you are using firefox with X11 forwarding. Most environment variables not specified here will inherit their values from Firefox.
73 |
74 | ## FAQ
75 | **Q:** Why isn't Pterosaur working in firebug?
76 | **A:** By default, pterosaur is only enbled for web content. You can enable it for browser chrome and extensions by setting [extensions.pterosaur.contentonly](#configuration) to false.
77 |
78 | **Q:** Can I use gvim with Pterosaur?
79 | **A:** Usually, yes. Pterosaur automatically tells vim to run in the console using the "-v" flag. If typing "gvim -v" on your computer brings up a console vim, you can probably use it for pterosaur. Make sure to set the [vimbinary](#configuration) to gvim.
80 |
81 | **Q:** Why am I having issues deleting text?
82 | **A:** Pterosaur uses your vim settings, which may prevent you from deleting text depending on your `set backspace` value. You can change this for all of vim in your ~/.vimrc, or just pterosaur in the ~/.pterosaurrc.
83 |
84 | ## Vim Info
85 | Pterosaur requires that you use a terminal version of vim with +clientserver support compiled in. You can test your vim's clientserver support by running:
86 |
87 | vim --version | grep clientserver
88 |
89 | +clientserver is usually good enough, but if you want to use plugins that call vim's "input()" function in Pterosaur you also need to have vim compiled without gui support. (Often terminal vim can be run in gui mode with a -g flag. Even if you never use the -g flag, support for this breaks the "input()" function in headless vim.)
90 |
91 | The easiest way to make sure you have +clientserver is to install your distro's "biggest" vim package. If you want to build an appropriate vim yourself, here's an example:
92 |
93 | hg clone https://vim.googlecode.com/hg/ vim
94 | cd vim
95 | ./configure --with-features=huge --disable-gui
96 | make
97 | sudo make install
98 |
99 | If you don't want to overwrite your normal vim, you can change the last line to something like:
100 |
101 | sudo cp src/vim /usr/bin/pterosaurvim
102 |
103 | In this case, make sure to edit firefox's **about:config** and set [extensions.pterosaur.vimbinary](#configuration) to `/usr/bin/pterosaurvim`
104 |
105 | Note that if you install a new vim binary, some distro-based vim settings you might take for granted, such as `set backspace += start` might need to be defined in your vimrc.
106 |
107 | ## Mac OSX notes
108 | - Pterosaur requires XQuartz to function on OSX. *(This is a requirement of vim's +clientserver functionality.)*
109 | - Pterosaur will **not** work with MacVim. You need to install a standard vim program with +clientserver using MacPorts or Homebrew.
110 | - If you have Homebrew, you can install vim with +clientserver using:
111 |
112 | `brew install vim --with-client-server`
113 |
114 | - If you have MacPorts, use:
115 |
116 | `sudo port install vim +huge +x11`
117 |
118 | - MacPorts will install vim to something like /opt/local/bin/vim. Make sure to set that as your [vimbinary](#configuration).
119 | - Note that if you install a new vim binary, some vim settings you might take for granted, such as `set backspace += start` might need to be defined in your vimrc
120 |
121 | ## Privacy
122 | Be aware that since Pterosaur sends all your keystrokes through vim, it can temporarily store sensitive data on your computer. For this reason, Pterosaur is automatically disabled for password fields. There is no such protection for other data, such as credit card numbers. You can wipe this data by quiting vim and destroying the `/tmp/vimbed/pterosaur*` directory. It should also automatically be destroyed when you quit Firefox.
123 |
124 | By default Pterosaur is disabled in private browsing mode. You can enable Pterosaur in prvate browsing by setting [extensions.pterosaur.allowprivate](#configuration) to true.
125 |
126 | ## Bugs
127 | - If you find a bug, please create a github issue.
128 |
129 | - Pterosaur does not yet support vim mode for google docs and will fail over to normal editing.
130 |
131 | ## Troubleshooting
132 | Pterosaur should "just work", but if it doesn't:
133 |
134 | 1. Make sure you are running master. It is the stable version.
135 |
136 | 2. Make sure the [vimbinary](#configuration) points to a version of vim with [+clientserver](#vim-info) enabled.
137 |
138 | 3. Set the [debugtty](#configuration) to a terminal and see if vim is running correctly.
139 |
140 | 4. Run `vim --serverlist`. See if there's a server starting with "PTEROSAUR"
141 |
142 | 6. If there's still a problem, create an issue and let me know the results of steps 3 and 4, as well as your operating system, firefox version, the webpage you're having problems with, and if you're running Pentadactyl/Vimperator.
143 |
144 | ## Hacking/Contributing
145 | - One of the best ways to contribute is to report bugs in the issues section.
146 |
147 | - You can also submit patches to fix issues. Find an issue that isn't assigned and let me know you're working on it.
148 |
149 | ## License
150 | AGPL v3
151 |
--------------------------------------------------------------------------------
/bootstrap.js:
--------------------------------------------------------------------------------
1 | /* This is part of Pterosaur.
2 | *
3 | * Copyright (c) 2015 James Kolb
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU Affero General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU Affero General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU Affero General Public License
16 | * along with this program. If not, see .
17 | */
18 | Components.utils.import("resource://gre/modules/Services.jsm");
19 |
20 | var scopes = {};
21 | function require(module)
22 | {
23 | if (!(module in scopes))
24 | {
25 | let url = "chrome://pterosaur/content/" + module + ".js";
26 | scopes[module] = {
27 | require: require,
28 | exports: {}
29 | };
30 | Services.scriptloader.loadSubScript(url, scopes[module]);
31 | }
32 | return scopes[module].exports;
33 | }
34 |
35 | var pterosaur;
36 |
37 | function startup(data, reason) {
38 | ///
39 | /// Bootstrap data structure @see https://developer.mozilla.org/en-US/docs/Extensions/Bootstrapped_extensions#Bootstrap_data
40 | ///
string id
41 | ///
string version
42 | ///
nsIFile installPath
43 | ///
nsIURI resourceURI
44 | ///
45 | /// Reason types:
46 | ///
APP_STARTUP
47 | ///
ADDON_ENABLE
48 | ///
ADDON_INSTALL
49 | ///
ADDON_UPGRADE
50 | ///
ADDON_DOWNGRADE
51 | ///
52 | pterosaur = require("pterosaur");
53 | forEachOpenWindow(pterosaur.setup);
54 | Services.wm.addListener(WindowListener);
55 | }
56 |
57 | var WindowListener =
58 | {
59 | onOpenWindow: function(xulWindow)
60 | {
61 | var window = xulWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
62 | .getInterface(Components.interfaces.nsIDOMWindow);
63 | function onWindowLoad()
64 | {
65 | window.removeEventListener("load", onWindowLoad);
66 | if (window.document.documentElement.getAttribute("windowtype") == "navigator:browser")
67 | pterosaur.setup(window);
68 | }
69 | window.addEventListener("load", onWindowLoad);
70 | },
71 | onCloseWindow: function(xulWindow) {
72 | var window = xulWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
73 | .getInterface(Components.interfaces.nsIDOMWindow);
74 | function onWindowUnload()
75 | {
76 | window.removeEventListener("unload", onWindowUnload);
77 | if (window.document.documentElement.getAttribute("windowtype") == "navigator:browser")
78 | {
79 | pterosaur.shutdown(window);
80 | }
81 | }
82 | window.addEventListener("unload", onWindowUnload);
83 | },
84 | onWindowTitleChange: function(xulWindow, newTitle) { }
85 | }
86 |
87 | function shutdown(data, reason) {
88 | ///
89 | /// Bootstrap data structure @see https://developer.mozilla.org/en-US/docs/Extensions/Bootstrapped_extensions#Bootstrap_data
90 | ///
string id
91 | ///
string version
92 | ///
nsIFile installPath
93 | ///
nsIURI resourceURI
94 | ///
95 | /// Reason types:
96 | ///
APP_SHUTDOWN
97 | ///
ADDON_DISABLE
98 | ///
ADDON_UNINSTALL
99 | ///
ADDON_UPGRADE
100 | ///
ADDON_DOWNGRADE
101 | ///
102 | forEachOpenWindow(pterosaur.shutdown);
103 | Services.wm.removeListener(WindowListener);
104 | }
105 | function install(data, reason) {
106 | ///
107 | /// Bootstrap data structure @see https://developer.mozilla.org/en-US/docs/Extensions/Bootstrapped_extensions#Bootstrap_data
108 | ///
string id
109 | ///
string version
110 | ///
nsIFile installPath
111 | ///
nsIURI resourceURI
112 | ///
113 | /// Reason types:
114 | ///
ADDON_INSTALL
115 | ///
ADDON_UPGRADE
116 | ///
ADDON_DOWNGRADE
117 | ///
118 | }
119 | function uninstall(data, reason) {
120 | ///
121 | /// Bootstrap data structure @see https://developer.mozilla.org/en-US/docs/Extensions/Bootstrapped_extensions#Bootstrap_data
122 | ///
string id
123 | ///
string version
124 | ///
nsIFile installPath
125 | ///
nsIURI resourceURI
126 | ///
127 | /// Reason types:
128 | ///
ADDON_UNINSTALL
129 | ///
ADDON_UPGRADE
130 | ///
ADDON_DOWNGRADE
131 | ///
132 | }
133 |
134 | function forEachOpenWindow(todo) {
135 | var windows = Services.wm.getEnumerator("navigator:browser")
136 | while (windows.hasMoreElements()) {
137 | todo(windows.getNext().QueryInterface(Components.interfaces.nsIDOMWindow));
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/chrome.manifest:
--------------------------------------------------------------------------------
1 | content pterosaur content/
2 |
--------------------------------------------------------------------------------
/content/minidactyl.jsm:
--------------------------------------------------------------------------------
1 | /* This is part of Pterosaur.
2 | *
3 | * Copyright (c) 2015 James Kolb
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU Affero General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU Affero General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU Affero General Public License
16 | * along with this program. If not, see .
17 | *
18 | * This file incorporates work covered under the following copyright and permission notice:
19 | * Copyright © 2006-2009 by Martin Stubenschrott
20 | * Copyright © 2007-2011 by Doug Kearns
21 | * Copyright © 2008-2011 by Kris Maglione
22 | *
23 | * For a full list of authors, refer the AUTHORS file.
24 | *
25 | * Permission is hereby granted, free of charge, to any person obtaining a
26 | * copy of this software and associated documentation files (the "Software"),
27 | * to deal in the Software without restriction, including without limitation
28 | * the rights to use, copy, modify, merge, publish, distribute, sublicense,
29 | * and/or sell copies of the Software, and to permit persons to whom the
30 | * Software is furnished to do so, subject to the following conditions:
31 | *
32 | * The above copyright notice and this permission notice shall be included in
33 | * all copies or substantial portions of the Software.
34 | *
35 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
36 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
37 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
38 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
40 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
41 | * DEALINGS IN THE SOFTWARE.
42 | */
43 | 'use strict';
44 |
45 | let EXPORTED_SYMBOLS = ["minidactyl"];
46 |
47 | const Cc = Components.classes;
48 | const Ci = Components.interfaces;
49 | const Cr = Components.results;
50 |
51 | var Environment = Components.classes["@mozilla.org/process/environment;1"].getService(Components.interfaces.nsIEnvironment);
52 |
53 | Components.utils.import("resource://gre/modules/FileUtils.jsm");
54 |
55 | var minidactyl = function(console, window, editing, focusManager, pluginType){
56 | this.console = console;
57 | this.window = window;
58 | this.editing = editing;
59 | this.focusManager = focusManager;
60 | this.pluginType = pluginType;
61 | var thisInst = this;
62 | /**
63 | * Converts a given DOM Node, Range, or Selection to a string. If
64 | * *html* is true, the output is HTML, otherwise it is presentation
65 | * text.
66 | *
67 | * @param {nsIDOMNode | nsIDOMRange | nsISelection} node The node to
68 | * stringify.
69 | * @param {boolean} html Whether the output should be HTML rather
70 | * than presentation text.
71 | */
72 | this.stringify = function stringify(node, html) {
73 | if (node instanceof Ci.nsISelection && node.isCollapsed)
74 | return "";
75 |
76 | if (node instanceof Ci.nsIDOMNode) {
77 | let range = node.ownerDocument.createRange();
78 | range.selectNode(node);
79 | node = range;
80 | }
81 | let doc = (node.getRangeAt ? node.getRangeAt(0) : node).startContainer;
82 | doc = doc.ownerDocument || doc;
83 |
84 | let encoder = Cc["@mozilla.org/layout/htmlCopyEncoder;1"].createInstance(Ci.nsIDocumentEncoder)
85 |
86 | encoder.init(doc, "text/unicode", encoder.OutputRaw|encoder.OutputPreformatted);
87 | if (node instanceof Ci.nsISelection)
88 | encoder.setSelection(node);
89 | else if (node instanceof Ci.nsIDOMRange)
90 | encoder.setRange(node);
91 |
92 | let str = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString)
93 | str.data = encoder.encodeToString();
94 |
95 |
96 | if (html)
97 | return str.data;
98 |
99 | let [result, length] = [{}, {}];
100 |
101 | let converter = Cc["@mozilla.org/widget/htmlformatconverter"].createInstance("nsIFromatConverter")
102 | converter.convert("text/html", str, str.data.length*2, "text/unicode", result, length);
103 | return result.value.QueryInterface(Ci.nsISupportsString).data;
104 | };
105 | this.code_key= JSON.parse('{"3":"Cancel","6":"Help","8":"BS","9":"Tab","12":"Clear","13":"Return","16":"Shift","17":"Control","18":"Alt","19":"Pause","20":"CapsLock","21":"Hangul","22":"Eisu","23":"Junja","24":"Final","25":"Kanji","27":"Esc","28":"Convert","29":"Nonconvert","30":"Accept","31":"Modechange","32":"Space","33":"PageUp","34":"PageDown","35":"End","36":"Home","37":"Left","38":"Up","39":"Right","40":"Down","41":"Select","42":"Print","43":"Execute","44":"Printscreen","45":"Insert","46":"Del","48":"0","49":"1","50":"2","51":"3","52":"4","53":"5","54":"6","55":"7","56":"8","57":"9","58":"Colon","59":";","60":"lt","61":"=","62":"GreaterThan","63":"QuestionMark","64":"At","65":"a","66":"b","67":"c","68":"d","69":"e","70":"f","71":"g","72":"h","73":"i","74":"j","75":"k","76":"l","77":"m","78":"n","79":"o","80":"p","81":"q","82":"r","83":"s","84":"t","85":"u","86":"v","87":"w","88":"x","89":"y","90":"z","91":"Win","93":"ContextMenu","95":"Sleep","96":"Numpad0","97":"Numpad1","98":"Numpad2","99":"Numpad3","100":"Numpad4","101":"Numpad5","102":"Numpad6","103":"Numpad7","104":"Numpad8","105":"Numpad9","106":"Multiply","107":"+","108":"Separator","109":"-","110":"Decimal","111":"Divide","112":"F1","113":"F2","114":"F3","115":"F4","116":"F5","117":"F6","118":"F7","119":"F8","120":"F9","121":"F10","122":"F11","123":"F12","124":"F13","125":"F14","126":"F15","127":"F16","128":"F17","129":"F18","130":"F19","131":"F20","132":"F21","133":"F22","134":"F23","135":"F24","144":"NumLock","145":"ScrollLock","146":"WinOemFjJisho","147":"WinOemFjMasshou","148":"WinOemFjTouroku","149":"WinOemFjLoya","150":"WinOemFjRoya","160":"Circumflex","161":"Exclamation","162":"DoubleQuote","163":"Hash","164":"Dollar","165":"Percent","166":"Ampersand","167":"Underscore","168":"OpenParen","169":"CloseParen","170":"Asterisk","171":"Plus","172":"Pipe","173":"HyphenMinus","174":"OpenCurlyBracket","175":"CloseCurlyBracket","176":"Tilde","181":"VolumeMute","182":"VolumeDown","183":"VolumeUp","188":",","190":".","191":"/","192":"`","219":"[","220":"\\\\","221":"]","222":"'+"'"+'","224":"Meta","225":"Altgr","227":"WinIcoHelp","228":"WinIco00","230":"WinIcoClear","233":"WinOemReset","234":"WinOemJump","235":"WinOemPa1","236":"WinOemPa2","237":"WinOemPa3","238":"WinOemWsctrl","239":"WinOemCusel","240":"WinOemAttn","241":"WinOemFinish","242":"WinOemCopy","243":"WinOemAuto","244":"WinOemEnlw","245":"WinOemBacktab","246":"Attn","247":"Crsel","248":"Exsel","249":"Ereof","250":"Play","251":"Zoom","253":"Pa1","254":"WinOemClear"}');
106 | this.key_code= JSON.parse('{"0":48,"1":49,"2":50,"3":51,"4":52,"5":53,"6":54,"7":55,"8":56,"9":57,"cancel":3,"help":6,"bs":8,"tab":9,"clear":12,"return":13,"cr":13,"enter":13,"shift":16,"control":17,"alt":18,"pause":19,"capslock":20,"kana":21,"hangul":21,"eisu":22,"junja":23,"final":24,"hanja":25,"kanji":25,"esc":27,"escape":27,"convert":28,"nonconvert":29,"accept":30,"modechange":31,"space":32," ":32,"pageup":33,"pagedown":34,"end":35,"home":36,"left":37,"up":38,"right":39,"down":40,"select":41,"print":42,"execute":43,"printscreen":44,"insert":45,"ins":45,"del":46,"colon":58,";":59,"lessthan":60,"=":61,"greaterthan":62,"questionmark":63,"at":64,"a":65,"b":66,"c":67,"d":68,"e":69,"f":70,"g":71,"h":72,"i":73,"j":74,"k":75,"l":76,"m":77,"n":78,"o":79,"p":80,"q":81,"r":82,"s":83,"t":84,"u":85,"v":86,"w":87,"x":88,"y":89,"z":90,"win":91,"contextmenu":93,"sleep":95,"numpad0":96,"numpad1":97,"numpad2":98,"numpad3":99,"numpad4":100,"numpad5":101,"numpad6":102,"numpad7":103,"numpad8":104,"numpad9":105,"multiply":106,"+":107,"plus":171,"add":107,"separator":108,"-":109,"minus":109,"subtract":109,"decimal":110,"divide":111,"f1":112,"f2":113,"f3":114,"f4":115,"f5":116,"f6":117,"f7":118,"f8":119,"f9":120,"f10":121,"f11":122,"f12":123,"f13":124,"f14":125,"f15":126,"f16":127,"f17":128,"f18":129,"f19":130,"f20":131,"f21":132,"f22":133,"f23":134,"f24":135,"numlock":144,"scrolllock":145,"winoemfjjisho":146,"winoemfjmasshou":147,"winoemfjtouroku":148,"winoemfjloya":149,"winoemfjroya":150,"circumflex":160,"exclamation":161,"doublequote":162,"hash":163,"dollar":164,"percent":165,"ampersand":166,"underscore":167,"openparen":168,"closeparen":169,"asterisk":170,"pipe":172,"hyphenminus":173,"opencurlybracket":174,"closecurlybracket":175,"tilde":176,"volumemute":181,"volumedown":182,"volumeup":183,",":188,".":190,"/":191,"`":192,"[":219,"\\\\":220,"]":221,"'+"'"+'":222,"meta":224,"altgr":225,"winicohelp":227,"winico00":228,"winicoclear":230,"winoemreset":233,"winoemjump":234,"winoempa1":235,"winoempa2":236,"winoempa3":237,"winoemwsctrl":238,"winoemcusel":239,"winoemattn":240,"winoemfinish":241,"winoemcopy":242,"winoemauto":243,"winoemenlw":244,"winoembacktab":245,"attn":246,"crsel":247,"exsel":248,"ereof":249,"play":250,"zoom":251,"pa1":253,"winoemclear":254,"<":60,"lt":60}');
107 | this.key_key = JSON.parse('{"0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","+":"+","plus":"Plus","add":"Add","`":"`","\\\\":"\\\\","bs":"BS",",":",","count":"count","]":"]","del":"Del","=":"=","esc":"Esc","escape":"Escape","insert":"Insert","ins":"Ins","leader":"Leader","lt":"LT","<":"<","nop":"Nop","[":"[","pass":"Pass",".":".","'+"'"+'":"'+"'"+'","return":"Return","cr":"CR","enter":"Enter",">":">",";":";","/":"/","space":"Space"," ":" ","-":"-","minus":"Minus","subtract":"Subtract","cancel":"Cancel","help":"Help","tab":"Tab","clear":"Clear","shift":"Shift","control":"Control","alt":"Alt","pause":"Pause","capslock":"CapsLock","kana":"Kana","hangul":"Hangul","eisu":"Eisu","junja":"Junja","final":"Final","hanja":"Hanja","kanji":"Kanji","convert":"Convert","nonconvert":"Nonconvert","accept":"Accept","modechange":"Modechange","pageup":"PageUp","pagedown":"PageDown","end":"End","home":"Home","left":"Left","up":"Up","right":"Right","down":"Down","select":"Select","print":"Print","execute":"Execute","printscreen":"Printscreen","colon":"Colon","lessthan":"LessThan","greaterthan":"GreaterThan","questionmark":"QuestionMark","at":"At","a":"a","b":"b","c":"c","d":"d","e":"e","f":"f","g":"g","h":"h","i":"i","j":"j","k":"k","l":"l","m":"m","n":"n","o":"o","p":"p","q":"q","r":"r","s":"s","t":"t","u":"u","v":"v","w":"w","x":"x","y":"y","z":"z","win":"Win","contextmenu":"ContextMenu","sleep":"Sleep","numpad0":"Numpad0","numpad1":"Numpad1","numpad2":"Numpad2","numpad3":"Numpad3","numpad4":"Numpad4","numpad5":"Numpad5","numpad6":"Numpad6","numpad7":"Numpad7","numpad8":"Numpad8","numpad9":"Numpad9","multiply":"Multiply","separator":"Separator","decimal":"Decimal","divide":"Divide","f1":"F1","f2":"F2","f3":"F3","f4":"F4","f5":"F5","f6":"F6","f7":"F7","f8":"F8","f9":"F9","f10":"F10","f11":"F11","f12":"F12","f13":"F13","f14":"F14","f15":"F15","f16":"F16","f17":"F17","f18":"F18","f19":"F19","f20":"F20","f21":"F21","f22":"F22","f23":"F23","f24":"F24","numlock":"NumLock","scrolllock":"ScrollLock","winoemfjjisho":"WinOemFjJisho","winoemfjmasshou":"WinOemFjMasshou","winoemfjtouroku":"WinOemFjTouroku","winoemfjloya":"WinOemFjLoya","winoemfjroya":"WinOemFjRoya","circumflex":"Circumflex","exclamation":"Exclamation","doublequote":"DoubleQuote","hash":"Hash","dollar":"Dollar","percent":"Percent","ampersand":"Ampersand","underscore":"Underscore","openparen":"OpenParen","closeparen":"CloseParen","asterisk":"Asterisk","pipe":"Pipe","hyphenminus":"HyphenMinus","opencurlybracket":"OpenCurlyBracket","closecurlybracket":"CloseCurlyBracket","tilde":"Tilde","volumemute":"VolumeMute","volumedown":"VolumeDown","volumeup":"VolumeUp","meta":"Meta","altgr":"Altgr","winicohelp":"WinIcoHelp","winico00":"WinIco00","winicoclear":"WinIcoClear","winoemreset":"WinOemReset","winoemjump":"WinOemJump","winoempa1":"WinOemPa1","winoempa2":"WinOemPa2","winoempa3":"WinOemPa3","winoemwsctrl":"WinOemWsctrl","winoemcusel":"WinOemCusel","winoemattn":"WinOemAttn","winoemfinish":"WinOemFinish","winoemcopy":"WinOemCopy","winoemauto":"WinOemAuto","winoemenlw":"WinOemEnlw","winoembacktab":"WinOemBacktab","attn":"Attn","crsel":"Crsel","exsel":"Exsel","ereof":"Ereof","play":"Play","zoom":"Zoom","pa1":"Pa1","winoemclear":"WinOemClear"}');
108 | /**
109 | * Converts the specified event to a string in dactyl key-code
110 | * notation. Returns null for an unknown event.
111 | *
112 | * @param {Event} event
113 | * @returns {string}
114 | */
115 | this.stringifyEvent= function stringify(event) {
116 | //if (isArray(event))
117 | // return event.map(e => this.stringify(e)).join("");
118 |
119 | if (event.dactylString)
120 | return event.dactylString;
121 |
122 | let key = null;
123 | let modifier = "";
124 |
125 | if (event.globKey)
126 | modifier += "*-";
127 | if (event.ctrlKey)
128 | modifier += "C-";
129 | if (event.altKey)
130 | modifier += "A-";
131 | if (event.metaKey)
132 | modifier += "M-";
133 |
134 | if (/^key/.test(event.type)) {
135 | let charCode = event.type == "keyup" ? 0 : event.charCode; // Why? --Kris
136 | if (charCode == 0) {
137 | if (event.keyCode in this.code_key) {
138 | key = this.code_key[event.keyCode];
139 |
140 | if (event.shiftKey && (key.length > 1 || key.toUpperCase() == key.toLowerCase()
141 | || event.ctrlKey || event.altKey || event.metaKey)
142 | || event.dactylShift)
143 | modifier += "S-";
144 | else if (!modifier && key.length === 1)
145 | if (event.shiftKey)
146 | key = key.toUpperCase();
147 | else
148 | key = key.toLowerCase();
149 |
150 | if (!modifier && key.length == 1)
151 | return key;
152 | }
153 | }
154 | // [Ctrl-Bug] special handling of mysterious , , , , bugs (OS/X)
155 | // (i.e., cntrl codes 27--31)
156 | // ---
157 | // For more information, see:
158 | // [*] Referenced mailing list msg: http://www.mozdev.org/pipermail/pentadactyl/2008-May/001548.html
159 | // [*] Mozilla bug 416227: event.charCode in keypress handler has unexpected values on Mac for Ctrl with chars in "[ ] _ \"
160 | // https://bugzilla.mozilla.org/show_bug.cgi?id=416227
161 | // [*] Mozilla bug 432951: Ctrl+'foo' doesn't seem same charCode as Meta+'foo' on Cocoa
162 | // https://bugzilla.mozilla.org/show_bug.cgi?id=432951
163 | // ---
164 | //
165 | // The following fixes are only activated if config.OS.isMacOSX.
166 | // Technically, they prevent mappings from (and
167 | // if your fancy keyboard permits such things>), but
168 | // these mappings are probably pathological (
169 | // certainly is on Windows), and so it is probably
170 | // harmless to remove the config.OS.isMacOSX if desired.
171 | //
172 | else if (/*config.OS.isMacOSX &&*/ event.ctrlKey && charCode >= 27 && charCode <= 31) {
173 | if (charCode == 27) { // [Ctrl-Bug 1/5] the bug
174 | key = "Esc";
175 | modifier = modifier.replace("C-", "");
176 | }
177 | else // [Ctrl-Bug 2,3,4,5/5] the , , , bugs
178 | key = String.fromCharCode(charCode + 64);
179 | }
180 | // a normal key like a, b, c, 0, etc.
181 | else if (charCode) {
182 | key = String.fromCharCode(charCode);
183 |
184 | if (!/^[^<\s]$/i.test(key) && key in this.key_code) {
185 | // a named charCode key ( and ) space can be shifted, must be forced
186 | if ((key.match(/^\s$/) && event.shiftKey) || event.dactylShift)
187 | modifier += "S-";
188 |
189 | key = this.code_key[this.key_code[key]];
190 | }
191 | else {
192 | // a shift modifier is only allowed if the key is alphabetical and used in a C-A-M- mapping in the uppercase,
193 | // or if the shift has been forced for a non-alphabetical character by the user while :map-ping
194 | if (key !== key.toLowerCase() && (event.ctrlKey || event.altKey || event.metaKey) || event.dactylShift)
195 | modifier += "S-";
196 | if (/^\s$/.test(key))
197 | key = let (s = charCode.toString(16)) "U" + "0000".substr(4 - s.length) + s;
198 | else if (modifier.length == 0)
199 | return key;
200 | }
201 | }
202 | if (key == null) {
203 | if (event.shiftKey)
204 | modifier += "S-";
205 | key = thisInst.key_key[event.key] || event.key;
206 | }
207 | if (key == null)
208 | return null;
209 | }
210 | else if (event.type == "click" || event.type == "dblclick") {
211 | if (event.shiftKey)
212 | modifier += "S-";
213 | if (event.type == "dblclick")
214 | modifier += "2-";
215 | // TODO: triple and quadruple click
216 |
217 | switch (event.button) {
218 | case 0:
219 | key = "LeftMouse";
220 | break;
221 | case 1:
222 | key = "MiddleMouse";
223 | break;
224 | case 2:
225 | key = "RightMouse";
226 | break;
227 | }
228 | }
229 |
230 | if (key == null)
231 | return null;
232 |
233 | return "<" + modifier + key + ">";
234 | };
235 | /**
236 | * Searches for the given executable file in the system executable
237 | * file paths as specified by the PATH environment variable.
238 | *
239 | * On Windows, if the unadorned filename cannot be found, the
240 | * extensions in the semicolon-separated list in the PATHSEP
241 | * environment variable are successively appended to the original
242 | * name and searched for in turn.
243 | *
244 | * @param {string} bin The name of the executable to find.
245 | * @returns {File|null}
246 | */
247 | this.pathSearch = function pathSearch(bin) {
248 | //if (bin instanceof File || File.isAbsolutePath(bin))
249 | //return this.File(bin);
250 |
251 | //TODO: WINDOWS_COMPAT
252 | let PATH_SEPERATOR=":";
253 | let dirs = Environment.get("PATH")
254 | .split(PATH_SEPERATOR);
255 |
256 | //TODO: WINDOWS_COMPAT Windows tries the CWD first TODO: desirable?
257 | //if (config.OS.isWindows)
258 | //dirs = [io.cwd].concat(dirs);
259 |
260 | for (let [, dir] in Iterator(dirs))
261 | try {
262 | let file = FileUtils.File(dir);
263 |
264 | file.append(bin);
265 |
266 | if (file.exists() && file.isFile() && file.isExecutable())
267 | return file;
268 |
269 | // TODO: couldn't we just palm this off to the start command?
270 | // automatically try to add the executable path extensions on windows
271 | /*
272 | if (config.OS.isWindows) {
273 | let extensions = services.environment.get("PATHEXT").split(";");
274 | for (let [, extension] in Iterator(extensions)) {
275 | file = dir.child(bin + extension);
276 | if (file.exists())
277 | return file;
278 | }
279 | }
280 | */
281 | }
282 | catch (e) {}
283 | return null;
284 | };
285 |
286 | /**
287 | * Original Pentadactyl comment (Has since been simplified and only takes one key):
288 | * Pushes keys onto the event queue from dactyl. It is similar to
289 | * Vim's feedkeys() method, but cannot cope with 2 partially-fed
290 | * strings, you have to feed one parseable string.
291 | *
292 | * @param {string} keys A string like "2" to push onto the event
293 | * queue. If you want "<" to be taken literally, prepend it with a
294 | * "\\".
295 | * @param {boolean} noremap Whether recursive mappings should be
296 | * disallowed.
297 | * @param {boolean} silent Whether the command should be echoed to the
298 | * command line.
299 | * @returns {boolean}
300 | */
301 | //NOTE: Do not use with pentadactyl. Use pentadactyl's feedkeys instead.
302 | this.feedkey = function (key, focusedElement) {
303 | let evt_obj = thisInst.parse(key)[0];
304 | ["keydown", "keypress", "keyup"].forEach(function(type){
305 | let evt = {};
306 | for(var dictKey in evt_obj){
307 | evt[dictKey] = evt_obj[dictKey];
308 | }
309 | evt['type'] = type;
310 | evt['key'] = key;
311 | evt['bubbles'] = true;
312 | evt['cancelable'] = true;
313 | //let evt = update({}, evt_obj, { type: type });
314 | if (type !== "keypress" && !evt.keyCode)
315 | evt.keyCode = evt._keyCode || 0;
316 |
317 | evt.isMacro = true;
318 | //evt.dactylMode = mode;
319 | //evt.dactylSavedEvents = savedEvents;
320 | //DOM.Event.feedingEvent = evt;
321 |
322 | //let doc = document.commandDispatcher.focusedWindow.document;
323 | //TODO_DESIGNMODE
324 | let doc = thisInst.window.content.document;
325 |
326 |
327 | //dactyl.focusedElement
328 | let target = thisInst.focusManager.getFocusedElementForWindow(thisInst.window, true, {})
329 | || ["complete", "interactive"].indexOf(doc.readyState) >= 0 && doc.documentElement
330 | || doc.defaultView;
331 |
332 | //if (target instanceof Element && !this.isInputElement(target) &&
333 | //["", ""].indexOf(key) == -1)
334 | // target = target.ownerDocument.documentElement;
335 |
336 | //let event = DOM.Event(doc, type, evt_obj);
337 | //let event = target.ownerDocument.createEvent('KeyEvents');
338 | let event = new thisInst.window.KeyboardEvent(type, evt);
339 | //if (!evt_obj.dactylString && !mode)
340 | thisInst.dispatchEvent(target, event, evt);
341 | //else if (type === "keypress")
342 | //events.events.keypress.call(events, event);
343 | });
344 | };
345 | this.isInputElement = function isInputElement(elem) {
346 | return elem instanceof Ci.nsIDOMElement && true/*TODO: DOM(elem).isEditable*/ ||
347 | isinstance(elem, [Ci.nsIDOMHTMLEmbedElement,
348 | Ci.nsIDOMHTMLObjectElement,
349 | Ci.nsIDOMHTMLSelectElement]);
350 | };
351 |
352 | /**
353 | * Dispatches an event to an element as if it were a native event.
354 | *
355 | * @param {Node} target The DOM node to which to dispatch the event.
356 | * @param {Event} event The event to dispatch.
357 | */
358 | this.dispatchEvent = function dispatch(target, event, extra) {
359 | try {
360 | //this.feedingEvent = extra;
361 |
362 | if (target instanceof Ci.nsIDOMElement) {
363 | return (target.ownerDocument || target.document || target).defaultView
364 | .QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils)
365 | .dispatchDOMEventViaPresShell(target, event, true);
366 | }
367 | else {
368 | target.dispatchEvent(event);
369 | return !event.defaultPrevented;
370 | }
371 | }
372 | catch (e) {
373 | console.log(e)
374 | //util.reportError(e);
375 | }
376 | finally {
377 | //this.feedingEvent = null;
378 | }
379 | };
380 | this.wrappedFile = function( file ) {
381 | var MODE_WRONLY = 0x02;
382 | var MODE_CREATE = 0x08;
383 | var MODE_TRUNCATE = 0x20;
384 |
385 | this.write = function(text){
386 | function getStream(defaultChar) {
387 | var stream = Components.classes["@mozilla.org/intl/converter-output-stream;1"].createInstance(Ci.nsIConverterOutputStream);
388 | stream.init(ofstream, encoding, 0, defaultChar)
389 | return stream;
390 | }
391 | let mode = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
392 | let perms = 0o600;
393 | let ofstream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
394 | ofstream.init(file, mode, perms, 0);
395 | let encoding = 'UTF8';
396 | try{
397 | var ocstream = getStream(0);
398 | ocstream.writeString(text)
399 | }
400 | catch (e if e.result == Cr.NS_ERROR_LOSS_OF_SIGNIFICANT_DATA) {
401 | ocstream.close();
402 | ocstream = getStream("?".charCodeAt(0));
403 | ocstream.writeString(text);
404 | return false;
405 | }
406 | finally {
407 | try {
408 | ocstream.close();
409 | }
410 | catch (e) {}
411 | ofstream.close();
412 | }
413 | return true;
414 | };
415 |
416 | this.read = function(encoding) {
417 | var ifstream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
418 | ifstream.init(file, -1, 0, 0);
419 | return this.readStream(ifstream, encoding || 'UTF-8');
420 |
421 | }
422 | this.readStream = function(ifstream, encoding) {
423 | try {
424 | var icstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"].createInstance(Ci.nsIConverterInputStream, Ci.nsIUnicharLineInputStream);
425 | icstream.init(ifstream, encoding || File.defaultEncoding, 4096, // buffer size
426 | icstream.DEFAULT_REPLACEMENT_CHARACTER);
427 |
428 | let buffer = [];
429 | let str = {};
430 | while (icstream.readString(4096, str) != 0)
431 | buffer.push(str.value);
432 | return buffer.join("");
433 | }
434 | finally {
435 | icstream.close();
436 | ifstream.close();
437 | }
438 | }
439 | this.path = file.path;
440 | };
441 | this.nodeContents = function nodeContents(node) {
442 | let range = node.ownerDocument.createRange();
443 | try {
444 | range.selectNodeContents(node);
445 | }
446 | catch(e) {}
447 | return range;
448 | };
449 | this.keyHandler = {
450 | mappings: {},
451 | listener: null,
452 | addKeyDown: function(key, callback){
453 | thisInst.keyHandler.mappings[key]=callback;
454 | },
455 | removeKeyDown: function(key){
456 | delete thisInst.keyHandler.mappings[key];
457 | },
458 | keydown: function(e){
459 | if (thisInst.editing()){
460 | var callback = thisInst.keyHandler.mappings[thisInst.stringifyEvent(e)];
461 | if (callback) {
462 | let returnVal = callback();
463 | if(!returnVal) {
464 | e.stopPropagation();
465 | e.preventDefault();
466 | }
467 | return returnVal;
468 | }
469 | }
470 | else{
471 | return true;
472 | }
473 | },
474 | onKeyPress: function(){
475 | //override this
476 | },
477 | keypress: function(e){
478 | let returnVal = thisInst.keyHandler.onKeyPress(e);
479 | if(!returnVal) {
480 | e.stopPropagation();
481 | e.preventDefault();
482 | }
483 | return returnVal;
484 | }
485 | };
486 |
487 | thisInst.window.addEventListener("keydown", thisInst.keyHandler.keydown, true);
488 | thisInst.window.addEventListener("keypress", thisInst.keyHandler.keypress, true);
489 |
490 | this.shutdown = function(){
491 | thisInst.window.removeEventListener("keydown", thisInst.keyHandler.keydown, true);
492 | thisInst.window.removeEventListener("keypress", thisInst.keyHandler.keypress, true);
493 | }
494 |
495 | this.parse = function parse(input, unknownOk=true) {
496 | //if (isArray(input))
497 | // return array.flatten(input.map(k => this.parse(k, unknownOk)));
498 |
499 | let out = [];
500 | for (let match in thisInst.iterateRegex(/<.*?>?>|[^<]|<(?!.*>)/g, input)) {
501 | let evt_str = match[0];
502 |
503 | let evt_obj = { ctrlKey: false, shiftKey: false, altKey: false, metaKey: false,
504 | keyCode: 0, charCode: 0, type: "keypress" };
505 |
506 | if (evt_str.length == 1) {
507 | evt_obj.charCode = evt_str.charCodeAt(0);
508 | evt_obj._keyCode = this.key_code[evt_str[0].toLowerCase()];
509 | evt_obj.shiftKey = evt_str !== evt_str.toLowerCase();
510 | }
511 | else {
512 | let [match, modifier, keyname] = evt_str.match(/^<((?:[*12CASM⌘]-)*)(.+?)>$/i) || [false, '', ''];
513 | modifier = new Set(modifier.toUpperCase());
514 | keyname = keyname.toLowerCase();
515 | evt_obj.dactylKeyname = keyname;
516 | if (/^u[0-9a-f]+$/.test(keyname))
517 | keyname = String.fromCharCode(parseInt(keyname.substr(1), 16));
518 |
519 | if (keyname && (unknownOk || keyname.length == 1 || /mouse$/.test(keyname) ||
520 | this.key_code[keyname] || this.pseudoKeys.has(keyname))) {
521 | evt_obj.globKey = modifier.has("*");
522 | evt_obj.ctrlKey = modifier.has("C");
523 | evt_obj.altKey = modifier.has("A");
524 | evt_obj.shiftKey = modifier.has("S");
525 | evt_obj.metaKey = modifier.has("M") || modifier.has("⌘");
526 | evt_obj.dactylShift = evt_obj.shiftKey;
527 |
528 | if (keyname.length == 1) { // normal characters
529 | if (evt_obj.shiftKey)
530 | keyname = keyname.toUpperCase();
531 |
532 | evt_obj.dactylShift = evt_obj.shiftKey && keyname.toUpperCase() == keyname.toLowerCase();
533 | evt_obj.charCode = keyname.charCodeAt(0);
534 | evt_obj.keyCode = this.key_code[keyname.toLowerCase()];
535 | }
536 | else if (this.pseudoKeys.has(keyname)) {
537 | evt_obj.dactylString = "<" + this.key_key[keyname] + ">";
538 | }
539 | else if (/mouse$/.test(keyname)) { // mouse events
540 | evt_obj.type = (modifier.has("2") ? "dblclick" : "click");
541 | evt_obj.button = ["leftmouse", "middlemouse", "rightmouse"].indexOf(keyname);
542 | delete evt_obj.keyCode;
543 | delete evt_obj.charCode;
544 | }
545 | else { // spaces, control characters, and <
546 | evt_obj.keyCode = this.key_code[keyname];
547 | evt_obj.charCode = 0; }
548 | }
549 | else { // an invalid sequence starting with <, treat as a literal
550 | out = out.concat(this.parse("" + evt_str.substr(1)));
551 | continue;
552 | }
553 | }
554 |
555 | // TODO: make a list of characters that need keyCode and charCode somewhere
556 | if (evt_obj.keyCode == 32 || evt_obj.charCode == 32)
557 | evt_obj.charCode = evt_obj.keyCode = 32; //
558 | if (evt_obj.keyCode == 60 || evt_obj.charCode == 60)
559 | evt_obj.charCode = evt_obj.keyCode = 60; //
560 |
561 | evt_obj.modifiers = (evt_obj.ctrlKey && Ci.nsIDOMNSEvent.CONTROL_MASK)
562 | | (evt_obj.altKey && Ci.nsIDOMNSEvent.ALT_MASK)
563 | | (evt_obj.shiftKey && Ci.nsIDOMNSEvent.SHIFT_MASK)
564 | | (evt_obj.metaKey && Ci.nsIDOMNSEvent.META_MASK);
565 |
566 | out.push(evt_obj);
567 | }
568 | return out;
569 | };
570 | this.iterateRegex = function iterate(regexp, string, lastIndex) {
571 | regexp.lastIndex = lastIndex = lastIndex || 0;
572 | let match;
573 | while (match = regexp.exec(string)) {
574 | lastIndex = regexp.lastIndex;
575 | yield match;
576 | regexp.lastIndex = lastIndex;
577 | if (match[0].length == 0 || !regexp.global)
578 | break;
579 | }
580 | };
581 | this.pseudoKeys = Set(["count", "leader", "nop", "pass"]);
582 | }
583 |
--------------------------------------------------------------------------------
/content/pterosaur.js:
--------------------------------------------------------------------------------
1 | /* This is part of Pterosaur.
2 | *
3 | * Copyright (c) 2015 James Kolb
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU Affero General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU Affero General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU Affero General Public License
16 | * along with this program. If not, see .
17 | *
18 | * This file incorporates work covered under the following copyright and permission notice:
19 | * Copyright © 2006-2009 by Martin Stubenschrott
20 | * Copyright © 2007-2011 by Doug Kearns
21 | * Copyright © 2008-2011 by Kris Maglione
22 | *
23 | * For a full list of authors, refer the AUTHORS file.
24 | *
25 | * Permission is hereby granted, free of charge, to any person obtaining a
26 | * copy of this software and associated documentation files (the "Software"),
27 | * to deal in the Software without restriction, including without limitation
28 | * the rights to use, copy, modify, merge, publish, distribute, sublicense,
29 | * and/or sell copies of the Software, and to permit persons to whom the
30 | * Software is furnished to do so, subject to the following conditions:
31 | *
32 | * The above copyright notice and this permission notice shall be included in
33 | * all copies or substantial portions of the Software.
34 | *
35 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
36 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
37 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
38 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
40 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
41 | * DEALINGS IN THE SOFTWARE.
42 | */
43 |
44 | var exports = {};
45 |
46 | function pterosaurWindow(thisWindow){
47 | var pterosaur = this;
48 |
49 | var pluginType = "placeholder";
50 |
51 | Components.utils.import("chrome://pterosaur/content/subprocess.jsm");
52 | Components.utils.import("chrome://pterosaur/content/minidactyl.jsm");
53 | Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
54 |
55 | var focusManager = Components.classes["@mozilla.org/focus-manager;1"] .getService(Components.interfaces.nsIFocusManager);
56 | var Environment = Components.classes["@mozilla.org/process/environment;1"].getService(Components.interfaces.nsIEnvironment);
57 | var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.pterosaur.");
58 | var defaultPrefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getDefaultBranch("extensions.pterosaur.");
59 |
60 | pterosaur.minidactyl = new minidactyl(console, thisWindow, function(){return textBoxType !== ""}, focusManager, "");
61 |
62 | var vimNsIProc = null;
63 | var vimPath = "";
64 | try{
65 | vimPath = pterosaur.minidactyl.pathSearch("vim").path;
66 | }
67 | catch (e){
68 | }
69 |
70 | defaultPrefs.setBoolPref("contentonly", true);
71 | defaultPrefs.setBoolPref("enabled", true);
72 | defaultPrefs.setBoolPref("autorestart", true);
73 | defaultPrefs.setBoolPref("restartnow", false);
74 | defaultPrefs.setBoolPref("allowPrivate", false);
75 | defaultPrefs.setBoolPref("verbose", false);
76 | defaultPrefs.setCharPref("vimbinary", vimPath);
77 | defaultPrefs.setCharPref("debugtty", "");
78 | defaultPrefs.setCharPref("rcfile", "~/.pterosaurrc");
79 | defaultPrefs.setCharPref("exitkey", "");
80 | defaultPrefs.setCharPref("envoverrides", "");
81 |
82 | var borrowed;
83 | var modeLine;
84 | var modeText;
85 | //Is pterosaur being used?
86 | var usingFullVim = false;
87 | var strictVimCheck = false;
88 | var leanVimCheck = false;
89 |
90 | var debugMode =false;
91 |
92 | var waitForVim = 0;
93 |
94 | var vimGame = false; //If vim is changing on it's own without user input (like in a game), we need to poll more aggressively
95 |
96 | var pterosaurModes;
97 |
98 | var PASS_THROUGH = {};
99 |
100 | function setupPluginConnections(){
101 | var head;
102 | var newPluginType;
103 | if (typeof thisWindow.dactyl != "undefined"){
104 | head = thisWindow.dactyl;
105 | newPluginType = "dactyl";
106 | } else if (typeof thisWindow.liberator != "undefined"){
107 | head = thisWindow.liberator;
108 | newPluginType = "vimperator";
109 | } else {
110 | head = null;
111 | newPluginType = "";
112 | }
113 |
114 | thisWindow.setTimeout(setupPluginConnections, 5000);
115 | if(pluginType == newPluginType){
116 | return;
117 | }
118 |
119 | var oldPluginType = pluginType;
120 | pluginType = newPluginType;
121 |
122 |
123 | if(!pluginType) {
124 | modeLine = thisWindow.document.createElement('div');
125 | modeText = thisWindow.document.createTextNode('');
126 | modeLine.appendChild(modeText);
127 | thisWindow.document.getElementById("main-window").appendChild(modeLine)
128 | } else if (!oldPluginType) {
129 | modeLine.parentNode.removeChild(modeLine);
130 | }
131 |
132 | if (pluginType == "dactyl") {
133 | borrowed = {
134 | modes: head.plugins.modes,
135 | commands: head.plugins.commands,
136 | options: head.plugins.options,
137 | focusedElement: function() {return head.focusedElement;},
138 | echo: function(msg){head.echo(msg, head.plugins.commandline.FORCE_SINGLELINE);},
139 | echoerr: head.echoerr,
140 | feedkey: head.plugins.events.feedkeys,
141 | focus: function(element){borrowed.focus(element)},
142 | editor: head.plugins.editor,
143 | mappings: {
144 | add: function(mode, keylist, desc, callback){
145 | keylist.forEach( function(key){ pterosaur.minidactyl.keyHandler.addKeyDown(key, callback);});
146 | }, remove: function(mode, key){
147 | return pterosaur.minidactyl.keyHandler.removeKeyDown(key);
148 | }
149 | },
150 | }
151 |
152 | if(usingFullVim){
153 | head.plugins.mappings.builtin.remove(borrowed.modes.INSERT, "");
154 | }
155 |
156 | borrowed.commands.add(["pterosaurrestart"],
157 | "Restarts vim process",
158 | function () {
159 | killVimbed();
160 | startVimbed();
161 | }, {
162 | argCount: "0",
163 | });
164 | }
165 | else if (pluginType == "vimperator") {
166 | borrowed = {
167 | modes: head.plugins.modes,
168 | commands: head.plugins.commands,
169 | options: head.plugins.options,
170 | focusedElement: function() {return head.focus;},
171 | echo: function(msg){head.echo(msg, head.plugins.commandline.FORCE_SINGLELINE);},
172 | echoerr: head.echoerr,
173 | //feedkey: head.plugins.events.feedkeys,
174 | feedkey: pterosaur.minidactyl.feedkey,
175 | focus: function(element){if (element) {element.focus()}},
176 | editor: null,
177 | mappings: {
178 | add: function(mode, keylist, desc, callback){
179 | keylist.forEach( function(key){ pterosaur.minidactyl.keyHandler.addKeyDown(key, callback);});
180 | }, remove: function(mode, key){
181 | return pterosaur.minidactyl.keyHandler.removeKeyDown(key);
182 | }
183 | },
184 | }
185 | borrowed.modes.push = borrowed.modes.set;
186 | borrowed.modes.pop = function(){
187 | if(borrowed.modes.main == borrowed.modes.VIM_COMMAND) {
188 | borrowed.modes.set(borrowed.modes.VIM_NORMAL);
189 | }
190 | };
191 |
192 | borrowed.commands.addUserCommand(["pterosaurrestart"],
193 | "Restarts vim process",
194 | function () {
195 | killVimbed();
196 | startVimbed();
197 | }, {
198 | argCount: "0",
199 | });
200 |
201 | } else {
202 | borrowed = {
203 | modes: {"INSERT": {char:'I', name: ""},
204 | addMode: function(name, object) { borrowed.modes[name] = object; borrowed.modes[name].name = name;},
205 | main: null,
206 | pop: function(){borrowed.modes.main = borrowed.modes.INSERT; borrowed.modes.updateModeline();},
207 | push: function(mode){borrowed.modes.main = mode; borrowed.modes.updateModeline()},
208 | reset: function(){focusManager.clearFocus(thisWindow);},
209 | updateModeline: function(){modeText.textContent = borrowed.modes.main.name.replace("VIM_","");}
210 | },
211 | commands: null,
212 | options: null,
213 | focusedElement: function(){return focusManager.getFocusedElementForWindow(thisWindow, true, {});},
214 | echo: function(out) {
215 | if(out === ""){
216 | borrowed.modes.updateModeline();
217 | }
218 | else {
219 | thisWindow.setTimeout(function(){modeText.textContent = out},1);
220 | }
221 | },
222 | echoerr: function(out) {thisWindow.alert(out)},
223 | feedkey: pterosaur.minidactyl.feedkey,
224 | focus: function(element){if (element) {element.focus()}},
225 | editor: null,
226 | mappings: {
227 | add: function(mode, keylist, desc, callback){
228 | keylist.forEach( function(key){ pterosaur.minidactyl.keyHandler.addKeyDown(key, callback);});
229 | }, remove: function(mode, key){
230 | return pterosaur.minidactyl.keyHandler.removeKeyDown(key);
231 | }
232 | },
233 | }
234 | borrowed.modes.main = borrowed.modes.INSERT;
235 | borrowed.modes.updateModeline();
236 | }
237 |
238 | borrowed.modes.addMode("VIM_INSERT", {
239 | char: "I",
240 | desription: "Vim normal mode",
241 | bases: [borrowed.modes.INSERT]
242 | });
243 |
244 | borrowed.modes.addMode("VIM_NORMAL", {
245 | char: "N",
246 | desription: "Vim normal mode",
247 | bases: [borrowed.modes.VIM_INSERT]
248 | });
249 |
250 | borrowed.modes.addMode("VIM_COMMAND", {
251 | char: "e",
252 | desription: "Vim normal mode",
253 | bases: [borrowed.modes.VIM_NORMAL]
254 | });
255 |
256 | borrowed.modes.addMode("VIM_SELECT", {
257 | char: "s",
258 | desription: "Vim selection mode",
259 | bases: [borrowed.modes.VIM_NORMAL]
260 | });
261 |
262 | borrowed.modes.addMode("VIM_VISUAL", {
263 | char: "V",
264 | desription: "Vim visual mode",
265 | bases: [borrowed.modes.VIM_NORMAL]
266 | });
267 |
268 | borrowed.modes.addMode("VIM_REPLACE", {
269 | char: "R",
270 | desription: "Vim replace mode",
271 | bases: [borrowed.modes.VIM_NORMAL]
272 | });
273 |
274 | pterosaurModes = [borrowed.modes.INSERT, borrowed.modes.AUTOCOMPLETE, borrowed.modes.VIM_INSERT, borrowed.modes.VIM_NORMAL, borrowed.modes.VIM_COMMAND, borrowed.modes.VIM_SELECT, borrowed.modes.VIM_VISUAL, borrowed.modes.VIM_REPLACE];
275 |
276 | pterosaur.borrowed = borrowed;
277 | }
278 | this.getTextBox = function(){return textBox;}
279 | this.getTextBoxType = function(){return textBoxType;}
280 | this.getGameTest = function(){return gameTest;}
281 | this.strictVim = strictVim;
282 | this.leanVim = leanVim;
283 | this.useFullVim = useFullVim;
284 |
285 | setupPluginConnections();
286 |
287 | thisWindow.setTimeout(startVimbed, 1);
288 |
289 | function useFullVim(){
290 | var focusedElement = borrowed.focusedElement();
291 | if(prefs.getBoolPref("contentonly") && focusedElement && focusedElement.ownerDocument.URL.substring(0,7) === "chrome:")
292 | return false;
293 | if (focusedElement && focusedElement.type === "password")
294 | return false;
295 | if (PrivateBrowsingUtils.isWindowPrivate(thisWindow) && !prefs.getBoolPref("allowPrivate"))
296 | return false;
297 | return vimStdin && vimFile && prefs.getBoolPref("enabled");
298 | }
299 |
300 | //In strict/lean vim we avoid handling keys by browser and handle them more strictly within vim.
301 |
302 | function leanVim(){
303 | return textBoxType === "ace" || [borrowed.modes.VIM_INSERT, borrowed.modes.VIM_SELECT].indexOf(borrowed.modes.main) == -1;
304 | }
305 | //Strict vim is like leanvim but also forces tabs and carriage returns to vim
306 | function strictVim(){
307 | return textBoxType === "ace" || borrowed.modes.main === borrowed.modes.VIM_COMMAND;
308 | }
309 |
310 | var webKeyTimeout = null;
311 |
312 | function updateVim(){
313 | if(sendToVim !== "" && allowedToSend) {
314 | if (webKeyTimeout){
315 | thisWindow.clearTimeout(webKeyTimeout);
316 | webKeyTimeout = null;
317 | }
318 | if(vimNsIProc.isRunning){
319 | thisWindow.setTimeout(updateVim, 10);
320 | return;
321 | }
322 | if (!stateCheck() || vimNsIProc.isRunning) //Yes, we just checked isrunning, but it has a good chance of changing due to statecheck
323 | {
324 | if(!useFullVim() || textBoxType === "")
325 | {
326 | sendToVim = "";
327 | } else {
328 | thisWindow.setTimeout(updateVim, 10);
329 | }
330 | return;
331 | }
332 |
333 | var tempSendToVim = sendToVim;
334 | sendToVim = "";
335 | vimStdin.write(unescape(encodeURIComponent(tempSendToVim))); //Converts to UTF8
336 | unsent=0;
337 | webKeyTimeout = thisWindow.setTimeout(webKeyTimeoutFunc, 250);
338 | }
339 | }
340 |
341 | function webKeyTimeoutFunc() {
342 | if (!leanVim() && [ESC, GS, '\r', '\t', ''].indexOf(lastKey) == -1){
343 | if(stateCheck() && !vimNsIProc.isRunning) {
344 | handleKeySending(lastKey);
345 | } else if (useFullVim() && textBoxType !== "") {
346 | webKeyTimeout = thisWindow.setTimeout(webKeyTimeoutFunc, 50);
347 | }
348 | }
349 | }
350 |
351 | var stateCheckTimeout = null;
352 | var pollsSkipped = 0;
353 |
354 | function stateCheckTimeoutFunc(){
355 | if (vimNsIProc && vimNsIProc.isRunning)
356 | {
357 | stateCheckTimeout = thisWindow.setTimeout(stateCheckTimeoutFunc, 50);
358 | return;
359 | }
360 | stateCheckTimeout = null
361 | if(stateCheck()) {
362 | if (pollsSkipped < 3 && borrowed.modes.main !== borrowed.modes.VIM_COMMAND){
363 | pollsSkipped++;
364 | } else {
365 | callPoll();
366 | pollsSkipped = 0;
367 | }
368 | }
369 | }
370 |
371 | var restarting = false;
372 | function stateCheck(){
373 | if (stateCheckTimeout) {
374 | thisWindow.clearTimeout(stateCheckTimeout);
375 | pollsSkipped = 0;
376 | }
377 |
378 | stateCheckTimeout = thisWindow.setTimeout(stateCheckTimeoutFunc, borrowed.modes.main === borrowed.modes.VIM_COMMAND ? 250 : 500);
379 |
380 | if (usingFullVim !== useFullVim())
381 | cleanupPterosaur();
382 |
383 | if (strictVimCheck !== (strictVim() && usingFullVim))
384 | handleStrictVim();
385 |
386 | if (leanVimCheck !== (leanVim() && usingFullVim))
387 | handleLeanVim();
388 |
389 | if(prefs.getBoolPref("restartnow") && !restarting)
390 | {
391 | killVimbed();
392 | restarting = true;
393 | //The delay here is mostly so you can see the about:config value change.
394 | thisWindow.setTimeout(function(){
395 | restarting = false;
396 | prefs.setBoolPref("restartnow", false);
397 | startVimbed();
398 | },500);
399 | return false;
400 | }
401 |
402 | //We're not using pterosaur. Exit out.
403 | if (!usingFullVim || pterosaurModes.indexOf(borrowed.modes.main) === -1) {
404 | if(textBoxType) {
405 | cleanupForTextbox();
406 | textBoxType = ""
407 | }
408 | return false;
409 | }
410 |
411 | //We switched focus
412 | if (borrowed.focusedElement() !== pterFocused || !textBoxType)
413 | {
414 | if(textBoxType)
415 | cleanupForTextbox();
416 | setupForTextbox();
417 | return false;
418 | }
419 |
420 | var cursorPos = textBoxGetSelection()
421 |
422 | //The cursor was moved outside of vim.
423 | if (savedCursorStart!=null &&
424 | (cursorPos.start.row != savedCursorStart.row || cursorPos.start.column != savedCursorStart.column) ||
425 | savedCursorEnd!=null &&
426 | (cursorPos.end.row != savedCursorEnd.row || cursorPos.end.column != savedCursorEnd.column))
427 | {
428 | updateTextbox(0);
429 | return false;
430 | }
431 |
432 | //The text was changd outside of vim
433 | if (savedText != null && textBoxGetValue() != savedText)
434 | {
435 | updateTextbox(1);
436 | return false;
437 | }
438 |
439 | return true;
440 | }
441 |
442 | var lastVal = null;
443 | var lastMeta = null;
444 | function updateFromVim(){
445 | var val = tmpfile.read();
446 | var metadata = metaTmpfile.read();
447 | var messages = messageTmpfile.read();
448 |
449 | //Exit immediately if nothing happens. (This is just for performance. It's not needed for correct behavior.)
450 | if(metadata === lastMeta && val === lastVal && (!messages || messages === "\n")) {
451 | callPoll();
452 | return;
453 | }
454 |
455 | if(vimNsIProc.isRunning){
456 | thisWindow.setTimeout(updateFromVim, 10);
457 | return;
458 | }
459 |
460 | if (!stateCheck() || vimNsIProc.isRunning)
461 | {
462 | if(useFullVim() && textBoxType) {
463 | thisWindow.setTimeout(updateFromVim, 10);
464 | }
465 | return;
466 | }
467 |
468 | lastVal = val;
469 | lastMeta = metadata;
470 |
471 | //Vim textfiles are new-line terminated, but browser text vals aren't neccesarily
472 | if (val !== '')
473 | val = val.slice(0,-1)
474 | else
475 | {
476 | //If we don't have any text at all, we caught the file right as it was emptied and we don't know anything.
477 | thisWindow.setTimeout(updateFromVim, 20);
478 | return;
479 | }
480 |
481 |
482 | metadata = metadata.split('\n');
483 | vimMode = metadata[0];
484 |
485 | if (vimMode === "c") {
486 | if (borrowed.modes.main !== borrowed.modes.VIM_COMMAND)
487 | {
488 | borrowed.modes.push(borrowed.modes.VIM_COMMAND);
489 | }
490 | if (metadata[1] !=="" && metadata[1] !== lastVimCommand)
491 | {
492 | lastVimCommand = metadata[1];
493 | var modestring = "";
494 | if (metadata[1][0] == "@")
495 | borrowed.echo("INPUT: " + metadata[1].slice(1));
496 | else
497 | {
498 | //If we aren't showing the mode, we need to add it here to distinguish vim commands from pentadactyl commands
499 | if(pluginType == "dactyl" && borrowed.options && borrowed.options["guioptions"].indexOf("s") == -1)
500 | modestring = "VIM COMMAND "
501 | else if(!pluginType)
502 | modestring = "COMMAND "
503 | borrowed.echo(modestring + metadata[1]);
504 | }
505 | }
506 | }
507 | else{
508 | if (borrowed.modes.main === borrowed.modes.VIM_COMMAND)
509 | {
510 | borrowed.modes.pop();
511 | }
512 | if (lastVimCommand)
513 | {
514 | borrowed.echo("")
515 | lastVimCommand=""
516 | }
517 | }
518 |
519 | if (messages && messages!=="\n" && vimMode!="c")
520 | {
521 | //TODO: If another message is written right now, we could lose it.
522 | messageTmpfile.write("");
523 |
524 | if(!unsent)
525 | {
526 | //TODO: We don't neccesarily want singleline, but without it we lose focus.
527 | borrowed.echo(messages.split("\n").slice(-1)[0]);
528 | }
529 |
530 | //We've clearing the entered command. Don't need/want to clear it later and lose our message.
531 | lastVimCommand=""
532 | }
533 |
534 | if (val !== savedText){
535 | if(!unsent){
536 | textBoxSetValue(val)
537 | }
538 | savedText = val;
539 | }
540 |
541 | if (textBoxType) {
542 | if(metadata.length > 2 && vimMode !== "c" && vimMode!== "e" && !unsent)
543 | {
544 | textBoxSetSelection(metadata[1], metadata[2])
545 | }
546 | else if(metadata.length > 3 && vimMode == "c")
547 | {
548 | textBoxSetSelection(metadata[2], metadata[3])
549 | }
550 |
551 |
552 | var cursorPos = textBoxGetSelection()
553 |
554 | if (savedCursorStart.row != cursorPos.start.row || savedCursorStart.column != cursorPos.start.column
555 | || savedCursorEnd.row != cursorPos.end.row || savedCursorEnd.column != cursorPos.end.column) {
556 | savedCursorStart = cursorPos.start;
557 | savedCursorEnd = cursorPos.end;
558 | }
559 | }
560 |
561 | if (vimMode === "e")
562 | {
563 | borrowed.echo("ERROR: "+metadata[1])
564 | }
565 | else if (vimMode === "n" && borrowed.modes.main !== borrowed.modes.VIM_NORMAL)
566 | {
567 | //If unsent, this has to be outdated info. Don't bother
568 | if(!unsent) {
569 | borrowed.echo("");
570 | if (borrowed.modes.main !== borrowed.modes.INSERT)
571 | {
572 | borrowed.modes.pop();
573 | }
574 | borrowed.modes.push(borrowed.modes.VIM_NORMAL);
575 | }
576 | }
577 | else if ((vimMode === "v" || vimMode ==="V") && borrowed.modes.main !==borrowed.modes.VIM_VISUAL)
578 | {
579 | //If unsent, this has to be outdated info. Don't bother.
580 | if(!unsent) {
581 | borrowed.echo("");
582 | if (borrowed.modes.main !== borrowed.modes.INSERT)
583 | {
584 | borrowed.modes.pop();
585 | }
586 | borrowed.modes.push(borrowed.modes.VIM_VISUAL);
587 | }
588 | }
589 | else if ((vimMode === "s" || vimMode ==="S") && borrowed.modes.main !==borrowed.modes.VIM_SELECT)
590 | {
591 | borrowed.echo("");
592 | if (borrowed.modes.main !== borrowed.modes.INSERT)
593 | {
594 | borrowed.modes.pop();
595 | }
596 | borrowed.modes.push(borrowed.modes.VIM_SELECT);
597 | }
598 | //R is replace and Rv is virtual replace
599 | else if ((vimMode[0]==="R") && borrowed.modes.main !==borrowed.modes.VIM_REPLACE)
600 | {
601 | borrowed.echo("");
602 | if (borrowed.modes.main !== borrowed.modes.INSERT)
603 | {
604 | borrowed.modes.pop();
605 | }
606 | borrowed.modes.push(borrowed.modes.VIM_REPLACE);
607 | }
608 | else if (vimMode === "i" && borrowed.modes.main !== borrowed.modes.VIM_INSERT)
609 | {
610 | borrowed.echo("");
611 | if (borrowed.modes.main !== borrowed.modes.INSERT)
612 | {
613 | borrowed.modes.pop();
614 | }
615 | borrowed.modes.push(borrowed.modes.VIM_INSERT);
616 | }
617 |
618 | if (pollTimeout){
619 | thisWindow.clearTimeout(pollTimeout);
620 | pollTimeout = null;
621 | }
622 | if (vimMode !== "c" && gameTest <= 40) {
623 | pollTimeout = thisWindow.setTimeout(function(){ pollTimeout = null }, 100);
624 | }
625 | }
626 |
627 | //Determines if vim is being used for a game or similar scenario where vim handles user input in a nonstandard way.
628 | //In these cases, we should spam poll for responsiveness since vim won't trigger the normal autocommands.
629 | var gameTest = 0;
630 |
631 | function pollTimeoutFunc(){
632 | if(!vimNsIProc.isRunning){
633 | pollTimeout = null;
634 | remoteExpr("Vimbed_Poll()");
635 | }else{
636 | pollTimeout = thisWindow.setTimeout(pollTimeoutFunc, 50);
637 | }
638 | }
639 |
640 | function callPoll(){
641 | if (!pollTimeout){
642 | var pollTimer = (vimMode == "c" || gameTest > 40 ? 1 : 250)
643 | //if vimMode == "c"(vimMode == "c" 1 : );
644 | pollTimeout = thisWindow.setTimeout(pollTimeoutFunc, pollTimer);
645 | }
646 | }
647 |
648 | function remoteExpr(expr){
649 | //The standard way to do this is:
650 | // vimNsIProc.run(false,["--servername", "pterosaur_" + uid, '--remote-expr', expr], 4);
651 | //but the below way is 5 times faster because remote-expr from the command line is so slow.
652 | //We could speed this up farther by just keeping a vim instance open just for sending remote_exprs, but this is good enough for now.
653 | try{
654 | vimNsIProc.run(false,["+call remote_expr('pterosaur_" + uid + "', '" + expr + "')", "+q!", "-u", "NONE", "-v", "-s", "/dev/null"], 7);
655 | }
656 | catch (e){
657 | console.trace();
658 | }
659 | }
660 |
661 | function createChromeSandbox(){
662 | return new Components.utils.Sandbox(thisWindow.document.nodePrincipal);
663 | }
664 |
665 | function createSandbox(){
666 | var doc = textBox.ownerDocument || thisWindow.content;
667 | var protocol = doc.location.protocol;
668 | var host = doc.location.host;
669 | if (typeof protocol === "string" && typeof host === "string")
670 | {
671 | return new Components.utils.Sandbox(protocol + "//" + host);
672 | }
673 | }
674 |
675 | function textBoxGetSelection(){
676 | switch (textBoxType) {
677 | case "ace":
678 | return textBoxGetSelection_ace()
679 | case "codeMirror":
680 | return textBoxGetSelection_codeMirror()
681 | case "normal":
682 | var text = textBox.value;
683 | if (text){
684 | var preStart = text.substr(0, textBox.selectionStart);
685 | var preEnd = text.substr(0, textBox.selectionEnd);
686 | var rowStart = 1 + preStart.replace(/[^\n]/g, "").length;
687 | var columnStart = 1 + preStart.replace(/[^]*\n/, "").length;
688 | var charStart = 1 + preStart.length;
689 | var rowEnd = 1 + preEnd.replace(/[^\n]/g, "").length;
690 | var columnEnd = 1 + preEnd.replace(/[^]*\n/, "").length;
691 | var charEnd = 1 + preEnd.length;
692 | return {"start": {"row": rowStart, "column": columnStart, "char": charStart}, "end": {"row":rowEnd, "column": columnEnd, "char":charEnd}};
693 | }
694 | return {"start": {"row": 1, "column": 1}, "end": {"row":1, "column": 1}};
695 | case "contentEditable":
696 | case "designMode":
697 | var fromBeginning = pterosaur.minidactyl.nodeContents(textBox.rootElement);
698 | var oldRange = textBox.selection.getRangeAt(0);
699 |
700 | fromBeginning.setEnd(oldRange.startContainer, oldRange.startOffset);
701 | var preStart = htmlToText(pterosaur.minidactyl.stringify(fromBeginning, true));
702 | fromBeginning.setEnd(oldRange.endContainer, oldRange.endOffset);
703 | var preEnd = htmlToText(pterosaur.minidactyl.stringify(fromBeginning, true));
704 |
705 | var rowStart = 1 + preStart.replace(/[^\n]/g, "").length;
706 | var columnStart = 1 + preStart.replace(/[^]*\n/, "").length;
707 | var rowEnd = 1 + preEnd.replace(/[^\n]/g, "").length;
708 | var columnEnd = 1 + preEnd.replace(/[^]*\n/, "").length;
709 | return {"start": {"row": rowStart, "column": columnStart}, "end": {"row":rowEnd, "column": columnEnd}};
710 | }
711 | }
712 |
713 | function textBoxGetSelection_ace(){
714 | var sandbox = createSandbox();
715 | if (!sandbox)
716 | return;
717 | sandbox.content = thisWindow.content;
718 | sandbox.editor = textBox.parentNode;
719 | sandbox.stringify = JSON.stringify;
720 | var sandboxScript="\
721 | var aceEditor = content.wrappedJSObject.ace.edit(editor);\
722 | range = stringify(aceEditor.getSession().getSelection().getRange());\
723 | ";
724 | Components.utils.evalInSandbox(sandboxScript, sandbox);
725 | return parseSandboxRangeForVim(sandbox);
726 | }
727 |
728 | function textBoxGetSelection_codeMirror(){
729 | var sandboxScript="\
730 | editor = editor.wrappedJSObject || editor;\
731 | var anchor = editor.CodeMirror.getCursor('anchor');\
732 | var head = editor.CodeMirror.getCursor('head');\
733 | var rangeObj = {};\
734 | if (head.line < anchor.line || head.line == anchor.line && head.ch < anchor.ch) {\
735 | rangeObj.start = {'row': head.line, 'column': head.ch};\
736 | rangeObj.end = {'row': anchor.line, 'column': anchor.ch};\
737 | } else {\
738 | rangeObj.start = {'row': anchor.line, 'column': anchor.ch};\
739 | rangeObj.end = {'row': head.line, 'column': head.ch};\
740 | }\
741 | range = stringify(rangeObj);\
742 | ";
743 |
744 | if (!textBox.wrappedJSObject && textBox.CodeMirror) {
745 | //This is codemirror at the chrome level alreay (probably from dev tools). We can trust it.
746 | var sandbox = createChromeSandbox();
747 | if (!sandbox)
748 | return;
749 | sandbox.editor = textBox;
750 | sandbox.stringify = JSON.stringify;
751 | Components.utils.evalInSandbox(sandboxScript, sandbox);
752 | } else {
753 | var sandbox = createSandbox();
754 | if (!sandbox)
755 | return;
756 | sandbox.editor = textBox;
757 | sandbox.stringify = JSON.stringify;
758 | Components.utils.evalInSandbox(sandboxScript, sandbox);
759 | }
760 | return parseSandboxRangeForVim(sandbox);
761 | }
762 |
763 | function parseSandboxRangeForVim(sandbox) {
764 | if (typeof sandbox.range === "string") {
765 | var range = JSON.parse(sandbox.range);
766 | range.start.row = parseInt(range.start.row) + 1;
767 | range.start.column = parseInt(range.start.column) + 1;
768 | range.end.row = parseInt(range.end.row) + 1;
769 | range.end.column = parseInt(range.end.column) + 1;
770 | return range;
771 | } else {
772 | console.log("Sandbox Error!");
773 | return {"start": {"column": 1, "row": 1}, "end": {"column": 1, "row": 1}}
774 | }
775 | }
776 |
777 | function textBoxSetSelectionFromSaved(saved){
778 | var start = (saved.start.char-1) + "," + (saved.start.column-1) + "," + (saved.start.row-1)
779 | var end = (saved.end.char-1) + "," + (saved.end.column-1) + "," + (saved.end.row-1)
780 | textBoxSetSelection(start, end);
781 | }
782 |
783 | function convertRowColumnToIndex(text, row, column){
784 | var column = parseInt(column);
785 | var lines = text.split("\n");
786 | if(row >= lines.length)
787 | row = lines.length - 1;
788 | var rowlength = lines[row].length;
789 | value = lines.slice(0, row).join("").length + parseInt(row);
790 | if(column > rowlength)
791 | return value + rowlength
792 | else
793 | return value + column
794 | }
795 |
796 | function textBoxSetSelection(start, end){
797 | switch (textBoxType) {
798 | case "ace":
799 | textBoxSetSelection_ace(start, end)
800 | break;
801 | case "codeMirror":
802 | textBoxSetSelection_codeMirror(start, end)
803 | break;
804 | case "normal":
805 | start = start.split(',');
806 | end = end.split(',');
807 | var value = textBox.value;
808 | textBox.setSelectionRange(convertRowColumnToIndex(value, start[2], start[1]), convertRowColumnToIndex(value, end[2], end[1]));
809 | break;
810 | case "contentEditable":
811 | case "designMode":
812 | start = start.split(",")
813 | end = end.split(",")
814 |
815 | var range = pterosaur.minidactyl.nodeContents(textBox.rootElement);
816 | var nodes = textBox.rootElement.childNodes;
817 | var nodeIndex = 0;
818 | var row = 0;
819 | var length = nodes.length;
820 | while(row tags. Only way to represent this is with parent node.
831 | range.setStart(textBox.rootElement, nodeIndex)
832 | }
833 | else{
834 | range.setStart(nodes[nodeIndex], Math.min(nodes[nodeIndex].length, start[1]))
835 | }
836 |
837 | while(row tags. Only way to represent this is with parent node.
848 | range.setEnd(textBox.rootElement, nodeIndex)
849 | }
850 | else{
851 | range.setEnd(nodes[nodeIndex], Math.min(nodes[nodeIndex].length, end[1]))
852 | }
853 |
854 | textBox.selection.removeAllRanges()
855 | textBox.selection.addRange(range)
856 | break;
857 | }
858 | }
859 |
860 | function textBoxSetSelection_ace(start, end){
861 | var sandbox = createSandbox();
862 | if (!sandbox)
863 | return;
864 | sandbox.start = start
865 | sandbox.end = end
866 | sandbox.content = thisWindow.content;
867 | sandbox.editor = textBox.parentNode;
868 | var sandboxScript="\
869 | var aceEditor = content.wrappedJSObject.ace.edit(editor);\
870 | start = start.split(',');\
871 | end = end.split(',');\
872 | aceEditor.getSession().getSelection().setSelectionRange(\
873 | {'start': {'row':start[2], 'column':start[1]},\
874 | 'end': {'row':end[2], 'column':end[1]}});\
875 | "
876 | Components.utils.evalInSandbox(sandboxScript, sandbox);
877 | }
878 |
879 | function textBoxSetSelection_codeMirror(start, end){
880 | var sandboxScript="\
881 | start = start.split(',');\
882 | end = end.split(',');\
883 | editor = editor.wrappedJSObject || editor;\
884 | editor.CodeMirror.setSelection({'line':parseInt(start[2]), 'ch':parseInt(start[1])}, {'line':parseInt(end[2]), 'ch':parseInt(end[1])});\
885 | "
886 |
887 | if (!textBox.wrappedJSObject && textBox.CodeMirror) {
888 | //This is codemirror at the chrome level alreay (probably from dev tools). We can trust it.
889 | var sandbox = createChromeSandbox();
890 | if (!sandbox)
891 | return;
892 | sandbox.start = start;
893 | sandbox.end = end;
894 | sandbox.editor = textBox;
895 | Components.utils.evalInSandbox(sandboxScript, sandbox);
896 | } else {
897 | var sandbox = createSandbox();
898 | if (!sandbox)
899 | return;
900 | sandbox.start = start;
901 | sandbox.end = end;
902 | sandbox.editor = textBox;
903 |
904 | Components.utils.evalInSandbox(sandboxScript, sandbox);
905 | }
906 | }
907 |
908 | function htmlToText(inText) {
909 | //Note that this function does not convert all html correctly. It just needs to convert html in contenteditables.
910 | //The results are treated as text so incorrect conversion is not a security issue.
911 | return inText.replace(/
]*>/g, '\n').replace(/<[^>]*>/g,'').replace(/ /g, ' ').replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&')
912 | }
913 |
914 | function setText(node, text){
915 | var nbsp = '\u00a0'
916 | text = text.replace(/^ /mg, nbsp).replace(/ /g, ' '+nbsp).replace(/ $/mg, nbsp)
917 |
918 | var lines = text.split('\n')
919 | var last = lines.length - 1;
920 | var failure = false;
921 |
922 | if (node.childNodes.length == last*2) {
923 | for (var i = 0; i < last; i++) {
924 | var currentNode = node.childNodes[i*2];
925 | if (currentNode.nodeType === 3) {
926 | if (currentNode.textContent !== lines[i]) {
927 | currentNode.textContent = lines[i];
928 | }
929 | } else {
930 | failure = true;
931 | break;
932 | }
933 | if(node.childNodes[i*2+1].nodeName !== "BR") {
934 | failure = true;
935 | break;
936 | }
937 | }
938 | } else {
939 | failure = true;
940 | }
941 |
942 | if (failure) {
943 | while (node.firstChild) {
944 | node.removeChild(node.firstChild);
945 | }
946 |
947 | var lines = text.split('\n')
948 | lines.forEach(function(line, index) {
949 | if (index != last) {
950 | node.appendChild(thisWindow.content.document.createTextNode(line));
951 | node.appendChild(thisWindow.content.document.createElement('br'));
952 | }
953 | })
954 | }
955 | }
956 |
957 | function textBoxSetValue(newVal) {
958 | switch (textBoxType) {
959 | case "ace":
960 | textBoxSetValue_ace(newVal);
961 | break;
962 | case "codeMirror":
963 | textBoxSetValue_codeMirror(newVal);
964 | break;
965 | case "normal":
966 | textBox.value = newVal;
967 | break;
968 | case "contentEditable":
969 | case "designMode":
970 | var newText = newVal + "\n";
971 | if (htmlToText(textBox.rootElement.innerHTML) != newText)
972 | {
973 | setText(textBox.rootElement, newText);
974 | }
975 | break;
976 | }
977 | }
978 |
979 | function textBoxSetValue_ace(newVal){
980 | var sandbox = createSandbox();
981 | if (!sandbox)
982 | return;
983 | sandbox.newVal = newVal;
984 | sandbox.content = thisWindow.content;
985 | sandbox.editor = textBox.parentNode;
986 | var sandboxScript="\
987 | var aceEditor = content.wrappedJSObject.ace.edit(editor);\
988 | if (aceEditor.getSession().getValue()!=newVal){\
989 | aceEditor.getSession().setValue(newVal);\
990 | }\
991 | "
992 | Components.utils.evalInSandbox(sandboxScript, sandbox);
993 | }
994 |
995 | function textBoxSetValue_codeMirror(newVal){
996 | var sandboxScript="\
997 | editor = editor.wrappedJSObject || editor;\
998 | if (editor.CodeMirror.getValue()!=newVal){\
999 | editor.CodeMirror.setValue(newVal);\
1000 | }\
1001 | "
1002 |
1003 | if (!textBox.wrappedJSObject && textBox.CodeMirror) {
1004 | //This is codemirror at the chrome level alreay (probably from dev tools). We can trust it.
1005 | var sandbox = createChromeSandbox();
1006 | if (!sandbox)
1007 | return;
1008 | sandbox.newVal = newVal
1009 | sandbox.editor = textBox;
1010 | Components.utils.evalInSandbox(sandboxScript, sandbox);
1011 | } else {
1012 | var sandbox = createSandbox();
1013 | if (!sandbox)
1014 | return;
1015 | sandbox.newVal = newVal
1016 | sandbox.editor = textBox;
1017 | Components.utils.evalInSandbox(sandboxScript, sandbox);
1018 | }
1019 | }
1020 |
1021 | function textBoxGetValue() {
1022 | switch (textBoxType) {
1023 | case "ace":
1024 | return textBoxGetValue_ace();
1025 | case "codeMirror":
1026 | return textBoxGetValue_codeMirror();
1027 | case "normal":
1028 | return textBox.value;
1029 | case "contentEditable":
1030 | case "designMode":
1031 | var retVal = htmlToText(textBox.rootElement.innerHTML);
1032 | if (retVal.slice(-1) == "\n")
1033 | {
1034 | return retVal.slice(0,-1);
1035 | } else {
1036 | return retVal;
1037 | }
1038 | }
1039 | }
1040 |
1041 | function textBoxGetValue_ace(){
1042 | var sandbox = createSandbox();
1043 | if (!sandbox)
1044 | return;
1045 | sandbox.content = thisWindow.content;
1046 | sandbox.editor = textBox.parentNode;
1047 | var sandboxScript="\
1048 | var aceEditor = content.wrappedJSObject.ace.edit(editor);\
1049 | value = aceEditor.getSession().getValue();\
1050 | "
1051 | Components.utils.evalInSandbox(sandboxScript, sandbox);
1052 | //Make sure it's a string to avoid letting malicious code escape.
1053 | var returnVal = sandbox.value
1054 | if (typeof returnVal === "string")
1055 | return returnVal;
1056 | else
1057 | console.log("Sandbox Error!");
1058 | return "Sandbox Error!"
1059 | }
1060 |
1061 | function textBoxGetValue_codeMirror(){
1062 | var sandboxScript="\
1063 | editor = editor.wrappedJSObject || editor;\
1064 | value = editor.CodeMirror.getValue();\
1065 | "
1066 |
1067 | if (!textBox.wrappedJSObject && textBox.CodeMirror) {
1068 | //This is codemirror at the chrome level alreay (probably from dev tools). We can trust it.
1069 | var sandbox = createChromeSandbox();
1070 | if (!sandbox)
1071 | return;
1072 | sandbox.editor = textBox;
1073 | Components.utils.evalInSandbox(sandboxScript, sandbox);
1074 | } else {
1075 | var sandbox = createSandbox();
1076 | if (!sandbox)
1077 | return;
1078 | sandbox.editor = textBox;
1079 | Components.utils.evalInSandbox(sandboxScript, sandbox);
1080 | }
1081 | //Make sure it's a string to avoid letting malicious code escape.
1082 | var returnVal = sandbox.value
1083 | if (typeof returnVal === "string")
1084 | return returnVal;
1085 | else
1086 | console.log("Sandbox Error!");
1087 | return "Sandbox Error!"
1088 | }
1089 |
1090 | //TODO: Need consistent capitalization for textbox
1091 | function cleanupForTextbox() {
1092 | if(pterFocused){
1093 | try{
1094 | pterFocused.ownerDocument.removeEventListener("click", pterClicked, false);
1095 | }
1096 | catch(e){
1097 | if (prefs.getBoolPref("verbose")) {
1098 | //This is probably a dead object error. We don't need to remove the event in that case.
1099 | console.log("Caught error (dead object errors are ok): " + e);
1100 | }
1101 | }
1102 | pterFocused = null;
1103 | }
1104 | if(!pluginType) {
1105 | modeLine.style.display="none";
1106 | }
1107 | if (prefs.getBoolPref("verbose")) {
1108 | console.log("cleanup");
1109 | }
1110 | unsent=1;
1111 | }
1112 |
1113 | function setupForTextbox() {
1114 | //Clear lingering command text
1115 | if (vimMode === "c")
1116 | vimStdin.write(ESC+"i");
1117 |
1118 | pterFocused = borrowed.focusedElement();
1119 |
1120 | if(pterFocused){
1121 | pterFocused.ownerDocument.addEventListener("click", pterClicked, false);
1122 | }
1123 |
1124 | updateTextbox(0);
1125 | }
1126 |
1127 | function pterClicked(){
1128 | thisWindow.setTimeout(stateCheck, 1);
1129 | }
1130 |
1131 | function updateTextbox(preserveMode) {
1132 | if (vimNsIProc.isRunning){
1133 | thisWindow.setTimeout(function(){updateTextbox(preserveMode);}, 25);
1134 | return;
1135 | }
1136 |
1137 | if(lastKey === ESC) {
1138 | lastKey = "";
1139 | }
1140 |
1141 | unsent=1
1142 | vimGame = false;
1143 |
1144 | //Saved values are processed. "last" values are unprocessed values of vimbed files
1145 | savedText = null;
1146 | savedCursorStart = null;
1147 | savedCursorEnd = null;
1148 | lastVal = null;
1149 | lastMeta = null;
1150 |
1151 | textBox = borrowed.focusedElement();
1152 |
1153 | if (textBox == null)
1154 | {
1155 | if (borrowed.editor && borrowed.editor.getEditor){
1156 | textBox = borrowed.editor.getEditor(thisWindow.document.commandDispatcher.focusedWindow);
1157 | }
1158 | if(textBox) {
1159 | textBoxType = "designMode";
1160 | } else {
1161 | textBoxType = "";
1162 | }
1163 | } else {
1164 | if(borrowed.focusedElement().isContentEditable) {
1165 | if(borrowed.focusedElement().offsetHeight == 0){
1166 | textBoxType = ""; //This is probably google doc type stuff that we can't handle.
1167 | } else {
1168 | var doc = textBox.ownerDocument || thisWindow.content;
1169 |
1170 | textBoxType = "contentEditable";
1171 | textBox = {};
1172 | textBox.rootElement = borrowed.focusedElement();
1173 | //Prserve any tags that wrap the WHOLE contenteditable
1174 | while (textBox.rootElement.childNodes.length == 1 && textBox.rootElement.childNodes[0].tagName && textBox.rootElement.childNodes[0].tagName != "BR") {
1175 | textBox.rootElement = textBox.rootElement.childNodes[0]
1176 | }
1177 |
1178 | textBox.selection = doc.getSelection();
1179 | }
1180 | } else if(/ace_text-input/.test(textBox.className)) {
1181 | textBoxType = "ace";
1182 | }
1183 | else if (textBox.parentNode && textBox.parentNode.parentNode && /CodeMirror/.test(textBox.parentNode.parentNode.className)) {
1184 | textBoxType = "codeMirror"
1185 | textBox = textBox.parentNode.parentNode;
1186 | }
1187 | else if (["INPUT", "TEXTAREA", "HTML:INPUT", "HTML:TEXTAREA"].indexOf(textBox.nodeName.toUpperCase()) >= 0) {
1188 | try{
1189 | //This will throw if I'm an input type that isn't textish
1190 | textBox.selectionStart;
1191 |
1192 | textBoxType = "normal";
1193 | }
1194 | catch(e){
1195 | textBoxType = "";
1196 | }
1197 | }
1198 | else {
1199 | if(borrowed.editor){
1200 | textBox = borrowed.editor.getEditor(thisWindow.document.commandDispatcher.focusedWindow); //Tabbing into designmode sets focusedEelement to html instead of null
1201 | } else {
1202 | textBox = null;
1203 | }
1204 | if(textBox) {
1205 | borrowed.focus(null);
1206 | textBoxType = "designMode";
1207 | } else {
1208 | textBoxType = "";
1209 | }
1210 | }
1211 | }
1212 |
1213 | if (textBoxType) {
1214 | if(!pluginType){
1215 | modeLine.style.display="block";
1216 | }
1217 |
1218 | var text = textBoxGetValue()
1219 | var cursorPos = textBoxGetSelection()
1220 | savedCursorStart = cursorPos.start;
1221 | savedCursorEnd = cursorPos.end;
1222 |
1223 | if(borrowed.modes.main == borrowed.modes.INSERT) {
1224 | borrowed.modes.push(borrowed.modes.VIM_INSERT);
1225 | }
1226 |
1227 | textBoxSetSelectionFromSaved(cursorPos);
1228 |
1229 | if (!tmpfile.write(text+"\n"))
1230 | throw Error("io.cantEncode");
1231 |
1232 | var vimCommand;
1233 |
1234 | vimCommand = "Vimbed_UpdateText(, , , , )";
1235 |
1236 | vimCommand = vimCommand.replace(//, cursorPos.start.row);
1237 | vimCommand = vimCommand.replace(//, cursorPos.start.column);
1238 | vimCommand = vimCommand.replace(//, cursorPos.end.row);
1239 | vimCommand = vimCommand.replace(//, cursorPos.end.column);
1240 | vimCommand = vimCommand.replace(//, preserveMode);
1241 |
1242 | if (prefs.getBoolPref("verbose")) {
1243 | console.log(vimCommand);
1244 | }
1245 |
1246 | remoteExpr(vimCommand);
1247 | } else if(pluginType === "vimperator") {
1248 | if (borrowed.modes.main !== borrowed.modes.INSERT) {
1249 | borrowed.modes.main = borrowed.modes.NORMAL;
1250 | }
1251 | }
1252 | }
1253 |
1254 | //Some sites need to receive key events in addition to sending them to vim. We don't do this for javascript editors because they handle js stuff themselves.
1255 | function handleKeySending(key) {
1256 | if (textBoxType == "normal") {
1257 | skipKeyPress = true;
1258 | try{
1259 | var value = textBoxGetValue()
1260 | var cursorPos = textBoxGetSelection()
1261 | var oldFocus = borrowed.focusedElement();
1262 | var valarray = value.split("\n")
1263 | var newCursor = false;
1264 | if (key === "\b") {
1265 | valarray[cursorPos.end.row - 1] = valarray[cursorPos.end.row -1].slice(0, cursorPos.end.column - 1) + ' ' + valarray[cursorPos.end.row - 1].slice(cursorPos.end.column - 1);
1266 | //newCursor = cursorPos;
1267 | newCursor = {};
1268 | newCursor.start = {};
1269 | newCursor.start.row = cursorPos.end.row;
1270 | newCursor.start.column = cursorPos.end.column + 1;
1271 | newCursor.end = newCursor.start;
1272 | key = "";
1273 | } else if (cursorPos.end.column > 1) {
1274 | valarray[cursorPos.end.row - 1] = valarray[cursorPos.end.row - 1].slice(0, cursorPos.end.column - 2) + valarray[cursorPos.end.row - 1].slice(cursorPos.end.column - 1)
1275 | newCursor = {};
1276 | newCursor.start = {};
1277 | newCursor.start.row = cursorPos.end.row;
1278 | newCursor.start.column = cursorPos.end.column - 1;
1279 | newCursor.end = newCursor.start;
1280 | }
1281 |
1282 |
1283 | if (newCursor) {
1284 | textBoxSetValue(valarray.join("\n"))
1285 | textBoxSetSelectionFromSaved(newCursor);
1286 |
1287 | borrowed.feedkey(key);
1288 |
1289 | if (oldFocus == borrowed.focusedElement()) {
1290 | textBoxSetValue(value);
1291 | textBoxSetSelectionFromSaved(cursorPos);
1292 | }
1293 | }
1294 | }
1295 | finally{
1296 | skipKeyPress = false;
1297 | }
1298 | } else if (["contentEditable", "designMode"].indexOf(textBoxType) != -1){
1299 | skipKeyPress = true;
1300 | try{
1301 | var value = htmlToText(textBox.rootElement.innerHTML);
1302 | var cursorPos = textBoxGetSelection()
1303 | var oldFocus = borrowed.focusedElement();
1304 |
1305 | borrowed.feedkey(key);
1306 | if (oldFocus == borrowed.focusedElement()) {
1307 | setText(textBox.rootElement, value);
1308 | textBoxSetSelectionFromSaved(cursorPos);
1309 | }
1310 | } finally{
1311 | skipKeyPress = false;
1312 | }
1313 | }
1314 | }
1315 |
1316 | var skipKeyPress = false;
1317 |
1318 | function onKeyPress(eventList) {
1319 | const KILL = false, PASS = true;
1320 | if (skipKeyPress) {
1321 | return PASS;
1322 | }
1323 |
1324 | if (!useFullVim()) {
1325 | return PASS;
1326 | }
1327 |
1328 | if (textBoxType === "") {
1329 | stateCheck();
1330 | if(textBoxType === "") {
1331 | return PASS;
1332 | }
1333 | }
1334 |
1335 | var inputChar = pterosaur.minidactyl.stringifyEvent(eventList[0]);
1336 |
1337 | if((borrowed.modes.main == borrowed.modes.VIM_NORMAL || lastKey === ESC) && inputChar === prefs.getCharPref("exitkey")){
1338 | borrowed.modes.reset();
1339 | return KILL;
1340 | }
1341 |
1342 | if (inputChar[0] === "<"){
1343 | switch(inputChar) {
1344 | case "":
1345 | case "":
1346 | queueForVim(' ');
1347 | break;
1348 | case "":
1349 | return specialKeyHandler("") === PASS_THROUGH; //At this point, websites already might have done their thing with tab. But if we grab it any earlier, we always move to the next field.
1350 | //These are already handled by lean VIM. If we're not leaning vim, let's let the browser handle them.
1351 | case "":
1352 | return PASS;
1353 | case "":
1354 | return PASS;
1355 | case "":
1356 | return PASS;
1357 | case "":
1358 | return PASS;
1359 | case "":
1360 | queueForVim('<');
1361 | break;
1362 | case "": //We already handled vim's return if we got here.
1363 | return PASS;
1364 | default:
1365 | if (inputChar.slice(0,3)===" 0){
1390 | gameTest -= 6;
1391 | }
1392 | updateVim();
1393 | }
1394 |
1395 | var handlingSpecialKey = false;
1396 |
1397 |
1398 | function getKeyBehavior(textBoxType, key) {
1399 | if (strictVim()) {
1400 | return "vim";
1401 | }
1402 | if(key === ""){
1403 | if(textBoxType === "codeMirror" && pluginType) //Carriage returns are broken in pentadactyl for codemirror, so we have to handle them in vim
1404 | return "vim";
1405 | else
1406 | return "linecheck";
1407 | }
1408 | if(key === ""){
1409 | return "web";
1410 | }
1411 | }
1412 |
1413 | //We want to manually handle carriage returns and tabs because otherwise forms can be submitted or fields can be tabbed out of before the textfield can finish updating.
1414 | function specialKeyHandler(key) {
1415 | if (handlingSpecialKey || textBoxType == "") {
1416 | return PASS_THROUGH;
1417 | }
1418 | var behavior = getKeyBehavior(textBoxType, key)
1419 | if (behavior !== "vim") {
1420 | //Make sure any autocomplete is calculated before we send the enter key
1421 | if(webKeyTimeout){
1422 | webKeyTimeout = null;
1423 | if (!leanVim() && stateCheck() && [ESC, '\r', '\t', ''].indexOf(lastKey) == -1){
1424 | handleKeySending(lastKey);
1425 | }
1426 | }
1427 |
1428 | if(borrowed.modes.main === borrowed.modes.VIM_INSERT) {
1429 | queueForVim(GS);
1430 | }
1431 |
1432 | allowedToSend = false;
1433 | if (behavior !== "web") {
1434 | if (key === "") {
1435 | queueForVim("\r");
1436 | } else if (key === ""){
1437 | queueForVim("\t");
1438 | }
1439 | }
1440 |
1441 | thisWindow.setTimeout( function() {
1442 | handlingSpecialKey=true;
1443 | try {
1444 | var value = textBoxGetValue() //Preserve the old value so the Return doesn't change it.
1445 | var cursorPos = textBoxGetSelection()
1446 | var oldFocus = borrowed.focusedElement();
1447 | borrowed.feedkey(key);
1448 | if(behavior !== "web"){
1449 | if (oldFocus == borrowed.focusedElement() && (behavior != "linecheck" || newLineCheck(value) && (behavior != "spaceCheck" || spaceCheck(value)))) {
1450 | textBoxSetValue(value);
1451 | textBoxSetSelectionFromSaved(cursorPos);
1452 | }
1453 | else {
1454 | sendToVim=""
1455 | }
1456 | }
1457 | } catch(e) {
1458 | console.trace();
1459 | } finally {
1460 | handlingSpecialKey=false;
1461 | allowedToSend = true;
1462 | updateVim();
1463 | }
1464 | }, 100) //Delay is to make sure forms are updated from vim before being submitted.
1465 | }
1466 | else {
1467 | if (key === "") {
1468 | queueForVim("\r");
1469 | } else if (key === ""){
1470 | queueForVim("\t");
1471 | }
1472 | }
1473 | return !PASS_THROUGH;
1474 | }
1475 |
1476 | //Returns true if the non-newline text is the same but the text is longer. Useful in figuring out if carriage return added a line(which we should ignore) or did something special
1477 | function newLineCheck(value){
1478 | var newVal = textBoxGetValue();
1479 | return newVal.replace(/[^\n]/g,"") > value.replace(/[^\n]/g,"");
1480 | }
1481 |
1482 | function spaceCheck(value){
1483 | return textBoxGetValue().replace(/\s/g,"") === value.replace(/\s/g,"")
1484 | }
1485 |
1486 | //Even passing through these functions changes web behavior. We need to completely add or remove them depending on vim strictness.
1487 | function handleLeanVim() {
1488 | leanVimCheck = leanVim() && useFullVim();
1489 | if (leanVimCheck) {
1490 | borrowed.mappings.add(
1491 | [borrowed.modes.VIM_INSERT],
1492 | [""],
1493 | ["Override websites' up behavior"],
1494 | function(){queueForVim(ESC + '[A');});
1495 | borrowed.mappings.add(
1496 | [borrowed.modes.VIM_INSERT],
1497 | [""],
1498 | ["Override websites' down behavior"],
1499 | function(){queueForVim(ESC + '[B');});
1500 | borrowed.mappings.add(
1501 | [borrowed.modes.VIM_INSERT],
1502 | [""],
1503 | ["Override websites' right behavior"],
1504 | function(){queueForVim(ESC + '[C');});
1505 | borrowed.mappings.add(
1506 | [borrowed.modes.VIM_INSERT],
1507 | [""],
1508 | ["Override websites' left behavior"],
1509 | function(){queueForVim(ESC + '[D');});
1510 | } else {
1511 | borrowed.mappings.remove(borrowed.modes.VIM_INSERT, "");
1512 | borrowed.mappings.remove(borrowed.modes.VIM_INSERT, "");
1513 | borrowed.mappings.remove(borrowed.modes.VIM_INSERT, "");
1514 | borrowed.mappings.remove(borrowed.modes.VIM_INSERT, "");
1515 | }
1516 | }
1517 |
1518 | function handleStrictVim() {
1519 | strictVimCheck = strictVim() && useFullVim();
1520 | if (strictVimCheck) {
1521 | borrowed.mappings.add(
1522 | [borrowed.modes.VIM_INSERT],
1523 | [""],
1524 | ["Override websites' tab behavior"],
1525 | function(){specialKeyHandler("");});
1526 |
1527 | } else {
1528 | borrowed.mappings.remove(borrowed.modes.VIM_INSERT, "");
1529 | }
1530 | }
1531 |
1532 | function cleanupPterosaur() {
1533 | usingFullVim = useFullVim();
1534 | if (usingFullVim) {
1535 | if(pluginType == "dactyl"){
1536 | thisWindow.dactyl.plugins.mappings.builtin.remove(borrowed.modes.INSERT, "");
1537 | }
1538 | borrowed.mappings.add(
1539 | [borrowed.modes.VIM_INSERT],
1540 | ["", ""],
1541 | ["Handle escape key"],
1542 | function(){
1543 | if (prefs.getCharPref("exitkey") === "" && (vimMode === "n" || lastKey === ESC))
1544 | {
1545 | borrowed.modes.reset();
1546 | }
1547 | else {
1548 | queueForVim(ESC);
1549 | return false;
1550 | }
1551 | });
1552 |
1553 | borrowed.mappings.add(
1554 | [borrowed.modes.VIM_INSERT],
1555 | [""],
1556 | ["Handle backspace key"],
1557 | function(){
1558 | if(skipKeyPress){
1559 | return PASS_THROUGH;
1560 | }
1561 | queueForVim("\b");
1562 | });
1563 |
1564 | borrowed.mappings.add(
1565 | [borrowed.modes.VIM_INSERT],
1566 | [""],
1567 | "Override refresh and send to vim.",
1568 | function(){
1569 | queueForVim("\x12");
1570 | },
1571 | {noTransaction: true});
1572 |
1573 | borrowed.mappings.add(
1574 | [borrowed.modes.VIM_INSERT],
1575 | [""],
1576 | ["Override websites' carriage return behavior"],
1577 | function(){
1578 | queueForVim("\r");
1579 | },
1580 | {noTransaction: true});
1581 |
1582 | borrowed.mappings.add(
1583 | [borrowed.modes.VIM_INSERT],
1584 | [""],
1585 | ["Override websites' carriage return behavior"],
1586 | function(){return specialKeyHandler("");});
1587 | }
1588 | else {
1589 | borrowed.mappings.remove( borrowed.modes.VIM_INSERT, "");
1590 | borrowed.mappings.remove( borrowed.modes.VIM_INSERT, "");
1591 | borrowed.mappings.remove( borrowed.modes.VIM_INSERT, "");
1592 | borrowed.mappings.remove( borrowed.modes.VIM_INSERT, "");
1593 | borrowed.mappings.remove( borrowed.modes.VIM_INSERT, "");
1594 | borrowed.mappings.remove( borrowed.modes.VIM_INSERT, "");
1595 |
1596 | if(pluginType == "dactyl") {
1597 | thisWindow.dactyl.plugins.mappings.builtin.add([borrowed.modes.INSERT],
1598 | [""], "Expand Insert mode abbreviation",
1599 | function () {
1600 | thisWindow.dactyl.plugins.editor.expandAbbreviation(borrowed.modes.INSERT);
1601 | return PASS_THROUGH;
1602 | });
1603 | }
1604 | }
1605 | }
1606 |
1607 | function startVimbed() {
1608 | vimFile = null;
1609 | try{
1610 | vimFile = thisWindow.FileUtils.File(prefs.getCharPref("vimbinary"));
1611 | }
1612 | catch (e) {
1613 | vimFile = pterosaur.minidactyl.pathSearch(prefs.getCharPref("vimbinary") || "vim");
1614 | if (vimFile) {
1615 | prefs.setCharPref("vimbinary", vimFile.path);
1616 | }
1617 | }
1618 |
1619 | if (vimFile && vimFile.exists()){
1620 | vimNsIProc = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
1621 | vimNsIProc.init(vimFile)
1622 | } else {
1623 | vimNsIProc = null;
1624 | borrowed.echoerr("No vim instance found. Please set one using the 'extensions.pterosaur.vimbinary' preference in about:config.");
1625 | stateCheck();
1626 | return false;
1627 | }
1628 |
1629 | uid = Math.floor(Math.random()*0x100000000).toString(16)
1630 | dir = thisWindow.FileUtils.File("/tmp/vimbed/pterosaur_"+uid);
1631 | tmpfile = thisWindow.FileUtils.File("/tmp/vimbed/pterosaur_"+uid+"/contents.txt");
1632 | metaTmpfile = thisWindow.FileUtils.File("/tmp/vimbed/pterosaur_"+uid+"/meta.txt");
1633 | messageTmpfile = thisWindow.FileUtils.File("/tmp/vimbed/pterosaur_"+uid+"/messages.txt");
1634 | vimbedFile = thisWindow.FileUtils.File("/tmp/vimbed/pterosaur_"+uid+"/vimbed.vim");
1635 |
1636 |
1637 | dir.create(thisWindow.Ci.nsIFile.DIRECTORY_TYPE, 0o700);
1638 | tmpfile.create(thisWindow.Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
1639 | metaTmpfile.create(thisWindow.Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
1640 | messageTmpfile.create(thisWindow.Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
1641 | vimbedFile.create(thisWindow.Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
1642 |
1643 | tmpfile = new pterosaur.minidactyl.wrappedFile(tmpfile);
1644 | metaTmpfile = new pterosaur.minidactyl.wrappedFile(metaTmpfile);
1645 | messageTmpfile = new pterosaur.minidactyl.wrappedFile(messageTmpfile);
1646 | vimbedFile = new pterosaur.minidactyl.wrappedFile(vimbedFile);
1647 |
1648 | copyVimbedFile(vimbedFile);
1649 |
1650 | if (!tmpfile)
1651 | throw Error("io.cantCreateTempFile");
1652 |
1653 | if (!metaTmpfile)
1654 | throw Error("io.cantCreateTempFile");
1655 |
1656 | if (!messageTmpfile)
1657 | throw Error("io.cantCreateTempFile");
1658 |
1659 | var env_overrides = prefs.getCharPref("envoverrides").split(" ");
1660 | var override_dict = {};
1661 |
1662 | for (var index in env_overrides)
1663 | {
1664 | var override = env_overrides[index];
1665 | var colonIndex = override.indexOf("=");
1666 | if (colonIndex !== -1) {
1667 | override_dict[override.substring(0, colonIndex)] = override;
1668 | }
1669 | }
1670 |
1671 | var TERM = Environment.get("TERM");
1672 |
1673 | if (!TERM || TERM === "linux")
1674 | TERM = "xterm";
1675 |
1676 | var env_variables = ["DISPLAY", "USER", "XDG_VTNR", "XDG_SESSION_ID", "SHELL", "PATH", "LANG", "SHLVL", "XDG_SEAT", "HOME", "LOGNAME", "WINDOWPATH", "XDG_RUNTIME_DIR", "XAUTHORITY"];
1677 | for (var index = 0, len = env_variables.length; index < len; index++) {
1678 | if(override_dict[env_variables[index]]){
1679 | var tmp = override_dict[env_variables[index]];
1680 | delete override_dict[env_variables[index]];
1681 | env_variables[index] = tmp;
1682 | }
1683 | else
1684 | env_variables[index] = env_variables[index] + "=" + Environment.get(env_variables[index]);
1685 | }
1686 | if(override_dict["TERM"]) {
1687 | env_variables.push(override_dict["TERM"])
1688 | delete override_dict["TERM"]
1689 | }
1690 | else
1691 | env_variables.push("TERM=" + TERM);
1692 |
1693 | for (key in override_dict)
1694 | env_variables.push(override_dict[key])
1695 |
1696 | var pterosaurRcExists = false;
1697 |
1698 | try{
1699 | var rcFile = thisWindow.FileUtils.File(prefs.getCharPref("rcfile"));
1700 | if (rcFile.exists()) {
1701 | pterosaurRcExists = true;
1702 | }
1703 | } catch(e){ }
1704 |
1705 | var startVimProcess = function(){
1706 | var thisUid = uid;
1707 | vimProcess = subprocess.call({ url: thisWindow.URL,
1708 | command: vimFile.path,
1709 | arguments: function(){
1710 | var toCall = ["--servername", "pterosaur_" + uid,
1711 | "-s", "/dev/null",
1712 | "-S", vimbedFile.path];
1713 |
1714 |
1715 |
1716 | if(pterosaurRcExists){
1717 | toCall.push("-S");
1718 | toCall.push(prefs.getCharPref("rcfile"));
1719 | }
1720 | toCall.push("-vf");
1721 | toCall.push('+call Vimbed_SetupVimbed("","")');
1722 | return toCall;
1723 | }(),
1724 | environment: env_variables,
1725 | charet: 'UTF-8',
1726 | stdin: function(stdin){
1727 | vimStdin = stdin;
1728 | stdin.write(ESC)
1729 | },
1730 | //TODO: Rather than waiting to update, maybe update right away and leave a standing allowance of 25 ms to update without changes if we receive one?
1731 | //This only makes sense if we make upate without changes faster by checking directly against saved.
1732 | stdout: function(data){
1733 | var debugtty = prefs.getCharPref("debugtty");
1734 | if(debugtty){
1735 | if (debugtty != oldDebug){
1736 | try{
1737 | debugTerminal = new pterosaur.minidactyl.wrappedFile(thisWindow.FileUtils.File(debugtty));
1738 | }
1739 | catch(e){
1740 | debugTerminal = null;
1741 | }
1742 | oldDebug = debugtty;
1743 | }
1744 | if (debugTerminal) {
1745 | try{
1746 | debugTerminal.write(data);
1747 | }
1748 | catch(e){
1749 | console.log("Failed to write to tty.");
1750 | }
1751 |
1752 | }
1753 | }
1754 |
1755 | if (thisUid == uid){
1756 | if(gameTest < 60){
1757 | gameTest++;
1758 | }
1759 |
1760 | updateFromVim();
1761 | }
1762 | },
1763 | stderr: function(data){
1764 | if (prefs.getBoolPref("verbose")) {
1765 | console.log("Stderr: " + data);
1766 | }
1767 | if (data.indexOf("--servername") != -1) {
1768 | thisWindow.setTimeout(function(){
1769 | borrowed.echoerr("Pterosaur requires vim with +clientserver enabled. \nThe vim binary '" + vimFile.path + "' does not have +clientserver enabled.");
1770 | }, 500);
1771 | killVimbed();
1772 | stateCheck();
1773 | }
1774 | },
1775 | done: function(result){
1776 | if (prefs.getBoolPref("verbose")) {
1777 | console.log("Vim shutdown");
1778 | }
1779 | //If vim closes early, restart it.
1780 | if(thisUid == uid && prefs.getBoolPref("autorestart")) {
1781 | vimRestartTimeout = thisWindow.setTimeout(function(){
1782 | if (prefs.getBoolPref("verbose")) {
1783 | console.log("Restarting vim");
1784 | }
1785 | startVimProcess();
1786 | }, 200);
1787 | }
1788 | }
1789 | });
1790 | };
1791 | startVimProcess();
1792 | }
1793 |
1794 | function copyVimbedFile(destination){
1795 | var request = new thisWindow.XMLHttpRequest();
1796 | request.open("GET", "chrome://pterosaur/content/vimbed/plugin/vimbed.vim", true); // async=true
1797 | request.responseType = "text";
1798 | request.onerror = function(event) {
1799 | console.log("Failed to load vimbed from pterosaur.");
1800 | };
1801 | request.onload = function(event) {
1802 | if (request.response) {
1803 | destination.write(request.response);
1804 | }
1805 | else
1806 | request.onerror(event);
1807 | };
1808 | request.send();
1809 | }
1810 |
1811 | var savedText = null;
1812 | var savedCursorStart = null;
1813 | var savedCursorEnd = null;
1814 | var vimMode = 'i';
1815 | var pterFocused = null;
1816 | var textBox;
1817 | var textBoxType;
1818 | var lastVimCommand = "";
1819 | var sendToVim = "";
1820 | var lastKey = "";
1821 | var allowedToSend = true;
1822 | var pollTimeout;
1823 | var vimRestartTimeout;
1824 |
1825 | var uid;
1826 | var dir;
1827 | var tmpfile;
1828 | var metaTmpfile;
1829 | var messageTmpfile;
1830 | var vimbedFile;
1831 |
1832 | var debugTerminal = null;
1833 | var oldDebug = "";
1834 |
1835 | var vimProcess;
1836 |
1837 | var vimFile = null;
1838 |
1839 | var vimStdin = null;
1840 | var ESC = '\x1b';
1841 | var GS = '\x1d';
1842 |
1843 | var unsent = 1;
1844 |
1845 | function killVimbed() {
1846 | uid = 0;
1847 | thisWindow.clearTimeout(vimRestartTimeout);
1848 | if (vimStdin) {
1849 | vimStdin.close();
1850 | vimStdin = null;
1851 | }
1852 | if (dir) {
1853 | dir.remove(true);
1854 | dir = null;
1855 | }
1856 | }
1857 |
1858 | this.onUnload = function(){
1859 | if(!pluginType){
1860 | try{
1861 | thisWindow.document.getElementById("main-window").removeChild(modeLine)
1862 | } catch(e){}
1863 | } else if (pluginType == "dactyl"){
1864 | borrowed.commands.user.remove("pterosaurrestart");
1865 | } else if (pluginType == "vimperator"){
1866 | borrowed.commands.removeUserCommand("pterosaurrestart");
1867 | }
1868 | pterosaur.minidactyl.shutdown();
1869 | killVimbed();
1870 | }
1871 | }
1872 |
1873 | exports.setup = function(thisWindow, startupAttempts){
1874 | var head;
1875 | if (typeof thisWindow.dactyl != "undefined"){
1876 | if (thisWindow.dactyl.fullyInitialized){
1877 | head = thisWindow.dactyl;
1878 | }
1879 | } else if (typeof thisWindow.liberator != "undefined"){
1880 | head = thisWindow.liberator;
1881 | }
1882 | if(head || startupAttempts > 0){
1883 | thisWindow.pterosaurWindow = (new pterosaurWindow(thisWindow));
1884 | } else {
1885 | thisWindow.setTimeout(function(){exports.setup(thisWindow, (startupAttempts || 0) + 1);}, 300);
1886 | }
1887 | }
1888 |
1889 | exports.shutdown = function(thisWindow){
1890 | if(thisWindow.pterosaurWindow)
1891 | thisWindow.pterosaurWindow.onUnload()
1892 | }
1893 |
--------------------------------------------------------------------------------
/content/pterosaur.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ardagnir/pterosaur/8aa4220b2c26d4211157cd4cd5c34b4b352a3d84/content/pterosaur.png
--------------------------------------------------------------------------------
/content/subprocess.jsm:
--------------------------------------------------------------------------------
1 | // -*- coding: utf-8 -*-
2 | // vim: et:ts=4:sw=4:sts=4:ft=javascript
3 | /* ***** BEGIN LICENSE BLOCK *****
4 | * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 | *
6 | * The contents of this file are subject to the Mozilla Public
7 | * License Version 1.1 (the "MPL"); you may not use this file
8 | * except in compliance with the MPL. You may obtain a copy of
9 | * the MPL at http://www.mozilla.org/MPL/
10 | *
11 | * Software distributed under the MPL is distributed on an "AS
12 | * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
13 | * implied. See the MPL for the specific language governing
14 | * rights and limitations under the MPL.
15 | *
16 | * The Original Code is subprocess.jsm.
17 | *
18 | * The Initial Developer of this code is Jan Gerber.
19 | * Portions created by Jan Gerber
20 | * are Copyright (C) 2011 Jan Gerber.
21 | * All Rights Reserved.
22 | *
23 | * Contributor(s):
24 | * Patrick Brunschwig
25 | *
26 | * Alternatively, the contents of this file may be used under the terms of
27 | * either the GNU General Public License Version 2 or later (the "GPL"), or
28 | * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29 | * in which case the provisions of the GPL or the LGPL are applicable instead
30 | * of those above. If you wish to allow use of your version of this file only
31 | * under the terms of either the GPL or the LGPL, and not to allow others to
32 | * use your version of this file under the terms of the MPL, indicate your
33 | * decision by deleting the provisions above and replace them with the notice
34 | * and other provisions required by the GPL or the LGPL. If you do not delete
35 | * the provisions above, a recipient may use your version of this file under
36 | * the terms of any one of the MPL, the GPL or the LGPL.
37 | * ***** END LICENSE BLOCK ***** */
38 |
39 | /*
40 | * Import into a JS component using
41 | * 'Components.utils.import("resource://firefogg/subprocess.jsm");'
42 | *
43 | * This object allows to start a process, and read/write data to/from it
44 | * using stdin/stdout/stderr streams.
45 | * Usage example:
46 | *
47 | * var p = subprocess.call({
48 | * command: '/bin/foo',
49 | * arguments: ['-v', 'foo'],
50 | * environment: [ "XYZ=abc", "MYVAR=def" ],
51 | * charset: 'UTF-8',
52 | * workdir: '/home/foo',
53 | * //stdin: "some value to write to stdin\nfoobar",
54 | * stdin: function(stdin) {
55 | * stdin.write("some value to write to stdin\nfoobar");
56 | * stdin.close();
57 | * },
58 | * stdout: function(data) {
59 | * dump("got data on stdout:" + data + "\n");
60 | * },
61 | * stderr: function(data) {
62 | * dump("got data on stderr:" + data + "\n");
63 | * },
64 | * done: function(result) {
65 | * dump("process terminated with " + result.exitCode + "\n");
66 | * },
67 | * mergeStderr: false
68 | * });
69 | * p.wait(); // wait for the subprocess to terminate
70 | * // this will block the main thread,
71 | * // only do if you can wait that long
72 | *
73 | *
74 | * Description of parameters:
75 | * --------------------------
76 | * Apart from , all arguments are optional.
77 | *
78 | * command: either a |nsIFile| object pointing to an executable file or a
79 | * String containing the platform-dependent path to an executable
80 | * file.
81 | *
82 | * arguments: optional string array containing the arguments to the command.
83 | *
84 | * environment: optional string array containing environment variables to pass
85 | * to the command. The array elements must have the form
86 | * "VAR=data". Please note that if environment is defined, it
87 | * replaces any existing environment variables for the subprocess.
88 | *
89 | * charset: Output is decoded with given charset and a string is returned.
90 | * If charset is undefined, "UTF-8" is used as default.
91 | * To get binary data, set this explicitly to null and the
92 | * returned string is not decoded in any way.
93 | *
94 | * workdir: optional; String containing the platform-dependent path to a
95 | * directory to become the current working directory of the subprocess.
96 | *
97 | * stdin: optional input data for the process to be passed on standard
98 | * input. stdin can either be a string or a function.
99 | * A |string| gets written to stdin and stdin gets closed;
100 | * A |function| gets passed an object with write and close function.
101 | * Please note that the write() function will return almost immediately;
102 | * data is always written asynchronously on a separate thread.
103 | *
104 | * stdout: an optional function that can receive output data from the
105 | * process. The stdout-function is called asynchronously; it can be
106 | * called mutliple times during the execution of a process.
107 | * At a minimum at each occurance of \n or \r.
108 | * Please note that null-characters might need to be escaped
109 | * with something like 'data.replace(/\0/g, "\\0");'.
110 | *
111 | * stderr: an optional function that can receive stderr data from the
112 | * process. The stderr-function is called asynchronously; it can be
113 | * called mutliple times during the execution of a process. Please
114 | * note that null-characters might need to be escaped with
115 | * something like 'data.replace(/\0/g, "\\0");'.
116 | * (on windows it only gets called once right now)
117 | *
118 | * done: optional function that is called when the process has terminated.
119 | * The exit code from the process available via result.exitCode. If
120 | * stdout is not defined, then the output from stdout is available
121 | * via result.stdout. stderr data is in result.stderr
122 | *
123 | * mergeStderr: optional boolean value. If true, stderr is merged with stdout;
124 | * no data will be provided to stderr. Default is false.
125 | *
126 | * bufferedOutput: optional boolean value. If true, stderr and stdout are buffered
127 | * and will only deliver data when a certain amount of output is
128 | * available. Enabling the option will give you some performance
129 | * benefits if your read a lot of data. Don't enable this if your
130 | * application works in a conversation-like mode. Default is false.
131 | *
132 | *
133 | * Description of object returned by subprocess.call(...)
134 | * ------------------------------------------------------
135 | * The object returned by subprocess.call offers a few methods that can be
136 | * executed:
137 | *
138 | * wait(): waits for the subprocess to terminate. It is not required to use
139 | * wait; done will be called in any case when the subprocess terminated.
140 | *
141 | * kill(hardKill): kill the subprocess. Any open pipes will be closed and
142 | * done will be called.
143 | * hardKill [ignored on Windows]:
144 | * - false: signal the process terminate (SIGTERM)
145 | * - true: kill the process (SIGKILL)
146 | *
147 | *
148 | * Other methods in subprocess
149 | * ---------------------------
150 | *
151 | * registerDebugHandler(functionRef): register a handler that is called to get
152 | * debugging information
153 | * registerLogHandler(functionRef): register a handler that is called to get error
154 | * messages
155 | *
156 | * example:
157 | * subprocess.registerLogHandler( function(s) { dump(s); } );
158 | */
159 |
160 | 'use strict';
161 |
162 | Components.utils.import("resource://gre/modules/ctypes.jsm");
163 |
164 | let EXPORTED_SYMBOLS = [ "subprocess" ];
165 |
166 | const Cc = Components.classes;
167 | const Ci = Components.interfaces;
168 |
169 | const NS_LOCAL_FILE = "@mozilla.org/file/local;1";
170 |
171 |
172 | //Windows API definitions
173 | if (ctypes.size_t.size == 8) {
174 | var WinABI = ctypes.default_abi;
175 | } else {
176 | var WinABI = ctypes.winapi_abi;
177 | }
178 | const WORD = ctypes.uint16_t;
179 | const DWORD = ctypes.uint32_t;
180 | const LPDWORD = DWORD.ptr;
181 |
182 | const UINT = ctypes.unsigned_int;
183 | const BOOL = ctypes.bool;
184 | const HANDLE = ctypes.size_t;
185 | const HWND = HANDLE;
186 | const HMODULE = HANDLE;
187 | const WPARAM = ctypes.size_t;
188 | const LPARAM = ctypes.size_t;
189 | const LRESULT = ctypes.size_t;
190 | const ULONG_PTR = ctypes.uintptr_t;
191 | const PVOID = ctypes.voidptr_t;
192 | const LPVOID = PVOID;
193 | const LPCTSTR = ctypes.jschar.ptr;
194 | const LPCWSTR = ctypes.jschar.ptr;
195 | const LPTSTR = ctypes.jschar.ptr;
196 | const LPSTR = ctypes.char.ptr;
197 | const LPCSTR = ctypes.char.ptr;
198 | const LPBYTE = ctypes.char.ptr;
199 |
200 | const CREATE_NEW_CONSOLE = 0x00000010;
201 | const CREATE_NO_WINDOW = 0x08000000;
202 | const CREATE_UNICODE_ENVIRONMENT = 0x00000400;
203 | const STARTF_USESHOWWINDOW = 0x00000001;
204 | const STARTF_USESTDHANDLES = 0x00000100;
205 | const SW_HIDE = 0;
206 | const DUPLICATE_SAME_ACCESS = 0x00000002;
207 | const STILL_ACTIVE = 259;
208 | const INFINITE = DWORD(0xFFFFFFFF);
209 | const WAIT_TIMEOUT = 0x00000102;
210 |
211 | /*
212 | typedef struct _SECURITY_ATTRIBUTES {
213 | DWORD nLength;
214 | LPVOID lpSecurityDescriptor;
215 | BOOL bInheritHandle;
216 | } SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;
217 | */
218 | const SECURITY_ATTRIBUTES = new ctypes.StructType("SECURITY_ATTRIBUTES", [
219 | {"nLength": DWORD},
220 | {"lpSecurityDescriptor": LPVOID},
221 | {"bInheritHandle": BOOL}
222 | ]);
223 |
224 | /*
225 | typedef struct _STARTUPINFO {
226 | DWORD cb;
227 | LPTSTR lpReserved;
228 | LPTSTR lpDesktop;
229 | LPTSTR lpTitle;
230 | DWORD dwX;
231 | DWORD dwY;
232 | DWORD dwXSize;
233 | DWORD dwYSize;
234 | DWORD dwXCountChars;
235 | DWORD dwYCountChars;
236 | DWORD dwFillAttribute;
237 | DWORD dwFlags;
238 | WORD wShowWindow;
239 | WORD cbReserved2;
240 | LPBYTE lpReserved2;
241 | HANDLE hStdInput;
242 | HANDLE hStdOutput;
243 | HANDLE hStdError;
244 | } STARTUPINFO, *LPSTARTUPINFO;
245 | */
246 | const STARTUPINFO = new ctypes.StructType("STARTUPINFO", [
247 | {"cb": DWORD},
248 | {"lpReserved": LPTSTR},
249 | {"lpDesktop": LPTSTR},
250 | {"lpTitle": LPTSTR},
251 | {"dwX": DWORD},
252 | {"dwY": DWORD},
253 | {"dwXSize": DWORD},
254 | {"dwYSize": DWORD},
255 | {"dwXCountChars": DWORD},
256 | {"dwYCountChars": DWORD},
257 | {"dwFillAttribute": DWORD},
258 | {"dwFlags": DWORD},
259 | {"wShowWindow": WORD},
260 | {"cbReserved2": WORD},
261 | {"lpReserved2": LPBYTE},
262 | {"hStdInput": HANDLE},
263 | {"hStdOutput": HANDLE},
264 | {"hStdError": HANDLE}
265 | ]);
266 |
267 | /*
268 | typedef struct _PROCESS_INFORMATION {
269 | HANDLE hProcess;
270 | HANDLE hThread;
271 | DWORD dwProcessId;
272 | DWORD dwThreadId;
273 | } PROCESS_INFORMATION, *LPPROCESS_INFORMATION;
274 | */
275 | const PROCESS_INFORMATION = new ctypes.StructType("PROCESS_INFORMATION", [
276 | {"hProcess": HANDLE},
277 | {"hThread": HANDLE},
278 | {"dwProcessId": DWORD},
279 | {"dwThreadId": DWORD}
280 | ]);
281 |
282 | /*
283 | typedef struct _OVERLAPPED {
284 | ULONG_PTR Internal;
285 | ULONG_PTR InternalHigh;
286 | union {
287 | struct {
288 | DWORD Offset;
289 | DWORD OffsetHigh;
290 | };
291 | PVOID Pointer;
292 | };
293 | HANDLE hEvent;
294 | } OVERLAPPED, *LPOVERLAPPED;
295 | */
296 | const OVERLAPPED = new ctypes.StructType("OVERLAPPED");
297 |
298 | //UNIX definitions
299 | const pid_t = ctypes.int32_t;
300 | const WNOHANG = 1;
301 | const F_GETFD = 1;
302 | const F_SETFL = 4;
303 |
304 | const LIBNAME = 0;
305 | const O_NONBLOCK = 1;
306 | const RLIM_T = 2;
307 | const RLIMIT_NOFILE = 3;
308 |
309 | function getPlatformValue(valueType) {
310 |
311 | if (! gXulRuntime)
312 | gXulRuntime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
313 |
314 | const platformDefaults = {
315 | // Windows API:
316 | 'winnt': [ 'kernel32.dll' ],
317 |
318 | // Unix API:
319 | // library name O_NONBLOCK RLIM_T RLIMIT_NOFILE
320 | 'darwin': [ 'libc.dylib', 0x04 , ctypes.uint64_t , 8 ],
321 | 'linux': [ 'libc.so.6', 2024 , ctypes.unsigned_long, 7 ],
322 | 'freebsd': [ 'libc.so.7', 0x04 , ctypes.int64_t , 8 ],
323 | 'openbsd': [ 'libc.so.61.0', 0x04 , ctypes.int64_t , 8 ],
324 | 'sunos': [ 'libc.so', 0x80 , ctypes.unsigned_long, 5 ]
325 | };
326 |
327 | return platformDefaults[gXulRuntime.OS.toLowerCase()][valueType];
328 | }
329 |
330 |
331 | var gDebugFunc = null,
332 | gLogFunc = null,
333 | gXulRuntime = null;
334 |
335 | function LogError(s) {
336 | if (gLogFunc)
337 | gLogFunc(s);
338 | else
339 | dump(s);
340 | }
341 |
342 | function debugLog(s) {
343 | if (gDebugFunc)
344 | gDebugFunc(s);
345 | }
346 |
347 | function setTimeout(callback, timeout) {
348 | var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
349 | timer.initWithCallback(callback, timeout, Ci.nsITimer.TYPE_ONE_SHOT);
350 | };
351 |
352 | function convertBytes(data, charset) {
353 | var string = '';
354 | charset = charset || 'UTF-8';
355 | var unicodeConv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
356 | .getService(Ci.nsIScriptableUnicodeConverter);
357 | try {
358 | unicodeConv.charset = charset;
359 | string = unicodeConv.ConvertToUnicode(data);
360 | } catch (ex) {
361 | LogError("String conversion failed: "+ex.toString()+"\n");
362 | string = '';
363 | }
364 | string += unicodeConv.Finish();
365 | return string;
366 | }
367 |
368 | function getCommandStr(command) {
369 | let commandStr = null;
370 | if (typeof(command) == "string") {
371 | let file = Cc[NS_LOCAL_FILE].createInstance(Ci.nsIFile);
372 | file.initWithPath(command);
373 | if (! (file.isExecutable() && file.isFile()))
374 | throw("File '"+command+"' is not an executable file");
375 | commandStr = command;
376 | }
377 | else {
378 | if (! (command.isExecutable() && command.isFile()))
379 | throw("File '"+command.path+"' is not an executable file");
380 | commandStr = command.path;
381 | }
382 |
383 | return commandStr;
384 | }
385 |
386 | function getWorkDir(workdir) {
387 | let workdirStr = null;
388 | if (typeof(workdir) == "string") {
389 | let file = Cc[NS_LOCAL_FILE].createInstance(Ci.nsIFile);
390 | file.initWithPath(workdir);
391 | if (! (file.isDirectory()))
392 | throw("Directory '"+workdir+"' does not exist");
393 | workdirStr = workdir;
394 | }
395 | else if (workdir) {
396 | if (! workdir.isDirectory())
397 | throw("Directory '"+workdir.path+"' does not exist");
398 | workdirStr = workdir.path;
399 | }
400 | return workdirStr;
401 | }
402 |
403 |
404 | var subprocess = {
405 | call: function(options) {
406 | options.mergeStderr = options.mergeStderr || false;
407 | options.bufferedOutput = options.bufferedOutput || false;
408 | options.workdir = options.workdir || null;
409 | options.environment = options.environment || [];
410 | if (options.arguments) {
411 | var args = options.arguments;
412 | options.arguments = [];
413 | args.forEach(function(argument) {
414 | options.arguments.push(argument);
415 | });
416 | } else {
417 | options.arguments = [];
418 | }
419 |
420 | options.libc = getPlatformValue(LIBNAME);
421 |
422 | if (gXulRuntime.OS.substring(0, 3) == "WIN") {
423 | return subprocess_win32(options);
424 | } else {
425 | return subprocess_unix(options);
426 | }
427 |
428 | },
429 | registerDebugHandler: function(func) {
430 | gDebugFunc = func;
431 | },
432 | registerLogHandler: function(func) {
433 | gLogFunc = func;
434 | },
435 |
436 | getPlatformValue: getPlatformValue
437 | };
438 |
439 |
440 |
441 | function subprocess_win32(options) {
442 | var kernel32dll = ctypes.open(options.libc),
443 | hChildProcess,
444 | active = true,
445 | done = false,
446 | exitCode = -1,
447 | child = {},
448 | stdinWorker = null,
449 | stdoutWorker = null,
450 | stderrWorker = null,
451 | pendingWriteCount = 0,
452 | readers = 2,
453 | stdinOpenState = 2,
454 | error = '',
455 | output = '';
456 |
457 | // stdin pipe states
458 | const OPEN = 2;
459 | const CLOSEABLE = 1;
460 | const CLOSED = 0;
461 |
462 | //api declarations
463 | /*
464 | BOOL WINAPI CloseHandle(
465 | __in HANDLE hObject
466 | );
467 | */
468 | var CloseHandle = kernel32dll.declare("CloseHandle",
469 | WinABI,
470 | BOOL,
471 | HANDLE
472 | );
473 |
474 | /*
475 | BOOL WINAPI CreateProcess(
476 | __in_opt LPCTSTR lpApplicationName,
477 | __inout_opt LPTSTR lpCommandLine,
478 | __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes,
479 | __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
480 | __in BOOL bInheritHandles,
481 | __in DWORD dwCreationFlags,
482 | __in_opt LPVOID lpEnvironment,
483 | __in_opt LPCTSTR lpCurrentDirectory,
484 | __in LPSTARTUPINFO lpStartupInfo,
485 | __out LPPROCESS_INFORMATION lpProcessInformation
486 | );
487 | */
488 | var CreateProcessW = kernel32dll.declare("CreateProcessW",
489 | WinABI,
490 | BOOL,
491 | LPCTSTR,
492 | LPTSTR,
493 | SECURITY_ATTRIBUTES.ptr,
494 | SECURITY_ATTRIBUTES.ptr,
495 | BOOL,
496 | DWORD,
497 | LPVOID,
498 | LPCTSTR,
499 | STARTUPINFO.ptr,
500 | PROCESS_INFORMATION.ptr
501 | );
502 |
503 | // /*
504 | // BOOL WINAPI ReadFile(
505 | // __in HANDLE hFile,
506 | // __out LPVOID ReadFileBuffer,
507 | // __in DWORD nNumberOfBytesToRead,
508 | // __out_opt LPDWORD lpNumberOfBytesRead,
509 | // __inout_opt LPOVERLAPPED lpOverlapped
510 | // );
511 | // */
512 | // var ReadFileBufferSize = 1024,
513 | // ReadFileBuffer = ctypes.char.array(ReadFileBufferSize),
514 | // ReadFile = kernel32dll.declare("ReadFile",
515 | // WinABI,
516 | // BOOL,
517 | // HANDLE,
518 | // ReadFileBuffer,
519 | // DWORD,
520 | // LPDWORD,
521 | // OVERLAPPED.ptr
522 | // );
523 | //
524 | // /*
525 | // BOOL WINAPI PeekNamedPipe(
526 | // __in HANDLE hNamedPipe,
527 | // __out_opt LPVOID lpBuffer,
528 | // __in DWORD nBufferSize,
529 | // __out_opt LPDWORD lpBytesRead,
530 | // __out_opt LPDWORD lpTotalBytesAvail,
531 | // __out_opt LPDWORD lpBytesLeftThisMessage
532 | // );
533 | // */
534 | // var PeekNamedPipe = kernel32dll.declare("PeekNamedPipe",
535 | // WinABI,
536 | // BOOL,
537 | // HANDLE,
538 | // ReadFileBuffer,
539 | // DWORD,
540 | // LPDWORD,
541 | // LPDWORD,
542 | // LPDWORD
543 | // );
544 | //
545 | // /*
546 | // BOOL WINAPI WriteFile(
547 | // __in HANDLE hFile,
548 | // __in LPCVOID lpBuffer,
549 | // __in DWORD nNumberOfBytesToWrite,
550 | // __out_opt LPDWORD lpNumberOfBytesWritten,
551 | // __inout_opt LPOVERLAPPED lpOverlapped
552 | // );
553 | // */
554 | // var WriteFile = kernel32dll.declare("WriteFile",
555 | // WinABI,
556 | // BOOL,
557 | // HANDLE,
558 | // ctypes.char.ptr,
559 | // DWORD,
560 | // LPDWORD,
561 | // OVERLAPPED.ptr
562 | // );
563 |
564 | /*
565 | BOOL WINAPI CreatePipe(
566 | __out PHANDLE hReadPipe,
567 | __out PHANDLE hWritePipe,
568 | __in_opt LPSECURITY_ATTRIBUTES lpPipeAttributes,
569 | __in DWORD nSize
570 | );
571 | */
572 | var CreatePipe = kernel32dll.declare("CreatePipe",
573 | WinABI,
574 | BOOL,
575 | HANDLE.ptr,
576 | HANDLE.ptr,
577 | SECURITY_ATTRIBUTES.ptr,
578 | DWORD
579 | );
580 |
581 | /*
582 | HANDLE WINAPI GetCurrentProcess(void);
583 | */
584 | var GetCurrentProcess = kernel32dll.declare("GetCurrentProcess",
585 | WinABI,
586 | HANDLE
587 | );
588 |
589 | /*
590 | DWORD WINAPI GetLastError(void);
591 | */
592 | var GetLastError = kernel32dll.declare("GetLastError",
593 | WinABI,
594 | DWORD
595 | );
596 |
597 | /*
598 | BOOL WINAPI DuplicateHandle(
599 | __in HANDLE hSourceProcessHandle,
600 | __in HANDLE hSourceHandle,
601 | __in HANDLE hTargetProcessHandle,
602 | __out LPHANDLE lpTargetHandle,
603 | __in DWORD dwDesiredAccess,
604 | __in BOOL bInheritHandle,
605 | __in DWORD dwOptions
606 | );
607 | */
608 | var DuplicateHandle = kernel32dll.declare("DuplicateHandle",
609 | WinABI,
610 | BOOL,
611 | HANDLE,
612 | HANDLE,
613 | HANDLE,
614 | HANDLE.ptr,
615 | DWORD,
616 | BOOL,
617 | DWORD
618 | );
619 |
620 |
621 | /*
622 | BOOL WINAPI GetExitCodeProcess(
623 | __in HANDLE hProcess,
624 | __out LPDWORD lpExitCode
625 | );
626 | */
627 | var GetExitCodeProcess = kernel32dll.declare("GetExitCodeProcess",
628 | WinABI,
629 | BOOL,
630 | HANDLE,
631 | LPDWORD
632 | );
633 |
634 | /*
635 | DWORD WINAPI WaitForSingleObject(
636 | __in HANDLE hHandle,
637 | __in DWORD dwMilliseconds
638 | );
639 | */
640 | var WaitForSingleObject = kernel32dll.declare("WaitForSingleObject",
641 | WinABI,
642 | DWORD,
643 | HANDLE,
644 | DWORD
645 | );
646 |
647 | /*
648 | BOOL WINAPI TerminateProcess(
649 | __in HANDLE hProcess,
650 | __in UINT uExitCode
651 | );
652 | */
653 | var TerminateProcess = kernel32dll.declare("TerminateProcess",
654 | WinABI,
655 | BOOL,
656 | HANDLE,
657 | UINT
658 | );
659 |
660 | //functions
661 | function popen(command, workdir, args, environment, child) {
662 | //escape arguments
663 | args.unshift(command);
664 | for (var i = 0; i < args.length; i++) {
665 | if (typeof args[i] != "string") { args[i] = args[i].toString(); }
666 | /* quote arguments with spaces */
667 | if (args[i].match(/\s/)) {
668 | args[i] = "\"" + args[i] + "\"";
669 | }
670 | /* If backslash is followed by a quote, double it */
671 | args[i] = args[i].replace(/\\\"/g, "\\\\\"");
672 | }
673 | command = args.join(' ');
674 |
675 | environment = environment || [];
676 | if(environment.length) {
677 | //An environment block consists of
678 | //a null-terminated block of null-terminated strings.
679 | //Using CREATE_UNICODE_ENVIRONMENT so needs to be jschar
680 | environment = ctypes.jschar.array()(environment.join('\0') + '\0');
681 | } else {
682 | environment = null;
683 | }
684 |
685 | var hOutputReadTmp = new HANDLE(),
686 | hOutputRead = new HANDLE(),
687 | hOutputWrite = new HANDLE();
688 |
689 | var hErrorRead = new HANDLE(),
690 | hErrorReadTmp = new HANDLE(),
691 | hErrorWrite = new HANDLE();
692 |
693 | var hInputRead = new HANDLE(),
694 | hInputWriteTmp = new HANDLE(),
695 | hInputWrite = new HANDLE();
696 |
697 | // Set up the security attributes struct.
698 | var sa = new SECURITY_ATTRIBUTES();
699 | sa.nLength = SECURITY_ATTRIBUTES.size;
700 | sa.lpSecurityDescriptor = null;
701 | sa.bInheritHandle = true;
702 |
703 | // Create output pipe.
704 |
705 | if(!CreatePipe(hOutputReadTmp.address(), hOutputWrite.address(), sa.address(), 0))
706 | LogError('CreatePipe hOutputReadTmp failed');
707 |
708 | // Create error pipe.
709 | if(!CreatePipe(hErrorReadTmp.address(), hErrorWrite.address(), sa.address(), 0))
710 | LogError('CreatePipe hErrorReadTmp failed');
711 |
712 | // Create input pipe.
713 | if (!CreatePipe(hInputRead.address(),hInputWriteTmp.address(),sa.address(), 0))
714 | LogError("CreatePipe hInputRead failed");
715 |
716 | // Create new output/error read handle and the input write handles. Set
717 | // the Properties to FALSE. Otherwise, the child inherits the
718 | // properties and, as a result, non-closeable handles to the pipes
719 | // are created.
720 | if (!DuplicateHandle(GetCurrentProcess(), hOutputReadTmp,
721 | GetCurrentProcess(),
722 | hOutputRead.address(), // Address of new handle.
723 | 0, false, // Make it uninheritable.
724 | DUPLICATE_SAME_ACCESS))
725 | LogError("DupliateHandle hOutputReadTmp failed");
726 |
727 | if (!DuplicateHandle(GetCurrentProcess(), hErrorReadTmp,
728 | GetCurrentProcess(),
729 | hErrorRead.address(), // Address of new handle.
730 | 0, false, // Make it uninheritable.
731 | DUPLICATE_SAME_ACCESS))
732 | LogError("DupliateHandle hErrorReadTmp failed");
733 |
734 | if (!DuplicateHandle(GetCurrentProcess(), hInputWriteTmp,
735 | GetCurrentProcess(),
736 | hInputWrite.address(), // Address of new handle.
737 | 0, false, // Make it uninheritable.
738 | DUPLICATE_SAME_ACCESS))
739 | LogError("DupliateHandle hInputWriteTmp failed");
740 |
741 | // Close inheritable copies of the handles.
742 | if (!CloseHandle(hOutputReadTmp)) LogError("CloseHandle hOutputReadTmp failed");
743 | if (!CloseHandle(hErrorReadTmp)) LogError("CloseHandle hErrorReadTmp failed");
744 | if (!CloseHandle(hInputWriteTmp)) LogError("CloseHandle failed");
745 |
746 | var pi = new PROCESS_INFORMATION();
747 | var si = new STARTUPINFO();
748 |
749 | si.cb = STARTUPINFO.size;
750 | si.dwFlags = STARTF_USESTDHANDLES;
751 | si.hStdInput = hInputRead;
752 | si.hStdOutput = hOutputWrite;
753 | si.hStdError = hErrorWrite;
754 |
755 | // Launch the process
756 | if(!CreateProcessW(null, // executable name
757 | command, // command buffer
758 | null, // process security attribute
759 | null, // thread security attribute
760 | true, // inherits system handles
761 | CREATE_UNICODE_ENVIRONMENT|CREATE_NO_WINDOW, // process flags
762 | environment, // envrionment block
763 | workdir, // set as current directory
764 | si.address(), // (in) startup information
765 | pi.address() // (out) process information
766 | ))
767 | throw("Fatal - Could not launch subprocess '"+command+"'");
768 |
769 | // Close any unnecessary handles.
770 | if (!CloseHandle(pi.hThread))
771 | LogError("CloseHandle pi.hThread failed");
772 |
773 | // Close pipe handles (do not continue to modify the parent).
774 | // You need to make sure that no handles to the write end of the
775 | // output pipe are maintained in this process or else the pipe will
776 | // not close when the child process exits and the ReadFile will hang.
777 | if (!CloseHandle(hInputRead)) LogError("CloseHandle hInputRead failed");
778 | if (!CloseHandle(hOutputWrite)) LogError("CloseHandle hOutputWrite failed");
779 | if (!CloseHandle(hErrorWrite)) LogError("CloseHandle hErrorWrite failed");
780 |
781 | //return values
782 | child.stdin = hInputWrite;
783 | child.stdout = hOutputRead;
784 | child.stderr = hErrorRead;
785 | child.process = pi.hProcess;
786 | return pi.hProcess;
787 | }
788 |
789 | /*
790 | * createStdinWriter ()
791 | *
792 | * Create a ChromeWorker object for writing data to the subprocess' stdin
793 | * pipe. The ChromeWorker object lives on a separate thread; this avoids
794 | * internal deadlocks.
795 | */
796 | function createStdinWriter() {
797 | debugLog("Creating new stdin worker\n");
798 | stdinWorker = new ChromeWorker("subprocess_worker_win.js");
799 | stdinWorker.onmessage = function(event) {
800 | switch(event.data) {
801 | case "WriteOK":
802 | pendingWriteCount--;
803 | debugLog("got OK from stdinWorker - remaining count: "+pendingWriteCount+"\n");
804 | break;
805 | case "ClosedOK":
806 | stdinOpenState = CLOSED;
807 | debugLog("Stdin pipe closed\n");
808 | break;
809 | default:
810 | debugLog("got msg from stdinWorker: "+event.data+"\n");
811 | }
812 | };
813 | stdinWorker.onerror = function(error) {
814 | pendingWriteCount--;
815 | exitCode = -2;
816 | LogError("got error from stdinWorker: "+error.message+"\n");
817 | };
818 |
819 | stdinWorker.postMessage({msg: "init", libc: options.libc});
820 | }
821 |
822 | /*
823 | * writeStdin()
824 | * @data: String containing the data to write
825 | *
826 | * Write data to the subprocess' stdin (equals to sending a request to the
827 | * ChromeWorker object to write the data).
828 | */
829 | function writeStdin(data) {
830 | ++pendingWriteCount;
831 | debugLog("sending "+data.length+" bytes to stdinWorker\n");
832 | var pipePtr = parseInt(ctypes.cast(child.stdin.address(), ctypes.uintptr_t).value);
833 |
834 | stdinWorker.postMessage({
835 | msg: 'write',
836 | pipe: pipePtr,
837 | data: data
838 | });
839 | }
840 |
841 | /*
842 | * closeStdinHandle()
843 | *
844 | * Close the stdin pipe, either directly or by requesting the ChromeWorker to
845 | * close the pipe. The ChromeWorker will only close the pipe after the last write
846 | * request process is done.
847 | */
848 |
849 | function closeStdinHandle() {
850 | debugLog("trying to close stdin\n");
851 | if (stdinOpenState != OPEN) return;
852 | stdinOpenState = CLOSEABLE;
853 |
854 | if (stdinWorker) {
855 | debugLog("sending close stdin to worker\n");
856 | var pipePtr = parseInt(ctypes.cast(child.stdin.address(), ctypes.uintptr_t).value);
857 | stdinWorker.postMessage({
858 | msg: 'close',
859 | pipe: pipePtr
860 | });
861 | }
862 | else {
863 | stdinOpenState = CLOSED;
864 | debugLog("Closing Stdin\n");
865 | CloseHandle(child.stdin) || LogError("CloseHandle hInputWrite failed");
866 | }
867 | }
868 |
869 |
870 | /*
871 | * createReader(pipe, name)
872 | *
873 | * @pipe: handle to the pipe
874 | * @name: String containing the pipe name (stdout or stderr)
875 | *
876 | * Create a ChromeWorker object for reading data asynchronously from
877 | * the pipe (i.e. on a separate thread), and passing the result back to
878 | * the caller.
879 | */
880 | function createReader(pipe, name, callbackFunc) {
881 | var worker = new ChromeWorker("subprocess_worker_win.js");
882 | worker.onmessage = function(event) {
883 | switch(event.data.msg) {
884 | case "data":
885 | debugLog("got "+event.data.count+" bytes from "+name+"\n");
886 | var data = '';
887 | if (options.charset === null) {
888 | data = event.data.data;
889 | }
890 | else
891 | data = convertBytes(event.data.data, options.charset);
892 |
893 | callbackFunc(data);
894 | break;
895 | case "done":
896 | debugLog("Pipe "+name+" closed\n");
897 | --readers;
898 | if (readers == 0) cleanup();
899 | break;
900 | case "error":
901 | exitCode = -2;
902 | LogError("Got msg from "+name+": "+event.data.data+"\n");
903 | break;
904 | default:
905 | debugLog("Got msg from "+name+": "+event.data.data+"\n");
906 | }
907 | };
908 |
909 | worker.onerror = function(errorMsg) {
910 | LogError("Got error from "+name+": "+errorMsg.message);
911 | exitCode = -2;
912 | };
913 |
914 | var pipePtr = parseInt(ctypes.cast(pipe.address(), ctypes.uintptr_t).value);
915 |
916 | worker.postMessage({
917 | msg: 'read',
918 | pipe: pipePtr,
919 | libc: options.libc,
920 | charset: options.charset === null ? "null" : options.charset,
921 | bufferedOutput: options.bufferedOutput,
922 | name: name
923 | });
924 |
925 | return worker;
926 | }
927 |
928 | /*
929 | * readPipes()
930 | *
931 | * Open the pipes for reading from stdout and stderr
932 | */
933 | function readPipes() {
934 |
935 | stdoutWorker = createReader(child.stdout, "stdout", function (data) {
936 | if(options.stdout) {
937 | setTimeout(function() {
938 | options.stdout(data);
939 | }, 0);
940 | } else {
941 | output += data;
942 | }
943 | });
944 |
945 |
946 | stderrWorker = createReader(child.stderr, "stderr", function (data) {
947 | var output = options.mergeStderr ? 'stdout' : 'stderr';
948 | if(options[output]) {
949 | setTimeout(function() {
950 | options[output](data);
951 | }, 0);
952 | } else {
953 | error += data;
954 | }
955 | });
956 | }
957 |
958 | /*
959 | * cleanup()
960 | *
961 | * close stdin if needed, get the exit code from the subprocess and invoke
962 | * the caller's done() function.
963 | *
964 | * Note: because stdout() and stderr() are called using setTimeout, we need to
965 | * do the same here in order to guarantee the message sequence.
966 | */
967 | function cleanup() {
968 | debugLog("Cleanup called\n");
969 | if(active) {
970 | active = false;
971 |
972 | closeStdinHandle(); // should only be required in case of errors
973 |
974 | var exit = new DWORD();
975 | GetExitCodeProcess(child.process, exit.address());
976 |
977 | if (exitCode > -2)
978 | exitCode = exit.value;
979 |
980 | if (stdinWorker)
981 | stdinWorker.postMessage({msg: 'stop'});
982 |
983 | setTimeout(function _done() {
984 | if (options.done) {
985 | try {
986 | options.done({
987 | exitCode: exitCode,
988 | stdout: output,
989 | stderr: error
990 | });
991 | }
992 | catch (ex) {
993 | // prevent from blocking if options.done() throws an error
994 | done = true;
995 | throw ex;
996 | }
997 | }
998 | done = true;
999 | }, 0);
1000 | kernel32dll.close();
1001 | }
1002 | }
1003 |
1004 | var cmdStr = getCommandStr(options.command);
1005 | var workDir = getWorkDir(options.workdir);
1006 |
1007 | //main
1008 | hChildProcess = popen(cmdStr, workDir, options.arguments, options.environment, child);
1009 |
1010 | readPipes();
1011 |
1012 | if (options.stdin) {
1013 | createStdinWriter();
1014 |
1015 | if(typeof(options.stdin) == 'function') {
1016 | try {
1017 | options.stdin({
1018 | write: function(data) {
1019 | writeStdin(data);
1020 | },
1021 | close: function() {
1022 | closeStdinHandle();
1023 | }
1024 | });
1025 | }
1026 | catch (ex) {
1027 | // prevent from failing if options.stdin() throws an exception
1028 | closeStdinHandle();
1029 | throw ex;
1030 | }
1031 | } else {
1032 | writeStdin(options.stdin);
1033 | closeStdinHandle();
1034 | }
1035 | }
1036 | else
1037 | closeStdinHandle();
1038 |
1039 | return {
1040 | kill: function(hardKill) {
1041 | // hardKill is currently ignored on Windows
1042 | var r = !!TerminateProcess(child.process, 255);
1043 | cleanup(-1);
1044 | return r;
1045 | },
1046 | wait: function() {
1047 | // wait for async operations to complete
1048 | var thread = Cc['@mozilla.org/thread-manager;1'].getService(Ci.nsIThreadManager).currentThread;
1049 | while (!done) thread.processNextEvent(true);
1050 |
1051 | return exitCode;
1052 | }
1053 | };
1054 | }
1055 |
1056 |
1057 | function subprocess_unix(options) {
1058 | // stdin pipe states
1059 | const OPEN = 2;
1060 | const CLOSEABLE = 1;
1061 | const CLOSED = 0;
1062 |
1063 | var libc = ctypes.open(options.libc),
1064 | active = true,
1065 | done = false,
1066 | exitCode = -1,
1067 | workerExitCode = 0,
1068 | child = {},
1069 | pid = -1,
1070 | stdinWorker = null,
1071 | stdoutWorker = null,
1072 | stderrWorker = null,
1073 | pendingWriteCount = 0,
1074 | readers = 2,
1075 | stdinOpenState = OPEN,
1076 | error = '',
1077 | output = '';
1078 |
1079 | //api declarations
1080 |
1081 | //pid_t fork(void);
1082 | var fork = libc.declare("fork",
1083 | ctypes.default_abi,
1084 | pid_t
1085 | );
1086 |
1087 | //NULL terminated array of strings, argv[0] will be command >> + 2
1088 | var argv = ctypes.char.ptr.array(options.arguments.length + 2);
1089 | var envp = ctypes.char.ptr.array(options.environment.length + 1);
1090 |
1091 | // posix_spawn_file_actions_t is a complex struct that may be different on
1092 | // each platform. We do not care about its attributes, we don't need to
1093 | // get access to them, but we do need to allocate the right amount
1094 | // of memory for it.
1095 | // At 2013/10/28, its size was 80 on linux, but better be safe (and larger),
1096 | // than crash when posix_spawn_file_actions_init fill `action` with zeros.
1097 | // Use `gcc sizeof_fileaction.c && ./a.out` to check that size.
1098 | var posix_spawn_file_actions_t = ctypes.uint8_t.array(100);
1099 |
1100 | //int posix_spawn(pid_t *restrict pid, const char *restrict path,
1101 | // const posix_spawn_file_actions_t *file_actions,
1102 | // const posix_spawnattr_t *restrict attrp,
1103 | // char *const argv[restrict], char *const envp[restrict]);
1104 | var posix_spawn = libc.declare("posix_spawn",
1105 | ctypes.default_abi,
1106 | ctypes.int,
1107 | pid_t.ptr,
1108 | ctypes.char.ptr,
1109 | posix_spawn_file_actions_t.ptr,
1110 | ctypes.voidptr_t,
1111 | argv,
1112 | envp
1113 | );
1114 |
1115 | //int posix_spawn_file_actions_init(posix_spawn_file_actions_t *file_actions);
1116 | var posix_spawn_file_actions_init = libc.declare("posix_spawn_file_actions_init",
1117 | ctypes.default_abi,
1118 | ctypes.int,
1119 | posix_spawn_file_actions_t.ptr
1120 | );
1121 |
1122 | //int posix_spawn_file_actions_destroy(posix_spawn_file_actions_t *file_actions);
1123 | var posix_spawn_file_actions_destroy = libc.declare("posix_spawn_file_actions_destroy",
1124 | ctypes.default_abi,
1125 | ctypes.int,
1126 | posix_spawn_file_actions_t.ptr
1127 | );
1128 |
1129 | // int posix_spawn_file_actions_adddup2(posix_spawn_file_actions_t *
1130 | // file_actions, int fildes, int newfildes);
1131 | var posix_spawn_file_actions_adddup2 = libc.declare("posix_spawn_file_actions_adddup2",
1132 | ctypes.default_abi,
1133 | ctypes.int,
1134 | posix_spawn_file_actions_t.ptr,
1135 | ctypes.int,
1136 | ctypes.int
1137 | );
1138 |
1139 | // int posix_spawn_file_actions_addclose(posix_spawn_file_actions_t *
1140 | // file_actions, int fildes);
1141 | var posix_spawn_file_actions_addclose = libc.declare("posix_spawn_file_actions_addclose",
1142 | ctypes.default_abi,
1143 | ctypes.int,
1144 | posix_spawn_file_actions_t.ptr,
1145 | ctypes.int
1146 | );
1147 |
1148 | //int pipe(int pipefd[2]);
1149 | var pipefd = ctypes.int.array(2);
1150 | var pipe = libc.declare("pipe",
1151 | ctypes.default_abi,
1152 | ctypes.int,
1153 | pipefd
1154 | );
1155 |
1156 | //int close(int fd);
1157 | var close = libc.declare("close",
1158 | ctypes.default_abi,
1159 | ctypes.int,
1160 | ctypes.int
1161 | );
1162 |
1163 | //pid_t waitpid(pid_t pid, int *status, int options);
1164 | var waitpid = libc.declare("waitpid",
1165 | ctypes.default_abi,
1166 | pid_t,
1167 | pid_t,
1168 | ctypes.int.ptr,
1169 | ctypes.int
1170 | );
1171 |
1172 | //int kill(pid_t pid, int sig);
1173 | var kill = libc.declare("kill",
1174 | ctypes.default_abi,
1175 | ctypes.int,
1176 | pid_t,
1177 | ctypes.int
1178 | );
1179 |
1180 | //int read(int fd, void *buf, size_t count);
1181 | var bufferSize = 1024;
1182 | var buffer = ctypes.char.array(bufferSize);
1183 | var read = libc.declare("read",
1184 | ctypes.default_abi,
1185 | ctypes.int,
1186 | ctypes.int,
1187 | buffer,
1188 | ctypes.int
1189 | );
1190 |
1191 | //ssize_t write(int fd, const void *buf, size_t count);
1192 | var write = libc.declare("write",
1193 | ctypes.default_abi,
1194 | ctypes.int,
1195 | ctypes.int,
1196 | ctypes.char.ptr,
1197 | ctypes.int
1198 | );
1199 |
1200 | //int chdir(const char *path);
1201 | var chdir = libc.declare("chdir",
1202 | ctypes.default_abi,
1203 | ctypes.int,
1204 | ctypes.char.ptr
1205 | );
1206 |
1207 | //int fcntl(int fd, int cmd, ... /* arg */ );
1208 | var fcntl = libc.declare("fcntl",
1209 | ctypes.default_abi,
1210 | ctypes.int,
1211 | ctypes.int,
1212 | ctypes.int,
1213 | ctypes.int
1214 | );
1215 |
1216 | function popen(command, workdir, args, environment, child) {
1217 | var _in,
1218 | _out,
1219 | _err,
1220 | pid,
1221 | rc,
1222 | i;
1223 | _in = new pipefd();
1224 | _out = new pipefd();
1225 | _err = new pipefd();
1226 |
1227 | var _args = argv();
1228 | args.unshift(command);
1229 | for(i=0;i= 0) {
1357 | posix_spawn_file_actions_addclose(action.address(), i);
1358 | }
1359 | }
1360 | }
1361 |
1362 | /*
1363 | * createStdinWriter ()
1364 | *
1365 | * Create a ChromeWorker object for writing data to the subprocess' stdin
1366 | * pipe. The ChromeWorker object lives on a separate thread; this avoids
1367 | * internal deadlocks.
1368 | */
1369 | function createStdinWriter() {
1370 | debugLog("Creating new stdin worker\n");
1371 | stdinWorker = new ChromeWorker("subprocess_worker_unix.js");
1372 | stdinWorker.onmessage = function(event) {
1373 | switch (event.data.msg) {
1374 | case "info":
1375 | switch(event.data.data) {
1376 | case "WriteOK":
1377 | pendingWriteCount--;
1378 | debugLog("got OK from stdinWorker - remaining count: "+pendingWriteCount+"\n");
1379 | break;
1380 | case "ClosedOK":
1381 | stdinOpenState = CLOSED;
1382 | debugLog("Stdin pipe closed\n");
1383 | break;
1384 | default:
1385 | debugLog("got msg from stdinWorker: "+event.data.data+"\n");
1386 | }
1387 | break;
1388 | case "debug":
1389 | debugLog("stdinWorker: "+event.data.data+"\n");
1390 | break;
1391 | case "error":
1392 | LogError("got error from stdinWorker: "+event.data.data+"\n");
1393 | pendingWriteCount = 0;
1394 | stdinOpenState = CLOSED;
1395 | exitCode = -2;
1396 | }
1397 | };
1398 | stdinWorker.onerror = function(error) {
1399 | pendingWriteCount = 0;
1400 | exitCode = -2;
1401 | closeStdinHandle();
1402 | LogError("got error from stdinWorker: "+error.message+"\n");
1403 | };
1404 | stdinWorker.postMessage({msg: "init", libc: options.libc});
1405 | }
1406 |
1407 | /*
1408 | * writeStdin()
1409 | * @data: String containing the data to write
1410 | *
1411 | * Write data to the subprocess' stdin (equals to sending a request to the
1412 | * ChromeWorker object to write the data).
1413 | */
1414 | function writeStdin(data) {
1415 | if (stdinOpenState == CLOSED) return; // do not write to closed pipes
1416 |
1417 | ++pendingWriteCount;
1418 | debugLog("sending "+data.length+" bytes to stdinWorker\n");
1419 | var pipe = parseInt(child.stdin);
1420 |
1421 | stdinWorker.postMessage({
1422 | msg: 'write',
1423 | pipe: pipe,
1424 | data: data
1425 | });
1426 | }
1427 |
1428 |
1429 | /*
1430 | * closeStdinHandle()
1431 | *
1432 | * Close the stdin pipe, either directly or by requesting the ChromeWorker to
1433 | * close the pipe. The ChromeWorker will only close the pipe after the last write
1434 | * request process is done.
1435 | */
1436 |
1437 | function closeStdinHandle() {
1438 | debugLog("trying to close stdin\n");
1439 | if (stdinOpenState != OPEN) return;
1440 | stdinOpenState = CLOSEABLE;
1441 |
1442 | if (stdinWorker) {
1443 | debugLog("sending close stdin to worker\n");
1444 | var pipePtr = parseInt(child.stdin);
1445 |
1446 | stdinWorker.postMessage({
1447 | msg: 'close',
1448 | pipe: pipePtr
1449 | });
1450 | }
1451 | else {
1452 | stdinOpenState = CLOSED;
1453 | debugLog("Closing Stdin\n");
1454 | close(child.stdin) && LogError("CloseHandle stdin failed");
1455 | }
1456 | }
1457 |
1458 |
1459 | /*
1460 | * createReader(pipe, name)
1461 | *
1462 | * @pipe: handle to the pipe
1463 | * @name: String containing the pipe name (stdout or stderr)
1464 | * @callbackFunc: function to be called with the read data
1465 | *
1466 | * Create a ChromeWorker object for reading data asynchronously from
1467 | * the pipe (i.e. on a separate thread), and passing the result back to
1468 | * the caller.
1469 | *
1470 | */
1471 | function createReader(pipe, name, callbackFunc) {
1472 | var worker = new ChromeWorker("subprocess_worker_unix.js");
1473 | worker.onmessage = function(event) {
1474 | switch(event.data.msg) {
1475 | case "data":
1476 | debugLog("got "+event.data.count+" bytes from "+name+"\n");
1477 | var data = '';
1478 | if (options.charset === null) {
1479 | data = event.data.data;
1480 | }
1481 | else
1482 | data = convertBytes(event.data.data, options.charset);
1483 |
1484 | callbackFunc(data);
1485 | break;
1486 | case "done":
1487 | debugLog("Pipe "+name+" closed\n");
1488 | if (event.data.data != 0) workerExitCode = event.data.data;
1489 | --readers;
1490 | if (readers == 0) cleanup();
1491 | break;
1492 | case "error":
1493 | LogError("Got error from "+name+": "+event.data.data);
1494 | exitCode = -2;
1495 | break;
1496 | default:
1497 | debugLog("Got msg from "+name+": "+event.data.data+"\n");
1498 | }
1499 | };
1500 | worker.onerror = function(error) {
1501 | LogError("Got error from "+name+": "+error.message);
1502 | exitCode = -2;
1503 | };
1504 |
1505 | worker.postMessage({
1506 | msg: 'read',
1507 | pipe: pipe,
1508 | pid: pid,
1509 | libc: options.libc,
1510 | charset: options.charset === null ? "null" : options.charset,
1511 | bufferedOutput: options.bufferedOutput,
1512 | name: name
1513 | });
1514 |
1515 | return worker;
1516 | }
1517 |
1518 | /*
1519 | * readPipes()
1520 | *
1521 | * Open the pipes for reading from stdout and stderr
1522 | */
1523 | function readPipes() {
1524 |
1525 | stdoutWorker = createReader(child.stdout, "stdout", function (data) {
1526 | if(options.stdout) {
1527 | setTimeout(function() {
1528 | options.stdout(data);
1529 | }, 0);
1530 | } else {
1531 | output += data;
1532 | }
1533 | });
1534 |
1535 | stderrWorker = createReader(child.stderr, "stderr", function (data) {
1536 | var output = options.mergeStderr ? 'stdout' : 'stderr';
1537 | if(options[output]) {
1538 | setTimeout(function() {
1539 | options[output](data);
1540 | }, 0);
1541 | } else {
1542 | error += data;
1543 | }
1544 | });
1545 |
1546 | }
1547 |
1548 | function cleanup() {
1549 | debugLog("Cleanup called\n");
1550 | if(active) {
1551 | active = false;
1552 |
1553 | closeStdinHandle(); // should only be required in case of errors
1554 |
1555 | var result, status = ctypes.int();
1556 | result = waitpid(child.pid, status.address(), 0);
1557 |
1558 | if (exitCode > -2) {
1559 | if (result > 0)
1560 | exitCode = status.value;
1561 | else
1562 | if (workerExitCode >= 0)
1563 | exitCode = workerExitCode;
1564 | else
1565 | exitCode = status.value;
1566 | }
1567 |
1568 | if (stdinWorker)
1569 | stdinWorker.postMessage({msg: 'stop'});
1570 |
1571 | setTimeout(function _done() {
1572 | if (options.done) {
1573 | try {
1574 | options.done({
1575 | exitCode: exitCode,
1576 | stdout: output,
1577 | stderr: error
1578 | });
1579 | }
1580 | catch(ex) {
1581 | // prevent from blocking if options.done() throws an error
1582 | done = true;
1583 | throw ex;
1584 | }
1585 |
1586 | }
1587 | done = true;
1588 | }, 0);
1589 |
1590 | libc.close();
1591 | }
1592 | }
1593 |
1594 | //main
1595 |
1596 | var cmdStr = getCommandStr(options.command);
1597 | var workDir = getWorkDir(options.workdir);
1598 |
1599 | child = {};
1600 | pid = popen(cmdStr, workDir, options.arguments, options.environment, child);
1601 |
1602 | debugLog("subprocess started; got PID "+pid+"\n");
1603 |
1604 | readPipes();
1605 |
1606 | if (options.stdin) {
1607 | createStdinWriter();
1608 | if(typeof(options.stdin) == 'function') {
1609 | try {
1610 | options.stdin({
1611 | write: function(data) {
1612 | writeStdin(data);
1613 | },
1614 | close: function() {
1615 | closeStdinHandle();
1616 | }
1617 | });
1618 | }
1619 | catch(ex) {
1620 | // prevent from failing if options.stdin() throws an exception
1621 | closeStdinHandle();
1622 | throw ex;
1623 | }
1624 | } else {
1625 | writeStdin(options.stdin);
1626 | closeStdinHandle();
1627 | }
1628 | }
1629 | else
1630 | closeStdinHandle();
1631 |
1632 |
1633 | return {
1634 | wait: function() {
1635 | // wait for async operations to complete
1636 | var thread = Cc['@mozilla.org/thread-manager;1'].getService(Ci.nsIThreadManager).currentThread;
1637 | while (! done) thread.processNextEvent(true);
1638 | return exitCode;
1639 | },
1640 | kill: function(hardKill) {
1641 | var rv = kill(pid, (hardKill ? 9: 15));
1642 | cleanup(-1);
1643 | return rv;
1644 | }
1645 | };
1646 | }
1647 |
--------------------------------------------------------------------------------
/content/subprocess_worker_unix.js:
--------------------------------------------------------------------------------
1 | /* ***** BEGIN LICENSE BLOCK *****
2 | * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3 | *
4 | * The contents of this file are subject to the Mozilla Public
5 | * License Version 1.1 (the "MPL"); you may not use this file
6 | * except in compliance with the MPL. You may obtain a copy of
7 | * the MPL at http://www.mozilla.org/MPL/
8 | *
9 | * Software distributed under the MPL is distributed on an "AS
10 | * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
11 | * implied. See the MPL for the specific language governing
12 | * rights and limitations under the MPL.
13 | *
14 | * The Original Code is subprocess.jsm.
15 | *
16 | * The Initial Developer of this code is Patrick Brunschwig.
17 | * Portions created by Patrick Brunschwig
18 | * are Copyright (C) 2011 Patrick Brunschwig.
19 | * All Rights Reserved.
20 | *
21 | * Contributor(s):
22 | * Jan Gerber
23 | *
24 | * Alternatively, the contents of this file may be used under the terms of
25 | * either the GNU General Public License Version 2 or later (the "GPL"), or
26 | * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27 | * in which case the provisions of the GPL or the LGPL are applicable instead
28 | * of those above. If you wish to allow use of your version of this file only
29 | * under the terms of either the GPL or the LGPL, and not to allow others to
30 | * use your version of this file under the terms of the MPL, indicate your
31 | * decision by deleting the provisions above and replace them with the notice
32 | * and other provisions required by the GPL or the LGPL. If you do not delete
33 | * the provisions above, a recipient may use your version of this file under
34 | * the terms of any one of the MPL, the GPL or the LGPL.
35 | * ***** END LICENSE BLOCK ***** */
36 |
37 | /*
38 | * ChromeWorker Object subprocess.jsm on Unix-like systems (Linux, Mac OS X, ...)
39 | * to process stdin/stdout/stderr on separate threads.
40 | *
41 | */
42 |
43 | // Being a ChromeWorker object, implicitly uses the following:
44 | // Components.utils.import("resource://gre/modules/ctypes.jsm");
45 |
46 | 'use strict';
47 |
48 | const BufferSize = 1024;
49 |
50 | var libc = null;
51 | var libcFunc = {};
52 |
53 |
54 | /*
55 | struct pollfd {
56 | int fd; // file descriptor
57 | short events; // events to look for
58 | short revents; // events returned
59 | };
60 | */
61 |
62 | var pollfd = new ctypes.StructType("pollfd",
63 | [ {'fd': ctypes.int},
64 | {'events': ctypes.short},
65 | {'revents': ctypes.short}
66 | ]);
67 |
68 | var WriteBuffer = ctypes.uint8_t.array(BufferSize);
69 | var ReadBuffer = ctypes.char.array(BufferSize);
70 |
71 |
72 | const POLLIN = 0x0001;
73 | const POLLOUT = 0x0004;
74 |
75 | const POLLERR = 0x0008; // some poll error occurred
76 | const POLLHUP = 0x0010; // file descriptor was "hung up"
77 | const POLLNVAL = 0x0020; // requested events "invalid"
78 |
79 | const WNOHANG = 0x01;
80 |
81 | const ECHILD = 10;
82 |
83 | const pid_t = ctypes.int32_t;
84 |
85 | const INDEFINITE = -1;
86 | const NOWAIT = 0;
87 | const WAITTIME = 200; // wait time for poll() in ms
88 |
89 | function initLibc(libName) {
90 | postMessage({msg: "debug", data: "initialising library with "+ libName});
91 |
92 | libc = ctypes.open(libName);
93 |
94 | libcFunc.pollFds = pollfd.array(1);
95 |
96 | // int poll(struct pollfd fds[], nfds_t nfds, int timeout);
97 | libcFunc.poll = libc.declare("poll",
98 | ctypes.default_abi,
99 | ctypes.int,
100 | libcFunc.pollFds,
101 | ctypes.unsigned_int,
102 | ctypes.int);
103 |
104 | //ssize_t write(int fd, const void *buf, size_t count);
105 | // NOTE: buf is declared as array of unsigned int8 instead of char to avoid
106 | // implicit charset conversion
107 | libcFunc.write = libc.declare("write",
108 | ctypes.default_abi,
109 | ctypes.int,
110 | ctypes.int,
111 | WriteBuffer,
112 | ctypes.int);
113 |
114 | //int read(int fd, void *buf, size_t count);
115 | libcFunc.read = libc.declare("read",
116 | ctypes.default_abi,
117 | ctypes.int,
118 | ctypes.int,
119 | ReadBuffer,
120 | ctypes.int);
121 |
122 | //int pipe(int pipefd[2]);
123 | libcFunc.pipefd = ctypes.int.array(2);
124 |
125 | //int close(int fd);
126 | libcFunc.close = libc.declare("close",
127 | ctypes.default_abi,
128 | ctypes.int,
129 | ctypes.int);
130 |
131 | //pid_t waitpid(pid_t pid, int *status, int options);
132 | libcFunc.waitpid = libc.declare("waitpid",
133 | ctypes.default_abi,
134 | pid_t,
135 | pid_t,
136 | ctypes.int.ptr,
137 | ctypes.int);
138 | }
139 |
140 | function closePipe(pipe) {
141 | libcFunc.close(pipe);
142 | }
143 |
144 | function writePipe(pipe, data) {
145 |
146 | postMessage({msg: "debug", data: "trying to write to "+pipe});
147 |
148 | let numChunks = Math.floor(data.length / BufferSize);
149 | let pData = new WriteBuffer();
150 |
151 | for (var chunk = 0; chunk <= numChunks; chunk ++) {
152 | let numBytes = chunk < numChunks ? BufferSize : data.length - chunk * BufferSize;
153 | for (var i=0; i < numBytes; i++) {
154 | pData[i] = data.charCodeAt(chunk * BufferSize + i) % 256;
155 | }
156 |
157 | let bytesWritten = libcFunc.write(pipe, pData, numBytes);
158 | if (bytesWritten != numBytes) {
159 | closePipe(pipe);
160 | libc.close();
161 | postMessage({ msg: "error", data: "error: wrote "+bytesWritten+" instead of "+numBytes+" bytes"});
162 | close();
163 | }
164 | }
165 | postMessage({msg: "info", data: "wrote "+data.length+" bytes of data"});
166 | }
167 |
168 |
169 | function readString(data, length, charset) {
170 | var r = '';
171 | for(var i = 0; i < length; i++) {
172 | if(data[i] == 0 && charset != "null") // stop on NULL character for non-binary data
173 | break;
174 |
175 | r += String.fromCharCode(data[i]);
176 | }
177 |
178 | return r;
179 | }
180 |
181 | function readPipe(pipe, charset, pid, bufferedOutput) {
182 | var p = new libcFunc.pollFds;
183 | p[0].fd = pipe;
184 | p[0].events = POLLIN | POLLERR | POLLHUP;
185 | p[0].revents = 0;
186 | var pollTimeout = WAITTIME;
187 | var exitCode = -1;
188 | var readCount = 0;
189 | var result, status = ctypes.int();
190 | result = 0;
191 |
192 | var dataStr = "";
193 | var dataObj = {};
194 |
195 | const i=0;
196 | while (true) {
197 | if (result == 0) {
198 | result = libcFunc.waitpid(pid, status.address(), WNOHANG);
199 | if (result > 0) {
200 | pollTimeout = NOWAIT;
201 | exitCode = parseInt(status.value);
202 | postMessage({msg: "debug", data: "waitpid signaled subprocess stop, exitcode="+status.value });
203 | }
204 | else if (result < 0) {
205 | postMessage({msg: "debug", data: "waitpid returned with errno="+ctypes.errno });
206 | if (ctypes.errno == ECHILD) {
207 | pollTimeout = NOWAIT;
208 | }
209 | }
210 | }
211 | p[i].revents = 0;
212 | var r = libcFunc.poll(p, 1, pollTimeout);
213 | if (pollTimeout == NOWAIT) {
214 | readCount = 0;
215 | }
216 | if (r > 0) {
217 | if (p[i].revents & POLLIN) {
218 | // postMessage({msg: "debug", data: "reading next chunk"});
219 |
220 | readCount = readPolledFd(p[i].fd, charset, dataObj);
221 | if (! bufferedOutput)
222 | postMessage({msg: "data", data: dataObj.value, count: dataObj.value.length});
223 | else
224 | dataStr += dataObj.value;
225 |
226 | if (readCount == 0) break;
227 | }
228 |
229 | if (p[i].revents & POLLHUP) {
230 | postMessage({msg: "debug", data: "poll returned HUP"});
231 | break;
232 | }
233 | else if (p[i].revents & POLLERR) {
234 | postMessage({msg: "error", data: "poll returned error"});
235 | break;
236 | }
237 | else if (p[i].revents != POLLIN) {
238 | postMessage({msg: "error", data: "poll returned "+p[i]});
239 | break;
240 | }
241 | }
242 | else
243 | if (pollTimeout == NOWAIT || r < 0) break;
244 | }
245 |
246 | // continue reading until the buffer is empty
247 | while (readCount > 0) {
248 | readCount = readPolledFd(pipe, charset, dataObj);
249 | if (! bufferedOutput)
250 | postMessage({msg: "data", data: dataObj.value, count: dataObj.value.length});
251 | else
252 | dataStr += dataObj.value;
253 |
254 | let r = libcFunc.poll(p, 1, NOWAIT);
255 | }
256 |
257 | if (bufferedOutput)
258 | postMessage({msg: "data", data: dataStr, count: dataStr.length});
259 |
260 | closePipe(pipe);
261 | postMessage({msg: "done", data: exitCode });
262 | libc.close();
263 | close();
264 | }
265 |
266 | function readPolledFd(pipe, charset, dataObj) {
267 | var line = new ReadBuffer();
268 | var r = libcFunc.read(pipe, line, BufferSize);
269 |
270 | if (r > 0) {
271 | var c = readString(line, r, charset);
272 | dataObj.value = c;
273 | }
274 | else
275 | dataObj.value = "";
276 |
277 | return r;
278 | }
279 |
280 | onmessage = function (event) {
281 | switch (event.data.msg) {
282 | case "init":
283 | initLibc(event.data.libc);
284 | break;
285 | case "read":
286 | initLibc(event.data.libc);
287 | readPipe(event.data.pipe, event.data.charset, event.data.pid, event.data.bufferedOutput);
288 | break;
289 | case "write":
290 | // data contents:
291 | // msg: 'write'
292 | // data: the data (string) to write
293 | // pipe: ptr to pipe
294 | writePipe(event.data.pipe, event.data.data);
295 | postMessage({msg: "info", data: "WriteOK"});
296 | break;
297 | case "close":
298 | postMessage({msg: "debug", data: "closing stdin\n"});
299 |
300 | closePipe(event.data.pipe);
301 | postMessage({msg: "info", data: "ClosedOK"});
302 | break;
303 | case "stop":
304 | libc.close(); // do not use libc after this point
305 | close();
306 | break;
307 | default:
308 | throw("error: Unknown command"+event.data.msg+"\n");
309 | }
310 | return;
311 | };
312 |
--------------------------------------------------------------------------------
/install.rdf:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 | pterosaur@ardagnir.github.com
8 | 1.1.2
9 | chrome://pterosaur/content/pterosaur.png
10 | 2
11 | true
12 |
13 |
14 |
15 | {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
16 | 30.0
17 | 38.*
18 |
19 |
20 |
21 | Pterosaur
22 | Make all firefox text vim.
23 | James Kolb
24 | http://github.com/ardagnir/pterosaur
25 |
26 |
27 |
--------------------------------------------------------------------------------