├── LICENSE
├── README.md
├── README.md.d
├── avatar.png
└── vv.gif
└── vv
/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 | # vv: VT View
2 |
3 | A simple image viewer for video terminals capable of sixel graphics.
4 |
5 | Quickly preview, delete, and move files. Particularly useful on remote
6 | machines over `ssh`.
7 |
8 |
9 |
10 | ## Installation
11 |
12 | It's a shell script. Just download
13 | [vv](https://github.com/hackerb9/vv/raw/main/vv) to a directory in
14 | your PATH (e.g., ~/bin or /usr/local/bin) and make it executable
15 | (chmod +x vv).
16 |
17 | ## Required dependencies
18 |
19 | * A sixel capable terminal (e.g., xterm -ti vt340).
20 | * ImageMagick
21 |
22 | ### Recommended but not required
23 |
24 | * ncurses-bin (for tput)
25 | * file (determine filetype by magic numbers rather than extension)
26 | * mediainfo (quickly count number of frames in a video)
27 | * GNU coreutils (for realpath, for deleting images to trashcan)
28 | * curl, w3m and w3m-img for text based reverse image search
29 | * Bash version >=5 (read bug workaround)
30 | * [sixvid](https://github.com/hackerb9/sixvid) & ffmpeg: so viewing a
31 | gif or mp4 will play an animation
32 | * poppler-utils (for pdfinfo to count pages in PDF files)
33 |
34 | ## Some nice features
35 | * Can display any image type. (Via ImageMagick).
36 | * Detects images by magic, not by extension.
37 | * Shows everything in the current working directory by default.
38 | * Loads directories recursively (default: ask; -r: always; -R: never).
39 | * Scales down large images to fit within terminal.
40 | * Supports "fit width" (`w`) mode; portrait pictures scroll vertically.
41 | * Can view at "100% zoom" (`1`). Cuts large picture into pieces, if necessary.
42 | * Has "best fit" (`B`), autorotate to use as much of the screen as possible.
43 | * Defaults to fast viewing [-F] to quickly preview and delete (`d`) images,
44 | or use [-f] to default to full-size (slower, highquality) view.
45 | * Hit (`v`) to view full-size (slower, highquality) for current image only,
46 | or use (`f`) to toggle between fast and full-size viewing mode.
47 | * Preview size can be increased (`+`), decreased (`-`), or reset (`0`).
48 | * Deleted (`d`) images are moved to Trashcan (Freedesktop standard).
49 | * Can undo (`u`) last trashed file.
50 | * Rename (`r`), move (`m`) and save-a-copy (`s`) remember the
51 | previously used directory.
52 | * Web reverse image search (`W`). (Currently uses yandex).
53 | * Slideshow mode (`S`).
54 | * Renaming a file (`r`) uses readline for easier editing.
55 | * Rename and move default to the last directory used.
56 | * If renaming or moving would overwrite an image with a different one,
57 | both images are shown side-by-side.
58 | * Directories are automatically created if nonexistent when moving a file.
59 | * Edit embedded comments (`C`). Works with JPEG, PNG, TIFF, GIF, and more.
60 | * Embedded comments can have multiple lines (use ^V^J for a new line).
61 | * Sets xterm to use more color registers for higher quality pictures.
62 | * Work on true DEC hardware (e.g., VT340).
63 | * Resizes current image when terminal resizes. (SIGWINCH).
64 | * Pixel height of preview is a multiple of the current text font height,
65 | so previews should be the right size no matter your screen resolution.
66 | * Pixel width of preview is always the full width of the terminal.
67 | * View videos (`v`) such as animated GIFs. (Requires 'sixvid' and ffmpeg).
68 | * Icons and small images can be zoomed in to screen size. (`z` to toggle).
69 | * Breadth first search. Images in current dir are shown before subdirs.
70 | * Images with transparency use the terminal's background color.
71 | * Thumbnails may be clicked on to open in your default viewer.
72 | (Requires a terminal that understands the
73 | [OSC 8](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda)
74 | escape sequence).
75 |
76 |
77 | ## NOTES
78 |
79 | ### Note 1
80 |
81 | This is designed mainly for quickly previewing, deleting, and renaming
82 | images over an ssh connection. For that reason, fast, small,
83 | low-quality images are emphasized and deletion is a single keystroke.
84 | (Note, undeletion is also a single key).
85 |
86 | ### Note 2
87 |
88 | libglib2.0-bin's `gio` will be used for moving files to the Trashcan, if
89 | it is installed, but it is not required. See the trash() and untrash()
90 | shell functions.
91 |
92 | ### Note 3
93 |
94 | Bash 4.4 had a bug where catching SIGWINCH in the middle of a normal
95 | 'read' would cause the stty to go insane. For that reason, in the main
96 | loop we use 'read -e' which uses readline and does not suffer from the
97 | bug. (Bash 5 is fine.)
98 |
99 | ### Note 4
100 |
101 | ImageMagick 6.9.12 has a few issues:
102 |
103 | * may not support webm video.
104 |
105 | * has a bug where a filename that has a colon in it will not work when
106 | frame zero is selected. As a workaround, this script uses
107 | "file://$filename[0]".
108 |
109 | * has a bug where RGB data is not read properly from sixel image files
110 |
111 | ## Todo
112 |
113 | * Add --cat option which just splats images out as fast as possible.
114 | * Handle genuine VT340 specially so it doesn't change foreground/background colors.
115 | * Reconsider `v` (view just this image fullscreen) and `f` (fullscreen
116 | toggle) keys. Maybe should either be modal or not. Would it help to
117 | redefine `Enter` to always switch to fast mode and 'f' to always switch
118 | to fullscreen mode?
119 | * Allow file sortorder to be changed interactively instead of editing
120 | script. (modification/access time, natural sort).
121 | * Show a quick overview of all images in the directory. (Like lsix).
122 | * Should not show pdf, odt, xls and other slow formats by default.
123 | * Currently prompt is less verbose if the screen width is too short,
124 | but maybe that should always be the case. Consider showing the succinct
125 | help only if a wrong key is hit.
126 | * Implement "-1" and "-w" to default to 1-for-1 and Wide view mode.
127 | * Consider using b9's feh key bindings.
128 | * Allow selecting a range of images for deletion.
129 | * imageinfo() calls ImageMagick's identify which is too slow.
130 | * Use exiftool for property adjustments, not imagemagick which fails.
131 | * Use an array of filenames so user can go back to previous, and
132 | so untrash won't take place of current image.
133 | * Use vi/nethack keys. (`j` next, `k` prev, `h` back to parent directory, `l` ?)
134 | * Include mycompare.sh to interactively compare two files.
135 | (Side-by-side or A/B)
136 | * Edit Caption, Title, Headline in IPTC, XMP
137 | * Allow user to force white/black background. (Mainly for text pdfs).
138 | Alternately, perhaps a key to disable alpha channel would be better.
139 | * Add a key for opening image in standard graphical viewer.
140 | (Maybe dial `M` for mime? `O` for open?)
141 | * Perhaps also allow graphical browser during reverse image search.
142 | * Maybe use multiprocessing by converting full screen images in patches.
143 | (Added benefit, extends Xterm's default 1000x1000 limitation).
144 | * Maybe quit immediately (batch mode) if only 1 image on command line.
145 | This would obviate the need for b9's `sixcat` program.
146 | * PDF documents should work like a directory, asking user if they want
147 | to open and show images inside.
148 | * CBZ, comicbook zip files should also work like directories.
149 | * Should handle when ImageMagick dies due restrictions in
150 | /etc/ImageMagick-6/policy.xml. (For example, viewing an xcf file
151 | will often overrun the memory limit).
152 |
153 | ## Questions
154 |
155 | * Should we allow SVG and EPS which are images, but can execute code?
156 | * Entering multiline comments are weird because you have to type `^V`
157 | `^J` to create a newline. Should they pop open an editor?
158 |
159 | ## About Metadata
160 |
161 | The author, hackerb9, has long added little notes and blurbs to
162 | images in the JPEG "Comments" field. However, that humble field has
163 | been extended by EXIF, IPTC, and XMP to a dizzying degree:
164 | Description, Caption, Headline, Title, .... If you are a
165 | professional photographer and have feedback on how this program can
166 | better show and manipulate metadata, please send a bug report at
167 | https://github.com/hackerb9/vv/issues/
168 |
169 | ### Here's what we know.
170 |
171 | The IPTC industry standards define Title, Description/Caption, and Headline as:
172 |
173 | #### "Title", AKA "Document Title", AKA "Object Name"
174 |
175 | A shorthand reference for the image or “photograph” - primarily for
176 | identification. The title of an image should be a short,
177 | human-readable name - text and/or numeric reference - and may take
178 | several forms. For photographers, this might be the filename of their
179 | original scan or digital camera file. The Title term should not be
180 | confused with the Headline term, which is a short synopsis of the
181 | photograph's content.
182 |
183 | Title Examples: _"IMG\_9873"_, or _"Sunrise Over Temple"_
184 |
185 | #### "Description", AKA "Caption"
186 |
187 | The Description field, often referred to as “Caption,” should report
188 | the who, what and why of what the photograph depicts. If there is a
189 | person or people in the image, this caption might include their names,
190 | and/or their roles in any action taking place. If the image depicts a
191 | location, then it should describe the location.
192 |
193 | Description Example: _"The Shore Temple of the Seven Pagodas was built
194 | under Narsimha II of the Pallava dynasty between 7th and 8th century
195 | AD and is dedicated to Lord Shiva. It resembles the structure of the
196 | Dharmaraja rath, but its tower rises much higher (approx. five stories
197 | or ~ 60 ft. high) and its stupa spire is small and slender."_
198 |
199 | #### Headline
200 |
201 | A headline is a brief, publishable synopsis or summary of the contents
202 | of the photograph. Like a news story's lead, the Headline should grab
203 | attention and summarize the image's content. Headlines must be
204 | succinct. Leave any supporting narrative for the Description field. Do
205 | not, however, confuse the Headline term with Title.
206 |
207 | Headline Example: _"Shore Temple, Malibalipuram, India"_
208 |
209 | ### IPTC Summary
210 |
211 | So, it sounds like, in theory, "Title" is supposed to be the title of
212 | the document, like a filename and would be where we jot down typical
213 | comments. HOWEVER: Microsoft Windows uses "Title" as the Caption and
214 | Flickr uses "Title" as the Headline. So, YMMV.
215 |
216 | For now, vv does not alter IPTC and only allows setting the "Comment"
217 | field using the `C` key`. However, the editproperty function should
218 | work once we figure out what the right field to edit is.
219 |
220 |
--------------------------------------------------------------------------------
/README.md.d/avatar.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hackerb9/vv/948c8ca5fe026df8faedad218864fb2da3b05709/README.md.d/avatar.png
--------------------------------------------------------------------------------
/README.md.d/vv.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hackerb9/vv/948c8ca5fe026df8faedad218864fb2da3b05709/README.md.d/vv.gif
--------------------------------------------------------------------------------
/vv:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # vv: VT View
4 |
5 | # Version 1.9.4
6 | # B9 November 2024
7 |
8 | # Use sixel graphics to show images inside a terminal (e.g., xterm).
9 | # Copyright (c) 2019..2024 hackerb9, under the terms of GNU GPL 3+.
10 |
11 | # Some nice features:
12 | # * Can display any image type. (Via ImageMagick).
13 | # * Detects images by magic, not by extension.
14 | # * Shows everything in the current working directory by default.
15 | # * Loads directories recursively (default: ask; -r: always; -R: never).
16 | # * Scales down large images to fit within terminal.
17 | # * Defaults to fast viewing [-F] to quickly preview and delete (d) images,
18 | # or use [-f] to default to full-size (slower, high quality) view.
19 | # * Hit (f) to view full-size (slower, high quality) for current image only,
20 | # or use (F) to toggle between fast and full-size viewing mode.
21 | # * Preview size can be increased (+), decreased (-), set (=), or reset (0).
22 | # * Supports "fit width" (w) mode; portrait pictures scroll vertically.
23 | # * Can view at "100% zoom" (1). Cuts large picture into pieces, if necessary.
24 | # * Has "best fit" (B), autorotate to use as much of the screen as possible.
25 | # * Deleted (d) images are moved to Trashcan (Freedesktop standard).
26 | # * Can undo (u) last trashed file.
27 | # * Reverse image search using w3m (R). (Currently scrapes yandex).
28 | # * Slideshow mode (S).
29 | # * Renaming a file (r) uses readline for easier editing.
30 | # * Move (m) and save-a-copy (s) remember previously used directory.
31 | # * Edit embedded comments (C). Works with JPEG, PNG, TIFF, GIF, and more.
32 | # * Embedded comments can have multiple lines (use ^V^J for a new line).
33 | # * Sets xterm to use more color registers for higher quality pictures.
34 | # * Should work on true DEC hardware (e.g., VT340).
35 | # * Resizes current image when terminal resizes. (SIGWINCH).
36 | # * Pixel height of preview is a multiple of the current text font height,
37 | # so previews should be the right size no matter your screen resolution.
38 | # * Pixel width of preview can use the full width of the terminal.
39 | # * View videos (v) such as animated GIFs. (Requires 'sixvid' and ffmpeg).
40 | # * Icons and small images can be zoomed in to screen size. (z to toggle).
41 | # * Breadth first search. Images in current dir are shown before subdirs.
42 |
43 | # Required Dependencies:
44 | # * A sixel capable terminal, such as 'xterm -ti vt340'.
45 | # * ImageMagick
46 |
47 | # Recommended but not required:
48 | # * ncurses-bin (for tput)
49 | # * file (determine filetype by magic numbers rather than extension)
50 | # * mediainfo (quickly count number of frames in a video)
51 | # * GNU coreutils (for realpath, for deleting images to trashcan)
52 | # * curl, w3m and w3m-img for text based reverse image search
53 | # * Bash version >=5 (read bug workaround)
54 | # * sixvid & ffmpeg: VT viewer so viewing an mp4 will play an animation
55 | # * poppler-utils (for pdfinfo to count pages in PDF files)
56 |
57 | # Note: This is designed mainly for quickly previewing, deleting,
58 | # and renaming images over an ssh connection. For that reason,
59 | # fast, small, low-quality images are emphasized and deletion
60 | # is a single keystroke. (Note, undeletion is also a single key).
61 | #
62 | # Design:
63 | #
64 | # This should feel like a command-line program that just happens
65 | # to have graphics. In particular, it should *NOT* take over the
66 | # whole screen.
67 | #
68 | # Current work is appended at the bottom. Old images should
69 | # scroll off the top.
70 | #
71 | # Keep hands on home row. Allow harder to reach keys -- like Esc
72 | # and arrows -- only as aliases for easier to hit keys.
73 | #
74 | # Common functions are mapped to a single key, without shift.
75 | # The most frequently used functions are on the home row.
76 | # Less common functions may include shift.
77 | #
78 | # As much as possible, reduce repetitive work. (Temporal locality.)
79 | #
80 | # Go as fast as possible, trading off quality if necessary.
81 | #
82 | # Should work even over a laggy ssh connection with a vintage VT340.
83 | #
84 | # Unix keys ^C, ^Z, ^W, ^L act reasonably and do not mess up the terminal.
85 | #
86 | # The user isn't a dummy, don't hide info merely to seem simple.
87 | #
88 | # Reduce cognitive load:
89 | #
90 | # * User shouldn't have to memorize which boolean flags are set.
91 | # Show status every time an image is displayed.
92 | #
93 | # * Help should not be overwhelming. Give just the most salient
94 | # bits, with ways the user can ask for more help.
95 | #
96 | # * "Don't make me read." As much as possible, make the state
97 | # predictable so an expert could type keys without seeing the
98 | # prompts and know exactly how vv will react. (Note: This is
99 | # the opposite of current touch screen interfaces).
100 | #
101 |
102 | #
103 | # For more info or to report a bug, please see
104 | # https://github.com/hackerb9/vv
105 |
106 | # Defaults you can change.
107 | declare -g timeout=0.25 # Max secs to wait for control sequence response.
108 | declare -gi ssdelay=5 # Num secs to linger during slideshow.
109 | declare -g viewmode="fast" # Show "fast" or "full" images.
110 | declare -gi previewlines=8 # Height of fast preview image (in text lines).
111 | declare -g background="gray20" # Default for bg (alpha) if autodetection fails
112 | declare -g foreground="gray80" # Default for fg (text) if autodetection fails
113 | declare -g rflag="ask" # Empty string means do not recurse dirs.
114 | declare -g sortorder="-v" # `ls` flag to sort files in "natural" order.
115 | #declare -g sortorder="-tru" # `ls` flag to sort files. Least recent viewed.
116 | #declare -g sortorder="-t" # `ls` flag to sort files. Most recent changed.
117 | declare -g traversal="breadth" # dir recursion: breadth/depth first or neither.
118 | declare -g shownotices="y" # Show optional messages.("Install X to get Y").
119 | #declare -g shownotices="" # Empty string to never mention such frippery.
120 |
121 | # Defaults for image processing flags. Note that opposite of "y" is "", not "n".
122 | # To disable, set to empty string. To enable, set to any string.
123 | declare -g dither="y" # Improve image quality by dithering if viewmode==full.
124 | declare -g aalias="y" # Smooths jaggies when zooming in on small images.
125 | declare -g enhance="" # Lightens dark images with gamma +1.5. Set by (e)
126 | declare -g zoomin="y" # Magnify small images to screen size (slower).
127 |
128 | # Defaults if terminal autodetection fails.
129 | declare -gi numcolors=16 # Num colors the terminal can show.
130 | declare -gi defaultwidth=800 defaultheight=480 # Default sixel screen size.
131 |
132 | # Global variables
133 | declare -gi LINES COLUMNS # Screen width and height in rows, cols of text.
134 | declare -gi width height # Screen width and height in pixels.
135 | declare -gi fontheight # Height of terminal's font in pixels.
136 | declare -gi previewsize=0 # Height of preview in pixels. (C.f., previewlines, above)
137 | declare -gi forcepsize=0 # Size of preview, if given on commandline.
138 | declare -g tmpdir # Directory for storing temporary files.
139 | declare -gA termkey # Array to hold terminfo key input sequences.
140 | declare -g currentview=$viewmode # Most recently used viewmode.
141 | declare -gi FrameCount # Number of image frames in file. >1 for videos.
142 | declare -gi ImageWidth # Image width in pixels.
143 | declare -gi ImageHeight # Image height in pixels.
144 |
145 | # Debugging stuff
146 | declare -g DEBUG=${DEBUG} # Set to anything to enable debugging
147 | declare -g TIME= # Set to anything to benchmark sixel creation
148 |
149 |
150 | debug() {
151 | if [[ "${DEBUG:-}" ]]; then
152 | echo "$@" >&2
153 | fi
154 | }
155 |
156 | cleanup() {
157 | # If the user hits ^C, we don't want them stuck in SIXEL mode
158 | echo -n $'\e\\' # Escape sequence to stop SIXEL
159 | stty -F/dev/tty echo # Reset terminal to show input characters.
160 | stty -F/dev/tty icanon # Allow backspace to work again.
161 | stty -F/dev/tty sane # For bash 4.4's SIGWINCH-in-read bug
162 | echo -en "\r"; tput el # Clear line for prompt.
163 | tput rmkx # Disable terminal application key sequences
164 | tput cnorm # Show the cursor.
165 | [[ -d "$tmpdir" ]] && rm -r "$tmpdir" # Erase temporary files.
166 | exit 0
167 | }
168 | trap cleanup SIGINT SIGHUP SIGABRT EXIT
169 |
170 |
171 | usage() {
172 | cat <&2
195 | echo "$(basename $0): FATAL ERROR: $@" >&2
196 | }
197 |
198 | notice() {
199 | # Display a "notice" — a minor message, such as a missing
200 | # optional program that would improve functionality, but
201 | # isn't strictly required.
202 | if [[ "$shownotices" ]]; then
203 | echo >&2
204 | echo "$(basename $0): notice: $@" >&2
205 | fi
206 | }
207 |
208 |
209 | prerequisites() {
210 | # Check that all necessary programs are installed.
211 | local -i returncode=0
212 |
213 | # Critical dependencies which cause fatal errors
214 | if ! command -v convert >/dev/null; then
215 | error "Please install ImageMagick for convert and identify"
216 | returncode=1
217 | fi
218 |
219 | # Non-fatal errors that simply degrade performance or capability
220 | if ! command -v tput >/dev/null; then
221 | notice "Please install ncurses-bin for tput and infocmp"
222 | # 'tput el' is used to clear the line.
223 | # 'infocmp' is used to interpret the arrow key sequences.
224 | alias tput=true; alias infocmp=true
225 | fi
226 | if ! command -v file >/dev/null; then
227 | notice "Please install 'file' for autodetecting images by magic"
228 | alias file=fakefile
229 | fi
230 | if ! command -v mediainfo >/dev/null; then
231 | # Note cannot use 'alias' here because it is run in a subshell.
232 | mediainfo() { fakemediainfo "$@" ; }
233 | fi
234 | if ! command -v realpath >/dev/null; then
235 | notice "Please install GNU coreutils for realpath"
236 | # Note cannot use 'alias' here because it is run in a subshell.
237 | realpath() { fakerealpath "$@" ; }
238 | fi
239 | if ! command -v w3m >/dev/null || command -v w3m-img >/dev/null; then
240 | function w3m {
241 | notice "Please install w3m and w3m-img for reverse image search"
242 | }
243 | alias w3m-img=w3m
244 | fi
245 | if ! command -v curl >/dev/null; then
246 | notice "Please install curl for reverse image search"
247 | fi
248 | if ! command -v numfmt >/dev/null; then
249 | numfmt() { tr '\t' ' '; } # Only needed for nicely grouping thousands
250 | fi
251 | if ! command -v fmt >/dev/null; then
252 | fmt() { cat ; } # Only needed for wrapping long comments
253 | fi
254 | if ! command -v pdfinfo >/dev/null; then
255 | pdfinfo() {
256 | notice "Page count is slow. Please install pdfinfo (poppler-utils)."
257 | echo "Pages: $(identify "$1" | grep -c PDF)"
258 | }
259 | fi
260 | if command -v chrome >/dev/null; then
261 | dumpdom() { chrome --headless --dump-dom "$@"; }
262 | elif command -v chromium >/dev/null; then
263 | dumpdom() { chromium --headless --dump-dom "$@"; }
264 | else
265 | dumpdom() {
266 | notice "If yandex mistakes w3m for a bot, please install chrome to run headless javascript."
267 | curl "$@"
268 | }
269 | fi
270 | if [[ $BASH_VERSINFO -lt 5 ]]; then
271 | notice "Kludging read for Bash4"
272 | BASH4BUG="-e"
273 | else
274 | BASH4BUG=""
275 | fi
276 |
277 | if ! tmpdir=$(mktemp -d --tmpdir "$(basename $0).$$.XXXXXX"); then
278 | echo "Error: Could not create temporary directory! Disk full?" >&2
279 | returncode=1
280 | fi
281 |
282 | if [[ returncode -eq 0 ]]; then
283 | return 0
284 | else
285 | # Die on fatal errors
286 | exit $returncode
287 | fi
288 |
289 | }
290 |
291 | autodetect() {
292 | # Various terminal initialization and configuration routines.
293 |
294 | # Before querying the terminal, wait for it to be ready.
295 | waitforterminal
296 |
297 | # Don't show escape sequences the terminal doesn't understand.
298 | stty -echo # Hush-a Mandara Ni Pari
299 |
300 | # Don't consume backspace key before 'read'.
301 | stty -icanon
302 |
303 | # Hide the cursor so it doesn't dash around when we show the prompt.
304 | tput civis
305 |
306 | # Make sure the terminal supports sixel graphics.
307 | hassixelordie
308 |
309 | # Terminal color palette ("registers") autodetection.
310 | read numcolors < <(getnumcolors $numcolors)
311 |
312 | # BUG: ImageMagick 6.9 can't send more than 256 colors anyhow.
313 | [[ numcolors -le 256 ]] || numcolors=256
314 |
315 | # Don't dither if we have enough colors. (Dither adds +1s to processing).
316 | # BUG: Unfortunately, we have to always dither since max colors is 256.
317 | [[ numcolors -le 256 ]] && dither="yup" || dither=""
318 |
319 | # Detect terminal background color (for alpha channel).
320 | background=$(getbg)
321 |
322 | # Autodetect the sixel screen size .
323 | windowchange
324 |
325 | # Make terminfo keys valid so we can catch arrow keys.
326 | inittermkey
327 |
328 | # Configure readline for input with 'read -e'
329 | configreadline
330 | }
331 |
332 | getbg() {
333 | # Send the xterm escape sequence to get the background color of
334 | # the terminal. Terminal responds: $'\e]11;rgb:ffff/0000/ffff\e\\'.
335 | # Prints results as hexadecimal (16-bit per channel) in the form
336 | # #RRRRGGGGBBBB (useful for ImageMagick).
337 | local p=11 # 11 is bg, 10 is fg in escape sequence
338 |
339 | # wait for terminal to be ready (up to 5 seconds)
340 | waitforterminal 5
341 |
342 | # Check for reverse video
343 | IFS=";?$" read -a REPLY -s -t $timeout -d "y" -p $'\e[?5$p'
344 | if [[ $? -le 128 && ( ${REPLY[2]} == 1 || ${REPLY[2]} == 3 ) ]]; then
345 | # Reversed colors!
346 | p=10
347 | fi
348 |
349 | # Query the terminal background (or foreground) color.
350 | IFS=";:/" read -a REPLY -r -s -t $timeout -d "\\" -p $'\e]'$p$';?\e\\'
351 | if [[ $? -le 128 && ${REPLY[1]:-} =~ ^rgb ]]; then
352 | echo '#'${REPLY[2]}${REPLY[3]}${REPLY[4]%%$'\e'*}
353 | else
354 | echo $background
355 | fi
356 | }
357 |
358 | getfg() {
359 | # Send the xterm escape sequence to get the fg color of the terminal.
360 | local p=10 # 11 is bg, 10 is fg in escape sequence
361 |
362 | # wait for terminal to be ready (up to 5 seconds)
363 | waitforterminal 5
364 |
365 | # Check for reverse video
366 | IFS=";?$" read -a REPLY -s -t $timeout -d "y" -p $'\e[?5$p'
367 | if [[ ${REPLY[2]} == 1 || ${REPLY[2]} == 3 ]]; then
368 | # Reversed colors!
369 | p=11
370 | fi
371 |
372 | # Query the terminal background (or foreground) color.
373 | IFS=";:/" read -a REPLY -r -s -t $timeout -d "\\" -p $'\e]'$p$';?\e\\'
374 | if [[ ${REPLY[1]} =~ ^rgb ]]; then
375 | echo '#'${REPLY[2]}${REPLY[3]}${REPLY[4]%%$'\e'*}
376 | else
377 | echo $background
378 | fi
379 | }
380 |
381 | windowchange() {
382 | # SIGWINCH handler: Called when terminal window is resized.
383 | # Send control sequence to query the sixel graphics geometry to
384 | # find out how large of a sixel image can be shown.
385 | # Sets global variables LINES, COLUMNS, width, height, and fontheight.
386 | local IFS=""; unset IFS # In case IFS was set before SIGWINCH
387 | read width height < <(getwindowsize)
388 |
389 | # Calculate height of terminal font in pixels
390 | # Note: this could be wrong because xterm returns max == 1000x1000.
391 | # TODO: maybe use echo $'\e[16t' to get width, height of font.
392 | LINES=$(tput lines); COLUMNS=$(tput cols)
393 | [[ $LINES -gt 0 ]] || LINES=24 # Default 24 rows of text.
394 | fontheight=height/LINES
395 | [[ fontheight -gt 0 ]] || fontheight=20 # Default 20px high font.
396 | debug "font height is $fontheight"
397 |
398 | # Trim returned height so we have room for two lines of text
399 | height=$(( fontheight * (LINES-2) ))
400 | debug "usable screen height is $height"
401 |
402 | if [[ $forcepsize == 0 ]]; then
403 | # Preview size height changes based on font size.
404 | if [[ $previewsize -ne $((fontheight*previewlines)) ]]; then
405 | [[ $previewsize ]] && SHOULDREDRAW=yup
406 | previewsize=fontheight*previewlines
407 | debug "preview height = fontheight × preview lines = $fontheight × $previewlines = $previewsize"
408 | fi
409 | else
410 | # Preview size forced by command line.
411 | previewsize=$forcepsize
412 | fi
413 | debug "preview size is ${width}x${previewsize} pixels"
414 |
415 | if [[ "$viewmode" == full || "$currentview" == full ]]; then
416 | SHOULDREDRAW=yup # Redraw the current image
417 | fi
418 | }
419 | trap windowchange SIGWINCH
420 |
421 |
422 | hassixelordie() {
423 | # Returns true if terminal is Sixel capable.
424 | # Otherwise, prints an error message and dies.
425 | local hassixel="" code IFS=";?c"
426 |
427 | # IS TERMINAL SIXEL CAPABLE? # Send Device Attributes
428 | if read -a REPLY -s -t 1 -d "c" -p $'\e[c' >&2; then
429 | for code in "${REPLY[@]}"; do
430 | if [[ $code == "4" ]]; then
431 | hassixel=yup
432 | break
433 | fi
434 | done
435 | fi
436 |
437 | # YAFT is vt102 compatible, cannot respond to vt220 escape sequence.
438 | if [[ "$TERM" == yaft* ]]; then hassixel=yeah; fi
439 |
440 | if [[ -z "$hassixel" ]]; then
441 | cat <<-EOF >&2
442 | Error: Your terminal does not report having sixel graphics support.
443 |
444 | Please use a sixel capable terminal, such as xterm -ti vt340, or
445 | ask your terminal manufacturer to add sixel support.
446 |
447 | You may test your terminal by viewing a single image, like so:
448 |
449 | convert foo.jpg -geometry 800x480 sixel:-
450 |
451 | If your terminal actually does support sixel, please file a bug
452 | report at http://github.com/hackerb9/vv/issues
453 | EOF
454 | read -s -t 1 -d "c" -p $'\e[c' >&2
455 | if [[ "$REPLY" ]]; then
456 | echo
457 | cat -v <<< "(Please mention device attribute codes: ${REPLY}c)"
458 | fi
459 |
460 | exit 1
461 | fi
462 | }
463 |
464 |
465 | getnumcolors() {
466 | # Detects number of colors the terminal can show and attempts to
467 | # increase the number if it's too low.
468 | # Argument $1: default number of colors if detection fails.
469 | # Output: Prints how many color registers the terminal has.
470 | local -i n=0
471 | local IFS=";" # Split reads on semicolons
472 |
473 | if read -a REPLY -s -t ${timeout} -d "S" -p $'\e[?1;1;0S' >&2; then
474 | [[ ${REPLY[1]} == "0" ]] && n=${REPLY[2]}
475 | fi
476 | # YAFT is vt102 compatible, cannot respond to vt220 escape sequence.
477 | if [[ "$TERM" == yaft* ]]; then n=256; fi
478 |
479 | # Increase colors, if needed
480 | if [[ $n -lt 256 ]]; then
481 | # Attempt to set the number of colors to 256.
482 | # This will work for xterm, but fail on a real vt340.
483 | if read -a REPLY -s -t ${timeout} -d "S" -p $'\e[?1;3;256S' >&2; then
484 | [[ ${REPLY[1]} == "0" ]] && n=${REPLY[2]}
485 | fi
486 | fi
487 |
488 | # Return the results (or the default if querying didn't work)
489 | [[ $n -gt 0 ]] || n=${1:-16}
490 | echo $n
491 | return
492 | }
493 |
494 |
495 | getwindowsize() {
496 | # Send control sequences to find how large of a sixel image can be shown.
497 | # Uses globals $defaultwidth, $defaultheight if terminal does not respond.
498 | # Outputs geometry as width then height. (echo $w $h)
499 |
500 | waitforterminal # Wait for terminal to be ready before querying.
501 | # Necessary for Xterm-344 due to slow redraw bug.
502 |
503 | local -i w=0 h=0 # for reading width and height integers
504 | local IFS=";" # temporarily split on semicolons
505 | local REPLY=(0 0 0 0) # array of results from terminal
506 |
507 | # Send control sequence to query the sixel graphics geometry.
508 | if read -a REPLY -s -t ${timeout} -d "S" -p $'\e[?2;1;0S' >&2; then
509 | if [[ ${#REPLY[@]} -ge 4 && ${REPLY[2]} -gt 0 && ${REPLY[3]} -gt 0 ]]; then
510 | w=${REPLY[2]}
511 | h=${REPLY[3]}
512 | else
513 | # Nope. Fall back to dtterm WindowOps to approximate sixel geometry.
514 | waitforterminal
515 | if read -a REPLY -s -t ${timeout} -d "t" -p $'\e[14t' >&2; then
516 | if [[ $? == 0 && ${#REPLY[@]} -ge 3 && ${REPLY[2]} -gt 0 ]]; then
517 | w=${REPLY[2]}
518 | h=${REPLY[1]}
519 | fi
520 | fi
521 | fi
522 | fi
523 |
524 | # Discard responses slow to arrive responses from the terminal.
525 | flushstdin
526 |
527 | # Return the results (or the default if querying didn't work)
528 | [[ w -gt 0 ]] || w=${defaultwidth}
529 | [[ h -gt 0 ]] || h=${defaultheight}
530 | echo $w $h
531 | debug "window size is $w x $h"
532 | return
533 | }
534 |
535 | waitforterminal() {
536 | # Send an escape sequence and wait for a response from the terminal.
537 | # This routine will let us know when an image transfer has finished
538 | # and it's okay to send escape sequences that request results.
539 | # WARNING. This *should* work with any terminal, but if it fails
540 | # it'll end up waiting for approximately forever (i.e., 60 seconds).
541 | flushstdin
542 | read -s -t ${1:-60} -d "c" -p $'\e[c'
543 | flushstdin
544 | }
545 |
546 | inittermkey() {
547 | # Build termkey array so we can recognize when the user hits keys
548 | # that send multiple characters. E.g., \eOB maps to "Down Arrow".
549 | local a x k
550 |
551 | # To be valid, we must enable terminal application mode key sequences.
552 | if tput smkx; then
553 | for k in $(infocmp -L1 | grep -E 'key_|cursor_'); do
554 | a=""; x=""
555 | # Example "k: key_down=\EOB,"
556 | a=${k#*key_}
557 | a=${a#*cursor_}
558 | a=${a%=*} # a: down
559 | x=${k#*=}
560 | x=${x%,*} # x: \EOB
561 | #debug termkey["$x"]="$a"
562 | termkey["$x"]="$a"
563 | done
564 | fi
565 | }
566 |
567 | configreadline() {
568 | # Configure input from the user so that 'read -e' (readline) works.
569 | # Note, bind will complain that "line editing is not enabled", but
570 | # we toss that spurious warning in /dev/null.
571 |
572 | # Editing happens on only one line of text, scrolling horizontally.
573 | bind "set horizontal-scroll-mode on" 2>/dev/null
574 |
575 | # XXX If I knew how to disable readline adding a space after
576 | # filename completion I would do so here. (See saverenamemove()).
577 | }
578 |
579 | parseescape() {
580 | # Parse terminal escape sequence for F-keys, arrows.
581 | # Read all the characters following an escape key has been hit
582 | # and then look it up in the termkey array.
583 | while read -t 0; do
584 | read -n 1 -s temp
585 | REPLY+="$temp"
586 | done
587 | esc=$'\E'
588 | REPLY=${REPLY/$esc/\\E} # Replace escape with backslash E
589 | REPLY=${termkey["$REPLY"]:-"$REPLY"}
590 | }
591 |
592 | flushstdin() {
593 | # flush stdin in case a key was hit twice by accident
594 | local REPLY
595 | while read -s -n1 -t .001; do :; done
596 | }
597 |
598 | e() {
599 | # Clear current line and print text on it without a linefeed
600 | echo -en "\r"
601 | tput el
602 | echo -en "$(tildify "$*")" # Not using $@ so I can pass args to echo.
603 | }
604 |
605 | E() {
606 | # Clear current line and print text on it with a linefeed
607 | e "$@"
608 | echo
609 | }
610 |
611 | tildify() {
612 | # Any arguments that look like $HOME/ get shortened to ~/
613 | local arg
614 | for arg; do
615 | arg=${arg/#$HOME\//\~/} # At beginning of line.
616 | arg=${arg// $HOME\// \~/} # After a space.
617 | arg=${arg//\n$HOME\//\n\~/} # After a newline escape.
618 | arg=${arg//\t$HOME\//\t\~/} # After a tab escape.
619 | arg=${arg// $HOME\// \~/} # After a tab.
620 | echo -n "$arg"
621 | done
622 | echo
623 | }
624 |
625 | s() {
626 | # Plural(s)
627 | [[ ${1%.*} -ne 1 ]] && echo -n "s"
628 | }
629 |
630 |
631 | declare -g lastuseddir="" # Static variable for default save/move dir.
632 | saverenamemove() {
633 | # Interactively save/rename/move image file $2 to a new name or dir.
634 |
635 | # "save" and "move" default to prompting for a directory name,
636 | # presuming the filename will be the same.
637 |
638 | # "rename" defaults to prompting for a filename, presuming the
639 | # directory will be the same.
640 |
641 | # Move and rename both use 'mv', so are functionally equivalent.
642 | # Move prompts with a directory, rename suggests a filename.
643 | # They both set outer scope "$f", which may be a bad idea.
644 | # (This allows user to rename again if need be.)
645 | # [TODO: This will get cleared up once we have a proper array of files.]
646 |
647 | local mode="$1"
648 | local file="$2"
649 |
650 | if [[ "$mode" == "rename" ]]; then
651 | local path=$(realpath --relative-base="$PWD" "$file")
652 | else
653 | local path=$(realpath "$file")
654 | fi
655 | local dir=$(dirname "$path")
656 | local ext=${f##*.}; [[ "$f" != "$ext" && "$ext" != */* ]] || ext=""
657 | local base=$(basename "$file" ".$ext")
658 | local IFS=$'\n' # Tildify shouldn't split on spaaces
659 | tput el
660 | stty echo # Temporarily show characters the user types.
661 | tput cnorm # Temporarily show the cursor.
662 | if [[ "$mode" == "rename" ]]; then
663 | read -d $'\r' -p "Rename to: " -e -i "$(tildify "$path")" newname
664 | elif [[ "$mode" == "save" ]]; then
665 | read -d $'\r' -p "Save a copy of $base in: " -e \
666 | -i "$(tildify "${lastuseddir:-$dir}/")" newname
667 | else
668 | read -d $'\r' -p "Move to: " -e -i "$(tildify "${lastuseddir:-$dir}/")" newname
669 | fi
670 | tput civis # Hide cursor.
671 | stty -echo # Hide input keys.
672 |
673 | newname=${newname/#~\//$HOME/} # untildify (for realpath.)
674 |
675 | # Remove trailing space from tab completion.
676 | if [[ "${newname}" =~ (.*[^ ])([ ]+)$ ]]; then
677 | newname="${BASH_REMATCH[1]}"
678 | fi
679 |
680 | if [[ $mode == "save" || $mode == "move" ]]; then
681 | [[ "$newname" == /* ]] || newname="$dir/$newname" # Make path absolute.
682 | fi
683 | [[ -d "$newname" ]] && newname+="/." # Use existing directory.
684 | [[ "$newname" != */ ]] || newname+="." # Never end with a "/" (for dirname.)
685 | mkdir -p "$(dirname "$newname")"
686 | newname=$(realpath "$newname" 2>/dev/null) # Canonicalize
687 |
688 | if [[ "$newname" && "$newname" != "$dir" && ! "$newname" -ef "$path" ]]
689 | then
690 | if [[ -d "$newname" ]]; then
691 | # New directory specified, so keep same filename
692 | newname="$newname/$base"
693 | fi
694 |
695 | local newext="${newname##*.}"
696 | if [[ "$newext" =~ jpe?g && "$ext" =~ jpe?g ]]; then
697 | # Special case: Allow renaming .jpg to .jpeg and vice-versa.
698 | ext="$newext"
699 | fi
700 |
701 | if [[ "$newname" != *"$ext" ]]; then
702 | # User specified filename without the extension.
703 | newname="$newname.$ext"
704 | fi
705 |
706 | local overwrite=""
707 | if [[ -e "$newname" ]]; then
708 | # Hmm... a file of that name already exists.
709 | if cmp -s "$path" "$newname"; then
710 | E "Notice: image already saved in $newname."
711 | return 1
712 | else
713 | E "Warning: A different image already exists with that filename."
714 | sidebyside "$path" "$newname"
715 | overwrite="(overwrite!) "
716 | fi
717 | fi
718 |
719 | # Extra warning to double check dangerous operations.
720 | if [[ "$overwrite" ]]; then
721 | # Okay to save/rename/move (possibly overwriting)?
722 | e "$mode $file to $overwrite$newname (y/N)? "
723 |
724 | read -s -n1
725 | case "$REPLY" in
726 | y|Y) # Yes, just continue.
727 | ;;
728 | n|N|*)
729 | E "$mode cancelled."
730 | return 1
731 | ;;
732 | esac
733 | fi
734 |
735 | if [[ $mode == "save" ]]; then
736 | if cp -p "$path" "$newname"; then
737 | E "Saved a copy of $file to $newname"
738 | else
739 | return 1
740 | fi
741 | elif [[ $mode == "rename" || $mode == "move" ]]; then
742 | if mv "$file" "$newname"; then
743 | E "Filename is now $newname";
744 | f="$newname" # Write to outerscope variable "$f". (!!!)
745 | else
746 | E "Failed: filename is still \"$file\""
747 | return 1
748 | fi
749 | fi
750 | else
751 | E "$mode cancelled."
752 | return
753 | fi
754 |
755 | if [[ $mode == "save" || $mode == "move" ]]; then
756 | # Remember the directory for easy saving next time.
757 | lastuseddir=$(dirname "$newname")
758 | fi
759 |
760 | return
761 | }
762 |
763 |
764 |
765 | sidebyside() {
766 | # Show two images side by side for quick comparison.
767 | local -i half=width/2
768 | montage -background $background -fill $foreground \
769 | -auto-orient \
770 | -geometry ">${half}x>$((height-fontheight))" \
771 | -label "$1" "$1" -label "$2" "$2" sixel:-
772 | SHOULDREDRAW=yup
773 | }
774 |
775 | editproperty() {
776 | # Given a property name and a filename,
777 | # show the property and let the user edit it.
778 | # Example property names: "comment", "caption", "title", "description"
779 | local propname="$1"
780 | local file="$2"
781 | local frame0="file://$file[0]" # Without file://, IM barfs on colons.
782 | local property=$(identify -format "%[$propname]" "$frame0" 2>/dev/null)
783 | local prompt="New $propname: "
784 |
785 | if [[ $(echo "$property" | wc -l) -gt 1 ]]; then
786 | prompt=""
787 | echo "WARNING: Existing $propname has multiple lines."
788 | echo " Use ^V^J to add new lines."
789 | fi
790 |
791 | stty echo # Temporarily show characters the user types.
792 | tput cnorm # Temporarily show the cursor.
793 | IFS= read -d $'\r' -e -i "$property" -p "$prompt" newproperty
794 | tput civis # Hide cursor.
795 | stty -echo # Hide input keys.
796 |
797 | if [[ "$newproperty" == "$property" || -z "$newproperty" ]]; then
798 | E "$propname editing cancelled."
799 | return
800 | fi
801 |
802 | e "Writing comment into $file..."
803 | local t=$(mktemp "/tmp/$(basename $0).XXXXXX") || return 1
804 | cp "$file" "$t" && convert "$t" -set "$propname" "$newproperty" "$file"
805 | rm "$t"
806 | }
807 |
808 | showproperty() {
809 | # Given a property name (e.g., "comment") and a filename,
810 | # Show the property. Return failure if the property doesn't exist.
811 | local propname="$1"
812 | local file="$2"
813 | local frame0="file://$file[0]"
814 | local property=$(identify -format "%[$propname]" "$frame0" 2>/dev/null) &&
815 | echo "$propname: $property"
816 | }
817 |
818 | reverseimagesearch() {
819 | # Given a filename of an image, do a web search for it to see if
820 | # it has been seen anywhere else.
821 |
822 | # Tip to future self: to screen scrape XHR / JSON, use Firefox's
823 | # Network inspector while uploading image to search engine. Right
824 | # click on the POST or GET and go to "COPY cURL". Then, from the
825 | # command line, prune that command down to the bare minimum.
826 | # Use json_pp to pretty print JSON data.
827 |
828 | yandeximagesearch "$1"
829 | }
830 |
831 | yandeximagesearch() {
832 | # Reverse image search using yandex and w3m
833 | # Yandex is not the best but has a simple interface we can access
834 | # (Unlike Tineye, Bing, and Google). Yandex does require
835 | # javascript, so we use 'chrome --dump-dom' to retrieve the html.
836 | local file="$1"
837 | local output resultPage deleteme="" # Local vars
838 | local scale=">1000x>1000" # Image size to scale to before searching.
839 | tput cnorm # Temporarily show cursor for w3m
840 |
841 | if [[ $FrameCount -gt 1 ]]; then
842 | # It's a video, so search only for first frame.
843 | echo "searching only first frame of video" >&2
844 | file="$tmpdir/frame0.jpg"
845 | convert "file://$1[0]" "$file"
846 | deleteme="$file"
847 | fi
848 |
849 | url="https://yandex.com/images/search?rpt=imageview"
850 | url+="&format=json"
851 | url+='&request=%7B%22blocks%22%3A%5B%7B%22block%22%3A%22cbir-controller__upload%3Aajax%22%7D%5D%7D'
852 | cookie=""
853 |
854 | # Upload the image and save the output to search through.
855 | # Note: Curl's "@filename" splits filenames with commas & semicolons.
856 | output=$(convert -sample "$scale" "$file" jpeg:- |
857 | curl --max-time 30 --cookie "$cookie" \
858 | --form upfile='@-;filename=foo.jpg' $url)
859 | if [[ $? -gt 0 ]]; then return; fi
860 |
861 | # First, check for Content-Based Image Recognition.
862 | # Look for "params":{"url":"cbir_id=4725%2FkrTprMr_05694&rpt=imageview"
863 | resultPage=$(echo "$output" | grep -o '"cbir_id=[^"]*"' )
864 | if [[ "$resultPage" ]]; then
865 | resultPage=${resultPage#\"}; resultPage=${resultPage%\"}
866 | resultPage="/images/search?$resultPage"
867 | fi
868 |
869 | if [[ -z "$resultPage" ]]; then
870 | echo "Couldn't find CBIR result from Yandex, trying img_url." >&2
871 | # Look for, eg: "nextPageUrl":"/images/search?text=&img_url=https%3A//www.fotopolis.pl/i/images/4/2/3/d2FjPTIzNDB4MQ%3D%3D_src_179423-1555946732rlzp7d96a9729_2048px22_1100mv.jpg&rpt=imagedups"
872 | resultPage=$(
873 | echo "$output" |
874 | sed -rn '
875 | s/&/\&/g;
876 | s/.*img_url=(http[^"&;]*).*/\1/p;
877 | ')
878 | if [[ "$resultPage" ]]; then
879 | echo "Oh good, img_url worked." >&2
880 | resultPage="/images/search?url=$resultPage&rpt=imageview"
881 | fi
882 | fi
883 |
884 |
885 | if [[ "$resultPage" ]]; then
886 | echo "Found yandex.com/$(unuriescape "$resultPage")" >&2
887 | dumpdom https://yandex.com$resultPage |
888 | sed 's|||' > "$tmpdir/yandex.html"
889 | w3m "$tmpdir/yandex.html"
890 | rm "$tmpdir/yandex.html" 2>/dev/null
891 | else
892 | echo "Error parsing results from Yandex." >&2
893 | fi
894 |
895 | # Old way. Maybe delete this.
896 | ## Use cookies to get page, then show in w3m
897 | # curl --cookie "$cookie" --form upfile=@"$file" $url | tee debug |
898 | # sed 's###' |
899 | # w3m -T text/html
900 |
901 | if [[ "$deleteme" ]]; then
902 | rm -f "$deleteme"
903 | fi
904 |
905 | tput civis # Hide cursor again
906 | }
907 |
908 | numframes() {
909 | # Given a filename, print the number of images in the file.
910 | # (For most images, this will be 1.)
911 | local file="$1"
912 |
913 | # ImageMagick can count frames in a gif or apng, but doesn't do well when
914 | # faced with a video. Rely on mediainfo/ffprobe instead.
915 | case $(mimetype "$file") in
916 | video/*) # («Radio killed?»)
917 | # MediaInfo is faster than convert, but doesn't handle GIF, APNG.
918 | mediainfo --Inform='Video;%FrameCount%' "$file"
919 | ;;
920 | *|image/*) # An image file. (default)
921 | shopt -s nocasematch
922 | if [[ $file == *gif || $file == *png ]]; then
923 | # Note, it is much faster to pipe to 'wc' than to use
924 | # `convert "$file[-1]" -format "%[scene]" info:-`
925 | identify "$file" | wc -l
926 | else
927 | echo 1
928 | fi
929 | shopt -u nocasematch
930 | ;;
931 | esac
932 | }
933 |
934 | fakemediainfo() {
935 | notice "Please install 'mediainfo' for counting video frames"
936 |
937 | # If mediainfo isn't installed, fake it using ffprobe.
938 | # This is slow and could take a quarter of a second to run.
939 | # (Mediainfo takes only a twentieth of a second.)
940 | while [[ $1 == -* ]]; do shift; done
941 |
942 | # Although the ffprobe documentation claims to have a -count_frames option,
943 | # it doesn't actually work. We must resort to an ugly kludge:
944 | # print everything and count the word "video".
945 | ffprobe -show_packets "$1" 2>/dev/null | grep -c video
946 | }
947 |
948 | fakerealpath() {
949 | if [[ "$1" == -* ]]; then
950 | notice "Please install GNU coreutils for realpath"
951 | while [[ "$1" == -* ]]; do shift; done
952 | fi
953 | [[ "$1" && "$1" != /* ]] && echo -n "$PWD/"
954 | echo "$1"
955 | }
956 |
957 |
958 | isimage() {
959 | # Returns true (0) if $1 is an image or video.
960 |
961 | # We use "file" first to check for magic cookies identifying images to
962 | # prune out formats that ImageMagick's "identify" would churn needlessly
963 | # turning into an image (ASCII text, word processing docs).
964 | local file="$1"
965 | local type=$(mimetype "$file")
966 |
967 | if [[ $type == image/svg* ]]; then
968 | # SVG files are special: ImageMagick might call inkscape which is slow.
969 | # if identify "msvg:$file[0]" >/dev/null 2>&1; then
970 | # return 0
971 | # else
972 | return 1
973 | # fi
974 | elif [[ "$file" == *sixel ]]; then
975 | # The magic database doesn't know sixel files yet, so go by fileext.
976 | return 0
977 | elif [[ $type == image/* ]]; then
978 | # Return true for an image.
979 | if identify "file://$file[0]" >/dev/null 2>&1 \
980 | || identify "$file" >/dev/null 2>&1; then
981 | return 0
982 | fi
983 | elif [[ $type == application/pdf || $type == application/postscript ]]; then
984 | # We could pretend PDFs are images by returning 0 here.
985 | # But, they ought to be treated like directories which the
986 | # user is asked if they wish to open.
987 | return 1
988 | elif [[ $type == application/dicom ]]; then
989 | # ImageMagick can view DICOM (Medical Imaging Data)
990 | return 0
991 | elif [[ $type == video/* ]]; then
992 | # Return true for videos.
993 | if mediainfo "$file" >/dev/null 2>&1; then
994 | return 0
995 | fi
996 | fi
997 |
998 | # Not viewable, return false.
999 | return 1
1000 | }
1001 |
1002 | trim() {
1003 | # Chop leading and trailing spaces from named variables.
1004 | local IFS; unset IFS
1005 | for var; do
1006 | read -rd '' $var <<<"${!var}"
1007 | done
1008 | }
1009 |
1010 | imageinfo() {
1011 | # Show name of image plus width, height, etc.
1012 | # This is called every time a new image is shown.
1013 | # Sets global variables FrameCount, ImageWidth, ImageHeight.
1014 | # If file is invalid, returns 1 (FALSE in Bourne shell).
1015 | local file="$1"
1016 | local type=$(mimetype "$file")
1017 | local key value
1018 | FrameCount=0
1019 |
1020 | # Kludge since magic database doesn't recognize sixel file format yet.
1021 | if [[ "$file" =~ \.six(el)?$ ]]; then
1022 | type=image/x-sixel
1023 | fi
1024 |
1025 | # Based on the filetype, detect parameters and print info.
1026 | case $type in
1027 | image/*|application/dicom)
1028 | # NB: Running sed repeatedly is faster than "identify -format".
1029 | local id=$(identify "$file[0]" 2>/dev/null)
1030 | # sample.miff MIFF 100x100 3072x2304+1486+1102 8-bit Palette sRGB 33c 33507B 0.000u 0:00.000
1031 | local wxh=$(sed -rn 's/.* ([0-9]+x[0-9]+) .*/\1/p' <<<$id)
1032 | local bitdepth=$(sed -rn 's/.* ([0-9]+-bit) .*/\1/p' <<<$id)
1033 | local colorspace=$(sed -rn 's/.*-bit ([^0-9]+) .*/\1/p' <<<$id)
1034 | local colors=$(sed -rn 's/.* ([0-9]+c) .*/\1/p' <<<$id)
1035 | ImageWidth=${wxh%x*}; ImageHeight=${wxh#*x}
1036 | echo -n " $wxh $bitdepth $colorspace $colors"
1037 | FrameCount=$(numframes "$file")
1038 | [[ $FrameCount -gt 1 ]] && echo -n " $FrameCount frames"
1039 | ;;
1040 | # NOTE: I used sed because identify -format can be very slow.
1041 | # For example, %w is fine, but %[width] takes 30x longer.
1042 | # Also slow: %z, %[bit-depth], %r, %[colorspace].
1043 |
1044 | application/pdf)
1045 | declare -A info
1046 | while IFS=: read key val
1047 | do
1048 | trim key val
1049 | info["$key"]="$val"
1050 | done < <(pdfinfo "$file")
1051 | local p=${info["Pages"]:-1}
1052 | local s=${info["Page size"]:-}
1053 | local t=${info["Title"]:-}
1054 | echo -n " $p page$(s $p)${s:+, }$s${t:+, }$t"
1055 | FrameCount=1 # Fake a FrameCount, else image will not be shown.
1056 | ImageWidth=0; ImageHeight=0; # Fake width and height
1057 | ;;
1058 |
1059 | application/postscript)
1060 | FrameCount=1 # Fake a FrameCount, else image will not be shown.
1061 | ImageWidth=0; ImageHeight=0; # Fake width and height
1062 | ;;
1063 |
1064 | video/*)
1065 | local -A a=(["Width"]= ["Height"]= ["Frame rate"]= ["Duration"]=)
1066 | local IFS=$'\n'
1067 | for line in $(mediainfo "$file"); do
1068 | key=${line%:*}
1069 | value=${line#*:}
1070 | trim key
1071 | trim value
1072 | a[$key]="$value"
1073 | done
1074 |
1075 | # Cleanup "1 366 pixels" -> "1366".
1076 | a["Width"]="${a["Width"]% pixels}"
1077 | a["Height"]="${a["Height"]% pixels}"
1078 | a["Width"]="${a["Width"]// }" # Mediainfo puts spaces in numbers!
1079 | a["Height"]="${a["Height"]// }"
1080 |
1081 | # Set global variables.
1082 | FrameCount=$(mediainfo --Inform='Video;%FrameCount%' "$file")
1083 | ImageWidth=${a["Width"]}
1084 | ImageHeight=${a["Height"]}
1085 |
1086 | # Okay, finally show the video info.
1087 | echo -n ${ImageWidth}x${ImageHeight} pixels, " "
1088 | echo -n ${FrameCount} frame$(s $FrameCount), " @"
1089 | echo -n ${a["Frame rate"]% FPS*} "fps, " ${a["Duration"]}.
1090 | ;;
1091 |
1092 | application/zip|application/rar|application/tar|application/7z)
1093 | case "$file" in
1094 | *.cb?|*.CB?)
1095 | echo -e " - ComicBook archives not supported (yet).\n"
1096 | return 1
1097 | ;;
1098 | *)
1099 | echo -e " - Skipping filetype '$type'.\n"
1100 | return 1
1101 | ;;
1102 | esac
1103 | ;;
1104 | *)
1105 | echo -e " - Skipping filetype '$type'.\n"
1106 | return 1
1107 | ;;
1108 | esac
1109 |
1110 | if [[ $FrameCount -eq 0 ]]; then
1111 | e "No images in $file\r"
1112 | return 1
1113 | else
1114 | echo # New line for sixel image to start at.
1115 | return 0
1116 | fi
1117 | }
1118 |
1119 | mimetype() {
1120 | # Given an image filename, report its MIME type. (e.g., "image/jpeg").
1121 | local type=$(file --mime-type --brief --dereference -- "$file")
1122 |
1123 | # Rarely, some file formats will not have a good MIME type.
1124 | if [[ $type == application/octet-stream ]]; then
1125 | case $file in
1126 | *miff|*MIFF) type="image/miff" ;; # ImageMagick.
1127 | *rgb|*RGB) type="image/sgi" ;; # SGI RLE color.
1128 | *bw|*BW) type="image/sgi" ;; # SGI RLE bw.
1129 | esac
1130 | fi
1131 | echo "$type"
1132 | }
1133 |
1134 | id() {
1135 | # Identify an image tersely, but more verbosely than imageinfo.
1136 | # Relies on imageinfo already having been called to set FrameCount.
1137 | local f="$1"
1138 | local size=$(du -h "$f")
1139 | size=${size%%$'\t'*}
1140 | local rp=$(realpath "$f")
1141 | if [[ $rp =~ ^$HOME ]]; then
1142 | rp=${rp/$HOME/\~} # Replace /home/username with ~
1143 | fi
1144 | echo -n "$rp: "
1145 | local format="%wx%h %m, ${size}B"
1146 | # format+=", %[colors] colors" # Calculated (too slow?)
1147 | format+="\n"
1148 | if [[ "$f" != *svg ]]; then
1149 | identify -format "$format" "file://$f[0]"
1150 | else
1151 | identify -format "$format" "msvg:$f[0]"
1152 | fi
1153 | local comment=$(identify -format "%[comment]" "file://$f[0]" 2>/dev/null)
1154 | if [[ "$comment" ]]; then
1155 | echo "Comment: $comment" | fmt -w "${COLUMNS:-75}" -s
1156 | fi
1157 | }
1158 |
1159 | fakefile() {
1160 | # A fake version of file that doesn't use magic cookies or look
1161 | # inside the file at all. Instead, it just considers the filename
1162 | # and returns "image/emagi" if the filename has a well-known
1163 | # extension (e.g., "bar.jpg"). [Note: "Emagi" are the magicians
1164 | # of the matrix and the makers of magic cookies.]
1165 | while [[ $1 == -* ]]; do shift; done
1166 |
1167 | ext=${1##*.}
1168 | shopt -s nocasematch
1169 | case "$ext" in
1170 | six|sixel|miff|mvg|\
1171 | jpg|jpeg|jp2|jpx|\
1172 | png|apng|gif|tif|tiff|\
1173 | webp|\
1174 | svg|eps|ps|pdf|psd|\
1175 | heif|jxr|jpeg2000|avif|\
1176 | raw|dng|\
1177 | pnm|ppm|pbm|xpm|xbm|\
1178 | pcx|sgi|yuv|dcx|dpx|avs|palm|pcd|pcds|fits|cin|\
1179 | targa|tga|\
1180 | macpaint|mac|pntg|pict|pic|\
1181 | amigapaint|iff|ilm|ilbm|lbm|\
1182 | bmp|ico|icon)
1183 | echo "image/$ext"
1184 | ;;
1185 | mp4|webm|mkv|avi|\
1186 | ogm|ogv|vp8|\
1187 | mov|m4v|mp2|\
1188 | wmv|asf|flv|3gp)
1189 | echo "video/$ext"
1190 | ;;
1191 | *)
1192 | echo "who/knows"
1193 | ;;
1194 | esac
1195 | shopt -u nocasematch
1196 | }
1197 |
1198 | showimage() {
1199 | # Shows the file named in $1 using sixel.
1200 |
1201 | # Global variable $viewmode is (usually) either "full", which
1202 | # enlarges it to the full size of the terminal window, or it is
1203 | # "fast", which scales the image down, removes colors, and takes
1204 | # other shortcuts for the fastest preview.
1205 |
1206 | # Note that "full size" is not exactly the same as "full screen".
1207 | # In a terminal emulator, the sixel graphics are just a window.
1208 | # However, if the terminal emulator is then maximized (F11 key, often),
1209 | # vv will automatically rescale the image to use the entire space,
1210 | # minus two lines for the title and prompt.
1211 |
1212 | [[ "$1" ]] || echo "Error, showimage() called without filename">&2
1213 |
1214 | # Show filename and other info
1215 | e "$f\t"
1216 | imageinfo "$f" || return 1 # Return error if 0 frames in file.
1217 |
1218 | if [[ "$f" =~ \.six(el)?$ ]]; then
1219 | echo "Warning: ImageMagick may show blackness when scaling sixel images." >&2
1220 | fi
1221 |
1222 | # dorotate gets set if viewmode is best fit and rotating the image
1223 | # would allow us to see more of it on the screen.
1224 | local dorotate=""
1225 |
1226 | # Maybe use ">$width" in geometry to disable zooming on tiny images
1227 | local gt=""
1228 | if [[ "$zoomin" ]]; then gt=""; else gt=">"; fi
1229 |
1230 | # Centering an image can slow down convert by <200ms. XXX Worth it?
1231 | local centering="-gravity center -extent ${width}x${height}"
1232 |
1233 | # crop gets set in "fit width" mode, below.
1234 | local crop=""
1235 |
1236 | # -flatten is needed for transparent PNGs,
1237 | # but would interfere with fitwidth's -crop option.
1238 | local flatten="-flatten"
1239 |
1240 | # geometry for ImageMagick's -geometry flag.
1241 | local geometry="$gt${width}x$gt${height}"
1242 |
1243 | local extract="-extract >${width}x>${height}" # Speed up large images
1244 |
1245 | # Configure options based on viewmode
1246 | case $viewmode in
1247 | fast)
1248 | geometry="$gt${width}x${previewsize}"
1249 | ;;
1250 | full)
1251 | ;;
1252 | bestfit)
1253 | dorotate=$(mayberotate "$1")
1254 | if [[ "$dorotate" ]]; then
1255 | extract="-extract >${height}x>${width}"
1256 | fi
1257 | ;;
1258 | width)
1259 | # fit width fits image width to screen, but not height
1260 | geometry="$gt${width}x"
1261 | # Round crop down to the height of a line of text to avoid gaps
1262 | crop="-crop x$(( (height/fontheight) * fontheight ))"
1263 | # Disable centering's -extent
1264 | centering=""
1265 | # Disable flattening multiple layers
1266 | flatten=""
1267 | # Don't shrink to screen height, as we'll be showing multiple crops.
1268 | extract=${extract%x*}
1269 | ;;
1270 | *)
1271 | error "Unknown viewmode '$viewmode'"
1272 | exit 1
1273 | esac
1274 |
1275 | currentview=$viewmode # Remember last used viewmode.
1276 |
1277 | # Save the sixel output so we can clear "Processing..." message.
1278 | local output=""
1279 |
1280 | # OSC 8 URI linking so user can click on image to open it
1281 | local osc8uri="file://`hostname --fqdn``realpath "$1"`"
1282 | debug "OSC 8 URI link goes to $osc8uri"
1283 |
1284 | # All set let's show it.
1285 | case $viewmode in
1286 | full|width|bestfit) # Large, high quality and slow. (about 1 second)
1287 | e "preparing $viewmode"
1288 | # If antialiasing is off, use -sample to resize the image.
1289 | if [[ $aalias ]]; then resize=geometry; else resize=sample; fi
1290 |
1291 | echo -n "${dorotate:+, rotated}"
1292 | echo -n "${enhance:+, enhanced}"
1293 | echo -n "${dither:+, dithered}"
1294 | echo -n "${aalias:+, antialiased}"
1295 | echo -en " view...\r"
1296 | output=$( ${DEBUG:+debugdo} ${TIME} \
1297 | convert -background $background -auto-orient ${dorotate} \
1298 | $extract \
1299 | -$resize "$geometry" \
1300 | $crop \
1301 | ${enhance:+-channel rgb -auto-level -gamma 1.5} \
1302 | +dither ${dither:+-dither floyd-steinberg} \
1303 | $centering \
1304 | -colors $numcolors \
1305 | "file://$1[0]" \
1306 | $flatten \
1307 | sixel:-)
1308 | # Note: -crop is used by fitwidth and interferes with -flatten.
1309 | ;;
1310 | *|fast) # Fast and cruddy
1311 | echo -en "preparing fastest preview\r" # About 0.15 seconds
1312 | if [[ $aalias ]]; then resize=geometry; else resize=sample; fi
1313 | # Note that -sample is faster for large images, but super cruddy.
1314 | # 3,000,000 pixels empirically found as where time benefit began.
1315 | [[ ImageWidth*ImageHeight -lt 3000000 ]] || resize=sample
1316 |
1317 | output=$(
1318 | echo -en "\e]8;;${osc8uri}\e\\" # Begin OSC 8 URI linking
1319 | ${DEBUG:+debugdo} ${TIME} \
1320 | convert "file://$1[0]" \
1321 | -auto-orient \
1322 | -$resize "$geometry" \
1323 | +repage -background $background \
1324 | -flatten +dither -colors $numcolors \
1325 | sixel:-
1326 | echo -en "\e]8;;\e\\" # End OSC 8 URI linking
1327 | )
1328 | # Note: -flatten and -background is needed for transparency.
1329 | # Note: +repage is needed for images with virtual canvases.
1330 | # Note: +dither (disable dither) saves ~200ms sixel creation time.
1331 | # Note: -colors 256 saves another ~200ms sixel creation time.
1332 | ;;
1333 | esac
1334 | tput el
1335 | if [[ "$output" ]]; then
1336 | local ST=$'\e\\\\' # String Terminator is Esc \.
1337 | echo -n "$output" | sed "s/-${ST}/${ST}\n/g" # (sed kludge for bug in IM 6.9.12)
1338 | SHOULDREDRAW="" # Reset redraw flag until SIGWINCH trips it
1339 | else
1340 | # Error. ImageMagick must have failed as $output is empty.
1341 | return 1
1342 | fi
1343 | return
1344 | }
1345 |
1346 | mayberotate() {
1347 | # Checks global variables $ImageWidth and $ImageHeight
1348 | # against the screen size in $width x $height.
1349 | # Prints "-rotate +90" if the image should be rotated to best fit
1350 | # in the current screen. Prints nothing otherwise.
1351 | if [[ $ImageHeight == $ImageWidth || $height == $width ]]; then
1352 | return
1353 | fi
1354 | if [[ -z "$zoomin" \
1355 | && $ImageHeight -le $height \
1356 | && $ImageWidth -lt $width ]]; then
1357 | # Small enough to fit in screen and not enlarging.
1358 | return
1359 | fi
1360 |
1361 |
1362 | local iorient=$((ImageHeight > ImageWidth))
1363 | local sorient=$((height > width))
1364 | if [[ $iorient != $sorient ]]; then
1365 | echo "-rotate +90"
1366 | fi
1367 | }
1368 |
1369 |
1370 | showprompt() {
1371 | if [[ $COLUMNS -lt 80 ]]; then
1372 | e "vv: " # Terse prompt
1373 | else
1374 | # Show long prompt after image.
1375 | echo -en "\r"
1376 | echo -n "Press space to keep, 'd' to delete, "
1377 | if [[ FrameCount -gt 1 ]]; then
1378 | echo -n "'v' for video, "
1379 | elif [[ $currentview != full ]]; then
1380 | echo -n "'f' for full, "
1381 | fi
1382 | echo -n "'h' for help, 'q' to quit."
1383 | tput el
1384 | fi
1385 | }
1386 |
1387 |
1388 |
1389 | declare -ig recursionlevel=0 # How many times doit() has called itself.
1390 | declare -g abortrecursion="" # Used to pop back up to the top level dir.
1391 | declare -g poprecursion="" # Used by checkrflag to pop up one level.
1392 | declare -g slideshow="" # Gets set to "yes" when running slideshow.
1393 | doit () {
1394 | # For every file, show it and ask what is to be done.
1395 | # This is the main loop of the program.
1396 | # With "-r", doit() calls itself recursively for subdirectories.
1397 | for f; do
1398 | if [[ "$abortrecursion" ]]; then
1399 | if [[ $recursionlevel -gt 1 ]]; then
1400 | recursionlevel=recursionlevel-1
1401 | return
1402 | else
1403 | abortrecursion=""
1404 | fi
1405 | fi
1406 |
1407 | # Found a directory, so maybe recurse
1408 | if [[ -d "$f" && ! -L "$f" ]]; then
1409 | # Allow Enter key to switch recursion flag to 'ask'.
1410 | if [[ $rflag ]] && read -t 0; then
1411 | rflag="ask"
1412 | fi
1413 |
1414 | f=$(echo "$f" | tr -s /) # Squeeze repeated /// to single /.
1415 | f=${f%/} # No / at end.
1416 |
1417 | # Recurse if directory was specified on command line or rflag≅yes.
1418 | if [[ $recursionlevel -eq 0 ]] || checkrflag "$f/"; then
1419 | e "$f/"
1420 | recursionlevel=recursionlevel+1
1421 | mapfile -t < <(sortrecur "$f"/*)
1422 | doit "${MAPFILE[@]}"
1423 | continue
1424 | else
1425 | # Special case for checkrflag: user hit 'x' to exit recursion.
1426 | if [[ "$poprecursion" ]]; then
1427 | poprecursion=""
1428 | recursionlevel=recursionlevel-1
1429 | return
1430 | fi
1431 | fi
1432 | fi
1433 | [[ -f "$f" ]] || continue;
1434 |
1435 | # Skip non-image files discovered through recursion.
1436 | # (Always attempts to show files specified on command line).
1437 | if [[ recursionlevel -gt 0 ]] && ! isimage "$f"; then
1438 | # The current file isn't an image.
1439 | throb
1440 | continue
1441 | fi
1442 |
1443 | # Show the image using sixels.
1444 | showimage "$f" || continue # Can return error if 0 frames in file.
1445 |
1446 | # Discard any keystrokes hit before read loop started.
1447 | flushstdin
1448 |
1449 | # Read a key loop.
1450 | while true; do
1451 |
1452 | if [[ $SHOULDREDRAW ]]; then
1453 | # Sigwinch interrupt handler resized screen
1454 | SHOULDREDRAW=""
1455 | echo
1456 | viewmode=$currentview showimage "$f"
1457 | continue 1
1458 | fi
1459 |
1460 | showprompt # Show "Press space to keep..."
1461 |
1462 | # Use read timeout to check several times a second for window resize.
1463 | REPLY=
1464 | while [[ -z $REPLY && -z $SHOULDREDRAW ]]; do
1465 | if read $BASH4BUG -s -n1 -t 0.25 < /dev/tty; then
1466 | break
1467 | else
1468 | # Read command returned an error (usually timeout).
1469 | local e=$?
1470 | if [[ "$slideshow" ]]; then
1471 | if doslideshow "$f"; then
1472 | continue 3 # User hit q to quit vv
1473 | else
1474 | continue 2 # User hit ESC to stop slideshow
1475 | fi
1476 | elif [[ $e -gt 128 ]]; then
1477 | # normal read timeout (just loop to allow for SIGWINCH)
1478 | continue 1 # Read a key loop.
1479 | else
1480 | echo "Error in read: $e. This shouldn't happen." >&2
1481 | continue 1
1482 | fi
1483 | fi
1484 | done
1485 |
1486 | if [[ $SHOULDREDRAW ]]; then
1487 | # Sigwinch interrupt handler resized screen
1488 | SHOULDREDRAW=""
1489 | echo
1490 | viewmode=$currentview showimage "$f"
1491 | continue 1
1492 | fi
1493 |
1494 | # if [[ "$slideshow" ]]; then
1495 | # if doslideshow "$f"; then
1496 | # continue 2
1497 | # fi
1498 | # fi
1499 |
1500 | # If we get here, then 'read' successfully got a key.
1501 | echo -en "\r"
1502 | tput el
1503 |
1504 | # Parse terminal escape sequence for F-keys, arrows.
1505 | if [[ "$REPLY" == $'\e' ]]; then parseescape; fi
1506 |
1507 | flushstdin # Remove extraneous keys. (E.g., SPC held down).
1508 |
1509 | case $REPLY in
1510 | " ") continue 2 # Space: Skip to next image.
1511 | ;;
1512 | d|t) mygio trash "$f" && echo "trashed $f"
1513 | sleep 0.25; flushstdin # Slow down deletes
1514 | continue 2
1515 | ;;
1516 | u) f=$(untrash) && echo "untrashed '$(tildify $f)'" && showimage "$f"
1517 | ;;
1518 | T) # Undocumented tool to show Trashcan in GUI browser.
1519 | mygio open trash://
1520 | ;;
1521 | # $'\cD') # Immediate, unrevocable delete. Too dangerous?
1522 | # rm "$f" && echo "deleted $f"
1523 | # sleep 0.25; flushstdin # Slow down deletes
1524 | # continue 2
1525 | # ;;
1526 |
1527 | f) E "Fitting to full size once ('F' for always)"
1528 | viewmode=full showimage "$f"
1529 | ;;
1530 | F) # Toggle full/fast view mode.
1531 | [[ $viewmode != full ]] && viewmode=full || viewmode=fast
1532 | E "Switching default viewmode to $viewmode."
1533 | if [[ $currentview != $viewmode ]]; then
1534 | showimage "$f"
1535 | fi
1536 | ;;
1537 | w) E "Fitting to screen width once ('W' for always)"
1538 | viewmode=width showimage "$f"
1539 | ;;
1540 | W) # Toggle fitwidth/fast view mode.
1541 | [[ $viewmode != width ]] && viewmode=width || viewmode=fast
1542 | E "Switching default viewmode to $viewmode."
1543 | if [[ $currentview != $viewmode ]]; then
1544 | showimage "$f"
1545 | fi
1546 | ;;
1547 | v) if [[ $FrameCount -le 1 ]]; then
1548 | # Just a single image, so temporarily use full mode.
1549 | viewmode=full showimage "$f"
1550 | else
1551 | # Allow lowercase 'v' for files we detect as videos.
1552 | e "Playing video\r"
1553 | sixvid "$f"
1554 | flushstdin
1555 | fi
1556 | ;;
1557 | V) e "Playing video\r"
1558 | sixvid "$f"
1559 | flushstdin
1560 | ;;
1561 |
1562 | M) e "Playing video\r"
1563 | # Undocumented for now. Should this use xdg-open?
1564 | mpv -loop "$f" || animate "$f"
1565 | flushstdin
1566 | ;;
1567 | b|$'\c?'|$'\cH') E "Back not implemented yet"
1568 | # b reserved for "back" once we implement it.
1569 | ;;
1570 |
1571 | c) identify -format \
1572 | "Comment: %[comment]\n" "file://$f[0]" 2>/dev/null \
1573 | | fmt -w "${COLUMNS:-75}" -s
1574 |
1575 | ;;
1576 | C) editproperty comment "$f"
1577 | ;;
1578 | i) id "$f" # Quick info
1579 | ;;
1580 | I) # Verbose info.
1581 | convert "file://$f[0]" \
1582 | -print "%[option:*]%[artifact:*]%[*]" \
1583 | null:- | grep -v '^filename='
1584 | echo $(realpath "$f")
1585 | local size=$(du -b "$f" | numfmt --grouping)
1586 | size=${size%% *}
1587 | echo "$size bytes"
1588 | identify -format '%[colors] unique colors\n' "$f"
1589 | ;;
1590 | r) # rename "$f"
1591 | saverenamemove rename "$f"
1592 | ;;
1593 | m) # rename "$f" # XXX do document.
1594 | saverenamemove move "$f"
1595 | ;;
1596 | s) #saveacopy "$f"
1597 | saverenamemove save "$f"
1598 | ;;
1599 | S|f5) # Allow F5 for folks used to other viewers.
1600 | if [[ "$slideshow" ]]; then
1601 | E "Slide show stopped"
1602 | slideshow=""
1603 | viewmode=${oldvmss:-fast}
1604 | else
1605 | E "Slide show mode. Hit 'p' to pause, 'Escape' to stop."
1606 | slideshow="yup"
1607 | oldvmss=$viewmode
1608 | viewmode="full"
1609 | fi
1610 | showimage "$f"
1611 | ;;
1612 | A) # Toggle antialiasing
1613 | if [[ "$aalias" ]]; then
1614 | E "Turning antialiasing off (show pixels when zooming in on small images)"
1615 | aalias=""
1616 | else
1617 | E "Turning antialiasing on (smooth small images when blown up)"
1618 | aalias=yup
1619 | fi
1620 | viewmode=$currentview showimage "$f"
1621 | ;;
1622 | B) # Toggle autorotate image to fit screen (portrait/landscape).
1623 | [[ $viewmode != bestfit ]] && viewmode=bestfit || viewmode=fast
1624 | E "Switching default viewmode to $viewmode."
1625 | if [[ $currentview != $viewmode ]]; then
1626 | showimage "$f"
1627 | fi
1628 | ;;
1629 | $'\cb') # Ctrl-B: Rotate this one image to fit the screen.
1630 | viewmode=bestfit showimage "$f"
1631 | ;;
1632 | D) # Toggle dither
1633 | if [[ "$dither" ]]; then
1634 | E "Turning dither off (load faster by not dithering)"
1635 | dither=""
1636 | else
1637 | E "Turning dither on (visually smooth fullscreen images)"
1638 | dither=yup
1639 | fi
1640 | if [[ $currentview != "fast" ]]; then
1641 | viewmode=$currentview showimage "$f"
1642 | fi
1643 | ;;
1644 | E) # Toggle enhance view
1645 | if [[ "$enhance" ]]; then
1646 | E "Turning enhanced view off"
1647 | enhance=""
1648 | else
1649 | E "Turning enhanced view on"
1650 | enhance=yup
1651 | fi
1652 | # XXX should enhance apply to fast view?
1653 | if [[ $currentview != "fast" ]]; then
1654 | viewmode=$currentview showimage "$f"
1655 | fi
1656 | ;;
1657 | e) e "temporarily showing enhanced view\r"
1658 | enhance=yup viewmode=full showimage "$f"
1659 | ;;
1660 | =) # Set preview size to specific number
1661 | if [[ $currentview == "fast" ]]; then
1662 | stty echo # Temporarily show characters the user types.
1663 | tput cnorm # Temporarily show the cursor.
1664 | echo -en "\r"; tput el # Clear line for prompt.
1665 | IFS= read -e -r -p "Height of preview in lines [$previewlines] ? "
1666 | tput civis
1667 | stty -echo
1668 |
1669 | if [[ "$REPLY" -le 0 || "$REPLY" -eq $previewlines ]]; then
1670 | E "Preview lines unchanged"
1671 | else
1672 | [[ "$REPLY" -lt $LINES ]] || REPLY=$((LINES-2)) # Max is #rows - 2
1673 | previewlines=$REPLY
1674 | E "Preview lines changed to $previewlines"
1675 | windowchange
1676 | fi
1677 | fi
1678 | ;;
1679 | +) # Zoom in preview
1680 | if [[ $currentview == "fast" ]]; then
1681 | previewlines=previewlines+1
1682 | [[ previewlines -le $((LINES-2)) ]] || previewlines=$((LINES-2))
1683 | windowchange
1684 | e "Preview lines changed to $previewlines"
1685 | fi
1686 | ;;
1687 | -) # Zoom out preview
1688 | if [[ $currentview == "fast" ]]; then
1689 | previewlines=previewlines-1
1690 | [[ previewlines -ge 1 ]] || previewlines=1
1691 | windowchange
1692 | e "Preview lines changed to $previewlines"
1693 | fi
1694 | ;;
1695 | 0) # Reset previewlines
1696 | previewlines=8
1697 | windowchange
1698 | e "Preview lines changed to $previewlines"
1699 | ;;
1700 | 1) # Show 100% dot-for-dot view
1701 | dotfordot "$f"
1702 | ;;
1703 | Z|z) # Magnify small images up to size of screen
1704 | togglezoomin "$f"
1705 | ;;
1706 | l|$'\cL') # l or ^L to redraw screen.
1707 | clear # Note: ^L doesn't work with bash4.
1708 | showimage "$f"
1709 | ;;
1710 | "") # ENTER key: show imageinfo and preview again.
1711 | # (XXX: Maybe not a good use of such a convenient key?)
1712 | viewmode=fast showimage "$f"
1713 | ;;
1714 | x) if [[ $recursionlevel -gt 0 ]]; then
1715 | E "Exiting directory $(dirname "$f")"
1716 | recursionlevel=recursionlevel-1
1717 | return
1718 | else
1719 | continue 2 # Allow x to also skip to next image
1720 | fi
1721 | ;;
1722 | X) if [[ $recursionlevel -gt 0 ]]; then
1723 | E "Exiting to top level directory"
1724 | abortrecursion=yes
1725 | recursionlevel=recursionlevel-1
1726 | return
1727 | fi
1728 | ;;
1729 | R) reverseimagesearch "$f"
1730 | showimage "$f"
1731 | ;;
1732 | y) yandeximagesearch "$f"
1733 | showimage "$f"
1734 | ;;
1735 | h|'?')
1736 | E "$(basename $0): Rapidly view and delete image files"
1737 | showcommonkeys
1738 | ;;
1739 | H)
1740 | E "$(basename $0): Advanced options"
1741 | showadvancedkeys
1742 | ;;
1743 | q|Q|'\E') exit
1744 | ;;
1745 | ,) enabledebugging
1746 | ;;
1747 | *)
1748 | echo "Unknown key: $REPLY" |cat -v >&2
1749 | ;;
1750 | esac;
1751 | done
1752 | done
1753 |
1754 | recursionlevel=recursionlevel-1
1755 | return
1756 | }
1757 |
1758 | showcommonkeys() {
1759 | cat << EOF
1760 | MOST USEFUL KEYS:
1761 |
1762 | SPACE: skip to next image.
1763 | f: view just the current image as full-size, higher quality.
1764 | F: toggle between always showing full-size images and fast previews.
1765 | v: Plays video using sixel (no sound).
1766 | +/-/0/=: increase/decrease/reset/set fast preview size.
1767 | d: trash image (also try 'gio list trash:' and 'gio trash --empty')
1768 | u: undo previous trash (can be used multiple times)
1769 | r: rename image file.
1770 | m: move image file to another directory.
1771 | s: save a copy of the image to another directory or filename.
1772 | q: quit.
1773 | H: SHOW ADVANCED KEYS.
1774 |
1775 | EOF
1776 | }
1777 | showadvancedkeys() {
1778 | cat </dev/null)
1945 | debug "$traversal"
1946 |
1947 |
1948 | case $traversal in
1949 | bfs|[Bb]readth*|[Bb]reath*)
1950 | # Breadth First Search: show images before opening subdirs.
1951 | sortdirslast "${MAPFILE[@]}"
1952 | ;;
1953 | dfs|[Dd]epth*|[Dd]eath*)
1954 | # "Death First Search" -- Prof. Vazirani.
1955 | echo "XXX Depth First Search: does anyone actually want this?" >&2
1956 | sortdirsfirst "${MAPFILE[@]}"
1957 | ;;
1958 | neither|*)
1959 | # Dirs are not special and are recursed into whenever seen.
1960 | showargs "${MAPFILE[@]}"
1961 | ;;
1962 | esac
1963 | }
1964 |
1965 | sortdirslast() {
1966 | # Input: a list of file and directory names.
1967 | # Output: list with files before directories.
1968 | # Breadth First Search makes sense when entering a directory, we
1969 | # usually want to see every image in it first before recursing
1970 | # into subdirectories.
1971 | local -a directories=
1972 | local name
1973 | local IFS=$'\n' # Don't split on spaces in filenames.
1974 | for name; do
1975 | if [[ -d "$name" ]]; then
1976 | directories+=($name)
1977 | else
1978 | echo "$name"
1979 | fi
1980 | done
1981 | for name in "${directories[@]}"; do
1982 | echo "$name"
1983 | done
1984 | }
1985 |
1986 | sortdirsfirst() {
1987 | # Input: a list of file and directory names.
1988 | # Output: list with directories before files.
1989 | # Depth First Search makes no sense. Just implementing it for completeness.
1990 | local -a files=
1991 | local name
1992 | local IFS=$'\n' # Don't split on spaces in filenames.
1993 | for name; do
1994 | if [[ -d "$name" ]]; then
1995 | echo "$name"
1996 | else
1997 | files+=($name)
1998 | fi
1999 | done
2000 | for name in "${files[@]}"; do
2001 | echo "$name"
2002 | done
2003 | }
2004 |
2005 | showargs() {
2006 | # Input: a list of file and directory names.
2007 | # Output: same list, with newlines between each item
2008 | local name
2009 | local IFS=$'\n' # Don't split on spaces in filenames.
2010 | for name; do
2011 | echo "$name"
2012 | done
2013 | }
2014 |
2015 |
2016 | togglezoomin() {
2017 | # Toggle zooming in on small images and update the view if necessary.
2018 | # Uses global variable "currentview".
2019 | # Sets global variable "zoomin".
2020 | local f="$1"
2021 | if [[ -z "$zoomin" ]]; then
2022 | echo "Zooming in on small images enabled."
2023 | zoomin=yup
2024 | else
2025 | echo "Zooming in on small images disabled"
2026 | zoomin=""
2027 | fi
2028 | viewmode=$currentview showimage "$f"
2029 | }
2030 |
2031 | doslideshow() {
2032 | # Wait for the user to hit a key or timeout after $ssdelay seconds.
2033 | # Returns false only if user wants to stop the slideshow.
2034 |
2035 | local file="$1"
2036 | e "Slideshow: p to pause, Esc to stop, Q to quit."
2037 |
2038 | while true; do
2039 | if read -s -n1 -t $ssdelay; then
2040 | tput el
2041 | if [[ "$REPLY" == $'\e' ]]; then parseescape; fi
2042 | case $REPLY in
2043 | " ") #Space for next image
2044 | break;
2045 | ;;
2046 | S|f5|'\E') # quit slideshow, but not whole program.
2047 | slideshow=""
2048 | viewmode=${oldvmss:-fast}
2049 | return 1
2050 | ;;
2051 | q|Q) exit # Quit everything!
2052 | ;;
2053 | p|P|*) # pause
2054 | e "Slideshow paused. Hit any key to continue or Esc to stop, Q to quit.\r"
2055 | read -s -n1
2056 | tput el
2057 | if [[ "$REPLY" == $'\e' ]]; then parseescape; fi
2058 | case $REPLY in
2059 | " ") break ;;
2060 | S|f5|'\E') # Stop slideshow.
2061 | slideshow=""
2062 | viewmode=${oldvmss:-fast}
2063 | return 1
2064 | ;;
2065 | q|Q) exit # Quit program completely.
2066 | ;;
2067 | esac
2068 | e "Slideshow: Press p to pause, Esc to stop, Q to quit."
2069 | ;;
2070 | esac
2071 | else
2072 | # Normal screensaver delay timeout; show the next image.
2073 | return 0
2074 | fi
2075 | done
2076 | }
2077 |
2078 | enabledebugging() {
2079 | # Debugging gobbledygook
2080 | DEBUG=yup
2081 | TIME=time
2082 | set -o functrace
2083 | trap '{ for ((i=${#FUNCNAME[@]}-1; i>=0; i--)); do echo -en "${BASH_LINENO[i]}: ${FUNCNAME[i]} " >&2 ; [[ $i != 0 ]] && echo -n " --> " ; done; echo ; } >&2' RETURN
2084 | }
2085 |
2086 | debugdo() {
2087 | # Both show the command and execute it
2088 | echo >&2
2089 | echo >&2
2090 | echo "$@" >&2
2091 | echo >&2
2092 | "$@"
2093 | }
2094 |
2095 | # ----------------------------------------------------------------------
2096 | # START OF TRASH SCRIPTS TO REPLACE 'gio trash' command.
2097 | mygio() {
2098 | # If the libglib2.0-bin's gio command isn't installed, we fake it.
2099 |
2100 | if command -v gioXXXXX >/dev/null; then
2101 | # gio exists, so use it.
2102 | # Ugh. Buggy when a filename has a colon in it. Prepending "file:" doesn't fix it.
2103 | gio "$@"
2104 | else
2105 |
2106 | # gio from libglib2.0-bin is missing, so use my shell script version.
2107 | case "$1" in
2108 | trash)
2109 | shift
2110 | trash "$@"
2111 | ;;
2112 | open)
2113 | shift
2114 | xdg-open "$@"
2115 | ;;
2116 | *) echo "Unsupported mygio command '$1'" >&2
2117 | ;;
2118 | esac
2119 | fi
2120 | }
2121 |
2122 | trash() {
2123 | # trash: Move files to ~/.local/share/Trash/files/.
2124 | # Well-nigh-compliant with FreeDesktop Trash Specification.
2125 | # https://specifications.freedesktop.org/trash-spec/trashspec-latest.html
2126 | #
2127 | # Handles same filename deletions, race conditions, URI-style escaping.
2128 | # Bugs: Does not handle $topdir for foreign mounts (e.g., removable drives).
2129 |
2130 | local trashdir=${XDG_DATA_HOME:-$HOME/.local/share}/Trash
2131 | if ! mkdir -p $trashdir/files || ! mkdir -p $trashdir/info; then
2132 | echo "Error: trash() could not create $trashdir/{files,info}.">&2
2133 | echo "Not deleting $@." >&2
2134 | return 1
2135 | fi
2136 |
2137 | for file; do
2138 | local path=$(uriescape "$(realpath "$file")")
2139 | local newname=$(realpath "$file" | tr / \!)
2140 |
2141 | # Allow same filename to be deleted repeatedly without loss.
2142 | # Creates trashinfo file first (atomically, to avoid race collisions).
2143 | if ! atomictouch "$trashdir/info/$newname.trashinfo"; then
2144 | local -i i=1
2145 | while ! atomictouch "$trashdir/info/$newname.$i.trashinfo"; do
2146 | i=i+1
2147 | done
2148 | newname=$newname.$i
2149 | fi
2150 |
2151 | # Write metadata to .trashinfo file
2152 | cat > "$trashdir/info/$newname.trashinfo" << EOF
2153 | [Trash Info]
2154 | Path=$path
2155 | DeletionDate=$(date +Y-%m-%dT%H:%M:%S)
2156 | EOF
2157 | mv "$file" "$trashdir/files/$newname"
2158 | done
2159 | }
2160 |
2161 | atomictouch() {
2162 | # If the file named by $1 does not exist, this creates it atomically.
2163 | # Otherwise, it return an error.
2164 | # This is atomic because Bash uses O_EXCL for noclobber.
2165 | ( set -C; >"$1"; ) 2>&-
2166 | }
2167 |
2168 | uriescape() {
2169 | # FROM RFC 2396, Uniform Resource Identifiers
2170 | # urireserved=";/?:@&=+$,"
2171 | # alnum="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
2172 | # mark="\-\_\.\!\~\*\'\(\)"
2173 | # unreserved="$alnum$mark"
2174 | # okaychars="$unreserved$urireserved"
2175 | # excluded='] <>#%"{}|\^[`' # also exclude control (00-1F and 7F hex).
2176 | local -i i
2177 | for (( i=0; i<${#1}; i++ )); do
2178 | local c=${1:i:1}
2179 | case $c in
2180 | a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|0|1|2|3|4|5|6|7|8|9|\;|\/|\?|\:|\@|\&|\=|\+|\$|\,|\-|\_|\.|\!|\~|\*|\'|\(|\))
2181 | echo -n "$c"
2182 | ;;
2183 | *) echo -n "$c" | hexdump -ve '/1 ":%02X"' | tr : %
2184 | ;;
2185 | esac
2186 | done
2187 | echo
2188 | }
2189 |
2190 | unuriescape() {
2191 | # FROM RFC 2396, Uniform Resource Identifiers
2192 | # urireserved=";/?:@&=+$,"
2193 | # alnum="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
2194 | # mark="\-\_\.\!\~\*\'\(\)"
2195 | # unreserved="$alnum$mark"
2196 | # okaychars="$unreserved$urireserved"
2197 | # excluded='] <>#%"{}|\^[`' # also exclude control (00-1F and 7F hex).
2198 | local -i i
2199 | for (( i=0; i<${#1}; i++ )); do
2200 | local c=${1:i:1}
2201 | case $c in
2202 | %) # Next two letters must be hex digits.
2203 | local -i j=i+1; local -i k=i+2
2204 | local h="${1:j:1}${1:k:1}"
2205 | i=i+2
2206 | c=$(echo -en '\x'"$h")
2207 | ;;
2208 | esac
2209 | echo -n "$c"
2210 | done
2211 | echo
2212 | }
2213 |
2214 | untrash() {
2215 | # untrash: Take the most recent file out of ~/.local/share/Trash/files.
2216 | #
2217 | # Puts file back where it came from, unless it would clobber another file.
2218 | # If a file of that name already exists, rename existing as .1, .2, ...
2219 | #
2220 | # If directory it was in is gone, then recreates the directory.
2221 | #
2222 | # Outputs the filename the of the untrashed file.
2223 | # Returns error if trash is empty.
2224 |
2225 | # Find last created infofile that points at an existing file
2226 | local trashdir=${XDG_DATA_HOME:-$HOME/.local/share}/Trash
2227 | local infofile=/dev/null.d/nonexistant
2228 | while true; do
2229 | local infofile=$(ls -tr "$trashdir/info/"* 2>/dev/null | tail -1)
2230 | if [[ ! "$infofile" ]]; then
2231 | E "Trashcan is empty." >&2
2232 | return 1
2233 | fi
2234 |
2235 | # Sanity check
2236 | [[ -e "$infofile" ]] || return 1 # No info, nothing to untrash.
2237 |
2238 | local trashname="${infofile%.trashinfo}"
2239 | trashname="${trashname#$trashdir/info/}"
2240 | trashname="$trashdir/files/$trashname"
2241 |
2242 | if [[ -e "$trashname" ]]; then
2243 | break
2244 | else
2245 | rm -f "$infofile" # Delete an infofile that points at nothing.
2246 | fi
2247 | done
2248 |
2249 | local Path=$(awk -e '/^Path=/ {print substr($0,6); exit;}' "$infofile")
2250 | Path=$(unuriescape "$Path")
2251 |
2252 | # Does directory even existing for us to write to?
2253 | if ! mkdir -p $(dirname "$Path") || ! [[ -w $(dirname "$Path") ]]; then
2254 | echo "Warning: Cannot write to '$(dirname "$Path")'" >&2
2255 | echo -n "Warning: Restoring to " >&2
2256 | if [[ -w "$PWD" ]]; then
2257 | tildify "$PWD" >&2
2258 | Path="$PWD/$(basename "$Path")"
2259 | else
2260 | tildify "$HOME" >&2
2261 | Path="$HOME/$(basename "$Path")"
2262 | fi
2263 | fi
2264 |
2265 | # Finally, we can restore the file.
2266 | if mv --backup=numbered "$trashname" "$Path" && rm "$infofile"; then
2267 | echo "$Path" # Return filename untrashed
2268 | return 0
2269 | else
2270 | return 1
2271 | fi
2272 | }
2273 |
2274 |
2275 | # END OF TRASH SCRIPTS
2276 | #----------------------------------------------------------------------
2277 |
2278 |
2279 |
2280 | ### MAIN ###
2281 | set -o nounset # Just for laughs, let's die on typos. ;-)
2282 |
2283 | # Check prerequisites
2284 | prerequisites
2285 |
2286 | # Determine window size, set up terminal
2287 | autodetect
2288 |
2289 | # Parse command line args
2290 | TEMP=$(getopt -o 'r::R,fF,S::,B,n:,dD,aA,g:,p:P:,?' \
2291 | --long 'recursive::,full-size,fast-view' \
2292 | --long 'slide-show::,slideshow::,best-fit' \
2293 | --long 'num-colors:,dither,no-dither' \
2294 | --long 'antialias,no-antialias' \
2295 | --long 'geometry:,preview-size:,preview-lines:' \
2296 | --long 'help' \
2297 | -n 'vv' -- "$@")
2298 |
2299 | if [ $? -ne 0 ]; then
2300 | echo >&2
2301 | usage >&2
2302 | exit 1
2303 | fi
2304 |
2305 | # Use getopt's results from TEMP
2306 | eval set -- "$TEMP"
2307 | unset TEMP
2308 |
2309 | while true; do
2310 | case "$1" in
2311 | -r|--recursi*)
2312 | case "$2" in
2313 | '') # No optional argument, so do nothing special.
2314 | rflag=yup
2315 | ;;
2316 | *) # Optional argument: yes, no, ask.
2317 | rflag=$2
2318 | ;;
2319 | esac
2320 | case "$rflag" in
2321 | ask) echo "Recursion will ask before entering each directory."
2322 | ;;
2323 | ""|no|off|false|False|F|0|nil|disable*)
2324 | rflag=""
2325 | echo "Recursion disabled."
2326 | ;;
2327 | *)
2328 | echo "Recursion enabled." | cat -v
2329 | ;;
2330 | esac
2331 | shift 2
2332 | continue
2333 | ;;
2334 | -R)
2335 | rflag=""
2336 | echo "Recursion disabled."
2337 | shift
2338 | continue
2339 | ;;
2340 | -f|--full*)
2341 | echo 'Full screen mode (slower, better quality)'
2342 | viewmode="full"
2343 | shift
2344 | continue
2345 | ;;
2346 | -F|--fast*)
2347 | echo 'Fast view mode (small, quick, low quality)'
2348 | viewmode="fast"
2349 | shift
2350 | continue
2351 | ;;
2352 | -B|--best-fit)
2353 | echo "Best-fit (full screen, auto-rotate to maximize screen usage)"
2354 | viewmode="bestfit"
2355 | shift
2356 | continue
2357 | ;;
2358 | -S|--slide-show|--slideshow)
2359 | slideshow=yup
2360 | oldvmss=fast
2361 | viewmode=full
2362 | case "$2" in
2363 | '') # No optional argument, so do nothing special.
2364 | true
2365 | ;;
2366 | *) # Optional argument sets time delay.
2367 | ssdelay=$2
2368 | ;;
2369 | esac
2370 | echo "Slideshow mode ($ssdelay second delay)"
2371 | shift 2
2372 | continue
2373 | ;;
2374 | -n|--num-colors)
2375 | numcolors=$2
2376 | echo "Number of colors: $numcolors. (Not used in Fast view)."
2377 | if [[ numcolors -eq 0 ]]; then usage; exit 1; fi
2378 | shift 2
2379 | continue
2380 | ;;
2381 | -d|--dither)
2382 | dither=yup
2383 | echo "Dithering on. (Smoother gradients in Full screen mode)."
2384 | shift
2385 | continue
2386 | ;;
2387 | -D|--no-dither)
2388 | dither=""
2389 | echo "Dithering off. (Faster rendering in Full screen mode)."
2390 | shift
2391 | continue
2392 | ;;
2393 | -a|--antialias)
2394 | aalias=yup
2395 | echo "Antialias on. (Smooth jaggies when scaling image)."
2396 | shift
2397 | continue
2398 | ;;
2399 | -A|--no-antialias)
2400 | aalias=""
2401 | echo "Antialiasing off. (Show pixel art as sharp)."
2402 | shift
2403 | continue
2404 | ;;
2405 | -g|--geometry)
2406 | width=${2%x*}
2407 | height=${2#*x}
2408 | echo "Terminal gemetry set to ${width}x${height} px."
2409 | if [[ width -eq 0 || height -eq 0 ]]; then usage; exit 1; fi
2410 | shift 2
2411 | continue
2412 | ;;
2413 | -P|--preview-size)
2414 | forcepsize=${2#*x} # Ignore width if given geometry (e.g., 800x256)
2415 | echo "Fast-view's preview size set to ${width}x${forcepsize}."
2416 | if [[ $forcepsize -eq 0 ]]; then usage; exit 1; fi
2417 | previewsize=$forcepsize
2418 | shift 2
2419 | continue
2420 | ;;
2421 | -p|--preview-lines)
2422 | previewlines=$2
2423 | if [[ $previewlines -eq 0 ]]; then usage; exit 1; fi
2424 | previewsize=fontheight*previewlines
2425 | echo "Fast-view's preview size set to ${width}x${previewsize}."
2426 | shift 2
2427 | continue
2428 | ;;
2429 | '-?'|--help)
2430 | usage
2431 | exit 0
2432 | ;;
2433 | --)
2434 | shift
2435 | break
2436 | ;;
2437 | *)
2438 | echo 'Internal error!' >&2
2439 | exit 1
2440 | ;;
2441 | esac
2442 | done
2443 |
2444 |
2445 | if [[ $# -gt 0 ]]; then
2446 | # Show all files/dirs mentioned on command line.
2447 | recursionlevel=0 # Allow one level of recursion for any
2448 | doit "$@" # directories named on command line.
2449 | else
2450 | # No arguments, so show everything in current working directory.
2451 | recursionlevel=1 # Do not complain about non-image files.
2452 | mapfile -t < <(sortrecur *) # Sort files for recursion.
2453 | doit "${MAPFILE[@]}" # Start recursing.
2454 | fi
2455 |
2456 | # Don't quit until images have finished transferring.
2457 | waitforterminal
2458 |
--------------------------------------------------------------------------------