Compare commits

..

13 Commits

Author SHA1 Message Date
itsjunetime 70b458207a Add more details to changelog and release 0.3.0 2025-03-01 19:00:18 -07:00
itsjunetime 1eee193d44 Implement fullscreen functionality 2025-03-01 18:27:34 -07:00
itsjunetime d2be289e80 Implement help page and delay receiving area to hopefully improve first-page performance a bit 2025-03-01 18:04:33 -07:00
itsjunetime 10e1f6cb9f Update deps 2025-02-28 10:29:23 -07:00
Mikołaj Pieczaba 7e4bee516b refactor: make fill_default use Vec::resize_with (#53) 2025-02-23 14:35:29 -07:00
itsjunetime aae1f9d37b Improve performance by better pre-allocating pixmap buffer 2025-02-21 20:56:25 -07:00
itsjunetime 70f3401702 Update to edition 2024 2025-02-21 08:58:44 -07:00
itsjunetime 9d2a730e40 Implement inverting colors 2025-02-19 15:24:27 -07:00
Andrew Chu 8c10a3c4bc Enable png feature for image crate (#51)
* Enable png feature for image crate

* Fix typo
2025-02-19 12:09:37 -07:00
June 524c069b83 Rewrite with mupdf as a backend (#50)
* Initial implementation of attempted mupdf rewrite

* Change back to no resizing and don't include alpha channel in conversion

* Remove some more dead code

* Make features more modular and call search more easily

* Switch to git dependency for my fixes

* Update deps

* Fix searching hehe

* Remove unnecessary CI steps?

* fontconfig in CI

* perftools in ci

* Final adjustments to conform to mupdf changes
2025-02-19 09:59:29 -07:00
itsjunetime e123351079 Implement Ctrl+Z functionality to suspend for job control 2025-01-16 14:12:21 -07:00
itsjunetime 490b66b273 Update ratatui dependencies 2025-01-01 16:53:29 -07:00
itsjunetime a2b728fae3 Update deps and release 0.2.0 2024-12-03 21:25:18 -07:00
15 changed files with 1962 additions and 934 deletions
+1 -19
View File
@@ -26,25 +26,7 @@ jobs:
- name: Install build dependencies - name: Install build dependencies
run: | run: |
sudo apt-get update sudo apt-get update
sudo apt-get install -y cmake libjpeg-dev libfontconfig1-dev libopenjp2-7-dev libopenjpip7 libopenjp2-7 libglib2.0-dev libnss3-dev libunwind-dev libgoogle-perftools-dev libboost-dev sudo apt-get install -y libfontconfig1-dev libgoogle-perftools-dev google-perftools
- name: Build newer poppler
run: |
wget https://poppler.freedesktop.org/poppler-23.10.0.tar.xz
tar xf poppler-23.10.0.tar.xz
cd poppler-23.10.0
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_C_COMPILER_LAUNCHER=sccache \
-DCMAKE_CXX_COMPILER_LAUNCHER=sccache \
-DENABLE_UNSTABLE_API_ABI_HEADERS=ON \
-DENABLE_GPGME=OFF \
-DENABLE_QT5=OFF \
-DENABLE_QT6=OFF \
-DENABLE_SPLASH=OFF \
-DENABLE_LIBCURL=OFF
make -j$(nproc)
sudo make install
sudo ldconfig
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Clippy - name: Clippy
run: cargo clippy -- -D warnings run: cargo clippy -- -D warnings
+10 -1
View File
@@ -1,4 +1,13 @@
# Unreleased # v0.3.0
- Update ratatui(-image) dependencies
- Enable Ctrl+Z/Suspend functionality
- Rewrite with mupdf as the backend for much better performance and rendering quality
- Support easy inversion of colors via `i` keypress
- Support for filling all available space with `f` keypress
- Change help text at bottom into full help page
# v0.2.0
- Add `--r-to-l` flag to support displaying pdfs that read from right to left - Add `--r-to-l` flag to support displaying pdfs that read from right to left
- Add `--max-wide` flag to restrict amount of pages that can appear on the screen at a time - Add `--max-wide` flag to restrict amount of pages that can appear on the screen at a time
Generated
+1402 -478
View File
File diff suppressed because it is too large Load Diff
+17 -10
View File
@@ -1,43 +1,45 @@
[package] [package]
name = "tdf" name = "tdf-viewer"
version = "0.1.0" version = "0.2.0"
authors = ["June Welker <junewelker@gmail.com>"] authors = ["June Welker <junewelker@gmail.com>"]
edition = "2021" edition = "2024"
description = "A terminal viewer for PDFs" description = "A terminal viewer for PDFs"
readme = "README.md" readme = "README.md"
homepage = "https://github.com/itsjunetime/tdf" homepage = "https://github.com/itsjunetime/tdf"
repository = "https://github.com/itsjunetime/tdf" repository = "https://github.com/itsjunetime/tdf"
license = "GPL-3.0-or-later" license = "AGPL-3.0-only"
keywords = ["pdf", "tui", "cli", "terminal"] keywords = ["pdf", "tui", "cli", "terminal"]
categories = ["command-line-utilities", "text-processing", "visualization"] categories = ["command-line-utilities", "text-processing", "visualization"]
default-run = "tdf" default-run = "tdf"
rust-version = "1.85"
[[bin]] [[bin]]
name = "tdf" name = "tdf"
path = "src/main.rs"
# lib only exists for benching # lib only exists for benching
[lib] [lib]
name = "tdf" name = "tdf"
[dependencies] [dependencies]
poppler-rs = { version = "0.24.1", default-features = false, features = ["v23_7"] }
cairo-rs = { version = "0.20.0", default-features = false, features = ["png"] }
# we're using this branch because it has significant performance fixes that I'm waiting on responses from the upstream devs to get upstreamed. See https://github.com/ratatui-org/ratatui/issues/1116 # we're using this branch because it has significant performance fixes that I'm waiting on responses from the upstream devs to get upstreamed. See https://github.com/ratatui-org/ratatui/issues/1116
ratatui = { git = "https://github.com/itsjunetime/ratatui.git" } ratatui = { git = "https://github.com/itsjunetime/ratatui.git" }
# ratatui = { path = "./ratatui/ratatui" } # ratatui = { path = "./ratatui/ratatui" }
# We're using this to have the vb64 feature (for faster base64 encoding, since that does take up a good bit of time when converting images to the Box<dyn ratatui_image::Protocol>. It also just includes a few more features that I'm waiting on main to upstream # We're using this to have the vb64 feature (for faster base64 encoding, since that does take up a good bit of time when converting images to the `Protocol`. It also just includes a few more features that I'm waiting on main to upstream
ratatui-image = { git = "https://github.com/itsjunetime/ratatui-image.git", branch = "vb64_on_personal", default-features = false } ratatui-image = { git = "https://github.com/itsjunetime/ratatui-image.git", branch = "vb64_on_personal", default-features = false }
# ratatui-image = { path = "./ratatui-image", features = ["vb64"], default-features = false } # ratatui-image = { path = "./ratatui-image", features = ["vb64"], default-features = false }
crossterm = { version = "0.28.1", features = ["event-stream"] } crossterm = { version = "0.28.1", features = ["event-stream"] }
image = { version = "0.25.1", features = ["png", "rayon"], default-features = false } image = { version = "0.25.1", features = ["pnm", "rayon", "png"], default-features = false }
notify = { version = "7.0.0", features = ["crossbeam-channel"] } notify = { version = "8.0.0", features = ["crossbeam-channel"] }
tokio = { version = "1.37.0", features = ["rt-multi-thread", "macros"] } tokio = { version = "1.37.0", features = ["rt-multi-thread", "macros"] }
futures-util = { version = "0.3.30", default-features = false } futures-util = { version = "0.3.30", default-features = false }
glib = "0.20.0"
itertools = "*" itertools = "*"
flume = { version = "0.11.0", default-features = false, features = ["async"] } flume = { version = "0.11.0", default-features = false, features = ["async"] }
xflags = "0.4.0-pre.2" xflags = "0.4.0-pre.2"
mimalloc = "0.1.43" mimalloc = "0.1.43"
nix = { version = "0.29.0", features = ["signal"] }
mupdf = { git = "https://github.com/itsjunetime/mupdf-rs", branch = "june/mupdf_1_25", default-features = false, features = ["svg", "system-fonts", "img"] }
rayon = { version = "*", default-features = false }
# for tracing with tokio-console # for tracing with tokio-console
console-subscriber = { version = "0.4.0", optional = true } console-subscriber = { version = "0.4.0", optional = true }
@@ -50,6 +52,8 @@ lto = "fat"
default = ["nightly"] default = ["nightly"]
nightly = ["ratatui-image/vb64"] nightly = ["ratatui-image/vb64"]
tracing = ["tokio/tracing", "dep:console-subscriber"] tracing = ["tokio/tracing", "dep:console-subscriber"]
epub = ["mupdf/epub"]
cbz = ["mupdf/cbz"]
[dev-dependencies] [dev-dependencies]
criterion = { version = "0.5.1", features = ["async_tokio"] } criterion = { version = "0.5.1", features = ["async_tokio"] }
@@ -152,3 +156,6 @@ unused_self = "warn"
used_underscore_binding = "warn" used_underscore_binding = "warn"
used_underscore_items = "warn" used_underscore_items = "warn"
zero_sized_map_values = "warn" zero_sized_map_values = "warn"
[patch.crates-io]
pathfinder_simd = { git = "https://github.com/itsjunetime/pathfinder.git" }
+67 -80
View File
@@ -1,23 +1,21 @@
GNU GENERAL PUBLIC LICENSE GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 29 June 2007 Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed. of this license document, but changing it is not allowed.
Preamble Preamble
The GNU General Public License is a free, copyleft license for The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works. software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast, to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the software for all its users.
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you price. Our General Public Licenses are designed to make sure that you
@@ -26,44 +24,34 @@ them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things. free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you Developers that use our General Public Licenses protect your rights
these rights or asking you to surrender the rights. Therefore, you have with two steps: (1) assert copyright on the software, and (2) offer
certain responsibilities if you distribute copies of the software, or if you this License which gives you legal permission to copy, distribute
you modify it: responsibilities to respect the freedom of others. and/or modify the software.
For example, if you distribute copies of such a program, whether A secondary benefit of defending all users' freedom is that
gratis or for a fee, you must pass on to the recipients the same improvements made in alternate versions of the program, if they
freedoms that you received. You must make sure that they, too, receive receive widespread use, become available for other developers to
or can get the source code. And you must show them these terms so they incorporate. Many developers of free software are heartened and
know their rights. encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
Developers that use the GNU GPL protect your rights with two steps: The GNU Affero General Public License is designed specifically to
(1) assert copyright on the software, and (2) offer you this License ensure that, in such cases, the modified source code becomes available
giving you legal permission to copy, distribute and/or modify it. to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
For the developers' and authors' protection, the GPL clearly explains An older license, called the Affero General Public License and
that there is no warranty for this free software. For both users' and published by Affero, was designed to accomplish similar goals. This is
authors' sake, the GPL requires that modified versions be marked as a different license, not a version of the Affero GPL, but Affero has
changed, so that their problems will not be attributed erroneously to released a new version of the Affero GPL which permits relicensing under
authors of previous versions. this license.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and The precise terms and conditions for copying, distribution and
modification follow. modification follow.
@@ -72,7 +60,7 @@ modification follow.
0. Definitions. 0. Definitions.
"This License" refers to version 3 of the GNU General Public License. "This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks. works, such as semiconductor masks.
@@ -549,35 +537,45 @@ to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program. License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License. 13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work, License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License, but the work with which it is combined will remain governed by version
section 13, concerning interaction through a network will apply to the 3 of the GNU General Public License.
combination as such.
14. Revised Versions of this License. 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will the GNU Affero General Public License from time to time. Such new versions
be similar in spirit to the present version, but may differ in detail to will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns. address new problems or concerns.
Each version is given a distinguishing version number. If the Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation. by the Free Software Foundation.
If the Program specifies that a proxy can decide which future If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you public statement of acceptance of a version permanently authorizes you
to choose that version for the Program. to choose that version for the Program.
@@ -635,40 +633,29 @@ the "copyright" line and a pointer to where the full notice is found.
Copyright (C) <year> <name of author> Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail. Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short If your software can interact with users remotely through a computer
notice like this when it starts in an interactive mode: network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
<program> Copyright (C) <year> <name of author> interface could display a "Source" link that leads users to an archive
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. of the code. There are many ways you could offer source, and different
This is free software, and you are welcome to redistribute it solutions will be better for different programs; see section 13 for the
under certain conditions; type `show c' for details. specific requirements.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school, You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary. if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>. <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+2 -2
View File
@@ -14,7 +14,7 @@ Designed to be performant, very responsive, and work well with even very large P
- Reactive layout - Reactive layout
## To Build ## To Build
First, you need to install the system dependencies. This includes packages such as (but not limited to) `cairo`, `gtk`, and `poppler`. If you're on linux, these will probably show up in your package manager as something like `libcairo-devel` or `cairo-dev`. First, you need to install the system dependencies. This will generally only include `libfontconfig`. If you're on linux, these will probably show up in your package manager as something like `libfontconfig1-devel` or `libfontconfig-dev`.
If it turns out that you're missing one of these, it will fail to compile and tell you what library you're missing. Find the development package for that library in your package manager, install it, and try to build again. Now, the important steps: If it turns out that you're missing one of these, it will fail to compile and tell you what library you're missing. Find the development package for that library in your package manager, install it, and try to build again. Now, the important steps:
@@ -30,4 +30,4 @@ I dunno. Just for fun, mostly.
Yeah, sure. Please do. Yeah, sure. Please do.
Please note, though, that all contributions will be treated as licensed under MPL-2.0. This is so that we can relicense to MPL-2.0 at some point in the future if we manage to move away from poppler as a backend (since that is the only dependency, at time of writing, which requires the GPLv3 license). Please note, though, that all contributions will be treated as licensed under MPL-2.0.
+5 -5
View File
@@ -6,15 +6,15 @@ use std::{
time::{SystemTime, UNIX_EPOCH} time::{SystemTime, UNIX_EPOCH}
}; };
use criterion::{criterion_group, criterion_main, profiler::Profiler, BenchmarkId, Criterion}; use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main, profiler::Profiler};
use futures_util::StreamExt; use futures_util::StreamExt;
use tdf::{ use tdf::{
converter::{ConvertedPage, ConverterMsg}, converter::{ConvertedPage, ConverterMsg},
renderer::{fill_default, PageInfo, RenderInfo} renderer::{PageInfo, RenderInfo, fill_default}
}; };
use utils::{ use utils::{
handle_converter_msg, handle_renderer_msg, render_doc, start_all_rendering, RenderState, handle_converter_msg, handle_renderer_msg, render_doc, start_all_rendering,
start_converting_loop, start_rendering_loop, RenderState start_converting_loop, start_rendering_loop
}; };
const FILES: [&str; 3] = [ const FILES: [&str; 3] = [
@@ -97,7 +97,7 @@ async fn render_all_files(path: &'static str) -> Vec<PageInfo> {
RenderInfo::Reloaded => (), RenderInfo::Reloaded => (),
RenderInfo::NumPages(num) => fill_default(&mut pages, num), RenderInfo::NumPages(num) => fill_default(&mut pages, num),
RenderInfo::Page(page) => { RenderInfo::Page(page) => {
let num = page.page; let num = page.page_num;
pages[num] = Some(page); pages[num] = Some(page);
} }
}; };
+8 -8
View File
@@ -1,13 +1,13 @@
use std::{hint::black_box, path::Path}; use std::{hint::black_box, path::Path};
use crossterm::terminal::WindowSize; use crossterm::terminal::WindowSize;
use flume::{r#async::RecvStream, unbounded, Sender}; use flume::{Sender, r#async::RecvStream, unbounded};
use futures_util::stream::StreamExt as _; use futures_util::stream::StreamExt as _;
use ratatui::layout::Rect; use ratatui::layout::Rect;
use ratatui_image::picker::{Picker, ProtocolType}; use ratatui_image::picker::{Picker, ProtocolType};
use tdf::{ use tdf::{
converter::{run_conversion_loop, ConvertedPage, ConverterMsg}, converter::{ConvertedPage, ConverterMsg, run_conversion_loop},
renderer::{fill_default, start_rendering, RenderError, RenderInfo, RenderNotif} renderer::{RenderError, RenderInfo, RenderNotif, fill_default, start_rendering}
}; };
pub fn handle_renderer_msg( pub fn handle_renderer_msg(
@@ -37,13 +37,13 @@ pub fn handle_converter_msg(
pages[num] = Some(page); pages[num] = Some(page);
let num_got = pages.iter().filter(|p| p.is_some()).count(); let first_none = pages.iter().position(Option::is_none);
// we have to tell it to jump to a certain page so that it will actually render it (since // we have to tell it to jump to a certain page so that it will actually render it (since
// it only renders fanning out from the page that we currently have selected) // it only renders fanning out from the page that we currently have selected)
to_converter_tx if let Some(first) = first_none {
.send(ConverterMsg::GoToPage(num_got)) to_converter_tx.send(ConverterMsg::GoToPage(first)).unwrap();
.unwrap(); }
} }
pub struct RenderState { pub struct RenderState {
@@ -63,7 +63,7 @@ pub fn start_rendering_loop(
Sender<RenderNotif> Sender<RenderNotif>
) { ) {
let pathbuf = path.as_ref().canonicalize().unwrap(); let pathbuf = path.as_ref().canonicalize().unwrap();
let str_path = format!("file://{}", pathbuf.into_os_string().to_string_lossy()); let str_path = pathbuf.into_os_string().to_string_lossy().to_string();
let (to_render_tx, from_main_rx) = unbounded(); let (to_render_tx, from_main_rx) = unbounded();
let (to_main_tx, from_render_rx) = unbounded(); let (to_main_tx, from_render_rx) = unbounded();
+1 -1
Submodule ratatui updated: 8bf0c1ef77...1166bebf44
-13
View File
@@ -1,13 +0,0 @@
#!/usr/bin/env bash
# 1. Pull the git source of poppler
# 2. cd poppler
# 3. git checkout poppler-23.07.0
# 4. mkdir build
# 5. cd build
# 6. cmake .. -DENABLE_GPGME=OFF -DENABLE_QT5=OFF -DENABLE_QT6=OFF -DENABLE_BOOST=OFF -DBUILD_SHARED_LIBS=OFF
# 7. cmake --build . --parallel $(nproc)
env SYSTEM_DEPS_POPPLER_GLIB_LINK=static \
SYSTEM_DEPS_POPPLER_GLIB_NO_PKG_CONFIG=1 \
SYSTEM_DEPS_POPPLER_GLIB_SEARCH_NATIVE=/path/to/poppler/build/glib \
SYSTEM_DEPS_POPPLER_GLIB_LIB=poppler-glib \
cargo perf --bin for_profiling --
+27 -14
View File
@@ -1,10 +1,11 @@
use flume::{Receiver, SendError, Sender, TryRecvError}; use flume::{Receiver, SendError, Sender, TryRecvError};
use futures_util::stream::StreamExt; use futures_util::stream::StreamExt;
use image::ImageFormat; use image::DynamicImage;
use itertools::Itertools; use itertools::Itertools;
use ratatui_image::{picker::Picker, protocol::Protocol, Resize}; use ratatui_image::{Resize, picker::Picker, protocol::Protocol};
use rayon::iter::ParallelIterator;
use crate::renderer::{fill_default, PageInfo, RenderError}; use crate::renderer::{PageInfo, RenderError, fill_default};
pub struct ConvertedPage { pub struct ConvertedPage {
pub page: Protocol, pub page: Protocol,
@@ -48,19 +49,31 @@ pub async fn run_conversion_loop(
let Some((page_info, new_iter)) = (idx_start..page) let Some((page_info, new_iter)) = (idx_start..page)
.interleave(page..idx_end) .interleave(page..idx_end)
.enumerate() .enumerate()
.skip(*iteration) // .skip(*iteration)
.find_map(|(i_idx, p_idx)| images[p_idx].take().map(|p| (p, i_idx))) .find_map(|(i_idx, p_idx)| images[p_idx].take().map(|p| (p, i_idx)))
else { else {
return Ok(None); return Ok(None);
}; };
let img_area = page_info.img_data.area; let mut dyn_img = image::load_from_memory_with_format(
&page_info.img_data.pixels,
image::ImageFormat::Pnm
)
.map_err(|e| RenderError::Converting(format!("Can't load image: {e}")))?;
let dyn_img = match dyn_img {
image::load_from_memory_with_format(&page_info.img_data.data, ImageFormat::Png) DynamicImage::ImageRgb8(ref mut img) =>
.map_err(|e| { for quad in &*page_info.result_rects {
RenderError::Render(format!("Couldn't convert Vec<u8> to DynamicImage: {e}")) img.par_enumerate_pixels_mut()
})?; .filter(|(x, y, _)| {
*x > quad.ul_x && *x < quad.lr_x && *y > quad.ul_y && *y < quad.lr_y
})
.for_each(|(_, _, px)| px.0[2] = px.0[2].saturating_sub(u8::MAX / 2));
},
_ => unreachable!()
};
let img_area = page_info.img_data.cell_area;
// We don't actually want to Crop this image, but we've already // We don't actually want to Crop this image, but we've already
// verified (with the ImageSurface stuff) that the image is the correct // verified (with the ImageSurface stuff) that the image is the correct
@@ -69,7 +82,7 @@ pub async fn run_conversion_loop(
let txt_img = picker let txt_img = picker
.new_protocol(dyn_img, img_area, Resize::None) .new_protocol(dyn_img, img_area, Resize::None)
.map_err(|e| { .map_err(|e| {
RenderError::Render(format!( RenderError::Converting(format!(
"Couldn't convert DynamicImage to ratatui image: {e}" "Couldn't convert DynamicImage to ratatui image: {e}"
)) ))
})?; })?;
@@ -79,15 +92,15 @@ pub async fn run_conversion_loop(
Ok(Some(ConvertedPage { Ok(Some(ConvertedPage {
page: txt_img, page: txt_img,
num: page_info.page, num: page_info.page_num,
num_results: page_info.search_results num_results: page_info.result_rects.len()
})) }))
} }
fn handle_notif(msg: ConverterMsg, images: &mut Vec<Option<PageInfo>>, page: &mut usize) { fn handle_notif(msg: ConverterMsg, images: &mut Vec<Option<PageInfo>>, page: &mut usize) {
match msg { match msg {
ConverterMsg::AddImg(img) => { ConverterMsg::AddImg(img) => {
let page_num = img.page; let page_num = img.page_num;
images[page_num] = Some(img); images[page_num] = Some(img);
} }
ConverterMsg::NumPages(n_pages) => { ConverterMsg::NumPages(n_pages) => {
+19 -24
View File
@@ -1,6 +1,6 @@
use std::{ use std::{
ffi::OsString, ffi::OsString,
io::{stdout, Read, Write}, io::{Read, Write, stdout},
num::NonZeroUsize, num::NonZeroUsize,
path::PathBuf path::PathBuf
}; };
@@ -8,17 +8,16 @@ use std::{
use crossterm::{ use crossterm::{
execute, execute,
terminal::{ terminal::{
disable_raw_mode, enable_raw_mode, window_size, EndSynchronizedUpdate, EndSynchronizedUpdate, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode,
EnterAlternateScreen, LeaveAlternateScreen enable_raw_mode, window_size
} }
}; };
use futures_util::{stream::StreamExt, FutureExt}; use futures_util::{FutureExt, stream::StreamExt};
use glib::{LogField, LogLevel, LogWriterOutput};
use notify::{Event, EventKind, RecursiveMode, Watcher}; use notify::{Event, EventKind, RecursiveMode, Watcher};
use ratatui::{backend::CrosstermBackend, Terminal}; use ratatui::{Terminal, backend::CrosstermBackend};
use ratatui_image::picker::Picker; use ratatui_image::picker::Picker;
use tdf::{ use tdf::{
converter::{run_conversion_loop, ConvertedPage, ConverterMsg}, converter::{ConvertedPage, ConverterMsg, run_conversion_loop},
renderer::{self, RenderError, RenderInfo, RenderNotif}, renderer::{self, RenderError, RenderInfo, RenderNotif},
tui::{BottomMessage, InputAction, MessageSetting, Tui} tui::{BottomMessage, InputAction, MessageSetting, Tui}
}; };
@@ -46,6 +45,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
optional -r,--r-to-l r_to_l: bool optional -r,--r-to-l r_to_l: bool
/// The maximum number of pages to display together, horizontally, at a time /// The maximum number of pages to display together, horizontally, at a time
optional -m,--max-wide max_wide: NonZeroUsize optional -m,--max-wide max_wide: NonZeroUsize
/// Fullscreen the pdf (hide document name, page count, etc)
optional -f,--fullscreen fullscreen: bool
/// PDF file to read /// PDF file to read
required file: PathBuf required file: PathBuf
}; };
@@ -80,8 +81,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
)?; )?;
// TODO: Handle non-utf8 file names? Maybe by constructing a CString and passing that in to the // TODO: Handle non-utf8 file names? Maybe by constructing a CString and passing that in to the
// poppler stuff instead of a rust string? // mupdf stuff instead of a rust string?
let file_path = format!("file://{}", path.clone().into_os_string().to_string_lossy()); let file_path = path.clone().into_os_string().to_string_lossy().to_string();
let mut window_size = window_size()?; let mut window_size = window_size()?;
@@ -161,11 +162,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut term = Terminal::new(backend)?; let mut term = Terminal::new(backend)?;
term.skip_diff(true); term.skip_diff(true);
// poppler has some annoying logging (e.g. if you request a page index out-of-bounds of a
// document's pages, then it will return `None`, but still log to stderr with CRITICAL level),
// so we want to just ignore all logging since this is a tui app.
glib::log_set_writer_func(noop);
execute!( execute!(
term.backend_mut(), term.backend_mut(),
EnterAlternateScreen, EnterAlternateScreen,
@@ -173,8 +169,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
)?; )?;
enable_raw_mode()?; enable_raw_mode()?;
let mut main_area = Tui::main_layout(&term.get_frame()); let mut fullscreen = flags.fullscreen.unwrap_or_default();
tui_tx.send(RenderNotif::Area(main_area[1]))?; let mut main_area = Tui::main_layout(&term.get_frame(), fullscreen);
tui_tx.send(RenderNotif::Area(main_area.page_area))?;
let mut tui_rx = tui_rx.into_stream(); let mut tui_rx = tui_rx.into_stream();
let mut from_converter = from_converter.into_stream(); let mut from_converter = from_converter.into_stream();
@@ -197,6 +194,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
to_converter.send(ConverterMsg::GoToPage(page))?; to_converter.send(ConverterMsg::GoToPage(page))?;
}, },
InputAction::Search(term) => tui_tx.send(RenderNotif::Search(term))?, InputAction::Search(term) => tui_tx.send(RenderNotif::Search(term))?,
InputAction::Invert => tui_tx.send(RenderNotif::Invert)?,
InputAction::Fullscreen => fullscreen = !fullscreen,
} }
} }
}, },
@@ -208,7 +207,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
to_converter.send(ConverterMsg::NumPages(num))?; to_converter.send(ConverterMsg::NumPages(num))?;
}, },
RenderInfo::Page(info) => { RenderInfo::Page(info) => {
tui.got_num_results_on_page(info.page, info.search_results); tui.got_num_results_on_page(info.page_num, info.result_rects.len());
to_converter.send(ConverterMsg::AddImg(info))?; to_converter.send(ConverterMsg::AddImg(info))?;
}, },
RenderInfo::Reloaded => tui.set_msg(MessageSetting::Some(BottomMessage::Reloaded)), RenderInfo::Reloaded => tui.set_msg(MessageSetting::Some(BottomMessage::Reloaded)),
@@ -224,10 +223,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}, },
}; };
let new_area = Tui::main_layout(&term.get_frame()); let new_area = Tui::main_layout(&term.get_frame(), fullscreen);
if new_area != main_area { if new_area != main_area {
main_area = new_area; main_area = new_area;
tui_tx.send(RenderNotif::Area(main_area[1]))?; tui_tx.send(RenderNotif::Area(main_area.page_area))?;
needs_redraw = true; needs_redraw = true;
} }
@@ -275,7 +274,7 @@ fn on_notify_ev(
match ev.kind { match ev.kind {
EventKind::Access(_) => (), EventKind::Access(_) => (),
EventKind::Remove(_) => to_tui_tx EventKind::Remove(_) => to_tui_tx
.send(Err(RenderError::Render("File was deleted".into()))) .send(Err(RenderError::Converting("File was deleted".into())))
.unwrap(), .unwrap(),
// This shouldn't fail to send unless the receiver gets disconnected. If that's // This shouldn't fail to send unless the receiver gets disconnected. If that's
// happened, then like the main thread has panicked or something, so it doesn't matter // happened, then like the main thread has panicked or something, so it doesn't matter
@@ -286,7 +285,3 @@ fn on_notify_ev(
} }
} }
} }
fn noop(_: LogLevel, _: &[LogField<'_>]) -> LogWriterOutput {
LogWriterOutput::Handled
}
+152 -168
View File
@@ -1,26 +1,24 @@
use std::thread; use std::{thread::sleep, time::Duration};
use cairo::{Antialias, Context, Format, Surface};
use crossterm::terminal::WindowSize; use crossterm::terminal::WindowSize;
use flume::{Receiver, SendError, Sender, TryRecvError}; use flume::{Receiver, SendError, Sender, TryRecvError};
use itertools::Itertools; use itertools::Itertools;
use poppler::{Color, Document, FindFlags, Page, Rectangle, SelectionStyle}; use mupdf::{Colorspace, Document, Matrix, Page, Pixmap};
use ratatui::layout::Rect; use ratatui::layout::Rect;
pub enum RenderNotif { pub enum RenderNotif {
Area(Rect), Area(Rect),
JumpToPage(usize), JumpToPage(usize),
Search(String), Search(String),
Reload Reload,
Invert
} }
#[derive(Debug)] #[derive(Debug)]
pub enum RenderError { pub enum RenderError {
Notify(notify::Error), Notify(notify::Error),
Doc(glib::Error), Doc(mupdf::error::Error),
// Don't like storing an error as a string but it needs to be Send to send to the main thread, Converting(String)
// and it's just going to be shown to the user, so whatever
Render(String)
} }
pub enum RenderInfo { pub enum RenderInfo {
@@ -32,14 +30,14 @@ pub enum RenderInfo {
#[derive(Clone)] #[derive(Clone)]
pub struct PageInfo { pub struct PageInfo {
pub img_data: ImageData, pub img_data: ImageData,
pub page: usize, pub page_num: usize,
pub search_results: usize pub result_rects: Vec<HighlightRect>
} }
#[derive(Clone)] #[derive(Clone)]
pub struct ImageData { pub struct ImageData {
pub data: Vec<u8>, pub pixels: Vec<u8>,
pub area: Rect pub cell_area: Rect
} }
#[derive(Default)] #[derive(Default)]
@@ -48,15 +46,13 @@ struct PrevRender {
contained_term: Option<bool> contained_term: Option<bool>
} }
#[inline]
pub fn fill_default<T: Default>(vec: &mut Vec<T>, size: usize) { pub fn fill_default<T: Default>(vec: &mut Vec<T>, size: usize) {
vec.clear(); vec.clear();
vec.reserve(size.saturating_sub(vec.len())); vec.resize_with(size, T::default);
for _ in 0..size {
vec.push(T::default());
}
} }
// this function has to be sync (non-async) because the poppler::Document needs to be held during // this function has to be sync (non-async) because the mupdf::Document needs to be held during
// most of it, but that's basically just a wrapper around `*c_void` cause it's just a binding to C // most of it, but that's basically just a wrapper around `*c_void` cause it's just a binding to C
// code, so it's !Send and thus can't be held across await points. So we can't call any of the // code, so it's !Send and thus can't be held across await points. So we can't call any of the
// async `send` or `recv` methods in this function body, since those create await points. Which // async `send` or `recv` methods in this function body, since those create await points. Which
@@ -71,18 +67,10 @@ pub fn fill_default<T: Default>(vec: &mut Vec<T>, size: usize) {
#[allow(clippy::needless_pass_by_value)] #[allow(clippy::needless_pass_by_value)]
pub fn start_rendering( pub fn start_rendering(
path: &str, path: &str,
mut sender: Sender<Result<RenderInfo, RenderError>>, sender: Sender<Result<RenderInfo, RenderError>>,
receiver: Receiver<RenderNotif>, receiver: Receiver<RenderNotif>,
size: WindowSize size: WindowSize
) -> Result<(), SendError<Result<RenderInfo, RenderError>>> { ) -> Result<(), SendError<Result<RenderInfo, RenderError>>> {
// first, wait 'til we get told what the current starting area is so that we can set it to
// know what to render to
let mut area = loop {
if let RenderNotif::Area(r) = receiver.recv().unwrap() {
break r;
}
};
// We want this outside of 'reload so that if the doc reloads, the search term that somebody // We want this outside of 'reload so that if the doc reloads, the search term that somebody
// set will still get highlighted in the reloaded doc // set will still get highlighted in the reloaded doc
let mut search_term = None; let mut search_term = None;
@@ -93,9 +81,11 @@ pub fn start_rendering(
let col_h = size.height / size.rows; let col_h = size.height / size.rows;
let mut stored_doc = None; let mut stored_doc = None;
let mut invert = false;
let mut preserved_area = None;
'reload: loop { 'reload: loop {
let doc = match Document::from_file(path, None) { let doc = match Document::open(path) {
Err(e) => { Err(e) => {
// if there's an error, tell the main loop // if there's an error, tell the main loop
sender.send(Err(RenderError::Doc(e)))?; sender.send(Err(RenderError::Doc(e)))?;
@@ -125,7 +115,16 @@ pub fn start_rendering(
} }
}; };
let n_pages = doc.n_pages() as usize; let n_pages = match doc.page_count() {
Ok(n) => n as usize,
Err(e) => {
sender.send(Err(RenderError::Doc(e)))?;
// just basic backoff i think
sleep(Duration::from_secs(1));
continue 'reload;
}
};
sender.send(Ok(RenderInfo::NumPages(n_pages)))?; sender.send(Ok(RenderInfo::NumPages(n_pages)))?;
// We're using this vec of bools to indicate which page numbers have already been rendered, // We're using this vec of bools to indicate which page numbers have already been rendered,
@@ -133,7 +132,7 @@ pub fn start_rendering(
// `split_at_mut` at 0 initially (which bascially makes `right == rendered && left == []`), // `split_at_mut` at 0 initially (which bascially makes `right == rendered && left == []`),
// doing basically nothing, but if we get a notification that something has been jumped to, // doing basically nothing, but if we get a notification that something has been jumped to,
// then we can split at that page and render at both sides of it // then we can split at that page and render at both sides of it
let mut rendered = vec![]; let mut rendered = Vec::new();
fill_default::<PrevRender>(&mut rendered, n_pages); fill_default::<PrevRender>(&mut rendered, n_pages);
let mut start_point = 0; let mut start_point = 0;
@@ -142,24 +141,38 @@ pub fn start_rendering(
// document. If there was a mechanism to say 'start this for-loop over' then I would do // document. If there was a mechanism to say 'start this for-loop over' then I would do
// that, but I don't think such a thing exists, so this is our attempt // that, but I don't think such a thing exists, so this is our attempt
'render_pages: loop { 'render_pages: loop {
// next, we gotta wait 'til we get told what the current starting area is so that we can
// set it to know what to render to
let area = match preserved_area {
Some(a) => a,
None => {
let new_area = loop {
if let RenderNotif::Area(r) = receiver.recv().unwrap() {
break r;
}
};
preserved_area = Some(new_area);
new_area
}
};
// what we do with a notif is the same regardless of if we're in the middle of // what we do with a notif is the same regardless of if we're in the middle of
// rendering the list of pages or we're all done // rendering the list of pages or we're all done
macro_rules! handle_notif { macro_rules! handle_notif {
($notif:ident) => { ($notif:ident) => {
match $notif { match $notif {
RenderNotif::Reload => continue 'reload, RenderNotif::Reload => continue 'reload,
RenderNotif::Area(new_area) => { RenderNotif::Invert => {
let bigger = invert = !invert;
new_area.width > area.width || new_area.height > area.height; for page in &mut rendered {
area = new_area; page.successful = false;
// we only want to re-render pages if the new area is greater than the old
// one, 'cause then we might need sharper images to make it all look good.
// If the new area is smaller, then the same high-quality-rendered images
// will still look fine, so it's ok to leave it.
if bigger {
fill_default(&mut rendered, n_pages);
continue 'render_pages;
} }
continue 'render_pages;
}
RenderNotif::Area(new_area) => {
preserved_area = Some(new_area);
fill_default(&mut rendered, n_pages);
continue 'render_pages;
} }
RenderNotif::JumpToPage(page) => { RenderNotif::JumpToPage(page) => {
start_point = page; start_point = page;
@@ -205,8 +218,8 @@ pub fn start_rendering(
.map(|(idx, p)| (start_point - (idx + 1), p)) .map(|(idx, p)| (start_point - (idx + 1), p))
); );
let area_w = f64::from(area.width) * f64::from(col_w); let area_w = f32::from(area.width) * f32::from(col_w);
let area_h = f64::from(area.height) * f64::from(col_h); let area_h = f32::from(area.height) * f32::from(col_h);
// we go through each page // we go through each page
for (num, rendered) in page_iter { for (num, rendered) in page_iter {
@@ -230,12 +243,12 @@ pub fn start_rendering(
// We know this is in range 'cause we're iterating over it but we still just want // We know this is in range 'cause we're iterating over it but we still just want
// to be safe // to be safe
let Some(page) = doc.page(num as i32) else { let page = match doc.load_page(num as i32) {
sender.send(Err(RenderError::Render(format!( Err(e) => {
"Couldn't get page {num} ({}) of doc?", sender.send(Err(RenderError::Doc(e)))?;
num as i32 continue;
))))?; }
continue; Ok(p) => p
}; };
let rendered_with_no_results = let rendered_with_no_results =
@@ -246,6 +259,7 @@ pub fn start_rendering(
&page, &page,
search_term.as_deref(), search_term.as_deref(),
rendered_with_no_results, rendered_with_no_results,
invert,
(area_w, area_h) (area_w, area_h)
) { ) {
// If we've already rendered it just fine and we don't need to render it again, // If we've already rendered it just fine and we don't need to render it again,
@@ -257,26 +271,34 @@ pub fn start_rendering(
// we make a potentially incorrect assumption here that writing the context // we make a potentially incorrect assumption here that writing the context
// to a png won't fail, and mark that it all rendered correctly here before // to a png won't fail, and mark that it all rendered correctly here before
// spawning off the thread to do so and send it. // spawning off the thread to do so and send it.
rendered.contained_term = Some(ctx.num_results > 0); rendered.contained_term = Some(ctx.result_rects.is_empty());
rendered.successful = true; rendered.successful = true;
// if this is the page that the user is currently trying to look at, don't let w = ctx.pixmap.width();
// bother spawning off a thread to render it to a png - it'll only slow let h = ctx.pixmap.height();
// down the time til the user can see it (due to the overhead of creating a let cap = (w * h * u32::from(ctx.pixmap.n())) as usize + 16;
// thread), but we still want to spawn threads to render the other pages let mut pixels = Vec::with_capacity(cap);
// since the effects of parallelizing that will be noticeable if the user if let Err(e) = ctx.pixmap.write_to(&mut pixels, mupdf::ImageFormat::PNM) {
// tries to move through pages more quickly sender.send(Err(RenderError::Doc(e)))?;
if num == start_point { continue;
render_ctx_to_png(&ctx, &mut sender, (col_w, col_h), num)?; };
} else {
let mut sender = sender.clone(); sender.send(Ok(RenderInfo::Page(PageInfo {
thread::spawn(move || { img_data: ImageData {
render_ctx_to_png(&ctx, &mut sender, (col_w, col_h), num) pixels,
}); cell_area: Rect {
} x: 0,
y: 0,
width: (ctx.surface_w / f32::from(col_w)) as u16,
height: (ctx.surface_h / f32::from(col_h)) as u16
}
},
page_num: num,
result_rects: ctx.result_rects
})))?;
} }
// And if we got an error, then obviously we need to propagate that // And if we got an error, then obviously we need to propagate that
Err(e) => sender.send(Err(RenderError::Render(e)))? Err(e) => sender.send(Err(RenderError::Doc(e)))?
} }
} }
@@ -295,34 +317,38 @@ pub fn start_rendering(
} }
struct RenderedContext { struct RenderedContext {
surface: Surface, pixmap: Pixmap,
num_results: usize, surface_w: f32,
surface_width: f64, surface_h: f32,
surface_height: f64 result_rects: Vec<HighlightRect>
} }
/// SAFETY: I think this is safe because, although the backing struct for `Surface` does contain
/// pointers to like the cairo_backend_t struct that all the cairo stuff is using, that struct is
/// basically just a vtable, so accessing it from multiple threads *should* be safe since we're
/// just calling the same functions with different data. The only other thing it holds reference to
/// is a `cairo_device_t`, but that seems to be thread-safe because it's managed through ref counts
/// and a mutex. Also, as far as I can tell from reading the source code, write_to_png_stream (the
/// only function we call on this struct) doesn't access the device at all, so we should be fine
/// there.
/// We want this to be Send so that we can delegate the png writing to a separate thread (since
/// that's the thing that takes the most time, by far, in this app).
unsafe impl Send for RenderedContext {}
fn render_single_page_to_ctx( fn render_single_page_to_ctx(
page: &Page, page: &Page,
search_term: Option<&str>, search_term: Option<&str>,
already_rendered_no_results: bool, already_rendered_no_results: bool,
(area_w, area_h): (f64, f64) invert: bool,
) -> Result<Option<RenderedContext>, String> { (area_w, area_h): (f32, f32)
let mut result_rects = search_term ) -> Result<Option<RenderedContext>, mupdf::error::Error> {
.as_ref() let mut max_hits = 10;
.map(|term| page.find_text_with_options(term, FindFlags::DEFAULT | FindFlags::MULTILINE)) let result_rects = loop {
.unwrap_or_default(); let rects = search_term
.as_ref()
// mupdf allocates a buffer of the size we give it to try to fill it with results. If we
// pass in u32::MAX, it allocates too much memory to function. If we pass too small of a
// number in, we may miss out on some of the results. Ideally, we'd like to make a better
// interface than this, but we're stuck with this kinda ugly looping until we make sure
// that we've found every instance of it on this page.
.map(|term| page.search(term, max_hits))
.transpose()?
.unwrap_or_default();
if rects.len() < (max_hits as usize) {
break rects;
}
max_hits *= 2;
};
// If there are no search terms on this page, and we've already rendered it with no search // If there are no search terms on this page, and we've already rendered it with no search
// terms, then just return none to avoid this computation // terms, then just return none to avoid this computation
@@ -331,7 +357,8 @@ fn render_single_page_to_ctx(
} }
// then, get the size of the page // then, get the size of the page
let (p_width, p_height) = page.size(); let bounds = page.bounds()?;
let (p_width, p_height) = (bounds.x1 - bounds.x0, bounds.y1 - bounds.y0);
// and get its aspect ratio // and get its aspect ratio
let p_aspect_ratio = p_width / p_height; let p_aspect_ratio = p_width / p_height;
@@ -353,93 +380,50 @@ fn render_single_page_to_ctx(
area_h / p_height area_h / p_height
}; };
let surface_width = p_width * scale_factor; let surface_w = p_width * scale_factor;
let surface_height = p_height * scale_factor; let surface_h = p_height * scale_factor;
let surface = cairo::ImageSurface::create( let colorspace = Colorspace::device_rgb();
Format::Rgb16_565, let matrix = Matrix::new_scale(scale_factor, scale_factor);
// No matter how big you make these arguments, the image will be drawn at the same
// size. So if you make them really big, the image will be drawn on a quarter of it. If
// you make them really small, the image will cover more than all of the surface.
//
// However, that only stands as long as you don't scale the context that you place this
// surface into. If you scale the dimensions of this image by n, then scale the context
// by that same amount, then it'll still fit perfectly into the context, but be
// rendered at higher quality.
surface_width as i32,
surface_height as i32
)
.map_err(|e| format!("Couldn't create ImageSurface: {e}"))?;
surface.set_device_scale(scale_factor, scale_factor);
let ctx = Context::new(surface).map_err(|e| format!("Couldn't create Context: {e}"))?; let mut pixmap = page.to_pixmap(&matrix, &colorspace, 0.0, false)?;
if invert {
// The default background color of PDFs (at least, I think) is white, so we need to set pixmap.invert()?;
// that as the background color, then paint, then render.
ctx.set_source_rgba(1.0, 1.0, 1.0, 1.0);
ctx.set_antialias(Antialias::None);
ctx.paint()
.map_err(|e| format!("Couldn't paint Context: {e}"))?;
page.render(&ctx);
let num_results = result_rects.len();
if !result_rects.is_empty() {
let mut highlight_color = Color::new();
highlight_color.set_red((u16::MAX / 5) * 4);
highlight_color.set_green((u16::MAX / 5) * 4);
let mut old_rect = Rectangle::new();
for rect in &mut result_rects {
// According to https://gitlab.freedesktop.org/poppler/poppler/-/issues/763, these rects
// need to be corrected since they use different references as the y-coordinate base
rect.set_y1(p_height - rect.y1());
rect.set_y2(p_height - rect.y2());
page.render_selection(
&ctx,
rect,
&mut old_rect,
SelectionStyle::Glyph,
&mut Color::new(),
&mut highlight_color
);
}
} }
let (x_res, y_res) = pixmap.resolution();
let new_x = (x_res as f32 * scale_factor) as i32;
let new_y = (y_res as f32 * scale_factor) as i32;
pixmap.set_resolution(new_x, new_y);
let result_rects = result_rects
.into_iter()
.map(|quad| {
let ul_x = (quad.ul.x * scale_factor) as u32;
let ul_y = (quad.ul.y * scale_factor) as u32;
let lr_x = (quad.lr.x * scale_factor) as u32;
let lr_y = (quad.lr.y * scale_factor) as u32;
HighlightRect {
ul_x,
ul_y,
lr_x,
lr_y
}
})
.collect::<Vec<_>>();
Ok(Some(RenderedContext { Ok(Some(RenderedContext {
surface: ctx.target(), pixmap,
num_results, surface_w,
surface_width, surface_h,
surface_height result_rects
})) }))
} }
fn render_ctx_to_png( #[derive(Clone)]
ctx: &RenderedContext, pub struct HighlightRect {
sender: &mut Sender<Result<RenderInfo, RenderError>>, pub ul_x: u32,
(col_w, col_h): (u16, u16), pub ul_y: u32,
page: usize pub lr_x: u32,
) -> Result<(), SendError<Result<RenderInfo, RenderError>>> { pub lr_y: u32
let mut img_data = Vec::with_capacity((ctx.surface_height * ctx.surface_width) as usize);
match ctx.surface.write_to_png(&mut img_data) {
Err(e) => sender.send(Err(RenderError::Render(format!(
"Couldn't write surface to png: {e}"
)))),
Ok(()) => sender.send(Ok(RenderInfo::Page(PageInfo {
img_data: ImageData {
data: img_data,
area: Rect {
width: ctx.surface_width as u16 / col_w,
height: ctx.surface_height as u16 / col_h,
x: 0,
y: 0
}
},
page,
search_results: ctx.num_results
})))
}
} }
+250 -110
View File
@@ -1,18 +1,26 @@
use std::{borrow::Cow, io::stdout, num::NonZeroUsize, rc::Rc}; use std::{borrow::Cow, io::stdout, num::NonZeroUsize};
use crossterm::{ use crossterm::{
event::{Event, KeyCode, MouseEventKind}, event::{Event, KeyCode, KeyModifiers, MouseEventKind},
execute, execute,
terminal::BeginSynchronizedUpdate terminal::{
BeginSynchronizedUpdate, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode,
enable_raw_mode
}
};
use nix::{
sys::signal::{Signal::SIGSTOP, kill},
unistd::Pid
}; };
use ratatui::{ use ratatui::{
Frame,
layout::{Constraint, Flex, Layout, Rect}, layout::{Constraint, Flex, Layout, Rect},
style::{Color, Style}, style::{Color, Style},
text::Span, symbols::border,
widgets::{Block, Borders, Padding}, text::{Span, Text},
Frame widgets::{Block, Borders, Clear, Padding}
}; };
use ratatui_image::{protocol::Protocol, Image}; use ratatui_image::{Image, protocol::Protocol};
use crate::{renderer::RenderError, skip::Skip}; use crate::{renderer::RenderError, skip::Skip};
@@ -25,7 +33,8 @@ pub struct Tui {
// jumping to a specific page // jumping to a specific page
prev_msg: Option<BottomMessage>, prev_msg: Option<BottomMessage>,
rendered: Vec<RenderedInfo>, rendered: Vec<RenderedInfo>,
page_constraints: PageConstraints page_constraints: PageConstraints,
showing_help_msg: bool
} }
#[derive(Default, Debug)] #[derive(Default, Debug)]
@@ -70,6 +79,12 @@ struct RenderedInfo {
num_results: Option<usize> num_results: Option<usize>
} }
#[derive(PartialEq)]
pub struct RenderLayout {
pub page_area: Rect,
pub top_and_bottom: Option<(Rect, Rect)>
}
impl Tui { impl Tui {
pub fn new(name: String, max_wide: Option<NonZeroUsize>, r_to_l: bool) -> Tui { pub fn new(name: String, max_wide: Option<NonZeroUsize>, r_to_l: bool) -> Tui {
Self { Self {
@@ -79,121 +94,138 @@ impl Tui {
bottom_msg: BottomMessage::Help, bottom_msg: BottomMessage::Help,
last_render: LastRender::default(), last_render: LastRender::default(),
rendered: vec![], rendered: vec![],
page_constraints: PageConstraints { max_wide, r_to_l } page_constraints: PageConstraints { max_wide, r_to_l },
showing_help_msg: false
} }
} }
pub fn main_layout(frame: &Frame<'_>) -> Rc<[Rect]> { pub fn main_layout(frame: &Frame<'_>, fullscreened: bool) -> RenderLayout {
Layout::default() if fullscreened {
.constraints([ RenderLayout {
Constraint::Length(3), page_area: frame.area(),
Constraint::Fill(1), top_and_bottom: None
Constraint::Length(3) }
]) } else {
.horizontal_margin(2) let layout = Layout::default()
.vertical_margin(1) .constraints([
.split(frame.area()) Constraint::Length(3),
Constraint::Fill(1),
Constraint::Length(3)
])
.horizontal_margin(2)
.vertical_margin(1)
.split(frame.area());
RenderLayout {
page_area: layout[1],
top_and_bottom: Some((layout[0], layout[2]))
}
}
} }
// TODO: Make a way to fill the width of the screen with one page and scroll down to view it // TODO: Make a way to fill the width of the screen with one page and scroll down to view it
pub fn render(&mut self, frame: &mut Frame<'_>, main_area: &[Rect]) { pub fn render(&mut self, frame: &mut Frame<'_>, full_layout: &RenderLayout) {
let top_block = Block::new() if self.showing_help_msg {
.padding(Padding { self.render_help_msg(frame);
right: 2, return;
left: 2, }
..Padding::default()
})
.borders(Borders::BOTTOM);
let top_area = top_block.inner(main_area[0]); if let Some((top_area, bottom_area)) = full_layout.top_and_bottom {
let top_block = Block::new()
.padding(Padding {
right: 2,
left: 2,
..Padding::default()
})
.borders(Borders::BOTTOM);
let page_nums_text = format!("{} / {}", self.page + 1, self.rendered.len()); let top_area = top_block.inner(top_area);
let top_layout = Layout::horizontal([ let page_nums_text = format!("{} / {}", self.page + 1, self.rendered.len());
Constraint::Fill(1),
Constraint::Length(page_nums_text.len() as u16)
])
.split(top_area);
let title = Span::styled(&self.name, Style::new().fg(Color::Cyan)); let top_layout = Layout::horizontal([
Constraint::Fill(1),
Constraint::Length(page_nums_text.len() as u16)
])
.split(top_area);
let page_nums = Span::styled(&page_nums_text, Style::new().fg(Color::Cyan)); let title = Span::styled(&self.name, Style::new().fg(Color::Cyan));
frame.render_widget(top_block, main_area[0]); let page_nums = Span::styled(&page_nums_text, Style::new().fg(Color::Cyan));
frame.render_widget(title, top_layout[0]);
frame.render_widget(page_nums, top_layout[1]);
let bottom_block = Block::new() frame.render_widget(top_block, top_area);
.padding(Padding { frame.render_widget(title, top_layout[0]);
top: 1, frame.render_widget(page_nums, top_layout[1]);
right: 2,
left: 2,
bottom: 0
})
.borders(Borders::TOP);
let bottom_area = bottom_block.inner(main_area[2]);
frame.render_widget(bottom_block, main_area[2]); let bottom_block = Block::new()
.padding(Padding {
top: 1,
right: 2,
left: 2,
bottom: 0
})
.borders(Borders::TOP);
let bottom_inside_block = bottom_block.inner(bottom_area);
let rendered_str = if !self.rendered.is_empty() { frame.render_widget(bottom_block, bottom_area);
format!(
"Rendered: {}%",
(self.rendered.iter().filter(|i| i.img.is_some()).count() * 100)
/ self.rendered.len()
)
} else {
String::new()
};
let bottom_layout = Layout::horizontal([
Constraint::Fill(1),
Constraint::Length(rendered_str.len() as u16)
])
.split(bottom_area);
let rendered_span = Span::styled(&rendered_str, Style::new().fg(Color::Cyan)); let rendered_str = if !self.rendered.is_empty() {
frame.render_widget(rendered_span, bottom_layout[1]); format!(
"Rendered: {}%",
(self.rendered.iter().filter(|i| i.img.is_some()).count() * 100)
/ self.rendered.len()
)
} else {
String::new()
};
let bottom_layout = Layout::horizontal([
Constraint::Fill(1),
Constraint::Length(rendered_str.len() as u16)
])
.split(bottom_inside_block);
let (msg_str, color): (Cow<'_, str>, _) = match self.bottom_msg { let rendered_span = Span::styled(&rendered_str, Style::new().fg(Color::Cyan));
BottomMessage::Help => ( frame.render_widget(rendered_span, bottom_layout[1]);
"/: Search, g: Go To Page, n: Next Search Result, N: Previous Search Result".into(),
Color::Blue let (msg_str, color): (Cow<'_, str>, _) = match self.bottom_msg {
), BottomMessage::Help => ("?: Show help page".into(), Color::Blue),
BottomMessage::Error(ref e) => (e.as_str().into(), Color::Red), BottomMessage::Error(ref e) => (e.as_str().into(), Color::Red),
BottomMessage::Input(ref input_state) => ( BottomMessage::Input(ref input_state) => (
match input_state { match input_state {
InputCommand::GoToPage(page) => format!("Go to: {page}"), InputCommand::GoToPage(page) => format!("Go to: {page}"),
InputCommand::Search(s) => format!("Search: {s}") InputCommand::Search(s) => format!("Search: {s}")
} }
.into(),
Color::Blue
),
BottomMessage::SearchResults(ref term) => {
let num_found = self
.rendered
.iter()
.filter_map(|r| r.num_results)
.sum::<usize>();
let num_searched = self
.rendered
.iter()
.filter(|r| r.num_results.is_some())
.count() * 100;
(
format!(
"Results for '{term}': {num_found} (searched: {}%)",
num_searched / self.rendered.len()
)
.into(), .into(),
Color::Blue Color::Blue
) ),
} BottomMessage::SearchResults(ref term) => {
BottomMessage::Reloaded => ("Document was reloaded!".into(), Color::Blue) let num_found = self
}; .rendered
.iter()
.filter_map(|r| r.num_results)
.sum::<usize>();
let num_searched = self
.rendered
.iter()
.filter(|r| r.num_results.is_some())
.count() * 100;
(
format!(
"Results for '{term}': {num_found} (searched: {}%)",
num_searched / self.rendered.len()
)
.into(),
Color::Blue
)
}
BottomMessage::Reloaded => ("Document was reloaded!".into(), Color::Blue)
};
let span = Span::styled(msg_str, Style::new().fg(color)); let span = Span::styled(msg_str, Style::new().fg(color));
frame.render_widget(span, bottom_layout[0]); frame.render_widget(span, bottom_layout[0]);
}
let mut img_area = main_area[1]; let mut img_area = full_layout.page_area;
let size = frame.area(); let size = frame.area();
if size == self.last_render.rect { if size == self.last_render.rect {
@@ -272,7 +304,7 @@ impl Tui {
fn render_single_page(&mut self, frame: &mut Frame<'_>, page_idx: usize, img_area: Rect) { fn render_single_page(&mut self, frame: &mut Frame<'_>, page_idx: usize, img_area: Rect) {
match self.rendered[page_idx].img { match self.rendered[page_idx].img {
Some(ref page_img) => frame.render_widget(Image::new(page_img), img_area), Some(ref mut page_img) => frame.render_widget(Image::new(page_img), img_area),
None => Self::render_loading_in(frame, img_area) None => Self::render_loading_in(frame, img_area)
}; };
} }
@@ -407,6 +439,12 @@ impl Tui {
))); )));
Some(InputAction::Redraw) Some(InputAction::Redraw)
} }
'i' => Some(InputAction::Invert),
'?' => {
self.showing_help_msg = true;
Some(InputAction::Redraw)
}
'f' => Some(InputAction::Fullscreen),
'n' if self.page < self.rendered.len() - 1 => { 'n' if self.page < self.rendered.len() - 1 => {
// TODO: If we can't find one, then maybe like block until we've verified // TODO: If we can't find one, then maybe like block until we've verified
// all the pages have been checked? // all the pages have been checked?
@@ -434,6 +472,34 @@ impl Tui {
jump_to_page(&mut self.page, &mut self.last_render.rect, prev_page) jump_to_page(&mut self.page, &mut self.last_render.rect, prev_page)
} }
'z' if key.modifiers.contains(KeyModifiers::CONTROL) => {
// [todo] better error handling here?
let mut backend = stdout();
execute!(
&mut backend,
LeaveAlternateScreen,
crossterm::cursor::Show
)
.unwrap();
disable_raw_mode().unwrap();
// This process will hang after the SIGSTOP call until we get
// foregrounded again by something else, at which point we need to
// re-setup everything so that it all gets drawn again.
kill(Pid::this(), SIGSTOP).unwrap();
enable_raw_mode().unwrap();
execute!(
&mut backend,
EnterAlternateScreen,
crossterm::cursor::Hide
)
.unwrap();
self.last_render.rect = Rect::default();
Some(InputAction::Redraw)
}
_ => None _ => None
} }
} }
@@ -450,8 +516,8 @@ impl Tui {
KeyCode::Down => self.change_page(PageChange::Next, ChangeAmount::WholeScreen), KeyCode::Down => self.change_page(PageChange::Next, ChangeAmount::WholeScreen),
KeyCode::Left => self.change_page(PageChange::Prev, ChangeAmount::Single), KeyCode::Left => self.change_page(PageChange::Prev, ChangeAmount::Single),
KeyCode::Up => self.change_page(PageChange::Prev, ChangeAmount::WholeScreen), KeyCode::Up => self.change_page(PageChange::Prev, ChangeAmount::WholeScreen),
KeyCode::Esc => match self.bottom_msg { KeyCode::Esc => match (self.showing_help_msg, &self.bottom_msg) {
BottomMessage::Help => Some(InputAction::QuitApp), (false, BottomMessage::Help) => Some(InputAction::QuitApp),
_ => { _ => {
// When we hit escape, we just want to pop off the current message and // When we hit escape, we just want to pop off the current message and
// show the underlying one. // show the underlying one.
@@ -480,7 +546,9 @@ impl Tui {
Some(InputAction::JumpingToPage(zero_page)) Some(InputAction::JumpingToPage(zero_page))
} else { } else {
self.set_msg(MessageSetting::Some(BottomMessage::Error( self.set_msg(MessageSetting::Some(BottomMessage::Error(
format!("Cannot jump to page {page}; there are only {rendered_len} pages in the document") format!(
"Cannot jump to page {page}; there are only {rendered_len} pages in the document"
)
))); )));
Some(InputAction::Redraw) Some(InputAction::Redraw)
} }
@@ -534,8 +602,8 @@ impl Tui {
pub fn show_error(&mut self, err: RenderError) { pub fn show_error(&mut self, err: RenderError) {
self.set_msg(MessageSetting::Some(BottomMessage::Error(match err { self.set_msg(MessageSetting::Some(BottomMessage::Error(match err {
RenderError::Notify(e) => format!("Auto-reload failed: {e}"), RenderError::Notify(e) => format!("Auto-reload failed: {e}"),
RenderError::Doc(e) => format!("Couldn't open document: {e}"), RenderError::Doc(e) => format!("Couldn't process document: {e}"),
RenderError::Render(e) => format!("Couldn't render page: {e}") RenderError::Converting(e) => format!("Couldn't convert page after rendering: {e}")
}))); })));
} }
@@ -560,16 +628,88 @@ impl Tui {
self.prev_msg = None; self.prev_msg = None;
self.bottom_msg = BottomMessage::default(); self.bottom_msg = BottomMessage::default();
} }
MessageSetting::Pop => self.bottom_msg = self.prev_msg.take().unwrap_or_default() MessageSetting::Pop =>
if self.showing_help_msg {
self.last_render.rect = Rect::default();
self.showing_help_msg = false;
} else {
self.bottom_msg = self.prev_msg.take().unwrap_or_default();
},
} }
} }
pub fn render_help_msg(&self, frame: &mut Frame<'_>) {
let frame_area = frame.area();
frame.render_widget(Clear, frame_area);
let block = Block::new()
.title("Help")
.padding(Padding::proportional(1))
.borders(Borders::ALL)
.border_set(border::ROUNDED)
.border_style(Color::Blue);
let help_span = Text::raw(HELP_PAGE);
let max_w: u16 = HELP_PAGE
.lines()
.map(str::len)
.max()
.unwrap_or_default()
.try_into()
.expect("Every help text line must be shorter than u16::MAX");
let layout = Layout::horizontal([
Constraint::Fill(1),
Constraint::Length(max_w + 6),
Constraint::Fill(1)
])
.split(frame_area);
let block_area = Layout::vertical([
Constraint::Fill(1),
Constraint::Length(u16::try_from(HELP_PAGE.lines().count()).unwrap() + 4),
Constraint::Fill(1)
])
.split(layout[1]);
let block_inner = block.inner(block_area[1]);
frame.render_widget(block, block_area[1]);
frame.render_widget(help_span, block_inner);
}
} }
static HELP_PAGE: &str = "\
l, h, left, right:
Go forward/backwards a single page
j, k, down, up:
Go forwards/backwards a screen's worth of pages
q, esc:
Quit
g:
Go to specific page (type numbers after 'g')
/:
Search
n, N:
Next/Previous search result
i:
Invert colors
f:
Remove borders/fullscreen
?:
Show this page
ctrl+z:
Suspend & background tdf \
";
pub enum InputAction { pub enum InputAction {
Redraw, Redraw,
JumpingToPage(usize), JumpingToPage(usize),
Search(String), Search(String),
QuitApp QuitApp,
Invert,
Fullscreen
} }
#[derive(Copy, Clone)] #[derive(Copy, Clone)]