├── .github
└── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
├── .gitignore
├── LICENSE
├── README.md
├── aria2-ng
└── index.html
├── buffer.py
├── dependencies.json
├── eaf-browser.el
├── easylist.txt
├── package-lock.json
├── package.json
└── screenshot.png
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: EAF Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | - If EAF was working correctly until a recent `git pull`, please refer to [Mandatory Procedures to Keep Your EAF Up-to-Date](https://github.com/manateelazycat/emacs-application-framework/discussions/527?sort=new) first.
11 | - Please check the `*eaf*` buffer, if there is any error shown in the `*eaf*` buffer, paste it here.
12 |
13 | **Describe the bug**
14 | A clear and concise description of what the bug is.
15 |
16 | **To Reproduce**
17 | Ensure you're on the latest master branch, then note the steps to reproduce the behavior.
18 |
19 | **Expected behavior**
20 | A clear and concise description of what you expected to happen.
21 |
22 | **Versions (please complete the following info):**
23 | - Distro and DE/WM:
24 | - Versions of Dependencies:
25 | - M-x emacs-version:
26 |
27 | **Screenshots**
28 | If applicable, add screenshots to help explain your problem.
29 |
30 | **Additional context**
31 | Add any other context about the problem here.
32 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: EAF Feature request
3 | about: Suggest an idea for the Emacs Application Framework
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of an alternative solutions or features you've considered, if any.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.elc
2 | *.pyc
3 | /.log/
4 | __pycache__
5 | node_modules/
6 | dist/
7 | tags
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### EAF Browser
2 |
3 |
4 |
5 |
6 | Browser application for the [Emacs Application Framework](https://github.com/emacs-eaf/emacs-application-framework).
7 |
8 | ### Load application
9 |
10 | [Install EAF](https://github.com/emacs-eaf/emacs-application-framework#install) first, then add below code in your emacs config:
11 |
12 | ```Elisp
13 | (add-to-list 'load-path "~/.emacs.d/site-lisp/emacs-application-framework/")
14 | (require 'eaf)
15 | (require 'eaf-browser)
16 | ```
17 |
18 | ### Dependency List
19 |
20 | | Package | Description |
21 | |:-----------------------------------------------------------|:----------------------------|
22 | | aria2 | Download files from the web |
23 | | [pycookiecheat](https://github.com/n8henrie/pycookiecheat) | Import cookies from Chrome |
24 |
25 | ### Import cookies from Chrome
26 |
27 | When you are used to using Chrome, you can set `eaf-browser-auto-import-chrome-cookies` to `t`, and the EAF browser will automatically import cookies from Chrome. You don't need to login separately in Chrome and EAF browser.
28 |
29 | #### Support chrome based browser
30 |
31 | Support import chrome based browser cooike by set `eaf-browser-chrome-browser-name` to:
32 |
33 | 1. Chrome (default)
34 | 2. Chromium
35 | 3. Brave
36 |
37 | [Do not Support Windows](https://github.com/n8henrie/pycookiecheat#how-about-windows)
38 |
39 | ### The keybinding of EAF Browser.
40 |
41 | Please press `Alt + z` to execute command `switch_to_input_mode` if some site can't input text.
42 |
43 | | Key | Event |
44 | | :---- | :------ |
45 | | `C--` | zoom_out |
46 | | `C-=` | zoom_in |
47 | | `C-0` | zoom_reset |
48 | | `C-s` | search_text_forward |
49 | | `C-r` | search_text_backward |
50 | | `C-n` | scroll_up |
51 | | `C-p` | scroll_down |
52 | | `C-f` | scroll_right |
53 | | `C-b` | scroll_left |
54 | | `C-v` | scroll_up_page |
55 | | `C-y` | yank_text |
56 | | `C-w` | kill_text |
57 | | `M-z` | switch_to_input_mode |
58 | | `M-e` | atomic_edit |
59 | | `M-c` | caret_toggle_browsing |
60 | | `M-D` | select_text |
61 | | `M-s` | open_link |
62 | | `M-S` | open_link_new_buffer |
63 | | `M-B` | open_link_background_buffer |
64 | | `C-/` | undo_action |
65 | | `M-_` | redo_action |
66 | | `M-w` | copy_text |
67 | | `M-f` | history_forward |
68 | | `M-b` | history_backward |
69 | | `M-q` | delete_cookie |
70 | | `M-Q` | delete_all_cookies |
71 | | `C-t` | toggle_password_autofill |
72 | | `C-d` | save_page_password |
73 | | `C-M-q` | clear_history |
74 | | `C-M-i` | import_chrome_history |
75 | | `C-M-s` | import_safari_history |
76 | | `M-v` | scroll_down_page |
77 | | `M-<` | watch-other-window-up-line |
78 | | `M->` | watch-other-window-down-line |
79 | | `M-p` | scroll_down_page |
80 | | `M-t` | new_blank_page |
81 | | `M-d` | toggle_dark_mode |
82 | | `M-l` | toggle_dark_mode_light_theme |
83 | | `SPC` | insert_or_scroll_up_page |
84 | | `J` | insert_or_select_left_tab |
85 | | `K` | insert_or_select_right_tab |
86 | | `j` | insert_or_scroll_up |
87 | | `k` | insert_or_scroll_down |
88 | | `h` | insert_or_scroll_left |
89 | | `l` | insert_or_scroll_right |
90 | | `f` | insert_or_open_link |
91 | | `F` | insert_or_open_link_background_buffer |
92 | | `O` | insert_or_open_link_new_buffer_other_window |
93 | | `B` | insert_or_open_link_background_buffer |
94 | | `c` | insert_or_caret_at_line |
95 | | `u` | insert_or_scroll_down_page |
96 | | `d` | insert_or_scroll_up_page |
97 | | `H` | insert_or_history_backward |
98 | | `L` | insert_or_history_forward |
99 | | `t` | insert_or_new_blank_page |
100 | | `T` | insert_or_recover_prev_close_page |
101 | | `i` | insert_or_focus_input |
102 | | `I` | insert_or_open_downloads_setting |
103 | | `r` | insert_or_refresh_page |
104 | | `g` | insert_or_scroll_to_begin |
105 | | `x` | insert_or_close_buffer |
106 | | `G` | insert_or_scroll_to_bottom |
107 | | `-` | insert_or_zoom_out |
108 | | `=` | insert_or_zoom_in |
109 | | `0` | insert_or_zoom_reset |
110 | | `m` | insert_or_save_as_bookmark |
111 | | `o` | insert_or_open_browser |
112 | | `y` | insert_or_download_youtube_video |
113 | | `Y` | insert_or_download_youtube_audio |
114 | | `p` | insert_or_toggle_device |
115 | | `P` | insert_or_duplicate_page |
116 | | `1` | insert_or_save_as_pdf |
117 | | `2` | insert_or_save_as_single_file |
118 | | `3` | insert_or_save_as_screenshot |
119 | | `v` | insert_or_view_source |
120 | | `e` | insert_or_edit_url |
121 | | `n` | insert_or_export_text |
122 | | `N` | insert_or_render_by_eww |
123 | | `,` | insert_or_switch_to_reader_mode |
124 | | `.` | insert_or_translate_text |
125 | | `;` | insert_or_translate_page |
126 | | `M-i` | immersive_translation |
127 | | `C-M-c` | copy_code |
128 | | `C-M-l` | copy_link |
129 | | `C-a` | select_all_or_input_text |
130 | | `M-u` | clear_focus |
131 | | `C-j` | open_downloads_setting |
132 | | `M-o` | eval_js |
133 | | `M-O` | eval_js_file |
134 | | `` | eaf-browser-send-esc-or-exit-fullscreen |
135 | | `M-,` | eaf-send-down-key |
136 | | `M-.` | eaf-send-up-key |
137 | | `M-m` | eaf-send-return-key |
138 | | `` | emacs-session-save |
139 | | `` | open_devtools |
140 | | `` | eaf-send-ctrl-return-sequence |
141 | | `C-` | eaf-send-ctrl-left-sequence |
142 | | `C-` | eaf-send-ctrl-right-sequence |
143 | | `C-` | eaf-send-ctrl-delete-sequence |
144 | | `C-` | eaf-send-ctrl-backspace-sequence |
145 |
--------------------------------------------------------------------------------
/buffer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright (C) 2018 Andy Stewart
5 | #
6 | # Author: Andy Stewart
7 | # Maintainer: Andy Stewart
8 | #
9 | # This program is free software: you can redistribute it and/or modify
10 | # it under the terms of the GNU General Public License as published by
11 | # the Free Software Foundation, either version 3 of the License, or
12 | # any later version.
13 | #
14 | # This program is distributed in the hope that it will be useful,
15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | # GNU General Public License for more details.
18 | #
19 | # You should have received a copy of the GNU General Public License
20 | # along with this program. If not, see .
21 |
22 | import os
23 | import re
24 | import threading
25 | import time
26 | import urllib
27 |
28 | from core.utils import *
29 | from core.webengine import BrowserBuffer
30 | from PyQt6.QtCore import QUrl, pyqtSlot
31 | from PyQt6.QtGui import QColor
32 | from PyQt6.QtWebEngineCore import QWebEngineUrlRequestInterceptor
33 | found_braveblock = True
34 | try:
35 | import braveblock
36 | except:
37 | found_braveblock = False
38 |
39 | class AppBuffer(BrowserBuffer):
40 | def __init__(self, buffer_id, url, arguments):
41 | BrowserBuffer.__init__(self, buffer_id, url, arguments, False)
42 |
43 | self.config_dir = get_emacs_config_dir()
44 |
45 | # When arguments is "temp_html_file", browser will load content of html file, then delete temp file.
46 | # Usually use for render html mail.
47 | if arguments == "temp_html_file":
48 | with open(url, "r") as html_file:
49 | self.buffer_widget.setHtml(html_file.read())
50 | if os.path.exists(url):
51 | os.remove(url)
52 | else:
53 | if arguments in ["pc", "phone"]:
54 | self.set_agent(arguments)
55 |
56 | self.buffer_widget.setUrl(QUrl(url))
57 |
58 | # Init emacs vars.
59 | (self.dark_mode_var,
60 | self.remember_history, self.blank_page_url,
61 | self.enable_adblocker, self.enable_autofill,
62 | self.enable_tampermonkey, self.tampermonkey_script_location,
63 | self.aria2_auto_file_renaming, self.aria2_proxy_host, self.aria2_proxy_port,
64 | self.chrome_history_file,
65 | self.safari_history_file,
66 | self.translate_language,
67 | self.text_selection_color,
68 | self.dark_mode_theme,
69 | self.auto_import_chrome_cookies,
70 | self.chrome_browser_name,
71 | ) = get_emacs_vars([
72 | "eaf-browser-dark-mode",
73 | "eaf-browser-remember-history",
74 | "eaf-browser-blank-page-url",
75 | "eaf-browser-enable-adblocker",
76 | "eaf-browser-enable-autofill",
77 | "eaf-browser-enable-tampermonkey",
78 | "eaf-browser-tampermonkey-location",
79 | "eaf-browser-aria2-auto-file-renaming",
80 | "eaf-browser-aria2-proxy-host",
81 | "eaf-browser-aria2-proxy-port",
82 | "eaf-browser-chrome-history-file",
83 | "eaf-browser-safari-history-file",
84 | "eaf-browser-translate-language",
85 | "eaf-browser-text-selection-color",
86 | "eaf-browser-dark-mode-theme",
87 | "eaf-browser-auto-import-chrome-cookies",
88 | "eaf-browser-chrome-browser-name"
89 | ])
90 |
91 | self.load_tampermonkey(url)
92 |
93 | # Use thread to avoid slow down open speed.
94 | threading.Thread(target=self.load_history).start()
95 |
96 | self.autofill = PasswordDb(os.path.join(os.path.dirname(self.config_dir), "browser", "password.db"))
97 | self.pw_autofill_id = 0
98 | self.pw_autofill_raw = None
99 |
100 | self.readability_js = None
101 |
102 | self.buffer_widget.init_dark_mode_js(__file__,
103 | self.text_selection_color,
104 | self.dark_mode_theme,
105 | {
106 | "brightness": 100,
107 | "constrast": 90,
108 | "sepia": 10,
109 | "mode": 0,
110 | "darkSchemeBackgroundColor": get_emacs_theme_background(),
111 | "darkSchemeForegroundColor": get_emacs_theme_foreground()})
112 |
113 | self.close_page.connect(self.record_close_page)
114 |
115 | self.buffer_widget.open_url = self.open_url_or_search_string
116 |
117 | self.buffer_widget.titleChanged.connect(self.change_title)
118 |
119 | self.buffer_widget.translate_selected_text.connect(translate_text)
120 |
121 | self.buffer_widget.urlChanged.connect(self.caret_exit)
122 |
123 | # Record url when url changed.
124 | self.buffer_widget.urlChanged.connect(self.update_url)
125 |
126 | # Draw progressbar.
127 | self.caret_browsing_js_raw = None
128 | self.progressbar_progress = 0
129 | self.progressbar_height = int(get_emacs_var("eaf-browser-progress-bar-height"))
130 | self.progressbar_color = QColor(get_emacs_var("eaf-browser-progress-bar-color"))
131 | self.buffer_widget.loadStarted.connect(self.start_progress)
132 | self.buffer_widget.loadProgress.connect(self.update_progress)
133 | self.is_loading = False
134 |
135 | # Update page position
136 | self.buffer_widget.web_page.scrollPositionChanged.connect(self.update_position)
137 |
138 | # Reset to default zoom when page init or page url changed.
139 | self.reset_default_zoom()
140 | self.buffer_widget.urlChanged.connect(lambda url: self.reset_default_zoom())
141 |
142 | # Reset zoom after page loading finish.
143 | # Otherwise page won't zoom if we call setUrl api in current page.
144 | self.buffer_widget.loadFinished.connect(lambda : self.buffer_widget.zoom_reset())
145 |
146 | self.buffer_widget.create_new_window = self.create_new_window
147 |
148 | self.start_loading_time = 0
149 |
150 | if found_braveblock and self.enable_adblocker:
151 | self.interceptor = AdBlockInterceptor(self.profile, self)
152 |
153 | if self.auto_import_chrome_cookies:
154 | # import cookies from Chrome automatically
155 | self.import_chrome_cookies(url)
156 |
157 | def import_chrome_cookies(self, url):
158 | from urllib.parse import urlparse
159 | from pycookiecheat import chrome_cookies # package that fetches cookies
160 | from PyQt6.QtNetwork import QNetworkCookie
161 | cookieStore = self.buffer_widget.page().profile().cookieStore()
162 | cookies = chrome_cookies(url, browser=self.chrome_browser_name)
163 | for name, value in cookies.items():
164 | qcookie = QNetworkCookie()
165 | qcookie.setName(name.encode())
166 | qcookie.setValue(value.encode())
167 | qcookie.setDomain(urlparse(url).netloc)
168 | cookieStore.setCookie(qcookie, QUrl())
169 |
170 | def load_tampermonkey(self,url):
171 | if self.enable_tampermonkey:
172 | try:
173 | for filepath in os.listdir(self.tampermonkey_script_location):
174 | script = TampermonkeyScript(os.path.join(self.tampermonkey_script_location,filepath))
175 | if script.can_run(url):
176 | self.buffer_widget.eval_js(script.content())
177 | except FileNotFoundError:
178 | message_to_emacs(f"{self.tampermonkey_script_location} is not found!")
179 |
180 |
181 | @interactive
182 | def update_theme(self, reload_config=True):
183 | if reload_config:
184 | (self.text_selection_color,
185 | self.dark_mode_theme
186 | ) = get_emacs_vars([
187 | "eaf-browser-text-selection-color",
188 | "eaf-browser-dark-mode-theme"])
189 |
190 | self.buffer_widget.init_dark_mode_js(__file__,
191 | self.text_selection_color,
192 | self.dark_mode_theme,
193 | {
194 | "brightness": 100,
195 | "constrast": 90,
196 | "sepia": 10,
197 | "mode": 0,
198 | "darkSchemeBackgroundColor": get_emacs_theme_background(),
199 | "darkSchemeForegroundColor": get_emacs_theme_foreground()})
200 |
201 | self.refresh_page()
202 |
203 | def load_history(self):
204 | self.history_list = []
205 | if self.remember_history:
206 | self.history_log_file_path = os.path.join(self.config_dir, "browser", "history", "log.txt")
207 |
208 | self.history_pattern = re.compile(r"^(.+)ᛝ(.+)ᛡ(.+)$")
209 | self.noprefix_url_pattern = re.compile(r"^(https?|file)://(.+)")
210 | self.nopostfix_url_pattern = re.compile(r"^[^#\?]*")
211 | self.history_close_file_path = os.path.join(self.config_dir, "browser", "history", "close.txt")
212 | touch(self.history_log_file_path)
213 | with open(self.history_log_file_path, "r", encoding="utf-8") as f:
214 | raw_list = f.readlines()
215 | for raw_his in raw_list:
216 | his_line = re.match(self.history_pattern, raw_his)
217 | if his_line is None: # Obsolete Old history format
218 | old_his = re.match("(.*)\s((https?|file):[^\s]+)$", raw_his)
219 | if old_his is not None:
220 | self.history_list.append(HistoryPage(old_his.group(1), old_his.group(2), 1))
221 | else:
222 | self.history_list.append(HistoryPage(his_line.group(1), his_line.group(2), his_line.group(3)))
223 |
224 | self.buffer_widget.titleChanged.connect(self.record_history)
225 |
226 | def drawForeground(self, painter, rect):
227 | # Draw progress bar.
228 | if self.progressbar_progress > 0 and self.progressbar_progress < 100:
229 | painter.setBrush(self.progressbar_color)
230 | painter.drawRect(0, 0,
231 | int(rect.width() * self.progressbar_progress * 1.0 / 100),
232 | int(self.progressbar_height))
233 |
234 | @pyqtSlot()
235 | def start_progress(self):
236 | ''' Initialize the Progress Bar.'''
237 | self.is_loading = True
238 |
239 | self.start_loading_time = time.time()
240 |
241 | self.progressbar_progress = 0
242 | self.update()
243 |
244 | @pyqtSlot(int)
245 | def update_progress(self, progress):
246 | ''' Update the Progress Bar.'''
247 | self.dark_mode_js_load(progress)
248 |
249 | self.progressbar_progress = progress
250 |
251 | if progress < 100:
252 | # Update progress.
253 | self.caret_js_ready = False
254 | self.update()
255 | elif progress == 100:
256 | print("[EAF] Browser {} loading time: {}s".format(self.url, time.time() - self.start_loading_time))
257 |
258 | if self.is_loading:
259 | self.is_loading = False
260 |
261 | self.buffer_widget.load_marker_file()
262 |
263 | cursor_foreground_color = ""
264 | cursor_background_color = ""
265 |
266 | if self.caret_browsing_js_raw is None:
267 | self.caret_browsing_js_raw = self.buffer_widget.read_js_content("caret_browsing.js")
268 |
269 | self.caret_browsing_js = self.caret_browsing_js_raw.replace("%1", cursor_foreground_color).replace("%2", cursor_background_color)
270 | self.buffer_widget.eval_js(self.caret_browsing_js)
271 | self.caret_js_ready = True
272 |
273 | if self.dark_mode_is_enabled():
274 | if self.dark_mode_var == "follow":
275 | cursor_foreground_color = self.theme_foreground_color
276 | cursor_background_color = self.theme_background_color
277 | else:
278 | cursor_foreground_color = "#FFF"
279 | cursor_background_color = "#000"
280 | else:
281 | if self.dark_mode_var == "follow":
282 | cursor_foreground_color = self.theme_foreground_color
283 | cursor_background_color = self.theme_background_color
284 | else:
285 | cursor_foreground_color = "#000"
286 | cursor_background_color = "#FFF"
287 |
288 | self.after_page_load_hook() # Run after page load hook
289 |
290 | def after_page_load_hook(self):
291 | ''' Hook to run after update_progress hits 100. '''
292 | self.init_pw_autofill()
293 |
294 | # Update input focus state.
295 | self.is_focus()
296 |
297 | def update_position(self):
298 | mode_line_height = get_emacs_func_cache_result("eaf-get-mode-line-height", [])
299 | if mode_line_height > 0.1:
300 | position = self.buffer_widget.web_page.scrollPosition().y()
301 | view_height = self.buffer_widget.height()
302 | page_height = self.buffer_widget.web_page.contentsSize().height()
303 |
304 | if page_height != 0:
305 | pos_percentage = '%.1f%%' % ((position + view_height) / page_height * 100)
306 | else:
307 | pos_percentage = '0.0%'
308 |
309 | eval_in_emacs("eaf--browser-update-position", [pos_percentage])
310 |
311 | @PostGui()
312 | def handle_input_response(self, callback_tag, result_content):
313 | ''' Handle input message.'''
314 | if not BrowserBuffer.handle_input_response(self, callback_tag, result_content):
315 | if callback_tag == "clear_history":
316 | self._clear_history()
317 | elif callback_tag == "import_chrome_history" or callback_tag == "import_safari_history":
318 | self._import_history(browser_name=callback_tag.split("_")[1])
319 | elif callback_tag == "delete_all_cookies":
320 | self._delete_all_cookies()
321 | elif callback_tag == "delete_cookie":
322 | self._delete_cookie()
323 |
324 | def try_start_aria2_daemon(self):
325 | ''' Try to start aria2 daemon.'''
326 | if not is_port_in_use(6800):
327 | with open(os.devnull, "w") as null_file:
328 | aria2_args = ["aria2c"]
329 |
330 | aria2_args.append("-d") # daemon
331 | aria2_args.append("-c") # continue download
332 | aria2_args.append("--auto-file-renaming={}".format(str(self.aria2_auto_file_renaming).lower()))
333 | aria2_args.append("-d {}".format(os.path.expanduser(self.download_path)))
334 |
335 | if self.aria2_proxy_host != "" and self.aria2_proxy_port != "":
336 | aria2_args.append("--all-proxy")
337 | aria2_args.append("http://{0}:{1}".format(self.aria2_proxy_host, self.aria2_proxy_port))
338 |
339 | aria2_args.append("--enable-rpc")
340 | aria2_args.append("--rpc-listen-all")
341 |
342 | import subprocess
343 | subprocess.Popen(aria2_args, stdout=null_file)
344 |
345 | @interactive(insert_or_do=True)
346 | def open_downloads_setting(self):
347 | ''' Open aria2 download manage page. '''
348 | self.try_start_aria2_daemon()
349 | index_file = os.path.join(os.path.dirname(__file__), "aria2-ng", "index.html")
350 | self.buffer_widget.open_url_new_buffer(QUrl.fromLocalFile(index_file).toString())
351 |
352 | def record_close_page(self, url):
353 | ''' Record closing pages.'''
354 | self.page_closed = True
355 | if self.remember_history and self.arguments != "temp_html_file" and url != "about:blank":
356 | touch(self.history_close_file_path)
357 | with open(self.history_close_file_path, "r") as f:
358 | close_urls = f.readlines()
359 | close_urls.append("{0}\n".format(url))
360 | open(self.history_close_file_path, "w").writelines(close_urls)
361 |
362 | @interactive(insert_or_do=True)
363 | def recover_prev_close_page(self):
364 | ''' Recover previous closed pages.'''
365 | if os.path.exists(self.history_close_file_path):
366 | with open(self.history_close_file_path, "r") as f:
367 | close_urls = f.readlines()
368 | if len(close_urls) > 0:
369 | # We need use rstrip remove \n char from url record.
370 | prev_close_url = close_urls.pop().rstrip()
371 | open_url_in_new_tab(prev_close_url)
372 | open(self.history_close_file_path, "w").writelines(close_urls)
373 |
374 | message_to_emacs("Recovery {0}".format(prev_close_url))
375 | else:
376 | message_to_emacs("No page need recovery.")
377 | else:
378 | message_to_emacs("No page need recovery.")
379 |
380 | @interactive
381 | def toggle_dark_mode_light_theme(self):
382 | if self.dark_mode_theme == "dark":
383 | self.dark_mode_theme = "light"
384 | else:
385 | self.dark_mode_theme = "dark"
386 |
387 | self.update_theme(False)
388 |
389 | message_to_emacs("Toggle dark mode light theme")
390 |
391 | def update_url(self, url):
392 | self.url = self.buffer_widget.url().toString()
393 |
394 | def add_password_entry(self):
395 | if self.pw_autofill_raw is None:
396 | self.pw_autofill_raw = self.buffer_widget.read_js_content("pw_autofill.js")
397 |
398 | self.buffer_widget.eval_js(self.pw_autofill_raw.replace("%1", "''"))
399 | password, form_data = self.buffer_widget.execute_js("retrievePasswordFromPage();")
400 | if password != "":
401 | from urllib.parse import urlparse
402 | self.autofill.add_entry(urlparse(self.current_url).hostname, password, form_data)
403 | message_to_emacs("Successfully recorded this page's password!")
404 | return True
405 | else:
406 | message_to_emacs("There is no password present in this page!")
407 | return False
408 |
409 | def pw_autofill_gen_id(self, id):
410 | if self.pw_autofill_raw is None:
411 | self.pw_autofill_raw = self.buffer_widget.read_js_content("pw_autofill.js")
412 |
413 | from urllib.parse import urlparse
414 | result = self.autofill.get_entries(urlparse(self.url).hostname, id)
415 | new_id = 0
416 | for row in result:
417 | new_id = row[0]
418 | password = row[2]
419 | form_data = row[3]
420 | self.buffer_widget.eval_js(self.pw_autofill_raw.replace("%1", form_data))
421 | self.buffer_widget.eval_js('autofillPassword("%s");' % password)
422 | break
423 | return new_id
424 |
425 | def init_pw_autofill(self):
426 | if self.enable_autofill:
427 | self.pw_autofill_id = self.pw_autofill_gen_id(0)
428 |
429 | @interactive
430 | def save_page_password(self):
431 | ''' Record form data.'''
432 | if self.enable_autofill:
433 | self.add_password_entry()
434 | else:
435 | message_to_emacs("Password autofill is not enabled! Enable with `C-t` (default binding)")
436 |
437 | @interactive
438 | def toggle_password_autofill(self):
439 | ''' Toggle Autofill status for password data'''
440 | if not self.enable_autofill:
441 | set_emacs_var("eaf-browser-enable-autofill", True)
442 | self.pw_autofill_id = self.pw_autofill_gen_id(0)
443 | message_to_emacs("Successfully enabled autofill!")
444 | self.enable_autofill = True
445 | else:
446 | self.pw_autofill_id = self.pw_autofill_gen_id(self.pw_autofill_id)
447 | if self.pw_autofill_id == 0:
448 | set_emacs_var("eaf-browser-enable-autofill", False)
449 | message_to_emacs("Successfully disabled password autofill!")
450 | self.enable_autofill = False
451 | else:
452 | message_to_emacs("Successfully changed password autofill id!")
453 |
454 | def is_good_history(self, history, new_url, ignore_history_list):
455 | for ignore_history in ignore_history_list:
456 | match = re.search(ignore_history, history.url, re.IGNORECASE)
457 | if match:
458 | return False
459 | return history.url == new_url or history.hit > 1
460 |
461 | def _record_history(self, new_title, new_url):
462 | # Throw traceback info if algorithm has bug and protection of historical record is not erased.
463 | try:
464 | noprefix_new_url_match = re.match(self.noprefix_url_pattern, new_url)
465 | ignore_history_list = get_emacs_var("eaf-browser-ignore-history-list")
466 | if noprefix_new_url_match is not None:
467 | found_url = False
468 | found_parent = False
469 | for history in self.history_list:
470 | noprefix_url_match = re.match(self.noprefix_url_pattern, history.url)
471 | if noprefix_url_match is not None:
472 | noprefix_url = noprefix_url_match.group(2)
473 | noprefix_new_url = noprefix_new_url_match.group(2)
474 | nopostfix_new_url_match = re.match(self.nopostfix_url_pattern, noprefix_new_url)
475 |
476 | if nopostfix_new_url_match is not None and noprefix_url == nopostfix_new_url_match.group():
477 | # increment parent url
478 | history.hit += 0.25
479 | found_parent = True
480 | if found_url:
481 | break
482 | if noprefix_url == noprefix_new_url: # found_url unique url
483 | history.title = new_title
484 | history.url = new_url
485 | history.hit += 0.5
486 | found_url = True
487 | if found_parent:
488 | break
489 |
490 | if not found_url:
491 | self.history_list.append(HistoryPage(new_title, new_url, 1))
492 |
493 | self.history_list.sort(key = lambda x: x.hit, reverse = True)
494 |
495 | self.history_list = [history for history in self.history_list if self.is_good_history(history, new_url, ignore_history_list)]
496 |
497 | with open(self.history_log_file_path, "w", encoding="utf-8") as f:
498 | f.writelines(map(lambda history: history.title + "ᛝ" + history.url + "ᛡ" + str(history.hit) + "\n", self.history_list))
499 | except Exception:
500 | import traceback
501 | message_to_emacs("Error in record_history: " + str(traceback.print_exc()))
502 |
503 | def record_history(self, new_title):
504 | ''' Record browser history.'''
505 | new_url = self.buffer_widget.filter_url(self.buffer_widget.get_url())
506 | if self.remember_history and self.buffer_widget.filter_title(new_title) != "" and \
507 | self.arguments != "temp_html_file" and new_title != "about:blank" and new_url != "about:blank":
508 | self._record_history(new_title, new_url)
509 |
510 | @interactive(insert_or_do=True)
511 | def new_blank_page(self):
512 | ''' Open new blank page.'''
513 | eval_in_emacs('eaf-open', [self.blank_page_url, "browser", "", 't'])
514 |
515 | @interactive(insert_or_do=True)
516 | def open_url_or_search_string(self, url):
517 | ''' Edit a URL or search a string.'''
518 | is_valid_url = get_emacs_func_result('eaf-is-valid-web-url', [url])
519 | if is_valid_url:
520 | wrap_url = get_emacs_func_result('eaf-wrap-url', [url])
521 | self.buffer_widget.setUrl(QUrl(wrap_url))
522 | self.load_tampermonkey(wrap_url)
523 | else:
524 | search_url = get_emacs_func_result('eaf--create-search-url', [url])
525 | self.buffer_widget.setUrl(QUrl(search_url))
526 | self.load_tampermonkey(search_url)
527 |
528 | def _clear_history(self):
529 | if os.path.exists(self.history_log_file_path):
530 | os.remove(self.history_log_file_path)
531 | message_to_emacs("Cleared browsing history.")
532 | else:
533 | message_to_emacs("There is no browsing history.")
534 |
535 | @interactive
536 | def clear_history(self):
537 | ''' Clear browsing history.'''
538 | self.send_input_message("Are you sure you want to clear all browsing history?", "clear_history", "yes-or-no")
539 |
540 | def _import_history(self, browser_name=None):
541 | import sqlite3
542 |
543 | if browser_name not in ["chrome", "safari"]:
544 | message_to_emacs("Failed to get browser_name")
545 | return
546 |
547 | if browser_name == "safari":
548 | dbpath = os.path.expanduser(self.safari_history_file)
549 | else:
550 | dbpath = os.path.expanduser(self.chrome_history_file)
551 |
552 | if not os.path.exists(dbpath):
553 | message_to_emacs("The chrome history file: '{}' not exist, please check your setting.".format(dbpath))
554 | return
555 |
556 | message_to_emacs("Importing from {}...".format(dbpath))
557 |
558 | conn = sqlite3.connect(dbpath)
559 | # Keep lastest entry in dict by last_visit_time asc order.
560 | if browser_name == "safari":
561 | cursor = conn.cursor()
562 | history_items = cursor.execute('SELECT id, url FROM history_items').fetchall()
563 | history_visits = cursor.execute('SELECT history_item, visit_time, title FROM history_visits order by visit_time asc').fetchall()
564 |
565 | max_visit_time = 0
566 | max_visit_save_file = os.path.join(os.path.dirname(self.config_dir), "browser", "safari_history_last_update_time.txt")
567 | if os.path.exists(max_visit_save_file):
568 | with open(max_visit_save_file, "r", encoding="utf-8") as f:
569 | try:
570 | max_visit_time = float(f.read())
571 | except ValueError as e:
572 | message_to_emacs("Failed to read safari_history_last_update_time.txt, error: " + str(e))
573 | max_visit_time = 0
574 |
575 | _histories = {}
576 | histories = {}
577 | for id, url in history_items:
578 | _histories[id] = [url, '']
579 |
580 | for history_item, visit_time, title in history_visits:
581 | if visit_time < max_visit_time:
582 | continue
583 |
584 | if history_item not in _histories:
585 | message_to_emacs("Parse safari history file error.")
586 | return
587 |
588 | _histories[history_item][-1] = (title)
589 |
590 | max_visit_time = history_visits[-1][1]
591 | with open(max_visit_save_file, "w") as f:
592 | f.write(str(max_visit_time))
593 |
594 | for id, url in history_items:
595 | url, title = _histories[id]
596 | if title is not None and len(title) > 0:
597 | histories[title] = url
598 | else:
599 | sql = 'select title, url from urls order by last_visit_time asc'
600 | # May fetch many by many not fetch all,
601 | # but this should called only once, so not important now.
602 | try:
603 | histories = conn.execute(sql).fetchall()
604 | except sqlite3.OperationalError as e:
605 | if e.args[0] == 'database is locked':
606 | message_to_emacs("The chrome history file is locked, please close your chrome app first.")
607 | else:
608 | message_to_emacs("Failed to read chrome history entries: {}.".format(e))
609 | return
610 |
611 | histories = dict(histories) # Drop duplications with same title.
612 | total = len(histories)
613 | for i, (title, url) in enumerate(histories.items(), 1):
614 | self._record_history(title, url)
615 | message_to_emacs("Importing {} / {} ...".format(i, total))
616 | message_to_emacs("{} {} history entries imported.".format(total, browser_name))
617 |
618 | @interactive
619 | def import_safari_history(self):
620 | ''' Import history entries from safari history db.'''
621 | self.send_input_message("Are you sure you want to import all history from safari?", "import_safari_history", "yes-or-no")
622 |
623 | @interactive
624 | def import_chrome_history(self):
625 | ''' Import history entries from chrome history db.'''
626 | self.send_input_message("Are you sure you want to import all history from chrome?", "import_chrome_history", "yes-or-no")
627 |
628 | def _delete_all_cookies(self):
629 | ''' Delete all cookies.'''
630 | self.buffer_widget.delete_all_cookies()
631 | message_to_emacs("Delete all cookies.")
632 |
633 | @interactive
634 | def delete_all_cookies(self):
635 | ''' Delete all cookies.'''
636 | self.send_input_message("Are you sure you want to delete all browsing cookies?", "delete_all_cookies", "yes-or-no")
637 |
638 | def _delete_cookie(self):
639 | ''' Delete cookie of current site.'''
640 | self.buffer_widget.delete_cookie()
641 | message_to_emacs("Delete cookie of {}.".format(self.buffer_widget.url().host()))
642 |
643 | @interactive
644 | def delete_cookie(self):
645 | ''' Delete cookie of current site.'''
646 | self.send_input_message("Are you sure you want to delete cookie of current site?", "delete_cookie", "yes-or-no")
647 |
648 | def load_readability_js(self):
649 | if self.readability_js is None:
650 | self.readability_js = open(os.path.join(os.path.dirname(__file__),
651 | "node_modules",
652 | "@mozilla",
653 | "readability",
654 | "Readability.js"
655 | ), encoding="utf-8").read()
656 |
657 | self.buffer_widget.eval_js(self.readability_js)
658 |
659 | @interactive(insert_or_do=True)
660 | def switch_to_reader_mode(self):
661 | if self.buffer_widget.execute_js("document.getElementById('readability-page-1') != null;"):
662 | message_to_emacs("Reader mode has been enable in current page.")
663 | else:
664 | self.load_readability_js()
665 |
666 | html = self.buffer_widget.execute_js("new Readability(document).parse().content;")
667 | if html is None:
668 | self.refresh_page()
669 | message_to_emacs("Cannot parse text content of current page, failed to switch reader mode.")
670 | else:
671 | self.buffer_widget.setHtml(get_emacs_var("eaf-browser-reader-mode-style") + html)
672 |
673 | @interactive(insert_or_do=True)
674 | def export_text(self):
675 | self.load_readability_js()
676 |
677 | text = self.buffer_widget.execute_js("new Readability(document).parse().textContent;")
678 | self.refresh_page()
679 | eval_in_emacs('eaf--browser-export-text', ["EAF-BROWSER-TEXT-" + self.url, text])
680 |
681 | @interactive(insert_or_do=True)
682 | def render_by_eww(self):
683 | self.load_readability_js()
684 |
685 | html = self.buffer_widget.execute_js("new Readability(document).parse().content;")
686 | if html is None:
687 | self.refresh_page()
688 | message_to_emacs("Cannot parse text content of current page, failed to render by eww.")
689 | else:
690 | import tempfile
691 |
692 | new_file, filename = tempfile.mkstemp(suffix=".html")
693 | with os.fdopen(new_file, 'w') as tmp:
694 | tmp.write(get_emacs_var("eaf-browser-reader-mode-style") + html)
695 |
696 | self.refresh_page()
697 | eval_in_emacs("eaf--browser-render-by-eww", [self.url, filename])
698 |
699 | def page_is_loading(self):
700 | return self.is_loading
701 |
702 | @interactive(insert_or_do=True)
703 | def translate_page(self):
704 | import locale
705 | system_language = locale.getdefaultlocale()[0].replace("_", "-")
706 | language = system_language if self.translate_language == "" else self.translate_language
707 |
708 | url = urllib.parse.quote(self.buffer_widget.url().toString(), safe='')
709 |
710 | open_url_in_new_tab_same_window("https://translate.google.com/translate?hl=en&sl=auto&tl={}&u={}".format(language, url), url)
711 | message_to_emacs("Translating page...")
712 |
713 | def get_new_window_buffer_id(self):
714 | ''' Return new browser window's buffer ID. '''
715 | import secrets
716 |
717 | return "{0}-{1}-{2}-{3}-{4}-{5}-{6}".format(
718 | secrets.token_hex(2),
719 | secrets.token_hex(2),
720 | secrets.token_hex(2),
721 | secrets.token_hex(2),
722 | secrets.token_hex(2),
723 | secrets.token_hex(2),
724 | secrets.token_hex(2))
725 |
726 | def create_new_window(self):
727 | ''' Create new browser window.'''
728 | # Generate buffer id same as eaf.el does.
729 | buffer_id = self.get_new_window_buffer_id()
730 |
731 | # Create buffer for create new browser window.
732 | app_buffer = self.create_buffer(buffer_id, "http://0.0.0.0", self.module_path, "")
733 |
734 | # Create emacs buffer with buffer id.
735 | eval_in_emacs('eaf--create-new-browser-buffer', [buffer_id])
736 |
737 | # Return new QWebEngineView for create new browser window.
738 | return app_buffer.buffer_widget
739 |
740 | def dark_mode_is_enabled(self):
741 | ''' Return bool of whether dark mode is enabled.'''
742 | dark_mode_var = get_emacs_var("eaf-browser-dark-mode")
743 | return (dark_mode_var == "force" or \
744 | dark_mode_var is True or \
745 | (dark_mode_var == "follow" and \
746 | self.theme_mode == "dark")) and \
747 | not self.url.startswith("devtools://")
748 |
749 | def init_web_page_background(self):
750 | self.buffer_widget.web_page.setBackgroundColor(QColor(get_emacs_theme_background()))
751 |
752 | class HistoryPage():
753 | def __init__(self, title, url, hit):
754 | self.title = title
755 | self.url = url
756 | self.hit = float(hit)
757 |
758 | class PasswordDb(object):
759 | def __init__(self, dbpath):
760 | import sqlite3
761 |
762 | self._conn = sqlite3.connect(dbpath)
763 | self._conn.execute("""
764 | CREATE TABLE IF NOT EXISTS autofill
765 | (id INTEGER PRIMARY KEY AUTOINCREMENT, host TEXT,
766 | password TEXT, form_data TEXT)
767 | """)
768 |
769 | def add_entry(self, host, password, form_data):
770 | result = self._conn.execute("""
771 | SELECT id, host, password, form_data FROM autofill
772 | WHERE host=? AND form_data=? ORDER BY id
773 | """, (host, str(form_data)))
774 | if len(list(result))>0:
775 | self._conn.execute("""
776 | UPDATE autofill SET password=?
777 | WHERE host=? and form_data=?
778 | """, (password, host, str(form_data)))
779 | else:
780 | self._conn.execute("""
781 | INSERT INTO autofill (host, password, form_data)
782 | VALUES (?, ?, ?)
783 | """, (host, password, str(form_data)))
784 | self._conn.commit()
785 |
786 | def get_entries(self, host, id):
787 | return self._conn.execute("""
788 | SELECT id, host, password, form_data FROM autofill
789 | WHERE host=? and id>? ORDER BY id
790 | """, (host, id))
791 |
792 | if found_braveblock:
793 | with open(os.path.join(os.path.dirname(__file__), "easylist.txt"), encoding="utf8") as f:
794 | raw_rules = f.readlines()
795 | easylist_adblocker = braveblock.Adblocker(rules=raw_rules)
796 |
797 | class AdBlockInterceptor(QWebEngineUrlRequestInterceptor):
798 | def __init__(self, profile, buffer):
799 | QWebEngineUrlRequestInterceptor.__init__(self)
800 | profile.setUrlRequestInterceptor(self)
801 | self.buffer = buffer
802 |
803 | def interceptRequest(self, info):
804 | # Ad Test site:
805 | # https://d3ward.github.io/toolz/adblock.html
806 |
807 | if self.buffer.enable_adblocker:
808 | url = info.requestUrl().toString()
809 |
810 | # Python's performance is not enough if just use re.compile to match 55000 rules.
811 | # We need use braveblock improve parse performance because braveblock implement by Rust.
812 | #
813 | # QWebEngineUrlRequestInterceptor will BLOCK main thread if this function is too slow.
814 | if easylist_adblocker.check_network_urls(
815 | url=url,
816 | source_url="", # do not set this url, source_url mean origin site to send ads
817 | request_type=""):
818 |
819 | # print("Block Ad: ", url)
820 | info.block(True)
821 |
822 | class TampermonkeyScript():
823 | # Currently, this class only supports match and export matching, and only supports regular expressions.
824 | def __init__(self,filepath):
825 | # Read the script's content
826 | self.file_content = ""
827 | with open(filepath,mode="r") as f:
828 | self.file_content = f.read()
829 |
830 | match_re = re.compile(r'// @match\s+(\S*)')
831 | export_re = re.compile(r'// @export\s+(\S*)')
832 |
833 | self.match_rules = match_re.findall(self.file_content)
834 | self.export_rules = export_re.findall(self.file_content)
835 |
836 |
837 | def can_run(self,url):
838 | for export_rule in self.export_rules:
839 | if re.match(export_rule,url):
840 | return False
841 |
842 | for match_rule in self.match_rules:
843 | if re.match(match_rule,url):
844 | return True
845 |
846 | return False
847 |
848 | def content(self):
849 | return self.file_content
850 |
--------------------------------------------------------------------------------
/dependencies.json:
--------------------------------------------------------------------------------
1 | {
2 | "pacman": [
3 | "aria2"
4 | ],
5 | "emerge": [
6 | "net-misc/aria2"
7 | ],
8 | "apt": [
9 | "aria2"
10 | ],
11 | "dnf": [
12 | "aria2"
13 | ],
14 | "pkg": [
15 | "aria2"
16 | ],
17 | "pip": {
18 | "linux": [
19 | "pysocks"
20 | ],
21 | "win32": [
22 | "pysocks"
23 | ],
24 | "darwin": [
25 | "pysocks"
26 | ]
27 | },
28 | "npm_install": true
29 | }
30 |
--------------------------------------------------------------------------------
/eaf-browser.el:
--------------------------------------------------------------------------------
1 | ;;; eaf-browser.el --- Browser plugins
2 |
3 | ;; Filename: eaf-browser.el
4 | ;; Description: Browser plugins
5 | ;; Author: Andy Stewart
6 | ;; Maintainer: Andy Stewart
7 | ;; Copyright (C) 2021, Andy Stewart, all rights reserved.
8 | ;; Created: 2021-07-20 22:30:28
9 | ;; Version: 0.1
10 | ;; Last-Updated: Sun Feb 6 15:25:47 2022 (-0500)
11 | ;; By: Mingde (Matthew) Zeng
12 | ;; URL: http://www.emacswiki.org/emacs/download/eaf-browser.el
13 | ;; Keywords:
14 | ;; Compatibility: GNU Emacs 28.0.50
15 | ;;
16 | ;; Features that might be required by this library:
17 | ;;
18 | ;;
19 | ;;
20 |
21 | ;;; This file is NOT part of GNU Emacs
22 |
23 | ;;; License
24 | ;;
25 | ;; This program is free software; you can redistribute it and/or modify
26 | ;; it under the terms of the GNU General Public License as published by
27 | ;; the Free Software Foundation; either version 3, or (at your option)
28 | ;; any later version.
29 |
30 | ;; This program is distributed in the hope that it will be useful,
31 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
32 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 | ;; GNU General Public License for more details.
34 |
35 | ;; You should have received a copy of the GNU General Public License
36 | ;; along with this program; see the file COPYING. If not, write to
37 | ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth
38 | ;; Floor, Boston, MA 02110-1301, USA.
39 |
40 | ;;; Commentary:
41 | ;;
42 | ;; Browser plugins
43 | ;;
44 |
45 | ;;; Installation:
46 | ;;
47 | ;; Put eaf-browser.el to your load-path.
48 | ;; The load-path is usually ~/elisp/.
49 | ;; It's set in your ~/.emacs like this:
50 | ;; (add-to-list 'load-path (expand-file-name "~/elisp"))
51 | ;;
52 | ;; And the following to your ~/.emacs startup file.
53 | ;;
54 | ;; (require 'eaf-browser)
55 | ;;
56 | ;; No need more.
57 |
58 | ;;; Customize:
59 | ;;
60 | ;;
61 | ;;
62 | ;; All of the above can customize by:
63 | ;; M-x customize-group RET eaf-browser RET
64 | ;;
65 |
66 | ;;; Change log:
67 | ;;
68 | ;; 2021/07/20
69 | ;; * First released.
70 | ;;
71 |
72 | ;;; Acknowledgements:
73 | ;;
74 | ;;
75 | ;;
76 |
77 | ;;; TODO
78 | ;;
79 | ;;
80 | ;;
81 |
82 | ;;; Require
83 |
84 |
85 | ;;; Code:
86 |
87 | (defgroup eaf-browser nil
88 | "The Browser application of Emacs application framework."
89 | :group 'eaf)
90 |
91 | (defcustom eaf-browser-search-engines `(("google" . "http://www.google.com/search?ie=utf-8&oe=utf-8&q=%s")
92 | ("duckduckgo" . "https://duckduckgo.com/?q=%s")
93 | ("bing" . "https://bing.com/search?q=%s"))
94 | "The default search engines offered by EAF.
95 |
96 | Each element has the form (NAME . URL).
97 | NAME is a search engine name, as a string.
98 | URL pecifies the url format for the search engine.
99 | It should have a %s as placeholder for search string."
100 | :type '(alist :key-type (string :tag "Search engine name")
101 | :value-type (string :tag "Search engine url")))
102 |
103 | (defcustom eaf-browser-default-search-engine "google"
104 | "The default search engine used by `eaf-open-browser' and `eaf-search-it'.
105 |
106 | It must defined at `eaf-browser-search-engines'."
107 | :type 'string)
108 |
109 | (defcustom eaf-browser-extension-list
110 | '("html" "htm")
111 | "The extension list of browser application."
112 | :type 'cons)
113 |
114 | (defcustom eaf-browser-continue-where-left-off nil
115 | "Similar to Chromium's Setting -> On start-up -> Continue where you left off.
116 |
117 | If non-nil, all active EAF Browser buffers will be saved before Emacs is killed,
118 | and will re-open them when calling `eaf-browser-restore-buffers' in the future session."
119 | :type 'boolean)
120 |
121 | (defcustom eaf-browser-fullscreen-move-cursor-corner nil
122 | "If non-nil, move the mouse cursor to the corner when fullscreen in the browser."
123 | :type 'boolean)
124 |
125 | (defcustom eaf-browser-enable-adblocker nil
126 | "If non-nil, enable adblocker for EAF Browser.
127 |
128 | AdBlocker will slow down the loading speed of EAF browser,
129 | because adblocker will check every url request before send to server.
130 | Recommand advertisement blocking on the router or proxy."
131 | :type 'boolean)
132 |
133 | (defcustom eaf-browser-enable-autofill nil
134 | "If non-nil, enable autofill password for EAF Browser."
135 | :type 'boolean)
136 |
137 | (defcustom eaf-browser-enable-tampermonkey nil
138 | "If non-nil, enable Tampermonkey scripts for EAF Browser."
139 | :type 'boolean)
140 |
141 | (defcustom eaf-browser-tampermonkey-location ""
142 | "If eaf-browser-enable-tampermonkey is non-nil, find scripts in here."
143 | :type 'string)
144 |
145 | (defcustom eaf-browser-remember-history t
146 | "If non-nil, remember browsing history for EAF Browser.
147 |
148 | The history file is stored in .emacs.d/eaf/browser/history/log.txt"
149 | :type 'boolean)
150 |
151 | (defcustom eaf-browser-ignore-history-list
152 | '("google.com/search" "file://")
153 | "A list of case insensitive regexp URL to ignore when saving EAF Browser history."
154 | :type 'cons)
155 |
156 | (defcustom eaf-browser-progress-bar-height "2"
157 | "Set progress bar height for EAF Browser."
158 | :type 'int)
159 |
160 | (defcustom eaf-browser-progress-bar-color (eaf-get-theme-foreground-color)
161 | "Color of progress bar in hex code `#hhhhhh'.
162 | Default is the foreground color of EAF buffer."
163 | :type 'string)
164 |
165 | (defcustom eaf-browser-text-selection-color "auto"
166 | "Possible values are `auto' or a hex code `#hhhhhh' of a color.
167 | If it is set to `auto', then the selection color will be automatically
168 | configured by darkreader.js."
169 | :type 'string)
170 |
171 | (defcustom eaf-browser-dark-mode-theme "dark"
172 | "Possible values are `dark' or `light' theme of the dark mode."
173 | :type 'string)
174 |
175 | (defcustom eaf-browser-blank-page-url "https://www.google.com"
176 | "Set the blank page url for EAF Browser."
177 | :type 'string)
178 |
179 | (defcustom eaf-browser-aria2-proxy-host ""
180 | "Set proxy host for aria2 downloader for EAF Browser."
181 | :type 'string)
182 |
183 | (defcustom eaf-browser-aria2-proxy-port ""
184 | "Set proxy port for aria2 downloader for EAF Browser."
185 | :type 'string)
186 |
187 | (defcustom eaf-browser-aria2-auto-file-renaming nil
188 | "If non-nil, aria2 downloader will auto rename files for EAF Browser."
189 | :type 'boolean)
190 |
191 | (defcustom eaf-browser-dark-mode "follow"
192 | "Configure the dark mode setting for EAF Browser.
193 |
194 | Options:
195 | - \"follow\" to follow Emacs theme
196 | - \"force\" to force dark mode
197 | - nil to disable dark mode"
198 | :type '(choice (const nil)
199 | string))
200 |
201 | (defcustom eaf-browser-chrome-history-file "~/.config/google-chrome/Default/History"
202 | "Set the chrome history file when exporting chrome history."
203 | :type 'string)
204 |
205 | (defcustom eaf-browser-safari-history-file "~/Library/Safari/History.db"
206 | "Set the chrome history file when exporting chrome history."
207 | :type 'string)
208 |
209 | (defcustom eaf-browser-translate-language ""
210 | "EAF browser will use current system locale if this option is empty"
211 | :type 'string)
212 |
213 | (defcustom eaf-browser-reader-mode-style
214 | ""
215 | "The string of css style used by reader-mode."
216 | :type 'string)
217 |
218 | (defcustom eaf-chrome-bookmark-file "~/.config/google-chrome/Default/Bookmarks"
219 | "The default chrome bookmark file to import."
220 | :type 'string)
221 |
222 | (defcustom eaf-browser-auto-import-chrome-cookies nil
223 | "If non-nil, import cookies from chrome."
224 | :type 'boolean)
225 |
226 | (defcustom eaf-browser-chrome-browser-name "Chrome"
227 | "The real chrome execute name, default is Chrome."
228 | :type 'string)
229 |
230 | (defcustom eaf-browser-caret-mode-keybinding
231 | '(("j" . "caret_next_line")
232 | ("k" . "caret_previous_line")
233 | ("l" . "caret_next_character")
234 | ("h" . "caret_previous_character")
235 | ("w" . "caret_next_word")
236 | ("b" . "caret_previous_word")
237 | (")" . "caret_next_sentence")
238 | ("(" . "caret_previous_sentence")
239 | ("g" . "caret_to_bottom")
240 | ("G" . "caret_to_top")
241 | ("/" . "caret_search_forward")
242 | ("?" . "caret_search_backward")
243 | ("." . "caret_clear_search")
244 | ("v" . "caret_toggle_mark")
245 | ("o" . "caret_rotate_selection")
246 | ("y" . "caret_translate_text")
247 | ("q" . "caret_exit")
248 | ("C-n" . "caret_next_line")
249 | ("C-p" . "caret_previous_line")
250 | ("C-f" . "caret_next_character")
251 | ("C-b" . "caret_previous_character")
252 | ("M-f" . "caret_next_word")
253 | ("M-b" . "caret_previous_word")
254 | ("M-e" . "caret_next_sentence")
255 | ("M-a" . "caret_previous_sentence")
256 | ("C-<" . "caret_to_bottom")
257 | ("C->" . "caret_to_top")
258 | ("C-s" . "caret_search_forward")
259 | ("C-r" . "caret_search_backward")
260 | ("C-." . "caret_clear_search")
261 | ("C-SPC" . "caret_toggle_mark")
262 | ("C-o" . "caret_rotate_selection")
263 | ("C-y" . "caret_translate_text")
264 | ("C-q" . "caret_exit")
265 | ("c" . "insert_or_caret_at_line")
266 | ("M-c" . "caret_toggle_browsing")
267 | ("" . "caret_exit"))
268 | "The keybinding of EAF Browser Caret Mode."
269 | :type 'cons)
270 |
271 | (defcustom eaf-browser-keybinding
272 | '(("C--" . "zoom_out")
273 | ("C-=" . "zoom_in")
274 | ("C-0" . "zoom_reset")
275 | ("C-s" . "search_text_forward")
276 | ("C-r" . "search_text_backward")
277 | ("C-n" . "scroll_up")
278 | ("C-p" . "scroll_down")
279 | ("C-f" . "scroll_right")
280 | ("C-b" . "scroll_left")
281 | ("C-v" . "scroll_up_page")
282 | ("C-y" . "yank_text")
283 | ("C-w" . "kill_text")
284 | ("M-z" . "switch_to_input_mode")
285 | ("M-e" . "atomic_edit")
286 | ("M-c" . "caret_toggle_browsing")
287 | ("M-D" . "select_text")
288 | ("M-s" . "open_link")
289 | ("M-S" . "open_link_new_buffer")
290 | ("M-B" . "open_link_background_buffer")
291 | ("C-/" . "undo_action")
292 | ("M-_" . "redo_action")
293 | ("M-w" . "copy_text")
294 | ("M-f" . "history_forward")
295 | ("M-b" . "history_backward")
296 | ("M-q" . "delete_cookie")
297 | ("M-Q" . "delete_all_cookies")
298 | ("C-t" . "toggle_password_autofill")
299 | ("C-d" . "save_page_password")
300 | ("C-M-q" . "clear_history")
301 | ("C-M-i" . "import_chrome_history")
302 | ("C-M-s" . "import_safari_history")
303 | ("M-v" . "scroll_down_page")
304 | ("M-<" . "scroll_to_begin")
305 | ("M->" . "scroll_to_bottom")
306 | ("M-p" . "duplicate_page")
307 | ("M-t" . "new_blank_page")
308 | ("M-d" . "toggle_dark_mode")
309 | ("M-l" . "toggle_dark_mode_light_theme")
310 | ("SPC" . "insert_or_scroll_up_page")
311 | ("J" . "insert_or_select_left_tab")
312 | ("K" . "insert_or_select_right_tab")
313 | ("j" . "insert_or_scroll_up")
314 | ("k" . "insert_or_scroll_down")
315 | ("h" . "insert_or_scroll_left")
316 | ("l" . "insert_or_scroll_right")
317 | ("f" . "insert_or_open_link")
318 | ("F" . "insert_or_open_link_new_buffer")
319 | ("O" . "insert_or_open_link_new_buffer_other_window")
320 | ("B" . "insert_or_open_link_background_buffer")
321 | ("c" . "insert_or_caret_at_line")
322 | ("u" . "insert_or_scroll_down_page")
323 | ("d" . "insert_or_scroll_up_page")
324 | ("H" . "insert_or_history_backward")
325 | ("L" . "insert_or_history_forward")
326 | ("t" . "insert_or_new_blank_page")
327 | ("T" . "insert_or_recover_prev_close_page")
328 | ("i" . "insert_or_focus_input")
329 | ("I" . "insert_or_open_downloads_setting")
330 | ("r" . "insert_or_refresh_page")
331 | ("g" . "insert_or_scroll_to_begin")
332 | ("x" . "insert_or_close_buffer")
333 | ("G" . "insert_or_scroll_to_bottom")
334 | ("-" . "insert_or_zoom_out")
335 | ("=" . "insert_or_zoom_in")
336 | ("0" . "insert_or_zoom_reset")
337 | ("m" . "insert_or_save_as_bookmark")
338 | ("o" . "insert_or_open_browser")
339 | ("y" . "insert_or_download_youtube_video")
340 | ("Y" . "insert_or_download_youtube_audio")
341 | ("p" . "insert_or_toggle_device")
342 | ("P" . "insert_or_duplicate_page")
343 | ("1" . "insert_or_save_as_pdf")
344 | ("2" . "insert_or_save_as_single_file")
345 | ("3" . "insert_or_save_as_screenshot")
346 | ("v" . "insert_or_view_source")
347 | ("e" . "insert_or_edit_url")
348 | ("n" . "insert_or_export_text")
349 | ("N" . "insert_or_render_by_eww")
350 | ("," . "insert_or_switch_to_reader_mode")
351 | ("." . "insert_or_translate_text")
352 | (";" . "insert_or_translate_page")
353 | ("M-i" . "immersive_translation")
354 | ("C-M-c" . "copy_code")
355 | ("C-M-l" . "copy_link")
356 | ("C-a" . "select_all_or_input_text")
357 | ("M-u" . "clear_focus")
358 | ("C-j" . "open_downloads_setting")
359 | ("M-o" . "eval_js")
360 | ("M-O" . "eval_js_file")
361 | ("" . "eaf-browser-send-esc-or-exit-fullscreen")
362 | ("M-," . "eaf-send-down-key")
363 | ("M-." . "eaf-send-up-key")
364 | ("M-m" . "eaf-send-return-key")
365 | ("" . "refresh_page")
366 | ("" . "open_devtools")
367 | ("" . "eaf-send-ctrl-return-sequence")
368 | ("C-" . "eaf-send-ctrl-left-sequence")
369 | ("C-" . "eaf-send-ctrl-right-sequence")
370 | ("C-" . "eaf-send-ctrl-delete-sequence")
371 | ("C-" . "eaf-send-ctrl-backspace-sequence")
372 | )
373 | "The keybinding of EAF Browser."
374 | :type 'cons)
375 |
376 | (defcustom eaf-browser-key-alias
377 | '(("C-a" . "")
378 | ("C-e" . ""))
379 | "The key alias of EAF Browser."
380 | :type 'cons)
381 |
382 | (defun eaf--browser-update-position (position-percentage)
383 | "Format mode line position indicator to show the current position in percentage."
384 | (setq-local mode-line-position `(,position-percentage))
385 | (force-mode-line-update))
386 |
387 | (defun eaf-browser-restore-buffers ()
388 | "EAF restore all opened EAF Browser buffers in the previous Emacs session.
389 |
390 | This should be used after setting `eaf-browser-continue-where-left-off' to t."
391 | (interactive)
392 | (if eaf-browser-continue-where-left-off
393 | (let* ((browser-restore-file-path
394 | (concat eaf-config-location
395 | (file-name-as-directory "browser")
396 | (file-name-as-directory "history")
397 | "restore.txt"))
398 | (browser-url-list
399 | (with-temp-buffer (insert-file-contents browser-restore-file-path)
400 | (split-string (buffer-string) "\n" t))))
401 | (if (eaf-epc-live-p eaf-epc-process)
402 | (dolist (url browser-url-list)
403 | (eaf-open-browser url))
404 | (dolist (url browser-url-list)
405 | (push `(,url "browser" "") eaf--active-buffers))
406 | (when eaf--active-buffers (eaf-open-browser (nth 0 (car eaf--active-buffers))))))
407 | (user-error "Please set `eaf-browser-continue-where-left-off' to t first!")))
408 |
409 | (defun eaf--browser-bookmark ()
410 | "Restore EAF buffer according to browser bookmark from the current file path or web URL."
411 | `((handler . eaf--bookmark-restore)
412 | (eaf-app . "browser")
413 | (defaults . ,(list eaf--bookmark-title))
414 | (filename . ,(eaf-get-path-or-url))))
415 |
416 | (defun eaf--browser-chrome-bookmark (name url)
417 | "Restore EAF buffer according to chrome bookmark of given title and web URL."
418 | `((handler . eaf--bookmark-restore)
419 | (eaf-app . "browser")
420 | (defaults . ,(list name))
421 | (filename . ,url)))
422 |
423 | (defun eaf--browser-bookmark-restore (bookmark)
424 | (eaf-open-browser (cdr (assq 'filename bookmark))))
425 |
426 | (defalias 'eaf--browser-firefox-bookmark 'eaf--browser-chrome-bookmark)
427 |
428 | (defvar eaf--firefox-bookmarks nil
429 | "Bookmarks that should be imported from firefox.")
430 |
431 | (defun eaf--useful-firefox-bookmark? (uri)
432 | "Check whether uri is a website url."
433 | (or (string-prefix-p "http://" uri)
434 | (string-prefix-p "https://" uri)))
435 |
436 | (defun eaf--firefox-bookmark-to-import? (title uri)
437 | "Check whether uri should be imported."
438 | (when (eaf--useful-firefox-bookmark? uri)
439 | (let ((old (gethash uri eaf--existing-bookmarks)))
440 | (when (or
441 | (not old)
442 | (and (string-equal old "") (not (string-equal title ""))))
443 | t))))
444 |
445 | (defun eaf--firefox-bookmark-to-import (title uri)
446 | (puthash uri title eaf--existing-bookmarks)
447 | (add-to-list 'eaf--firefox-bookmarks (cons uri title)))
448 |
449 | (defun eaf-import-firefox-bookmarks ()
450 | "Command to import firefox bookmarks."
451 | (interactive)
452 | (when (eaf-read-input "In order to import, you should first backup firefox's bookmarks to a json file. Continue?" "yes-or-no" "" "")
453 | (let ((fx-bookmark-file (read-file-name "Choose firefox bookmark file:")))
454 | (if (not (file-exists-p fx-bookmark-file))
455 | (message "Firefox bookmark file: '%s' is not exist." fx-bookmark-file)
456 | (setq eaf--firefox-bookmarks nil)
457 | (setq eaf--existing-bookmarks (eaf--load-existing-bookmarks))
458 | (let ((orig-bookmark-record-fn bookmark-make-record-function)
459 | (data (json-read-file fx-bookmark-file)))
460 | (cl-labels ((fn (item)
461 | (pcase (alist-get 'typeCode item)
462 | (1
463 | (let ((title (alist-get 'title item ""))
464 | (uri (alist-get 'uri item)))
465 | (when (eaf--firefox-bookmark-to-import? title uri)
466 | (eaf--firefox-bookmark-to-import title uri))))
467 | (2
468 | (mapc #'fn (alist-get 'children item))))))
469 | (fn data)
470 | (dolist (bm eaf--firefox-bookmarks)
471 | (let ((uri (car bm))
472 | (title (cdr bm)))
473 | (setq-local bookmark-make-record-function
474 | #'(lambda () (eaf--browser-firefox-bookmark title uri)))
475 | (bookmark-set title)))
476 | (setq-local bookmark-make-record-function orig-bookmark-record-fn)
477 | (bookmark-save)
478 | (message "Import success.")))))))
479 |
480 | (defun eaf--create-new-browser-buffer (new-window-buffer-id)
481 | "Function for creating a new browser buffer with the specified NEW-WINDOW-BUFFER-ID."
482 | (let ((eaf-buffer
483 | ;; Create a buffer which name look like first buffer (but
484 | ;; different). this can prevent mode-line flicker. the
485 | ;; buffer's name will be changed to title when title is
486 | ;; ready.
487 | (generate-new-buffer
488 | (concat (buffer-name (car (buffer-list))) " "))))
489 | (with-current-buffer eaf-buffer
490 | (eaf--gen-keybinding-map (eaf--get-app-bindings "browser"))
491 | (eaf-mode)
492 | (set (make-local-variable 'eaf--buffer-id) new-window-buffer-id)
493 | (set (make-local-variable 'eaf--buffer-url) "")
494 | (set (make-local-variable 'eaf--buffer-app-name) "browser"))
495 | (switch-to-buffer eaf-buffer)
496 | ;; When user open new window by click link, we should clean
497 | ;; minibuffer's message, for it may be show useless info.
498 | (message nil)))
499 |
500 | (defun eaf-browser--duplicate-page-in-new-tab (url)
501 | "Duplicate a new tab for the dedicated URL."
502 | (eaf-open (eaf-wrap-url url) "browser" nil t))
503 |
504 | (defun eaf-is-valid-web-url (url)
505 | "Return the same URL if it is valid."
506 | (when (and url
507 | ;; URL should not include blank char.
508 | (< (length (split-string url)) 2)
509 | ;; Use regexp matching URL.
510 | (or (and
511 | (string-prefix-p "file://" url)
512 | (string-suffix-p ".html" url))
513 | ;; Normal url address.
514 | (string-match "^\\(https?://\\)?[a-z0-9]+\\([-.][a-z0-9]+\\)*.+\\..+[a-z0-9.]\\{1,6\\}\\(:[0-9]{1,5}\\)?\\(/.*\\)?$" url)
515 | ;; Localhost url.
516 | (string-match "^\\(https?://\\)?\\(localhost\\|127.0.0.1\\):[0-9]+/?" url)))
517 | url))
518 |
519 | (defun eaf-wrap-url (url)
520 | "Wraps URL with prefix http:// if URL does not include it."
521 | (if (or (string-prefix-p "http://" url)
522 | (string-prefix-p "https://" url)
523 | (string-prefix-p "file://" url)
524 | (string-prefix-p "chrome://" url))
525 | url
526 | (concat "http://" url)))
527 |
528 | ;;;###autoload
529 | (defun eaf-open-browser-in-background (url &optional args)
530 | "Open browser with the specified URL and optional ARGS in background."
531 | (setq eaf--monitor-configuration-p nil)
532 | (let ((save-buffer (current-buffer)))
533 | (eaf-open-browser url args)
534 | (switch-to-buffer save-buffer))
535 | (setq eaf--monitor-configuration-p t))
536 |
537 | ;;;###autoload
538 | (defun eaf-open-browser-with-history ()
539 | "A wrapper around `eaf-open-browser' that provides browser history candidates.
540 |
541 | If URL is an invalid URL, it will use `eaf-browser-default-search-engine' to search URL as string literal.
542 |
543 | This function works best if paired with a fuzzy search package."
544 | (interactive)
545 | (let* ((browser-history-file-path
546 | (concat eaf-config-location
547 | (file-name-as-directory "browser")
548 | (file-name-as-directory "history")
549 | "log.txt"))
550 | (history-pattern "^\\(.+\\)ᛝ\\(.+\\)ᛡ\\(.+\\)$")
551 | (history-file-exists (file-exists-p browser-history-file-path))
552 | (history (completing-read
553 | "[EAF/browser] Search || URL || History: "
554 | (if history-file-exists
555 | (mapcar
556 | (lambda (h) (when (string-match history-pattern h)
557 | (format "[%s] ⇰ %s" (match-string 1 h) (match-string 2 h))))
558 | (with-temp-buffer (insert-file-contents browser-history-file-path)
559 | (split-string (buffer-string) "\n" t)))
560 | nil)))
561 | (history-url (eaf-is-valid-web-url (when (string-match "⇰\s\\(.+\\)$" history)
562 | (match-string 1 history)))))
563 | (cond (history-url (eaf-open-browser history-url))
564 | ((eaf-is-valid-web-url history) (eaf-open-browser history))
565 | (t (eaf-search-it history)))))
566 |
567 | (defun eaf--create-search-url (search-string &optional search-engine use-user-engine)
568 | "Create a search-url for SEARCH-STRING using SEARCH-ENGINE.
569 |
570 | SEARCH-ENGINE is defaulted to `eaf-browser-default-search-engine'.
571 | When USE-USER-ENGINE is non-nil, user can choose a search engine defined in `eaf-browser-search-engines'"
572 | (let* ((real-search-engine (if use-user-engine
573 | (let ((all-search-engine (mapcar #'car eaf-browser-search-engines)))
574 | (completing-read
575 | (format "[EAF/browser] Select search engine (default %s): " eaf-browser-default-search-engine)
576 | all-search-engine nil t nil nil eaf-browser-default-search-engine))
577 | (or search-engine eaf-browser-default-search-engine)))
578 | (link (or (cdr (assoc real-search-engine
579 | eaf-browser-search-engines))
580 | (error (format "[EAF/browser] Search engine %s is unknown to EAF!" real-search-engine))))
581 | (search-url (format link search-string)))
582 | search-url))
583 |
584 | ;;;###autoload
585 | (defun eaf-search-it (&optional search-string search-engine)
586 | "Use SEARCH-ENGINE search SEARCH-STRING.
587 |
588 | If called interactively, SEARCH-STRING is defaulted to symbol or region string.
589 | The user can enter a customized SEARCH-STRING. SEARCH-ENGINE is defaulted
590 | to `eaf-browser-default-search-engine' with a prefix arg, the user is able to
591 | choose a search engine defined in `eaf-browser-search-engines'"
592 | (interactive)
593 | (let* ((current-symbol (if mark-active
594 | (if (eq major-mode 'pdf-view-mode)
595 | (progn
596 | (declare-function pdf-view-active-region-text "pdf-view.el")
597 | (car (pdf-view-active-region-text)))
598 | (buffer-substring (region-beginning) (region-end)))
599 | (symbol-at-point)))
600 | (search-string (if search-string search-string
601 | (let ((search-string (read-string (format "[EAF/browser] Search (%s): " current-symbol))))
602 | (if (string-blank-p search-string) current-symbol
603 | search-string))))
604 | (use-user-engine current-prefix-arg)
605 | (search-url (eaf--create-search-url search-string search-engine use-user-engine)))
606 | (eaf-open search-url "browser")))
607 |
608 | (defun eaf-browser-send-esc-or-exit-fullscreen ()
609 | "Escape fullscreen status if browser current is fullscreen.
610 | Otherwise send key 'esc' to browser."
611 | (interactive)
612 | (if eaf-fullscreen-p
613 | (eaf-call-async "eval_function" eaf--buffer-id "exit_fullscreen" "")
614 | (eaf-call-async "send_key" eaf--buffer-id "")))
615 |
616 | (defun eaf-browser-is-loading ()
617 | "Return non-nil if current page is loading."
618 | (interactive)
619 | (when (and (string= eaf--buffer-app-name "browser")
620 | (string= (eaf-call-sync "execute_function" eaf--buffer-id "page_is_loading") "True"))))
621 |
622 | (defun eaf--browser-get-window-width (&optional window)
623 | "Get WINDOW allocation."
624 | (let* ((window-edges (window-pixel-edges window))
625 | (x (nth 0 window-edges))
626 | (w (- (nth 2 window-edges) x)))
627 | w))
628 |
629 | (defun eaf--browser-export-text (buffer-name html-text)
630 | (let ((eaf-export-text-buffer (get-buffer-create buffer-name)))
631 | (with-current-buffer eaf-export-text-buffer
632 | ;; Insert html text.
633 | (read-only-mode -1)
634 | (erase-buffer)
635 | (insert html-text)
636 | ;; Convert multiple blank lines to single line.
637 | (goto-char (point-min))
638 | (ignore-errors
639 | (while (re-search-forward "\\(^\\s-*$\\)\n" nil t)
640 | (replace-match "\n")
641 | (forward-char 1)))
642 | ;; Try to remove first blank line.
643 | (goto-char (point-min))
644 | (when (looking-at-p "[[:blank:]]*$")
645 | (kill-line))
646 | ;; Try olivetti mode.
647 | (let ((window-width (/ (eaf--browser-get-window-width) (window-font-width))))
648 | (when (featurep 'olivetti)
649 | (olivetti-mode 1)
650 | (olivetti-set-width (floor (* window-width 0.618)))))
651 | (read-only-mode 1))
652 | (switch-to-buffer eaf-export-text-buffer)))
653 |
654 | (defun eaf--browser-render-by-eww (url filepath)
655 | (eww-open-file filepath)
656 |
657 | (setq-local header-line-format (format "EAF Browser: %s" url))
658 |
659 | ;; Try olivetti mode.
660 | (let ((window-width (/ (eaf--browser-get-window-width) (window-font-width))))
661 | (when (featurep 'olivetti)
662 | (olivetti-mode 1)
663 | (olivetti-set-width (floor (* window-width 0.618))))))
664 |
665 | (defun eaf--atomic-edit (buffer-id focus-text)
666 | "EAF Browser: edit FOCUS-TEXT with Emacs's BUFFER-ID."
667 | (eaf-edit-buffer-popup buffer-id "eaf-%s-atomic-edit" "" focus-text))
668 |
669 | (defun eaf-edit-buffer-cancel ()
670 | "Cancel EAF Browser focus text input and closes the buffer."
671 | (interactive)
672 | (kill-buffer)
673 | (delete-window)
674 | (message "[EAF/%s] Edit cancelled!" eaf--buffer-app-name))
675 |
676 | (defun eaf--toggle-caret-browsing (caret-status)
677 | "Toggle caret browsing given CARET-STATUS."
678 | (if caret-status
679 | (eaf--gen-keybinding-map eaf-browser-caret-mode-keybinding t)
680 | (eaf--gen-keybinding-map eaf-browser-keybinding))
681 | (setq eaf--buffer-map-alist (list (cons t eaf-mode-map))))
682 |
683 | (defun eaf-import-chrome-bookmarks ()
684 | "Command to import chrome bookmarks."
685 | (interactive)
686 | (when (eaf-read-input "Are you sure to import chrome bookmarks to EAF" "yes-or-no" "" "")
687 | (if (not (file-exists-p eaf-chrome-bookmark-file))
688 | (message "Chrome bookmark file: '%s' is not exist, check `eaf-chrome-bookmark-file` setting." eaf-chrome-bookmark-file)
689 | (let ((orig-bookmark-record-fn bookmark-make-record-function)
690 | (data (json-read-file eaf-chrome-bookmark-file)))
691 | (cl-labels ((fn (item)
692 | (pcase (alist-get 'type item)
693 | ("url"
694 | (let ((name (alist-get 'name item))
695 | (url (alist-get 'url item)))
696 | (if (not (equal "chrome://bookmarks/" url))
697 | (progn
698 | (setq-local bookmark-make-record-function
699 | #'(lambda () (eaf--browser-chrome-bookmark name url)))
700 | (bookmark-set name)))))
701 | ("folder"
702 | (mapc #'fn (alist-get 'children item))))))
703 | (fn (alist-get 'bookmark_bar (alist-get 'roots data)))
704 | (setq-local bookmark-make-record-function orig-bookmark-record-fn)
705 | (bookmark-save)
706 | (message "Import success."))))))
707 |
708 | ;;;###autoload
709 | (defun eaf-open-browser (url &optional args)
710 | "Open EAF browser application given a URL and ARGS."
711 | (interactive "M[EAF/browser] URL: ")
712 | (eaf-open (eaf-wrap-url url) "browser" args))
713 |
714 | (defun eaf-open-browser-same-window (url current-url &optional args)
715 | (setq current-url (url-unhex-string current-url))
716 | (catch 'found-rss-reader-buffer
717 | (eaf-for-each-eaf-buffer
718 | (when (string-equal eaf--buffer-url current-url)
719 | (select-window (get-buffer-window buffer))
720 | (eaf-open (eaf-wrap-url url) "browser" args)
721 | (throw 'found-rss-reader-buffer buffer)))))
722 |
723 | ;;;###autoload
724 | (defun eaf-open-browser-other-window (url &optional args)
725 | "Open EAF browser application given a URL and ARGS in other window."
726 | (interactive "M[EAF/browser] URL: ")
727 | (when (< (length (window-list)) 2)
728 | (split-window-right))
729 | (other-window 1)
730 | (eaf-open (eaf-wrap-url url) "browser" args))
731 |
732 | (defun eaf-open-url-at-point ()
733 | "Open URL at current point by EAF browser."
734 | (interactive)
735 | (eaf-open-browser (eaf-pick-url-under-cursor)))
736 |
737 | (defun eaf-pick-url-under-cursor ()
738 | (if (eq major-mode 'org-mode)
739 | (let ((object (org-element-context)))
740 | (when (eq (car object) 'link)
741 | (org-element-property :raw-link object)))
742 | (browse-url-url-at-point)))
743 |
744 | (defun eaf-toggle-proxy()
745 | "Toggle proxy to none or default proxy."
746 | (interactive)
747 | (eaf-call-sync "toggle_proxy"))
748 |
749 | (defun eaf-get-mode-line-height ()
750 | (let ((mode-line-height (face-attribute 'mode-line :height)))
751 | (if (eq mode-line-height 'unspecified)
752 | 1.0
753 | mode-line-height)))
754 |
755 | (add-to-list 'eaf-app-binding-alist '("browser" . eaf-browser-keybinding))
756 |
757 | (setq eaf-browser-module-path (concat (file-name-directory load-file-name) "buffer.py"))
758 | (add-to-list 'eaf-app-module-path-alist '("browser" . eaf-browser-module-path))
759 |
760 | (add-to-list 'eaf-app-bookmark-handlers-alist '("browser" . eaf--browser-bookmark))
761 |
762 | (add-to-list 'eaf-app-bookmark-restore-alist '("browser" . eaf--browser-bookmark-restore))
763 |
764 | (add-to-list 'eaf-app-extensions-alist '("browser" . eaf-browser-extension-list))
765 |
766 | (provide 'eaf-browser)
767 |
768 | ;;; eaf-browser.el ends here
769 |
--------------------------------------------------------------------------------
/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "browser",
3 | "lockfileVersion": 2,
4 | "requires": true,
5 | "packages": {
6 | "": {
7 | "dependencies": {
8 | "@mozilla/readability": "^0.6.0",
9 | "darkreader": "^4.9.34"
10 | }
11 | },
12 | "node_modules/@mozilla/readability": {
13 | "version": "0.6.0",
14 | "resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.6.0.tgz",
15 | "integrity": "sha512-juG5VWh4qAivzTAeMzvY9xs9HY5rAcr2E4I7tiSSCokRFi7XIZCAu92ZkSTsIj1OPceCifL3cpfteP3pDT9/QQ==",
16 | "license": "Apache-2.0",
17 | "engines": {
18 | "node": ">=14.0.0"
19 | }
20 | },
21 | "node_modules/darkreader": {
22 | "version": "4.9.58",
23 | "resolved": "https://registry.npmjs.org/darkreader/-/darkreader-4.9.58.tgz",
24 | "integrity": "sha512-D/JGoJqW3m2AWBLhO+Pev+eThfs+CwRT4bcLb/1zKjql2yVwG0lx8C2XRDdSVGHw4y11n26W7syWoBpUfuhMqQ==",
25 | "funding": {
26 | "type": "opencollective",
27 | "url": "https://opencollective.com/darkreader/donate"
28 | }
29 | }
30 | },
31 | "dependencies": {
32 | "@mozilla/readability": {
33 | "version": "0.6.0",
34 | "resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.6.0.tgz",
35 | "integrity": "sha512-juG5VWh4qAivzTAeMzvY9xs9HY5rAcr2E4I7tiSSCokRFi7XIZCAu92ZkSTsIj1OPceCifL3cpfteP3pDT9/QQ=="
36 | },
37 | "darkreader": {
38 | "version": "4.9.58",
39 | "resolved": "https://registry.npmjs.org/darkreader/-/darkreader-4.9.58.tgz",
40 | "integrity": "sha512-D/JGoJqW3m2AWBLhO+Pev+eThfs+CwRT4bcLb/1zKjql2yVwG0lx8C2XRDdSVGHw4y11n26W7syWoBpUfuhMqQ=="
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "@mozilla/readability": "^0.6.0",
4 | "darkreader": "^4.9.34"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/emacs-eaf/eaf-browser/8fa75f55bd237a4bd0579733a29038fcb07c0426/screenshot.png
--------------------------------------------------------------------------------