Compare commits

...

3 Commits

Author SHA1 Message Date
2ff15bbce0 Fix clippy warnings 2023-11-21 18:30:34 +01:00
874120108b Remove commented code 2023-11-21 18:20:05 +01:00
a9729005ff Fix cargo warnings 2023-11-21 18:16:27 +01:00
3 changed files with 38 additions and 159 deletions

View File

@@ -1,42 +1,32 @@
use cairo::{Context, Format, ImageSurface, ImageSurfaceData, ImageSurfaceDataOwned};
use glib::{clone, Bytes};
use gtk::{gdk::Texture, Picture};
use pdfium_render::{pdfium, prelude::*};
use poppler::{Document, Page};
use std::{
collections::BTreeMap,
path::{Path, PathBuf},
sync::{Arc, Mutex},
rc::Rc,
};
use async_channel::{Receiver, Sender};
use async_channel::Sender;
type PageNumber = usize;
pub type MyPageType = Page;
pub struct PageCache {
document: Document,
// render_config: PdfRenderConfig,
max_num_stored_pages: usize,
pages: BTreeMap<usize, Arc<MyPageType>>,
pages: BTreeMap<usize, Rc<MyPageType>>,
}
impl PageCache {
pub fn new(
document: Document,
// render_config: PdfRenderConfig,
max_num_stored_pages: usize,
) -> Self {
pub fn new(document: Document, max_num_stored_pages: usize) -> Self {
PageCache {
document,
// render_config,
max_num_stored_pages,
pages: BTreeMap::new(),
}
}
pub fn get_page(&self, page_number: usize) -> Option<Arc<MyPageType>> {
self.pages.get(&page_number).map(Arc::clone)
pub fn get_page(&self, page_number: usize) -> Option<Rc<MyPageType>> {
self.pages.get(&page_number).map(Rc::clone)
}
pub fn cache_pages(&mut self, page_numbers: Vec<usize>) {
@@ -46,26 +36,8 @@ impl PageCache {
continue;
}
// let page = self.document.pages().get(page_number as u16).unwrap();
// let image = page.render_with_config(&self.render_config).unwrap();
// // TODO: does this clone?
// let bytes = Bytes::from(image.as_bytes());
// let page = Texture::from_bytes(&bytes).unwrap();
if let Some(page) = self.document.page(page_number as i32) {
// let image = Picture::new();
// // poppler.rend
// let surface = ImageSurface::create(Format::Rgb24, 10, 10).unwrap();
// let context = Context::new(&surface).unwrap();
// page.render(&context);
// context.paint().expect("Could not paint");
// println!("Surface: {:?}", surface);
// let page = surface;
// let page = surface.take_data().unwrap();
// context.draw
self.pages.insert(page_number, Arc::new(page));
self.pages.insert(page_number, Rc::new(page));
if self.pages.len() > self.max_num_stored_pages && self.pages.len() > 2 {
let _result = self.remove_most_distant_page(page_number);
@@ -100,12 +72,12 @@ impl PageCache {
CacheCommand::GetCurrentTwoPages { page_left_number } => {
if let Some(page_left) = self.get_page(page_left_number) {
if let Some(page_right) = self.get_page(page_left_number + 1) {
Some(CacheResponse::TwoPagesLoaded {
Some(CacheResponse::TwoPagesRetrieved {
page_left,
page_right,
})
} else {
Some(CacheResponse::SinglePageLoaded { page: page_left })
Some(CacheResponse::SinglePageRetrieved { page: page_left })
}
} else {
// TODO: if page left was not empty, this could be because page turning was too quick.
@@ -127,12 +99,12 @@ pub enum CacheResponse {
DocumentLoaded {
num_pages: usize,
},
SinglePageLoaded {
page: Arc<MyPageType>,
SinglePageRetrieved {
page: Rc<MyPageType>,
},
TwoPagesLoaded {
page_left: Arc<MyPageType>,
page_right: Arc<MyPageType>,
TwoPagesRetrieved {
page_left: Rc<MyPageType>,
page_right: Rc<MyPageType>,
},
}
@@ -141,21 +113,11 @@ where
F: Fn(CacheResponse) + 'static,
{
let (command_sender, command_receiver) = async_channel::unbounded();
// let (response_sender, response_receiver) = async_channel::unbounded();
let path: PathBuf = file.as_ref().to_path_buf();
glib::spawn_future_local(async move {
println!("async loading of document:...");
// Load pdf document here since Document is not thread safe and cannot be passed from main thread
// let pdfium = Pdfium::default();
// let document = pdfium.load_pdf_from_file(&path, None).unwrap();
// let render_config = PdfRenderConfig::new()
// .set_target_width(2000)
// .set_maximum_height(2000)
// .rotate_if_landscape(PdfPageRenderRotation::Degrees90, true);
// let num_pages = document.pages().iter().count();
let uri = format!("file://{}", path.to_str().unwrap());
let document = poppler::Document::from_file(&uri, None).unwrap();
@@ -164,20 +126,15 @@ where
let mut cache = PageCache::new(document, 10);
loop {
if let Ok(command) = command_receiver.recv().await {
// if !command_receiver.is_empty() {
// // ignore command if more up to date ones are available
// continue;
// }
if let Some(response) = cache.process_command(command).await {
// response_sender.send_blocking(response).unwrap();
println!("Command processed, activating receiver....");
receiver(response);
}
} else {
// Sender was closed, cache not needed anymore
break;
while let Ok(command) = command_receiver.recv().await {
// if !command_receiver.is_empty() {
// // ignore command if more up to date ones are available
// continue;
// }
if let Some(response) = cache.process_command(command).await {
// response_sender.send_blocking(response).unwrap();
println!("Command processed, activating receiver....");
receiver(response);
}
}
});

View File

@@ -1,22 +1,7 @@
use std::{
cell::RefCell, collections::BTreeMap, path::Path, rc::Rc, sync::Arc, thread, time::Duration,
};
use cairo::Context;
use async_channel::Sender;
use cairo::{Context, Format, ImageSurface, ImageSurfaceData, ImageSurfaceDataOwned};
use gtk::{
gdk::Paintable, gio, glib, prelude::*, subclass::drawing_area, Application, ApplicationWindow,
Box, Button, DrawingArea, FileChooserAction, FileChooserDialog, HeaderBar, Label, Orientation,
Picture, ResponseType,
};
use poppler::{Document, Page};
use crate::{
cache::{self, CacheCommand, MyPageType, PageCache},
ui::Ui,
};
use glib::clone;
use gtk::prelude::*;
use crate::ui::Ui;
use gtk::{prelude::*, DrawingArea};
pub fn draw(ui: &mut Ui, area: &DrawingArea, context: &Context) {
println!("Draw");
@@ -25,29 +10,12 @@ pub fn draw(ui: &mut Ui, area: &DrawingArea, context: &Context) {
}
let document_canvas = ui.document_canvas.as_ref().unwrap();
// let left_page = document_canvas.left_page.as_ref().unwrap();
// let left_page = left_page.as_ref();
// let data: Vec<u8> = left_page.into_iter().map(|x| x.to_owned()).collect();
// let data: Vec<u8> = page.iter().map(|x| x.clone()).collect();
// let surface = ImageSurface::create_for_data(data, Format::Rgb24, 0, 0, 0).unwrap();
// context.set_source_surface(surface, 0.0, 0.0);
// context.paint();
if document_canvas.num_pages.unwrap_or(0) > 1 {
draw_two_pages(ui, area, context);
} else {
draw_single_page(ui, area, context);
}
// gio::spawn_blocking(move || {
// ui.document_canvas
// .as_mut()
// .unwrap()
// .cache_surrounding_pages();
// });
println!("Finished drawing");
document_canvas.cache_surrounding_pages();
}
@@ -136,18 +104,8 @@ fn draw_single_page(ui: &Ui, area: &DrawingArea, context: &Context) {
}
let page = document_canvas.left_page.as_ref().unwrap();
// let page = ImageSurface::create_for_data(page.into(), Format::Rgb24, 0, 0, 0).unwrap();
// context.set_source_surface(page, 0, 0);
// Draw background
// context.set_source_rgba(1.0, 1.0, 1.0, 1.0);
// context.paint().unwrap();
// context.fill().expect("uh oh");
// context.paint().unwrap();
let (w, h) = page.size();
// let w = page.width() as f64;
// let h = page.height() as f64;
let width_diff = area.width() as f64 / w;
let height_diff = area.height() as f64 / h;

View File

@@ -1,18 +1,14 @@
use std::{
cell::RefCell, collections::BTreeMap, path::Path, rc::Rc, sync::Arc, thread, time::Duration,
};
use std::{cell::RefCell, path::Path, rc::Rc};
use async_channel::Sender;
use cairo::{Context, Format, ImageSurface, ImageSurfaceData, ImageSurfaceDataOwned};
use cairo::{Context, Format, ImageSurface};
use gtk::{
gdk::Paintable, gio, glib, prelude::*, subclass::drawing_area, Application, ApplicationWindow,
Box, Button, DrawingArea, FileChooserAction, FileChooserDialog, HeaderBar, Label, Orientation,
Picture, ResponseType,
glib, Application, ApplicationWindow, Box, Button, DrawingArea, FileChooserAction,
FileChooserDialog, HeaderBar, Label, Orientation, ResponseType,
};
use poppler::{Document, Page};
use crate::{
cache::{self, CacheCommand, MyPageType, PageCache},
cache::{self, CacheCommand, MyPageType},
draw,
};
use glib::clone;
@@ -24,7 +20,6 @@ pub struct Ui {
header_bar: gtk::HeaderBar,
page_indicator: gtk::Label,
drawing_area: gtk::DrawingArea,
picture: Picture,
pub drawing_context: cairo::Context,
pub document_canvas: Option<DocumentCanvas>,
}
@@ -33,8 +28,8 @@ pub struct DocumentCanvas {
current_page_number: usize,
pub num_pages: Option<usize>,
page_cache_sender: Sender<CacheCommand>,
pub left_page: Option<Arc<MyPageType>>,
pub right_page: Option<Arc<MyPageType>>,
pub left_page: Option<Rc<MyPageType>>,
pub right_page: Option<Rc<MyPageType>>,
}
impl DocumentCanvas {
@@ -49,7 +44,7 @@ impl DocumentCanvas {
}
pub fn increase_page_number(&mut self) {
if self.current_page_number >= self.num_pages.unwrap_or(0) - 2 {
if self.current_page_number >= self.num_pages.unwrap_or(0).saturating_sub(2) {
return;
}
@@ -57,11 +52,7 @@ impl DocumentCanvas {
}
pub fn decrease_page_number(&mut self) {
if self.current_page_number <= 0 {
return;
}
self.current_page_number -= 1;
self.current_page_number = self.current_page_number.saturating_sub(1);
}
pub fn cache_initial_pages(&self) {
@@ -136,7 +127,7 @@ fn update_page_status(ui: &Ui) {
ui.page_indicator.set_label(page_status.as_str());
}
fn process_right_click(ui: &mut Ui, x: f64, y: f64) {
fn process_right_click(ui: &mut Ui, _x: f64, _y: f64) {
if ui.document_canvas.is_none() {
return;
}
@@ -200,12 +191,6 @@ impl Ui {
.hexpand(true)
.vexpand(true)
.build(),
picture: Picture::builder()
.width_request(400)
.height_request(300)
.hexpand(true)
.vexpand(true)
.build(),
drawing_context: create_drawing_context(),
document_canvas: None,
};
@@ -213,7 +198,6 @@ impl Ui {
ui.borrow().header_bar.pack_start(&open_file_button);
app_wrapper.prepend(&ui.borrow().drawing_area);
// app_wrapper.prepend(&ui.borrow().picture);
app_wrapper.append(&ui.borrow().bottom_bar);
ui.borrow().bottom_bar.append(&ui.borrow().page_indicator);
@@ -231,8 +215,6 @@ impl Ui {
ui.borrow().drawing_area.add_controller(click_left);
ui.borrow().drawing_area.add_controller(click_right);
// ui.borrow().picture.add_controller(click_left);
// ui.borrow().picture.add_controller(click_right);
ui.borrow().drawing_area.set_draw_func(
glib::clone!(@weak ui => move |area, context, _, _| {
@@ -277,7 +259,6 @@ fn choose_file(ui: Rc<RefCell<Ui>>, window: &ApplicationWindow) {
pub fn load_document(file: impl AsRef<Path>, ui: Rc<RefCell<Ui>>) {
println!("Loading file...");
// TODO: catch errors, maybe show error dialog
// let uri = format!("file://{}", file.as_ref().to_str().unwrap());
let sender = cache::spawn_async_cache(
file,
@@ -286,12 +267,12 @@ pub fn load_document(file: impl AsRef<Path>, ui: Rc<RefCell<Ui>>) {
ui.borrow_mut().document_canvas.as_mut().unwrap().num_pages = Some(num_pages);
update_page_status(&ui.borrow())
}
cache::CacheResponse::SinglePageLoaded { page } => {
cache::CacheResponse::SinglePageRetrieved { page } => {
ui.borrow_mut().document_canvas.as_mut().unwrap().left_page = Some(page);
ui.borrow_mut().document_canvas.as_mut().unwrap().right_page = None;
ui.borrow().drawing_area.queue_draw();
}
cache::CacheResponse::TwoPagesLoaded {
cache::CacheResponse::TwoPagesRetrieved {
page_left,
page_right,
} => {
@@ -303,23 +284,6 @@ pub fn load_document(file: impl AsRef<Path>, ui: Rc<RefCell<Ui>>) {
);
println!("Spawned async cache");
// // gtk::spawn
// glib::spawn_future_local(clone!(@weak ui => async move {
// println!("Waiting for cache response:...");
// while let Ok(cache_response) = receiver.recv().await {
// match cache_response{
// cache::CacheResponse::DocumentLoaded { num_pages } => {ui.borrow_mut().document_canvas.as_mut().unwrap().num_pages = Some(num_pages); update_page_status(&ui.borrow())},
// cache::CacheResponse::SinglePageLoaded { page } => { ui.borrow_mut().document_canvas.as_mut().unwrap().left_page = Some(page);
// ui.borrow_mut().document_canvas.as_mut().unwrap().right_page = None;
// ui.borrow().drawing_area.queue_draw();
// },
// cache::CacheResponse::TwoPagesLoaded { page_left, page_right } => { ui.borrow_mut().document_canvas.as_mut().unwrap().left_page = Some(page_left);
// ui.borrow_mut().document_canvas.as_mut().unwrap().right_page = Some(page_right);
// ui.borrow().drawing_area.queue_draw();
// }
// }
// }
// }));
let document_canvas = DocumentCanvas::new(sender);
document_canvas.cache_initial_pages();