├── .github
└── workflows
│ └── test.yml
├── .gitignore
├── .gitmodules
├── LICENSE
├── README.md
├── build.zig
├── build.zig.zon
├── docs
└── config.md
└── src
├── Cache.zig
├── Context.zig
├── config
├── Config.zig
└── config.json
├── handlers
├── DocumentHandler.zig
├── PdfHandler.zig
└── types.zig
├── main.zig
└── modes
├── CommandMode.zig
└── ViewMode.zig
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: test
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | pull_request:
8 |
9 | jobs:
10 | compile:
11 | strategy:
12 | fail-fast: false
13 | matrix:
14 | os: [ubuntu-latest, macos-latest]
15 | runs-on: ${{ matrix.os }}
16 |
17 | steps:
18 | - uses: actions/checkout@v4
19 | with:
20 | submodules: recursive
21 |
22 | - uses: mlugg/setup-zig@v1
23 | with:
24 | version: 0.14.0
25 |
26 | - run: zig build
27 | lint:
28 | runs-on: ubuntu-latest
29 | steps:
30 | - uses: actions/checkout@v4
31 | - uses: mlugg/setup-zig@v1
32 | - run: zig fmt --check src/*.zig
33 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # This file is for zig-specific build artifacts.
2 | # If you have OS-specific or editor-specific files to ignore,
3 | # such as *.swp or .DS_Store, put those in your global
4 | # ~/.gitignore and put this in your ~/.gitconfig:
5 | #
6 | # [core]
7 | # excludesfile = ~/.gitignore
8 | #
9 | # Cheers!
10 | # -andrewrk
11 |
12 | .zig-cache/
13 | zig-out/
14 | /release/
15 | /debug/
16 | /build/
17 | /build-*/
18 | /docgen_tmp/
19 |
20 | # Although this was renamed to .zig-cache, let's leave it here for a few
21 | # releases to make it less annoying to work with multiple branches.
22 | zig-cache/
23 |
24 | *.pdf
25 | *.typst
26 | target/
27 | *.jpg
28 | lima.yaml
29 | .vscode
30 | *.log
31 | *.epub
32 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "deps/mupdf"]
2 | path = deps/mupdf
3 | url = https://github.com/ArtifexSoftware/mupdf.git
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | 📑
4 |
fancy-cat
5 |
6 |
7 | PDF viewer for terminals using the Kitty image protocol
8 |
9 |
10 |
11 |
12 | 
13 |
14 | ## Usage
15 |
16 | ```sh
17 | fancy-cat
18 | ```
19 |
20 | ### Commands
21 |
22 | fancy-cat uses a modal interface similar to Neovim. There are two modes: view mode and command mode. To enter command mode you type `:` by default (this can be changed in the config file)
23 |
24 | #### Available Commands
25 |
26 | - `:` - jump to the specified page number
27 | - `:q` - quit the application
28 |
29 | ### Configuration
30 |
31 | fancy-cat can be configured through a JSON config file located at `~/.config/fancy-cat/config.json`. The file is automatically created on the first run with default settings.
32 |
33 | The default `config.json` can be found [here](./src/config/config.json) and documentation on the config options can be found [here](./docs/config.md)
34 |
35 | ## Installation
36 |
37 | `fancy-cat` is available in the following repositories:
38 |
39 | [](https://repology.org/project/fancy-cat/versions)
40 |
41 | ### Nix
42 |
43 | Available as a Nix package [here](https://github.com/freref/fancy-cat-nix).
44 |
45 | ## Build Instructions
46 |
47 | ### Requirements
48 |
49 | - Zig version `0.14.0`
50 | - Terminal emulator with the Kitty image protocol (e.g. Kitty, Ghostty, WezTerm, etc.)
51 |
52 | ### Build
53 |
54 | 1. Fetch submodules:
55 |
56 | ```
57 | git submodule update --init --recursive
58 | ```
59 |
60 | 2. Build the project:
61 |
62 | ```sh
63 | zig build --release=small
64 | ```
65 |
66 | > [!NOTE]
67 | > There is a [known issue](https://github.com/freref/fancy-cat/issues/18) with some processors; if the build fails on step 7/10 with the error `LLVM ERROR: Do not know how to expand the result of this operator!` then try the command below instead:
68 | >
69 | > ```sh
70 | > zig build -Dcpu="skylake" --release=small
71 | > ```
72 |
73 | 3. Install:
74 |
75 | ```sh
76 | # Add to your PATH
77 | # Linux
78 | mv zig-out/bin/fancy-cat ~/.local/bin/
79 |
80 | # macOS
81 | mv zig-out/bin/fancy-cat /usr/local/bin/
82 | ```
83 |
84 | ### Run
85 |
86 | ```sh
87 | zig build run --
88 | ```
89 |
90 | ## Features
91 |
92 | - ✅ Filewatch (hot-reload)
93 | - ✅ Runtime config
94 | - ✅ Custom keymappings
95 | - ✅ Modal interface
96 | - ✅ Commands
97 | - ✅ Colorize mode (dark-mode)
98 | - ✅ Status bar
99 | - ✅ Page navigation (zoom, prev, next, etc.)
100 |
101 | ## License
102 |
103 | [AGPL-3.0-or-later](https://spdx.org/licenses/AGPL-3.0-or-later.html)
104 |
105 | ## Contributing
106 |
107 | Contributions are welcome.
108 |
--------------------------------------------------------------------------------
/build.zig:
--------------------------------------------------------------------------------
1 | const std = @import("std");
2 |
3 | fn addMupdfStatic(exe: *std.Build.Step.Compile, b: *std.Build, prefix: []const u8) void {
4 | exe.addIncludePath(.{ .cwd_relative = b.fmt("{s}/include", .{prefix}) });
5 | exe.addLibraryPath(.{ .cwd_relative = b.fmt("{s}/lib", .{prefix}) });
6 |
7 | exe.addObjectFile(.{ .cwd_relative = b.fmt("{s}/lib/libmupdf.a", .{prefix}) });
8 | exe.addObjectFile(.{ .cwd_relative = b.fmt("{s}/lib/libmupdf-third.a", .{prefix}) });
9 |
10 | exe.linkLibC();
11 | }
12 |
13 | fn addMupdfDynamic(exe: *std.Build.Step.Compile, target: std.Target) void {
14 | if (target.os.tag == .macos and target.cpu.arch == .aarch64) {
15 | exe.addIncludePath(.{ .cwd_relative = "/opt/homebrew/include" });
16 | exe.addLibraryPath(.{ .cwd_relative = "/opt/homebrew/lib" });
17 | } else if (target.os.tag == .macos and target.cpu.arch == .x86_64) {
18 | exe.addIncludePath(.{ .cwd_relative = "/usr/local/include" });
19 | exe.addLibraryPath(.{ .cwd_relative = "/usr/local/lib" });
20 | } else if (target.os.tag == .linux) {
21 | exe.addIncludePath(.{ .cwd_relative = "/home/linuxbrew/.linuxbrew/include" });
22 | exe.addLibraryPath(.{ .cwd_relative = "/home/linuxbrew/.linuxbrew/lib" });
23 |
24 | const linux_libs = [_][]const u8{
25 | "mupdf-third", "harfbuzz",
26 | "freetype", "jbig2dec",
27 | "jpeg", "openjp2",
28 | "gumbo", "mujs",
29 | };
30 | for (linux_libs) |lib| exe.linkSystemLibrary(lib);
31 | }
32 | exe.linkSystemLibrary("mupdf");
33 | exe.linkSystemLibrary("z");
34 | exe.linkLibC();
35 | }
36 |
37 | pub fn build(b: *std.Build) void {
38 | const target = b.standardTargetOptions(.{});
39 | const optimize = b.standardOptimizeOption(.{});
40 |
41 | var useVendorMupdf = true;
42 | const prefix = "./local";
43 | const location = "./deps/mupdf/local";
44 |
45 | std.fs.cwd().access("./deps/mupdf/Makefile", .{}) catch |err| {
46 | if (err == error.FileNotFound) {
47 | useVendorMupdf = false;
48 | } else {
49 | std.debug.print("Error: {s}\n", .{@errorName(err)});
50 | return;
51 | }
52 | };
53 |
54 | var make_args = std.ArrayList([]const u8).init(b.allocator);
55 | defer make_args.deinit();
56 |
57 | make_args.append("make") catch unreachable;
58 |
59 | // use as many cores as possible by default (like zig) I dont know how to check for j arg
60 | const cpu_count = std.Thread.getCpuCount() catch 1;
61 | make_args.append(b.fmt("-j{d}", .{cpu_count})) catch unreachable;
62 |
63 | make_args.append("-C") catch unreachable;
64 | make_args.append("deps/mupdf") catch unreachable;
65 |
66 | if (target.result.os.tag == .linux) {
67 | make_args.append("HAVE_X11=no") catch unreachable;
68 | make_args.append("HAVE_GLUT=no") catch unreachable;
69 | }
70 |
71 | make_args.append("XCFLAGS=-w -DTOFU -DTOFU_CJK -DFZ_ENABLE_PDF=1 " ++
72 | "-DFZ_ENABLE_XPS=0 -DFZ_ENABLE_SVG=0 -DFZ_ENABLE_CBZ=0 " ++
73 | "-DFZ_ENABLE_IMG=0 -DFZ_ENABLE_HTML=0 -DFZ_ENABLE_EPUB=0") catch unreachable;
74 | make_args.append("tools=no") catch unreachable;
75 | make_args.append("apps=no") catch unreachable;
76 |
77 | const prefix_arg = b.fmt("prefix={s}", .{prefix});
78 | make_args.append(prefix_arg) catch unreachable;
79 | make_args.append("install") catch unreachable;
80 |
81 | const mupdf_build_step = b.addSystemCommand(make_args.items);
82 |
83 | const exe = b.addExecutable(.{
84 | .name = "fancy-cat",
85 | .root_source_file = b.path("src/main.zig"),
86 | .target = target,
87 | .optimize = optimize,
88 | });
89 | exe.headerpad_max_install_names = true;
90 |
91 | const deps = .{
92 | .vaxis = b.dependency("vaxis", .{ .target = target, .optimize = optimize }),
93 | .fzwatch = b.dependency("fzwatch", .{ .target = target, .optimize = optimize }),
94 | .fastb64z = b.dependency("fastb64z", .{ .target = target, .optimize = optimize }),
95 | };
96 |
97 | exe.root_module.addImport("fastb64z", deps.fastb64z.module("fastb64z"));
98 | exe.root_module.addImport("vaxis", deps.vaxis.module("vaxis"));
99 | exe.root_module.addImport("fzwatch", deps.fzwatch.module("fzwatch"));
100 |
101 | exe.root_module.addAnonymousImport("metadata", .{ .root_source_file = b.path("build.zig.zon") });
102 |
103 | if (useVendorMupdf) {
104 | exe.step.dependOn(&mupdf_build_step.step);
105 | addMupdfStatic(exe, b, location);
106 | b.installArtifact(exe);
107 | b.getInstallStep().dependOn(&mupdf_build_step.step);
108 | } else {
109 | addMupdfDynamic(exe, target.result);
110 | b.installArtifact(exe);
111 | }
112 |
113 | const run_cmd = b.addRunArtifact(exe);
114 | if (b.args) |args| run_cmd.addArgs(args);
115 | b.step("run", "Run the app").dependOn(&run_cmd.step);
116 | }
117 |
--------------------------------------------------------------------------------
/build.zig.zon:
--------------------------------------------------------------------------------
1 | .{
2 | .name = .fancy_cat,
3 | .version = "0.4.0",
4 | .fingerprint = 0x866b0119567be39e, // Changing this has security and trust implications.
5 | .minimum_zig_version = "0.14.0",
6 | .dependencies = .{
7 | .vaxis = .{
8 | .url = "https://github.com/freref/libvaxis/archive/6a37605dde55898dcca4769dd3eb1e333959c209.tar.gz",
9 | .hash = "vaxis-0.1.0-BWNV_K3yCACrTy3A5cbZElLyICx5a2O2EzPxmgVRcbKJ",
10 | },
11 | .fzwatch = .{
12 | .url = "https://github.com/freref/fzwatch/archive/6d5b49ed5a8ee3ed08f0e80b8f340cc3c8c8ac6e.tar.gz",
13 | .hash = "fzwatch-0.1.0-AAAAAFwxAACmGB7IN0835JkUIEuY_0zDJr_KGkZZQ2SI",
14 | },
15 | .fastb64z = .{
16 | .url = "https://github.com/freref/fastb64z/archive/fa3f34a4528609a8778124641b080e90d93c357a.tar.gz",
17 | .hash = "fastb64z-1.0.0-AAAAAPufAAC1oOmqjUybDgnEHsOlgJKIjnUWwFy3i3TJ",
18 | },
19 | },
20 | .paths = .{
21 | "build.zig",
22 | "build.zig.zon",
23 | "src",
24 | },
25 | }
26 |
--------------------------------------------------------------------------------
/docs/config.md:
--------------------------------------------------------------------------------
1 | # Configuration
2 |
3 | Configuration file location: `~/.config/fancy-cat/config.json`
4 |
5 | ## KeyMap
6 |
7 | Each binding requires:
8 |
9 | - `key`: `u8` (single character) - The main key to trigger the action
10 | - `modifiers`: Array of strings - Optional modifier keys. Available modifiers:
11 | - `shift`
12 | - `alt`
13 | - `ctrl`
14 | - `super`
15 | - `hyper`
16 | - `meta`
17 | - `caps_lock`
18 | - `num_lock`
19 |
20 | ```jsonc
21 | {
22 | "next": { "key": "n" }, // Next page
23 | "prev": { "key": "p" }, // Previous page
24 | "scroll_up": { "key": "k" }, // Move viewport up
25 | "scroll_down": { "key": "j" }, // Move viewport down
26 | "scroll_left": { "key": "h" }, // Move viewport left
27 | "scroll_right": { "key": "l" }, // Move viewport right
28 | "zoom_in": { "key": "i" }, // Increase zoom level
29 | "zoom_out": { "key": "o" }, // Decrease zoom level
30 | "width_mode": { "key": "w" }, // Toggle width mode
31 | "colorize": { "key": "z" }, // Toggle color inversion
32 | "quit": { "key": "c", "modifiers": ["ctrl"] } // Exit program
33 | }
34 | ```
35 |
36 | ## FileMonitor
37 |
38 | Controls automatic reloading when PDF file changes. Useful for live previewing:
39 |
40 | - `enabled`: `bool` - Toggle file change detection
41 | - `latency`: `f16` - Time between file checks in seconds
42 |
43 | ## General
44 |
45 | > [!NOTE]
46 | > fancy-cat uses color inversion for better terminal viewing. By default, it runs in dark mode where white pixels are displayed as black (0x000000) and black pixels as white (0xffffff). You can customize these colors to match your terminal theme - set white to your terminal's background color and black to your desired text.
47 |
48 | - `colorize`: `bool` - Toggle color inversion for dark/light mode
49 | - `white`: `i32` - Hex color code for white pixels in colorized mode
50 | - `black`: `i32` - Hex color code for black pixels in colorized mode
51 | - `size`: `f32` - PDF size relative to screen (0.0-1.0)
52 | - `zoom_step`: `f32` - How much to zoom in/out per keystroke
53 | - `zoom_min`: `f32` - Maximum zoom out level
54 | - `scroll_step`: `f32` - Pixels to move per scroll command
55 |
56 | ## StatusBar
57 |
58 | Configure the information bar at screen bottom:
59 |
60 | - `enabled`: `bool` - Show/hide the status bar
61 | - `style`: Status bar appearance
62 | - `bg`: Array of 3 `u8` values [r, g, b] - Text color (0-255)
63 | - `fg`: Array of 3 `u8` values [r, g, b] - Status bar color (0-255)
64 |
65 | ## Config
66 |
67 | Configure the LRU cache
68 |
69 | - `enabled`: `bool` - Allow/disallow caching
70 | - `lru_size`: `ìnteger` - Amount of recently visited pages that get cached
71 |
--------------------------------------------------------------------------------
/src/Cache.zig:
--------------------------------------------------------------------------------
1 | const Self = @This();
2 | const std = @import("std");
3 | const Config = @import("config/Config.zig");
4 | const vaxis = @import("vaxis");
5 |
6 | pub const Key = struct { colorize: bool, page: u16 };
7 | pub const CachedImage = struct { image: vaxis.Image };
8 |
9 | const Node = struct {
10 | key: Key,
11 | value: CachedImage,
12 | prev: ?*Node,
13 | next: ?*Node,
14 | };
15 |
16 | allocator: std.mem.Allocator,
17 | map: std.AutoHashMap(Key, *Node),
18 | head: ?*Node,
19 | tail: ?*Node,
20 | config: *Config,
21 | lru_size: usize,
22 | mutex: std.Thread.Mutex,
23 |
24 | pub fn init(allocator: std.mem.Allocator, config: *Config) Self {
25 | return .{
26 | .allocator = allocator,
27 | .map = std.AutoHashMap(Key, *Node).init(allocator),
28 | .head = null,
29 | .tail = null,
30 | .config = config,
31 | .lru_size = config.cache.lru_size,
32 | .mutex = .{},
33 | };
34 | }
35 |
36 | pub fn deinit(self: *Self) void {
37 | self.mutex.lock();
38 | defer self.mutex.unlock();
39 | var current = self.head;
40 | while (current) |node| {
41 | const next = node.next;
42 | self.allocator.destroy(node);
43 | current = next;
44 | }
45 | self.map.deinit();
46 | }
47 |
48 | pub fn clear(self: *Self) void {
49 | self.mutex.lock();
50 | defer self.mutex.unlock();
51 |
52 | var current = self.head;
53 | while (current) |node| {
54 | // TODO clear the image from the terminal everywhere
55 | // Currently assuming the terminal takes care of it somewhat
56 | //self.vx.freeImage(self.tty.anyWriter(), node.value.image.id);
57 | const next = node.next;
58 | self.allocator.destroy(node);
59 | current = next;
60 | }
61 |
62 | self.map.clearRetainingCapacity();
63 | self.head = null;
64 | self.tail = null;
65 | }
66 |
67 | pub fn get(self: *Self, key: Key) ?CachedImage {
68 | self.mutex.lock();
69 | defer self.mutex.unlock();
70 | const node = self.map.get(key) orelse return null;
71 | self.moveToFront(node);
72 | return node.value;
73 | }
74 |
75 | pub fn put(self: *Self, key: Key, image: CachedImage) !bool {
76 | self.mutex.lock();
77 | defer self.mutex.unlock();
78 | if (self.map.get(key)) |node| {
79 | self.moveToFront(node);
80 | return false;
81 | }
82 |
83 | const new_node = try self.allocator.create(Node);
84 | new_node.* = .{
85 | .key = key,
86 | .value = image,
87 | .prev = null,
88 | .next = null,
89 | };
90 |
91 | try self.map.put(key, new_node);
92 | self.addToFront(new_node);
93 |
94 | if (self.map.count() > self.lru_size) {
95 | const tail_node = self.tail orelse unreachable;
96 | _ = self.map.remove(tail_node.key);
97 | self.removeNode(tail_node);
98 | self.allocator.destroy(tail_node);
99 | }
100 |
101 | return true;
102 | }
103 |
104 | pub fn remove(self: *Self, key: Key) bool {
105 | self.mutex.lock();
106 | defer self.mutex.unlock();
107 |
108 | const node = self.map.get(key) orelse return false;
109 |
110 | _ = self.map.remove(key);
111 | self.removeNode(node);
112 | self.allocator.destroy(node);
113 |
114 | return true;
115 | }
116 |
117 | fn addToFront(self: *Self, node: *Node) void {
118 | node.next = self.head;
119 | node.prev = null;
120 |
121 | if (self.head) |head| {
122 | head.prev = node;
123 | } else {
124 | self.tail = node;
125 | }
126 |
127 | self.head = node;
128 | }
129 |
130 | fn removeNode(self: *Self, node: *Node) void {
131 | if (node.prev) |prev| {
132 | prev.next = node.next;
133 | } else {
134 | self.head = node.next;
135 | }
136 |
137 | if (node.next) |next| {
138 | next.prev = node.prev;
139 | } else {
140 | self.tail = node.prev;
141 | }
142 | }
143 |
144 | fn moveToFront(self: *Self, node: *Node) void {
145 | if (self.head == node) return;
146 | self.removeNode(node);
147 | self.addToFront(node);
148 | }
149 |
--------------------------------------------------------------------------------
/src/Context.zig:
--------------------------------------------------------------------------------
1 | const std = @import("std");
2 | const vaxis = @import("vaxis");
3 | const ViewMode = @import("modes/ViewMode.zig");
4 | const CommandMode = @import("modes/CommandMode.zig");
5 | const fzwatch = @import("fzwatch");
6 | const Config = @import("config/Config.zig");
7 | const DocumentHandler = @import("handlers/DocumentHandler.zig");
8 | const Cache = @import("./Cache.zig");
9 |
10 | pub const panic = vaxis.panic_handler;
11 |
12 | const Event = union(enum) {
13 | key_press: vaxis.Key,
14 | mouse: vaxis.Mouse,
15 | winsize: vaxis.Winsize,
16 | file_changed,
17 | };
18 |
19 | pub const ModeType = enum { view, command };
20 | pub const Mode = union(ModeType) { view: ViewMode, command: CommandMode };
21 |
22 | pub const Context = struct {
23 | const Self = @This();
24 |
25 | allocator: std.mem.Allocator,
26 | should_quit: bool,
27 | tty: vaxis.Tty,
28 | vx: vaxis.Vaxis,
29 | mouse: ?vaxis.Mouse,
30 | document_handler: DocumentHandler,
31 | page_info_text: []u8,
32 | current_page: ?vaxis.Image,
33 | watcher: ?fzwatch.Watcher,
34 | watcher_thread: ?std.Thread,
35 | config: *Config,
36 | current_mode: Mode,
37 | reload_page: bool,
38 | cache: Cache,
39 | should_check_cache: bool,
40 |
41 | pub fn init(allocator: std.mem.Allocator, args: [][:0]u8) !Self {
42 | const path = args[1];
43 | const initial_page = if (args.len == 3)
44 | try std.fmt.parseInt(u16, args[2], 10)
45 | else
46 | null;
47 |
48 | const config = try allocator.create(Config);
49 | errdefer allocator.destroy(config);
50 | config.* = try Config.init(allocator);
51 |
52 | var document_handler = try DocumentHandler.init(allocator, path, initial_page, config);
53 | errdefer document_handler.deinit();
54 |
55 | var watcher: ?fzwatch.Watcher = null;
56 | if (config.file_monitor.enabled) {
57 | watcher = try fzwatch.Watcher.init(allocator);
58 | if (watcher) |*w| try w.addFile(path);
59 | }
60 |
61 | const vx = try vaxis.init(allocator, .{});
62 | const tty = try vaxis.Tty.init();
63 |
64 | return .{
65 | .allocator = allocator,
66 | .should_quit = false,
67 | .tty = tty,
68 | .vx = vx,
69 | .document_handler = document_handler,
70 | .page_info_text = &[_]u8{},
71 | .current_page = null,
72 | .watcher = watcher,
73 | .mouse = null,
74 | .watcher_thread = null,
75 | .config = config,
76 | .current_mode = undefined,
77 | .reload_page = true,
78 | .cache = Cache.init(allocator, config),
79 | .should_check_cache = config.cache.enabled,
80 | };
81 | }
82 |
83 | pub fn deinit(self: *Self) void {
84 | switch (self.current_mode) {
85 | .command => |*state| state.deinit(),
86 | .view => {},
87 | }
88 | if (self.watcher) |*w| {
89 | w.stop();
90 | if (self.watcher_thread) |thread| thread.join();
91 | w.deinit();
92 | }
93 |
94 | if (self.page_info_text.len > 0) self.allocator.free(self.page_info_text);
95 |
96 | self.allocator.destroy(self.config);
97 | self.cache.deinit();
98 | self.document_handler.deinit();
99 | self.vx.deinit(self.allocator, self.tty.anyWriter());
100 | self.tty.deinit();
101 | }
102 |
103 | fn callback(context: ?*anyopaque, event: fzwatch.Event) void {
104 | switch (event) {
105 | .modified => {
106 | const loop = @as(*vaxis.Loop(Event), @ptrCast(@alignCast(context.?)));
107 | loop.postEvent(Event.file_changed);
108 | },
109 | }
110 | }
111 |
112 | fn watcherWorker(self: *Self, watcher: *fzwatch.Watcher) !void {
113 | try watcher.start(.{ .latency = self.config.file_monitor.latency });
114 | }
115 |
116 | pub fn run(self: *Self) !void {
117 | self.current_mode = .{ .view = ViewMode.init(self) };
118 |
119 | var loop: vaxis.Loop(Event) = .{
120 | .tty = &self.tty,
121 | .vaxis = &self.vx,
122 | };
123 |
124 | try loop.init();
125 | try loop.start();
126 | defer loop.stop();
127 | try self.vx.enterAltScreen(self.tty.anyWriter());
128 | try self.vx.queryTerminal(self.tty.anyWriter(), 1 * std.time.ns_per_s);
129 | try self.vx.setMouseMode(self.tty.anyWriter(), true);
130 |
131 | if (self.config.file_monitor.enabled) {
132 | if (self.watcher) |*w| {
133 | w.setCallback(callback, &loop);
134 | self.watcher_thread = try std.Thread.spawn(.{}, watcherWorker, .{ self, w });
135 | }
136 | }
137 |
138 | while (!self.should_quit) {
139 | loop.pollEvent();
140 |
141 | while (loop.tryEvent()) |event| {
142 | try self.update(event);
143 | }
144 |
145 | try self.draw();
146 |
147 | var buffered = self.tty.bufferedWriter();
148 | try self.vx.render(buffered.writer().any());
149 | try buffered.flush();
150 | }
151 | }
152 |
153 | pub fn changeMode(self: *Self, new_state: ModeType) void {
154 | switch (self.current_mode) {
155 | .command => |*state| state.deinit(),
156 | .view => {},
157 | }
158 |
159 | switch (new_state) {
160 | .view => self.current_mode = .{ .view = ViewMode.init(self) },
161 | .command => self.current_mode = .{ .command = CommandMode.init(self) },
162 | }
163 | }
164 |
165 | pub fn resetCurrentPage(self: *Self) void {
166 | self.document_handler.resetZoomAndScroll();
167 | self.should_check_cache = self.config.cache.enabled;
168 | self.reload_page = true;
169 | }
170 |
171 | pub fn handleKeyStroke(self: *Self, key: vaxis.Key) !void {
172 | const km = self.config.key_map;
173 |
174 | // Global keybindings
175 | if (key.matches(km.quit.codepoint, km.quit.mods)) {
176 | self.should_quit = true;
177 | return;
178 | }
179 |
180 | try switch (self.current_mode) {
181 | .view => |*state| state.handleKeyStroke(key, km),
182 | .command => |*state| state.handleKeyStroke(key, km),
183 | };
184 | }
185 |
186 | pub fn update(self: *Self, event: Event) !void {
187 | switch (event) {
188 | .key_press => |key| try self.handleKeyStroke(key),
189 | .mouse => |mouse| self.mouse = mouse,
190 | .winsize => |ws| {
191 | try self.vx.resize(self.allocator, self.tty.anyWriter(), ws);
192 | self.document_handler.resetDefaultZoom();
193 | self.document_handler.resetZoomAndScroll();
194 | self.cache.clear();
195 | self.reload_page = true;
196 | },
197 | .file_changed => {
198 | try self.document_handler.reloadDocument();
199 | _ = self.cache.remove(.{
200 | .colorize = self.config.general.colorize,
201 | .page = self.document_handler.current_page_number,
202 | });
203 | self.reload_page = true;
204 | },
205 | }
206 | }
207 |
208 | pub fn getPage(
209 | self: *Self,
210 | page_number: u16,
211 | window_width: u32,
212 | window_height: u32,
213 | ) !vaxis.Image {
214 | if (self.should_check_cache) {
215 | if (self.cache.get(.{
216 | .colorize = self.config.general.colorize,
217 | .page = page_number,
218 | })) |cached| {
219 | // Once we get the cached image we don't need to check the cache anymore because
220 | // The only actions a user can take is zoom or scrolling, but we don't cache those
221 | // Or go to the next page, at which point we set check_cache to true again
222 | self.should_check_cache = false;
223 | return cached.image;
224 | }
225 | }
226 |
227 | const encoded_image = try self.document_handler.renderPage(
228 | page_number,
229 | window_width,
230 | window_height,
231 | );
232 | defer self.allocator.free(encoded_image.base64);
233 |
234 | const image = try self.vx.transmitPreEncodedImage(
235 | self.tty.anyWriter(),
236 | encoded_image.base64,
237 | encoded_image.width,
238 | encoded_image.height,
239 | .rgb,
240 | );
241 |
242 | if (!self.should_check_cache) return image;
243 |
244 | _ = try self.cache.put(.{
245 | .colorize = self.config.general.colorize,
246 | .page = page_number,
247 | }, .{ .image = image });
248 | self.should_check_cache = false;
249 |
250 | return image;
251 | }
252 |
253 | pub fn drawCurrentPage(self: *Self, win: vaxis.Window) !void {
254 | if (self.reload_page) {
255 | const winsize = try vaxis.Tty.getWinsize(self.tty.fd);
256 | const pix_per_col = try std.math.divCeil(u16, win.screen.width_pix, win.screen.width);
257 | const pix_per_row = try std.math.divCeil(u16, win.screen.height_pix, win.screen.height);
258 | const x_pix = winsize.cols * pix_per_col;
259 | var y_pix = winsize.rows * pix_per_row;
260 | if (self.config.status_bar.enabled) {
261 | y_pix -|= 2 * pix_per_row;
262 | }
263 |
264 | self.current_page = try self.getPage(
265 | self.document_handler.getCurrentPageNumber(),
266 | x_pix,
267 | y_pix,
268 | );
269 |
270 | self.reload_page = false;
271 | }
272 |
273 | if (self.current_page) |img| {
274 | const dims = try img.cellSize(win);
275 | const x_off = (win.width - dims.cols) / 2;
276 | var y_off = (win.height - dims.rows) / 2;
277 | if (self.config.status_bar.enabled) {
278 | y_off -|= 1; // room for status bar
279 | }
280 | const center = win.child(.{
281 | .x_off = x_off,
282 | .y_off = y_off,
283 | .width = dims.cols,
284 | .height = dims.rows,
285 | });
286 | try img.draw(center, .{ .scale = .contain });
287 | }
288 | }
289 |
290 | pub fn drawStatusBar(self: *Self, win: vaxis.Window) !void {
291 | const status_bar = win.child(.{
292 | .x_off = 0,
293 | .y_off = win.height -| 2,
294 | .width = win.width,
295 | .height = 1,
296 | });
297 | status_bar.fill(vaxis.Cell{ .style = self.config.status_bar.style });
298 | const mode_text = switch (self.current_mode) {
299 | .view => "VIS",
300 | .command => "CMD",
301 | };
302 | _ = status_bar.print(
303 | &.{
304 | .{ .text = mode_text, .style = self.config.status_bar.style },
305 | .{ .text = " ", .style = self.config.status_bar.style },
306 | .{ .text = self.document_handler.getPath(), .style = self.config.status_bar.style },
307 | },
308 | .{ .col_offset = 1 },
309 | );
310 | if (self.page_info_text.len > 0) {
311 | self.allocator.free(self.page_info_text);
312 | }
313 | self.page_info_text = try std.fmt.allocPrint(
314 | self.allocator,
315 | "{d}:{d}",
316 | .{
317 | self.document_handler.getCurrentPageNumber() + 1,
318 | self.document_handler.getTotalPages(),
319 | },
320 | );
321 | _ = status_bar.print(
322 | &.{.{ .text = self.page_info_text, .style = self.config.status_bar.style }},
323 | .{ .col_offset = @intCast(win.width -| self.page_info_text.len -| 1) },
324 | );
325 | }
326 |
327 | pub fn draw(self: *Self) !void {
328 | const win = self.vx.window();
329 | win.clear();
330 |
331 | try self.drawCurrentPage(win);
332 |
333 | if (self.config.status_bar.enabled) {
334 | try self.drawStatusBar(win);
335 | }
336 |
337 | if (self.current_mode == .command) {
338 | self.current_mode.command.drawCommandBar(win);
339 | }
340 | }
341 | };
342 |
--------------------------------------------------------------------------------
/src/config/Config.zig:
--------------------------------------------------------------------------------
1 | const Self = @This();
2 | const std = @import("std");
3 | const vaxis = @import("vaxis");
4 |
5 | /// XXX There is a lot of redundancy, e.g the default values. Worth checking if its necessary
6 | /// JSON parsing is also worth looking over again
7 | pub const KeyMap = struct {
8 | next: vaxis.Key = .{ .codepoint = 'n', .mods = .{} },
9 | prev: vaxis.Key = .{ .codepoint = 'p', .mods = .{} },
10 | scroll_up: vaxis.Key = .{ .codepoint = 'k', .mods = .{} },
11 | scroll_down: vaxis.Key = .{ .codepoint = 'j', .mods = .{} },
12 | scroll_left: vaxis.Key = .{ .codepoint = 'h', .mods = .{} },
13 | scroll_right: vaxis.Key = .{ .codepoint = 'l', .mods = .{} },
14 | zoom_in: vaxis.Key = .{ .codepoint = 'i', .mods = .{} },
15 | zoom_out: vaxis.Key = .{ .codepoint = 'o', .mods = .{} },
16 | width_mode: vaxis.Key = .{ .codepoint = 'w', .mods = .{} },
17 | colorize: vaxis.Key = .{ .codepoint = 'z', .mods = .{} },
18 | quit: vaxis.Key = .{ .codepoint = 'c', .mods = .{ .ctrl = true } },
19 | enter_command_mode: vaxis.Key = .{ .codepoint = ':', .mods = .{} },
20 | exit_command_mode: vaxis.Key = .{ .codepoint = vaxis.Key.escape, .mods = .{} },
21 | execute_command: vaxis.Key = .{ .codepoint = vaxis.Key.enter, .mods = .{} },
22 | };
23 |
24 | /// File monitor will be used to watch for changes to files and rerender them
25 | pub const FileMonitor = struct {
26 | enabled: bool = true,
27 | // Amount of time to wait inbetween polling for file changes
28 | latency: f16 = 0.1,
29 | };
30 |
31 | pub const General = struct {
32 | colorize: bool = false,
33 | white: i32 = 0x000000,
34 | black: i32 = 0xffffff,
35 | // size of the pdf
36 | // 1 is the whole screen
37 | size: f32 = 1.0,
38 | // percentage
39 | zoom_step: f32 = 1.25,
40 | zoom_min: f32 = 1.0,
41 | // pixels
42 | scroll_step: f32 = 100.0,
43 | };
44 |
45 | pub const StatusBar = struct {
46 | // status bar shows the page numbers and file name
47 | enabled: bool = true,
48 | style: vaxis.Cell.Style = .{
49 | .bg = .{ .rgb = .{ 216, 74, 74 } },
50 | .fg = .{ .rgb = .{ 255, 255, 255 } },
51 | },
52 | };
53 |
54 | pub const Cache = struct {
55 | enabled: bool = true,
56 | // Number of pages to cache
57 | lru_size: usize = 10,
58 | };
59 |
60 | key_map: KeyMap,
61 | file_monitor: FileMonitor,
62 | general: General,
63 | status_bar: StatusBar,
64 | cache: Cache,
65 |
66 | pub fn init(allocator: std.mem.Allocator) !Self {
67 | // Create config file in ~/.config/fancy-cat/config.json
68 | const config_file = @embedFile("config.json");
69 | const home = try std.process.getEnvVarOwned(allocator, "HOME");
70 | defer if (home.len != 1) allocator.free(home);
71 |
72 | var config_path_buf: [std.fs.max_path_bytes]u8 = undefined;
73 | const config_dir = try std.fmt.bufPrint(&config_path_buf, "{s}/.config/fancy-cat", .{home});
74 |
75 | std.fs.makeDirAbsolute(config_dir) catch |err| {
76 | if (err != error.PathAlreadyExists) return err;
77 | };
78 |
79 | const config_path = try std.fmt.bufPrint(
80 | &config_path_buf,
81 | "{s}/.config/fancy-cat/config.json",
82 | .{home},
83 | );
84 |
85 | const file = blk: {
86 | if (std.fs.openFileAbsolute(config_path, .{})) |f| {
87 | break :blk f;
88 | } else |err| {
89 | if (err == error.FileNotFound) {
90 | const f = try std.fs.createFileAbsolute(config_path, .{});
91 | defer f.close();
92 | try f.writeAll(config_file);
93 | break :blk try std.fs.openFileAbsolute(config_path, .{});
94 | } else {
95 | return err;
96 | }
97 | }
98 | };
99 | defer file.close();
100 |
101 | const content = try file.readToEndAlloc(allocator, 1024 * 1024);
102 | defer allocator.free(content);
103 |
104 | var parsed = try std.json.parseFromSlice(std.json.Value, allocator, content, .{});
105 | defer parsed.deinit();
106 |
107 | const root = parsed.value.object;
108 |
109 | return Self{
110 | .key_map = if (root.get("KeyMap")) |km| try parseKeyMap(km, allocator) else .{},
111 | .file_monitor = if (root.get("FileMonitor")) |fm| try parseFileMonitor(fm, allocator) else .{},
112 | .general = if (root.get("General")) |g| try parseGeneral(g, allocator) else .{},
113 | .status_bar = if (root.get("StatusBar")) |sb| try parseStatusBar(sb, allocator) else .{},
114 | .cache = if (root.get("Cache")) |c| try parseCache(c, allocator) else .{},
115 | };
116 | }
117 |
118 | fn parseKeyMap(value: std.json.Value, allocator: std.mem.Allocator) !KeyMap {
119 | const obj = value.object;
120 | var keymap = KeyMap{};
121 |
122 | inline for (std.meta.fields(KeyMap)) |field| {
123 | const field_name = field.name;
124 | if (obj.get(field_name)) |key_value| {
125 | @field(keymap, field_name) = try parseKeyBinding(key_value, allocator);
126 | }
127 | }
128 |
129 | return keymap;
130 | }
131 |
132 | fn parseKeyBinding(value: std.json.Value, allocator: std.mem.Allocator) !vaxis.Key {
133 | const obj = value.object;
134 |
135 | const key_value = obj.get("key") orelse return error.MissingKeyField;
136 | const key = try std.json.innerParseFromValue([]const u8, allocator, key_value, .{});
137 | defer allocator.free(key);
138 | if (key.len == 0) return error.EmptyKey;
139 |
140 | var modifiers = vaxis.Key.Modifiers{};
141 | if (obj.get("modifiers")) |mods| {
142 | for (mods.array.items) |mod| {
143 | const mod_str = try std.json.innerParseFromValue([]const u8, allocator, mod, .{});
144 | defer allocator.free(mod_str);
145 |
146 | if (std.mem.eql(u8, mod_str, "ctrl")) {
147 | modifiers.ctrl = true;
148 | }
149 | // TODO Add more modifiers
150 | }
151 | }
152 |
153 | if (vaxis.Key.name_map.get(key)) |codepoint| {
154 | std.debug.print("key_value: {any}, key: {s}, codepoint: {any}\n", .{ key_value, key, codepoint });
155 | return vaxis.Key{
156 | .codepoint = codepoint,
157 | .mods = modifiers,
158 | };
159 | }
160 |
161 | return vaxis.Key{
162 | .codepoint = @as(u21, key[0]),
163 | .mods = modifiers,
164 | };
165 | }
166 |
167 | fn parseFileMonitor(value: std.json.Value, allocator: std.mem.Allocator) !FileMonitor {
168 | const obj = value.object;
169 |
170 | return FileMonitor{
171 | .enabled = try std.json.innerParseFromValue(
172 | bool,
173 | allocator,
174 | obj.get("enabled") orelse .{ .bool = true },
175 | .{},
176 | ),
177 | .latency = try std.json.innerParseFromValue(
178 | f16,
179 | allocator,
180 | obj.get("latency") orelse .{ .float = 0.1 },
181 | .{},
182 | ),
183 | };
184 | }
185 |
186 | fn parseGeneral(value: std.json.Value, allocator: std.mem.Allocator) !General {
187 | const obj = value.object;
188 |
189 | const white = obj.get("white") orelse std.json.Value{ .string = "0x000000" };
190 | const black = obj.get("black") orelse std.json.Value{ .string = "0xffffff" };
191 |
192 | return General{
193 | .colorize = try std.json.innerParseFromValue(
194 | bool,
195 | allocator,
196 | obj.get("colorize") orelse .{ .bool = false },
197 | .{},
198 | ),
199 | .white = try std.fmt.parseInt(i32, white.string[2..], 16),
200 | .black = try std.fmt.parseInt(i32, black.string[2..], 16),
201 | .size = try std.json.innerParseFromValue(
202 | f32,
203 | allocator,
204 | obj.get("size") orelse .{ .float = 1.0 },
205 | .{},
206 | ),
207 | .zoom_step = try std.json.innerParseFromValue(
208 | f32,
209 | allocator,
210 | obj.get("zoom_step") orelse .{ .float = 1.25 },
211 | .{},
212 | ),
213 | .zoom_min = try std.json.innerParseFromValue(
214 | f32,
215 | allocator,
216 | obj.get("zoom_min") orelse .{ .float = 1.0 },
217 | .{},
218 | ),
219 | .scroll_step = try std.json.innerParseFromValue(
220 | f32,
221 | allocator,
222 | obj.get("scroll_step") orelse .{ .float = 100.0 },
223 | .{},
224 | ),
225 | };
226 | }
227 |
228 | fn parseStatusBar(value: std.json.Value, allocator: std.mem.Allocator) !StatusBar {
229 | const obj = value.object;
230 |
231 | const enabled = try std.json.innerParseFromValue(
232 | bool,
233 | allocator,
234 | obj.get("enabled") orelse .{ .bool = true },
235 | .{},
236 | );
237 |
238 | if (obj.get("style")) |style_val| {
239 | const style_obj = style_val.object;
240 | const bg = style_obj.get("bg").?.object;
241 | const fg = style_obj.get("fg").?.object;
242 |
243 | const bg_rgb = bg.get("rgb").?.array;
244 | const fg_rgb = fg.get("rgb").?.array;
245 |
246 | const style: vaxis.Cell.Style = .{
247 | .bg = .{ .rgb = .{
248 | try std.json.innerParseFromValue(u8, allocator, bg_rgb.items[0], .{}),
249 | try std.json.innerParseFromValue(u8, allocator, bg_rgb.items[1], .{}),
250 | try std.json.innerParseFromValue(u8, allocator, bg_rgb.items[2], .{}),
251 | } },
252 | .fg = .{ .rgb = .{
253 | try std.json.innerParseFromValue(u8, allocator, fg_rgb.items[0], .{}),
254 | try std.json.innerParseFromValue(u8, allocator, fg_rgb.items[1], .{}),
255 | try std.json.innerParseFromValue(u8, allocator, fg_rgb.items[2], .{}),
256 | } },
257 | };
258 |
259 | return StatusBar{
260 | .enabled = enabled,
261 | .style = style,
262 | };
263 | }
264 |
265 | return .{};
266 | }
267 |
268 | fn parseCache(value: std.json.Value, allocator: std.mem.Allocator) !Cache {
269 | const obj = value.object;
270 |
271 | return Cache{
272 | .enabled = try std.json.innerParseFromValue(
273 | bool,
274 | allocator,
275 | obj.get("enabled") orelse .{ .bool = true },
276 | .{},
277 | ),
278 | .lru_size = try std.json.innerParseFromValue(
279 | usize,
280 | allocator,
281 | obj.get("lru_size") orelse .{ .integer = 10 },
282 | .{},
283 | ),
284 | };
285 | }
286 |
--------------------------------------------------------------------------------
/src/config/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "KeyMap": {
3 | "next": { "key": "n", "modifiers": [] },
4 | "prev": { "key": "p", "modifiers": [] },
5 | "scroll_up": { "key": "k", "modifiers": [] },
6 | "scroll_down": { "key": "j", "modifiers": [] },
7 | "scroll_left": { "key": "h", "modifiers": [] },
8 | "scroll_right": { "key": "l", "modifiers": [] },
9 | "zoom_in": { "key": "i", "modifiers": [] },
10 | "zoom_out": { "key": "o", "modifiers": [] },
11 | "width_mode": { "key": "w", "modifiers": [] },
12 | "colorize": { "key": "z", "modifiers": [] },
13 | "quit": { "key": "c", "modifiers": ["ctrl"] },
14 | "enter_command_mode": { "key": "colon", "modifiers": [] },
15 | "exit_command_mode": { "key": "escape", "modifiers": [] },
16 | "execute_command": { "key": "enter", "modifiers": [] }
17 | },
18 | "FileMonitor": {
19 | "enabled": true,
20 | "latency": 0.1
21 | },
22 | "General": {
23 | "colorize": false,
24 | "white": "0x000000",
25 | "black": "0xffffff",
26 | "size": 1.0,
27 | "zoom_step": 1.25,
28 | "zoom_min": 1.0,
29 | "scroll_step": 100.0
30 | },
31 | "StatusBar": {
32 | "enabled": true,
33 | "style": {
34 | "bg": { "rgb": [216, 74, 74] },
35 | "fg": { "rgb": [255, 255, 255] }
36 | }
37 | },
38 | "Cache": {
39 | "enabled": true,
40 | "lru_size": 10
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/handlers/DocumentHandler.zig:
--------------------------------------------------------------------------------
1 | const Self = @This();
2 | const std = @import("std");
3 | const Config = @import("../config/Config.zig");
4 | const PdfHandler = @import("./PdfHandler.zig");
5 | const types = @import("./types.zig");
6 |
7 | pub const FileFormat = enum {
8 | pdf,
9 | // epub,
10 |
11 | pub fn fromPath(path: []const u8) !FileFormat {
12 | if (std.mem.endsWith(u8, path, ".pdf")) {
13 | return .pdf;
14 | } // else if (std.mem.endsWith(u8, path, ".epub")) {
15 | // return .epub;
16 | // }
17 | return types.DocumentError.UnsupportedFileFormat;
18 | }
19 | };
20 |
21 | pdf_handler: PdfHandler,
22 | current_page_number: u16,
23 | file_format: FileFormat,
24 |
25 | pub fn init(
26 | allocator: std.mem.Allocator,
27 | path: []const u8,
28 | initial_page: ?u16,
29 | config: *Config,
30 | ) !Self {
31 | // TODO use this for conditional rendering
32 | const format = try FileFormat.fromPath(path);
33 |
34 | var pdf_handler = try PdfHandler.init(allocator, path, config);
35 | errdefer pdf_handler.deinit();
36 |
37 | const current_page_number = if (initial_page) |page| blk: {
38 | if (page < 1 or page > pdf_handler.total_pages) {
39 | return types.DocumentError.InvalidPageNumber;
40 | }
41 | break :blk page - 1;
42 | } else 0;
43 |
44 | return .{
45 | .pdf_handler = pdf_handler,
46 | .current_page_number = current_page_number,
47 | .file_format = format,
48 | };
49 | }
50 |
51 | pub fn deinit(self: *Self) void {
52 | self.pdf_handler.deinit();
53 | }
54 |
55 | pub fn reloadDocument(self: *Self) !void {
56 | try self.pdf_handler.reloadDocument();
57 | if (self.current_page_number >= self.pdf_handler.total_pages) {
58 | self.current_page_number = self.pdf_handler.total_pages - 1;
59 | }
60 | }
61 |
62 | pub fn renderPage(
63 | self: *Self,
64 | page_number: u16,
65 | window_width: u32,
66 | window_height: u32,
67 | ) !types.EncodedImage {
68 | return try self.pdf_handler.renderPage(page_number, window_width, window_height);
69 | }
70 |
71 | pub fn zoomIn(self: *Self) void {
72 | self.pdf_handler.zoomIn();
73 | }
74 |
75 | pub fn zoomOut(self: *Self) void {
76 | self.pdf_handler.zoomOut();
77 | }
78 |
79 | pub fn toggleColor(self: *Self) void {
80 | self.pdf_handler.toggleColor();
81 | }
82 |
83 | pub fn scroll(self: *Self, direction: types.ScrollDirection) void {
84 | self.pdf_handler.scroll(direction);
85 | }
86 |
87 | pub fn resetDefaultZoom(self: *Self) void {
88 | self.pdf_handler.resetDefaultZoom();
89 | }
90 |
91 | pub fn resetZoomAndScroll(self: *Self) void {
92 | self.pdf_handler.resetZoomAndScroll();
93 | }
94 |
95 | pub fn toggleWidthMode(self: *Self) void {
96 | self.pdf_handler.toggleWidthMode();
97 | }
98 | pub fn goToPage(self: *Self, page_num: u16) bool {
99 | if (page_num >= 1 and page_num <= self.getTotalPages() and page_num != self.current_page_number + 1) {
100 | self.current_page_number = @as(u16, @intCast(page_num)) - 1;
101 | return true;
102 | }
103 | return false;
104 | }
105 | pub fn changePage(self: *Self, delta: i32) bool {
106 | const new_page = @as(i32, @intCast(self.current_page_number)) + delta;
107 |
108 | if (new_page >= 0 and new_page < self.getTotalPages()) {
109 | self.current_page_number = @as(u16, @intCast(new_page));
110 | return true;
111 | }
112 | return false;
113 | }
114 |
115 | // getters
116 |
117 | pub fn getCurrentPageNumber(self: *Self) u16 {
118 | return self.current_page_number;
119 | }
120 |
121 | pub fn getPath(self: *Self) []const u8 {
122 | return self.pdf_handler.path;
123 | }
124 |
125 | pub fn getTotalPages(self: *Self) u16 {
126 | return self.pdf_handler.total_pages;
127 | }
128 |
--------------------------------------------------------------------------------
/src/handlers/PdfHandler.zig:
--------------------------------------------------------------------------------
1 | const Self = @This();
2 | const std = @import("std");
3 | const fastb64z = @import("fastb64z");
4 | const vaxis = @import("vaxis");
5 | const Config = @import("../config/Config.zig");
6 | const types = @import("./types.zig");
7 | const c = @cImport({
8 | @cInclude("mupdf/fitz.h");
9 | @cInclude("mupdf/pdf.h");
10 | });
11 |
12 | allocator: std.mem.Allocator,
13 | ctx: [*c]c.fz_context,
14 | doc: [*c]c.fz_document,
15 | total_pages: u16,
16 | path: []const u8,
17 | active_zoom: f32,
18 | default_zoom: f32,
19 | width_mode: bool,
20 | y_offset: f32,
21 | x_offset: f32,
22 | y_center: f32,
23 | x_center: f32,
24 | config: *Config,
25 |
26 | pub fn init(
27 | allocator: std.mem.Allocator,
28 | path: []const u8,
29 | config: *Config,
30 | ) !Self {
31 | const ctx = c.fz_new_context(null, null, c.FZ_STORE_UNLIMITED) orelse {
32 | std.debug.print("Failed to create mupdf context\n", .{});
33 | return types.DocumentError.FailedToCreateContext;
34 | };
35 | errdefer c.fz_drop_context(ctx);
36 |
37 | c.fz_register_document_handlers(ctx);
38 | c.fz_set_error_callback(ctx, null, null);
39 | c.fz_set_warning_callback(ctx, null, null);
40 |
41 | const doc = c.fz_open_document(ctx, path.ptr) orelse {
42 | const err_msg = c.fz_caught_message(ctx);
43 | std.debug.print("Failed to open document: {s}\n", .{err_msg});
44 | return types.DocumentError.FailedToOpenDocument;
45 | };
46 | errdefer c.fz_drop_document(ctx, doc);
47 |
48 | const total_pages = @as(u16, @intCast(c.fz_count_pages(ctx, doc)));
49 |
50 | return .{
51 | .allocator = allocator,
52 | .ctx = ctx,
53 | .doc = doc,
54 | .total_pages = total_pages,
55 | .path = path,
56 | .active_zoom = 0,
57 | .default_zoom = 0,
58 | .width_mode = false,
59 | .y_offset = 0,
60 | .x_offset = 0,
61 | .y_center = 0,
62 | .x_center = 0,
63 | .config = config,
64 | };
65 | }
66 |
67 | pub fn deinit(self: *Self) void {
68 | c.fz_drop_document(self.ctx, self.doc);
69 | c.fz_drop_context(self.ctx);
70 | }
71 |
72 | pub fn reloadDocument(self: *Self) !void {
73 | if (self.doc) |doc| {
74 | c.fz_drop_document(self.ctx, doc);
75 | self.doc = null;
76 | }
77 |
78 | self.doc = c.fz_open_document(self.ctx, self.path.ptr) orelse {
79 | std.debug.print("Failed to reload document\n", .{});
80 | return types.DocumentError.FailedToOpenDocument;
81 | };
82 |
83 | self.total_pages = @as(u16, @intCast(c.fz_count_pages(self.ctx, self.doc.?)));
84 | }
85 |
86 | fn calculateZoomLevel(self: *Self, window_width: u32, window_height: u32, bound: c.fz_rect) void {
87 | var scale: f32 = 0;
88 | if (self.width_mode) {
89 | scale = @as(f32, @floatFromInt(window_width)) / bound.x1;
90 | } else {
91 | scale = @min(
92 | @as(f32, @floatFromInt(window_width)) / bound.x1,
93 | @as(f32, @floatFromInt(window_height)) / bound.y1,
94 | );
95 | }
96 |
97 | // initial zoom
98 | if (self.default_zoom == 0) {
99 | self.default_zoom = scale * self.config.general.size;
100 | }
101 |
102 | if (self.active_zoom == 0) {
103 | self.active_zoom = self.default_zoom;
104 | }
105 |
106 | self.active_zoom = @max(self.active_zoom, self.config.general.zoom_min);
107 | }
108 |
109 | fn calculateXY(self: *Self, view_width: f32, view_height: f32, bound: c.fz_rect) void {
110 | // translation to center view
111 | self.x_center = (bound.x1 - view_width / self.active_zoom) / 2;
112 | self.y_center = (bound.y1 - view_height / self.active_zoom) / 2;
113 |
114 | if (self.x_offset == 0 and self.y_offset == 0 and self.width_mode) {
115 | self.y_offset = self.y_center;
116 | }
117 |
118 | // don't scroll off page
119 | self.x_offset = c.fz_clamp(self.x_offset, -self.x_center, self.x_center);
120 | self.y_offset = c.fz_clamp(self.y_offset, -self.y_center, self.y_center);
121 | }
122 |
123 | pub fn renderPage(
124 | self: *Self,
125 | page_number: u16,
126 | window_width: u32,
127 | window_height: u32,
128 | ) !types.EncodedImage {
129 | const page = c.fz_load_page(self.ctx, self.doc, page_number);
130 | defer c.fz_drop_page(self.ctx, page);
131 | const bound = c.fz_bound_page(self.ctx, page);
132 |
133 | self.calculateZoomLevel(window_width, window_height, bound);
134 |
135 | // document view
136 | const view_width = @max(1, @min(
137 | self.active_zoom * bound.x1,
138 | @as(f32, @floatFromInt(window_width)),
139 | ));
140 | const view_height = @max(1, @min(
141 | self.active_zoom * bound.y1,
142 | @as(f32, @floatFromInt(window_height)),
143 | ));
144 |
145 | self.calculateXY(view_width, view_height, bound);
146 |
147 | const bbox = c.fz_make_irect(
148 | 0,
149 | 0,
150 | @intFromFloat(view_width),
151 | @intFromFloat(view_height),
152 | );
153 | const pix = c.fz_new_pixmap_with_bbox(self.ctx, c.fz_device_rgb(self.ctx), bbox, null, 0);
154 | defer c.fz_drop_pixmap(self.ctx, pix);
155 | c.fz_clear_pixmap_with_value(self.ctx, pix, 0xFF);
156 |
157 | var ctm = c.fz_scale(self.active_zoom, self.active_zoom);
158 | ctm = c.fz_pre_translate(ctm, self.x_offset - self.x_center, self.y_offset - self.y_center);
159 |
160 | const dev = c.fz_new_draw_device(self.ctx, ctm, pix);
161 | defer c.fz_drop_device(self.ctx, dev);
162 | c.fz_run_page(self.ctx, page, dev, c.fz_identity, null);
163 | c.fz_close_device(self.ctx, dev);
164 |
165 | if (self.config.general.colorize) {
166 | c.fz_tint_pixmap(self.ctx, pix, self.config.general.black, self.config.general.white);
167 | }
168 |
169 | const width = @as(usize, @intCast(@abs(bbox.x1)));
170 | const height = @as(usize, @intCast(@abs(bbox.y1)));
171 | const samples = c.fz_pixmap_samples(self.ctx, pix);
172 |
173 | const base64Encoder = fastb64z.standard.Encoder;
174 | const sample_count = width * height * 3;
175 |
176 | const b64_buf = try self.allocator.alloc(u8, base64Encoder.calcSize(sample_count));
177 | const encoded = base64Encoder.encode(b64_buf, samples[0..sample_count]);
178 |
179 | return types.EncodedImage{
180 | .base64 = encoded,
181 | .width = @intCast(width),
182 | .height = @intCast(height),
183 | };
184 | }
185 |
186 | pub fn zoomIn(self: *Self) void {
187 | self.active_zoom *= self.config.general.zoom_step;
188 | }
189 |
190 | pub fn zoomOut(self: *Self) void {
191 | self.active_zoom /= self.config.general.zoom_step;
192 | }
193 |
194 | pub fn toggleColor(self: *Self) void {
195 | self.config.general.colorize = !self.config.general.colorize;
196 | }
197 |
198 | pub fn scroll(self: *Self, direction: types.ScrollDirection) void {
199 | const step = self.config.general.scroll_step / self.active_zoom;
200 | switch (direction) {
201 | .Up => {
202 | const translation = self.y_offset + step;
203 | if (self.y_offset < translation) {
204 | self.y_offset = translation;
205 | } else {
206 | self.y_offset = std.math.nextAfter(f32, self.y_offset, std.math.inf(f32));
207 | }
208 | },
209 | .Down => {
210 | const translation = self.y_offset - step;
211 | if (self.y_offset > translation) {
212 | self.y_offset = translation;
213 | } else {
214 | self.y_offset = std.math.nextAfter(f32, self.y_offset, -std.math.inf(f32));
215 | }
216 | },
217 | .Left => {
218 | const translation = self.x_offset + step;
219 | if (self.x_offset < translation) {
220 | self.x_offset = translation;
221 | } else {
222 | self.x_offset = std.math.nextAfter(f32, self.x_offset, std.math.inf(f32));
223 | }
224 | },
225 | .Right => {
226 | const translation = self.x_offset - step;
227 | if (self.x_offset > translation) {
228 | self.x_offset = translation;
229 | } else {
230 | self.x_offset = std.math.nextAfter(f32, self.x_offset, -std.math.inf(f32));
231 | }
232 | },
233 | }
234 | }
235 |
236 | pub fn resetDefaultZoom(self: *Self) void {
237 | self.default_zoom = 0;
238 | }
239 |
240 | pub fn resetZoomAndScroll(self: *Self) void {
241 | self.active_zoom = self.default_zoom;
242 | self.y_offset = 0;
243 | self.x_offset = 0;
244 | }
245 |
246 | pub fn toggleWidthMode(self: *Self) void {
247 | self.default_zoom = 0;
248 | self.active_zoom = 0;
249 | self.width_mode = !self.width_mode;
250 | }
251 |
--------------------------------------------------------------------------------
/src/handlers/types.zig:
--------------------------------------------------------------------------------
1 | // Types used in document handlers
2 | pub const EncodedImage = struct { base64: []const u8, width: u16, height: u16 };
3 |
4 | pub const ScrollDirection = enum { Up, Down, Left, Right };
5 |
6 | pub const DocumentError = error{
7 | FailedToCreateContext,
8 | FailedToOpenDocument,
9 | InvalidPageNumber,
10 | UnsupportedFileFormat,
11 | };
12 |
--------------------------------------------------------------------------------
/src/main.zig:
--------------------------------------------------------------------------------
1 | const std = @import("std");
2 | const Context = @import("Context.zig").Context;
3 |
4 | // Types for build.zig.zon
5 | // For now metadata is only used in main.zig, but can move it to types.zig if needed eleswhere
6 | // This wont be necessary once https://github.com/ziglang/zig/pull/22907 is merged
7 |
8 | const PackageName = enum { fancy_cat };
9 |
10 | const DependencyType = struct {
11 | url: []const u8,
12 | hash: []const u8,
13 | };
14 |
15 | const DependenciesType = struct {
16 | vaxis: DependencyType,
17 | fzwatch: DependencyType,
18 | fastb64z: DependencyType,
19 | };
20 |
21 | const MetadataType = struct {
22 | name: PackageName,
23 | fingerprint: u64,
24 | version: []const u8,
25 | minimum_zig_version: []const u8,
26 | dependencies: DependenciesType,
27 | paths: []const []const u8,
28 | };
29 |
30 | const metadata: MetadataType = @import("metadata");
31 |
32 | pub fn main() !void {
33 | const args = try std.process.argsAlloc(std.heap.page_allocator);
34 | defer std.process.argsFree(std.heap.page_allocator, args);
35 |
36 | if (args.len == 2 and (std.mem.eql(u8, args[1], "--version") or std.mem.eql(u8, args[1], "-v"))) {
37 | const stdout = std.io.getStdOut().writer();
38 | try stdout.print("fancy-cat version {s}\n", .{metadata.version});
39 | return;
40 | }
41 |
42 | if (args.len < 2 or args.len > 3) {
43 | const stderr = std.io.getStdErr().writer();
44 | try stderr.writeAll("Usage: fancy-cat \n");
45 | return;
46 | }
47 |
48 | var gpa = std.heap.GeneralPurposeAllocator(.{}){};
49 | defer {
50 | const deinit_status = gpa.deinit();
51 | if (deinit_status == .leak) {
52 | std.log.err("memory leak", .{});
53 | }
54 | }
55 | const allocator = gpa.allocator();
56 |
57 | var app = try Context.init(allocator, args);
58 | defer app.deinit();
59 |
60 | try app.run();
61 | }
62 |
--------------------------------------------------------------------------------
/src/modes/CommandMode.zig:
--------------------------------------------------------------------------------
1 | const Self = @This();
2 | const std = @import("std");
3 | const vaxis = @import("vaxis");
4 | const Context = @import("../Context.zig").Context;
5 | const Config = @import("../config/Config.zig");
6 | const ViewMode = @import("./ViewMode.zig");
7 | const TextInput = vaxis.widgets.TextInput;
8 |
9 | context: *Context,
10 | text_input: TextInput,
11 |
12 | pub fn init(context: *Context) Self {
13 | return .{
14 | .context = context,
15 | .text_input = TextInput.init(context.allocator, &context.vx.unicode),
16 | };
17 | }
18 |
19 | pub fn deinit(self: *Self) void {
20 | const win = self.context.vx.window();
21 | win.hideCursor();
22 | self.text_input.deinit();
23 | }
24 |
25 | pub fn handleKeyStroke(self: *Self, key: vaxis.Key, km: Config.KeyMap) !void {
26 | if (key.matches(km.exit_command_mode.codepoint, km.exit_command_mode.mods)) {
27 | self.context.changeMode(.view);
28 | return;
29 | }
30 |
31 | if (key.matches(km.execute_command.codepoint, km.execute_command.mods)) {
32 | self.executeCommand(self.text_input.buf.firstHalf());
33 | self.context.changeMode(.view);
34 | return;
35 | }
36 |
37 | try self.text_input.update(.{ .key_press = key });
38 | }
39 |
40 | pub fn drawCommandBar(self: *Self, win: vaxis.Window) void {
41 | const command_bar = win.child(.{
42 | .x_off = 0,
43 | .y_off = win.height - 1,
44 | .width = win.width,
45 | .height = 1,
46 | });
47 | _ = command_bar.print(&.{.{ .text = ":" }}, .{ .col_offset = 0 });
48 |
49 | const child = win.child(.{
50 | .x_off = 1,
51 | .y_off = win.height - 1,
52 | .width = win.width,
53 | .height = 1,
54 | });
55 |
56 | self.text_input.draw(child);
57 | }
58 |
59 | pub fn executeCommand(self: *Self, cmd: []const u8) void {
60 | const cmd_str = std.mem.trim(u8, cmd, " ");
61 |
62 | if (std.mem.eql(u8, cmd_str, "q")) {
63 | self.context.should_quit = true;
64 | }
65 |
66 | if (std.fmt.parseInt(u16, cmd_str, 10)) |page_num| {
67 | const success = self.context.document_handler.goToPage(page_num);
68 | if (success) {
69 | self.context.resetCurrentPage();
70 | }
71 | } else |_| {}
72 | }
73 |
--------------------------------------------------------------------------------
/src/modes/ViewMode.zig:
--------------------------------------------------------------------------------
1 | const Self = @This();
2 | const vaxis = @import("vaxis");
3 | const Context = @import("../Context.zig").Context;
4 | const CommandMode = @import("./CommandMode.zig");
5 | const Config = @import("../config/Config.zig");
6 |
7 | context: *Context,
8 |
9 | pub const KeyAction = struct {
10 | codepoint: u21,
11 | mods: vaxis.Key.Modifiers,
12 | handler: *const fn (*Context) void,
13 | };
14 |
15 | pub fn init(context: *Context) Self {
16 | return .{
17 | .context = context,
18 | };
19 | }
20 |
21 | pub fn handleKeyStroke(self: *Self, key: vaxis.Key, km: Config.KeyMap) !void {
22 | // O(n) but n is small
23 | // Centralized key handling
24 | const key_actions = &[_]KeyAction{
25 | .{
26 | .codepoint = km.next.codepoint,
27 | .mods = km.next.mods,
28 | .handler = struct {
29 | fn action(s: *Context) void {
30 | if (s.document_handler.changePage(1)) {
31 | s.resetCurrentPage();
32 | }
33 | }
34 | }.action,
35 | },
36 | .{
37 | .codepoint = km.prev.codepoint,
38 | .mods = km.prev.mods,
39 | .handler = struct {
40 | fn action(s: *Context) void {
41 | if (s.document_handler.changePage(-1)) {
42 | s.resetCurrentPage();
43 | }
44 | }
45 | }.action,
46 | },
47 | .{
48 | .codepoint = km.zoom_in.codepoint,
49 | .mods = km.zoom_in.mods,
50 | .handler = struct {
51 | fn action(s: *Context) void {
52 | s.document_handler.zoomIn();
53 | s.reload_page = true;
54 | }
55 | }.action,
56 | },
57 | .{
58 | .codepoint = km.zoom_out.codepoint,
59 | .mods = km.zoom_out.mods,
60 | .handler = struct {
61 | fn action(s: *Context) void {
62 | s.document_handler.zoomOut();
63 | s.reload_page = true;
64 | }
65 | }.action,
66 | },
67 | .{
68 | .codepoint = km.width_mode.codepoint,
69 | .mods = km.width_mode.mods,
70 | .handler = struct {
71 | fn action(s: *Context) void {
72 | s.document_handler.toggleWidthMode();
73 | s.reload_page = true;
74 | }
75 | }.action,
76 | },
77 | .{
78 | .codepoint = km.scroll_up.codepoint,
79 | .mods = km.scroll_up.mods,
80 | .handler = struct {
81 | fn action(s: *Context) void {
82 | s.document_handler.scroll(.Up);
83 | s.reload_page = true;
84 | }
85 | }.action,
86 | },
87 | .{
88 | .codepoint = km.scroll_down.codepoint,
89 | .mods = km.scroll_down.mods,
90 | .handler = struct {
91 | fn action(s: *Context) void {
92 | s.document_handler.scroll(.Down);
93 | s.reload_page = true;
94 | }
95 | }.action,
96 | },
97 | .{
98 | .codepoint = km.scroll_left.codepoint,
99 | .mods = km.scroll_left.mods,
100 | .handler = struct {
101 | fn action(s: *Context) void {
102 | s.document_handler.scroll(.Left);
103 | s.reload_page = true;
104 | }
105 | }.action,
106 | },
107 | .{
108 | .codepoint = km.scroll_right.codepoint,
109 | .mods = km.scroll_right.mods,
110 | .handler = struct {
111 | fn action(s: *Context) void {
112 | s.document_handler.scroll(.Right);
113 | s.reload_page = true;
114 | }
115 | }.action,
116 | },
117 | .{
118 | .codepoint = km.colorize.codepoint,
119 | .mods = km.colorize.mods,
120 | .handler = struct {
121 | fn action(s: *Context) void {
122 | s.document_handler.toggleColor();
123 | s.reload_page = true;
124 | }
125 | }.action,
126 | },
127 | .{
128 | .codepoint = km.enter_command_mode.codepoint,
129 | .mods = km.enter_command_mode.mods,
130 | .handler = struct {
131 | fn action(s: *Context) void {
132 | s.changeMode(.command);
133 | }
134 | }.action,
135 | },
136 | };
137 |
138 | for (key_actions) |action| {
139 | if (key.matches(action.codepoint, action.mods)) {
140 | action.handler(self.context);
141 | return;
142 | }
143 | }
144 | }
145 |
--------------------------------------------------------------------------------