├── .gitignore ├── extras └── emacs-reader-logo.png ├── manifest.scm ├── .envrc ├── default.nix ├── .clang-format ├── test └── vm │ ├── README.org │ ├── wayland.scm │ └── x.scm ├── .dir-locals.el ├── render ├── render-theme.h ├── mupdf-helpers.h ├── render-threads.h ├── render-theme.c ├── elisp-helpers.h ├── render-core.h ├── render-threads.c ├── mupdf-helpers.c ├── elisp-helpers.c └── render-core.c ├── NEWS ├── .github └── workflows │ └── c-cpp.yml ├── reader-bookmark.el ├── doc ├── notes.org └── 18-05-notes.org ├── reader-saveplace.el ├── CONTRIBUTORS ├── Makefile ├── reader-outline.el ├── README.org ├── reader.el └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.so 2 | *.dylib 3 | *.dll 4 | *.o 5 | *.~undo-tree~ 6 | TAGS 7 | /worktrees/ 8 | -------------------------------------------------------------------------------- /extras/emacs-reader-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/divyaranjan1905/emacs-reader/HEAD/extras/emacs-reader-logo.png -------------------------------------------------------------------------------- /manifest.scm: -------------------------------------------------------------------------------- 1 | (specifications->manifest 2 | '("gcc-toolchain" 3 | "gdb" 4 | "clang" ; for clangd 5 | "mupdf" 6 | "make")) 7 | -------------------------------------------------------------------------------- /.envrc: -------------------------------------------------------------------------------- 1 | if command -v guix >/dev/null 2>&1; then 2 | echo "Guix is available." 3 | eval "$(guix shell --search-paths)" 4 | elif command -v nix >/dev/null 2>&1; then 5 | echo "Nix is available." 6 | use nix 7 | else 8 | echo "Neither Guix nor Nix found. GNU Guix is recommended." 9 | fi 10 | -------------------------------------------------------------------------------- /default.nix: -------------------------------------------------------------------------------- 1 | # Nix shell support is added, but most of us do not use Nix. So GNU 2 | # Guix is preferred if you can choose. 3 | 4 | { pkgs ? import { }, }: 5 | 6 | pkgs.mkShell { 7 | packages = 8 | [ pkgs.mupdf-headless pkgs.gnumake pkgs.clang-tools pkgs.gcc pkgs.gdb ]; 9 | } 10 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | # .clang-format 2 | 3 | BasedOnStyle: GNU 4 | 5 | # Basic layout 6 | IndentWidth: 8 7 | TabWidth: 8 8 | UseTab: Always 9 | BreakBeforeBraces: Allman 10 | 11 | # Function signatures 12 | AlwaysBreakAfterReturnType: TopLevel 13 | AlignAfterOpenBracket: Align 14 | AlignOperands: true 15 | 16 | # Pointer and reference style 17 | PointerAlignment: Right 18 | 19 | # Other 20 | ColumnLimit: 80 21 | SpaceBeforeParens: ControlStatements 22 | -------------------------------------------------------------------------------- /test/vm/README.org: -------------------------------------------------------------------------------- 1 | #+TITLE: GNU Guix VM for testing. 2 | #+AUTHOR: tusharhero 3 | 4 | See =(info "(guix) Invoking guix system")=. 5 | 6 | The basic command is: 7 | #+begin_src bash 8 | sudo -sE $(guix system vm x.scm --share=$PWD/../../=/emacs-reader) -m 2048 9 | #+end_src 10 | 11 | + =-m= describes the amount of memory available to the vm. 12 | + =--share= shares the emacs-reader project with the vm at 13 | /emacs-reader. 14 | 15 | Adjust the command accordingly. 16 | -------------------------------------------------------------------------------- /.dir-locals.el: -------------------------------------------------------------------------------- 1 | ;;; Directory Local Variables -*- no-byte-compile: t -*- 2 | ;;; For more information see (info "(emacs) Directory Variables") 3 | 4 | ((nil . ((mode . envrc) 5 | (require-final-newline . t) 6 | (show-trailing-whitespace . t))) 7 | (c-mode . ((eval . (eglot-ensure)) 8 | (before-save-hook . (eglot-format-buffer)) 9 | (indent-tabs-mode . t) 10 | (c-basic-offset . 2) 11 | (tab-width . 8) 12 | (c-default-style . "gnu") 13 | (fill-column . 80))) 14 | (c-ts-mode . ((eval . (eglot-ensure)) 15 | (before-save-hook . (eglot-format-buffer)) 16 | (indent-tabs-mode . t) 17 | (c-basic-offset . 2) 18 | (tab-width . 8) 19 | (c-default-style . "gnu") 20 | (fill-column . 80))) 21 | (emacs-lisp-mode . ((mode . aggressive-indent))) 22 | (scheme-mode . ((mode . aggressive-indent)))) 23 | -------------------------------------------------------------------------------- /render/render-theme.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2025 Divya Ranjan Pattanaik 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "elisp-helpers.h" 18 | #include "render-core.h" 19 | 20 | emacs_value emacs_set_dark_theme(emacs_env *env, ptrdiff_t nargs, emacs_value *args, 21 | void *data); 22 | -------------------------------------------------------------------------------- /NEWS: -------------------------------------------------------------------------------- 1 | ;;; -*- mode: auto-fill; mode: org; -*- 2 | See =(info "(standards) NEWS File")=. User facing changes per release 3 | are to be recorded here. 4 | 5 | * Version 0.3.2 6 | - Fix reader-outline when original source buffer is killed. 7 | - Correct keybindings for C-v/M-v. 8 | - Enhance build system on GNU/Linux and MS Windows. 9 | 10 | * Version 0.3.1 11 | - Start NEWS file. 12 | - Fix MS Windows build. 13 | - Fix the order of reader outline, where the last heading would show 14 | up at the beginning, now they show up at the end. 15 | - Fix bug where setting the left-fringe-width would disable the 16 | centering. 17 | - Add new customize option, =reader-default-fit=, for setting the 18 | default fitting (fit to height or fit to width). 19 | - Add a new command, =reader-reset-size=, to reset scaling to 1.0. 20 | - Fix scrolling when =pixel-scroll-precision-mode= is enabled. 21 | - Fix =revert-buffer= to respect the theme, page and scale of the document. 22 | -------------------------------------------------------------------------------- /render/mupdf-helpers.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2025 Divya Ranjan Pattanaik 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #ifndef MUPDF_HELPERS_H 18 | #define MUPDF_HELPERS_H 19 | 20 | #include "render-core.h" 21 | #include 22 | #include 23 | #include 24 | 25 | int 26 | doc_page_width(EmacsWinState *win_state); 27 | int 28 | doc_page_height(EmacsWinState *win_state); 29 | 30 | void 31 | fail(const char *msg); 32 | void 33 | lock_mutex(void *user, int lock); 34 | void 35 | unlock_mutex(void *user, int lock); 36 | int 37 | init_main_ctx(DocState *state); 38 | int 39 | load_mupdf_doc(DocState *state); 40 | 41 | void 42 | reset_doc_state(DocState *state); 43 | void 44 | free_cached_page(DocState *state, CachedPage *cp); 45 | void 46 | free_cache_window(DocState *doc_state, EmacsWinState *win_state); 47 | void 48 | free_cached_pages_pool(DocState *state); 49 | 50 | #endif 51 | -------------------------------------------------------------------------------- /.github/workflows/c-cpp.yml: -------------------------------------------------------------------------------- 1 | name: CI for emacs-reader 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | jobs: 10 | 11 | build-macos: 12 | runs-on: macos-latest 13 | steps: 14 | - name: Checkout code 15 | uses: actions/checkout@v3 16 | 17 | - name: Install dependencies 18 | run: | 19 | brew update 20 | brew install gcc make mupdf 21 | 22 | - name: Build with make 23 | run: make all 24 | 25 | build-gnu-linux: 26 | runs-on: ubuntu-latest 27 | steps: 28 | - name: Checkout code 29 | uses: actions/checkout@v3 30 | with: 31 | submodules: recursive 32 | 33 | - name: Install dependencies 34 | run: sudo apt-get update && sudo apt-get install -y gcc make git mupdf libmupdf-dev 35 | 36 | - name: Build with make 37 | run: make all 38 | 39 | build-windows: 40 | runs-on: windows-latest 41 | steps: 42 | - name: Checkout code 43 | uses: actions/checkout@v3 44 | with: 45 | submodules: recursive 46 | 47 | - name: Install MSYS2 48 | uses: msys2/setup-msys2@v2 49 | with: 50 | update: true 51 | install: >- 52 | make 53 | mingw-w64-x86_64-gcc 54 | git 55 | pkg-config 56 | emacs 57 | 58 | - name: Build with GCC and Make 59 | shell: msys2 {0} 60 | run: | 61 | gcc --version 62 | make all 63 | -------------------------------------------------------------------------------- /render/render-threads.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2025 Divya Ranjan Pattanaik 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #ifndef RENDER_THREADS_H 18 | #define RENDER_THREADS_H 19 | 20 | #include "render-core.h" 21 | #include 22 | 23 | #define MAX_POOL_SIZE 8 // Max no. of threads to be used 24 | 25 | typedef struct ThreadJob 26 | { 27 | void *(*func)(void *arg); 28 | void *arg; 29 | struct ThreadJob *next; 30 | } ThreadJob; 31 | 32 | typedef struct TaskQueue 33 | { 34 | ThreadJob *head, *tail; 35 | pthread_mutex_t q_mutex; 36 | pthread_cond_t q_cond; 37 | } JobQueue; 38 | 39 | typedef struct 40 | { 41 | pthread_t threads[MAX_POOL_SIZE]; 42 | pthread_mutex_t leader_mutex; 43 | pthread_cond_t leader_cond; 44 | int leader_exists; 45 | JobQueue job_queue; 46 | } ThreadPool; 47 | 48 | typedef struct 49 | { 50 | DocState *doc_state; 51 | EmacsWinState *win_state; 52 | CachedPage *cp; 53 | } DrawThreadArgs; 54 | 55 | extern ThreadPool g_thread_pool; 56 | 57 | void 58 | job_queue_init(JobQueue *queue); 59 | void 60 | job_queue_destroy(JobQueue *queue); 61 | void 62 | job_queue_push(JobQueue *queue, ThreadJob *job); 63 | ThreadJob * 64 | job_queue_pop(JobQueue *queue); 65 | void 66 | submit_job(void *(*func)(void *arg), void *arg, ThreadPool *pool); 67 | void * 68 | thread_routine(void *arg); 69 | void 70 | threadpool_init(ThreadPool *pool); 71 | void 72 | threadpool_destroy(ThreadPool *pool); 73 | 74 | #endif 75 | -------------------------------------------------------------------------------- /reader-bookmark.el: -------------------------------------------------------------------------------- 1 | ;;; reader-bookmark.el --- bookmarks integration for the emacs-reader -*- lexical-binding: t; -*- 2 | 3 | ;; Copyright (C) 2025 Tushar 4 | 5 | ;; This program is free software; you can redistribute it and/or modify 6 | ;; it under the terms of the GNU General Public License as published by 7 | ;; the Free Software Foundation, either version 3 of the License, or 8 | ;; (at your option) any later version. 9 | 10 | ;; This program is distributed in the hope that it will be useful, 11 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | ;; GNU General Public License for more details. 14 | 15 | ;; You should have received a copy of the GNU General Public License 16 | ;; along with this program. If not, see . 17 | 18 | ;;; Commentary: 19 | 20 | ;;; Code: 21 | 22 | (require 'reader) 23 | (require 'bookmark) 24 | 25 | (defun reader-bookmark-make-record () 26 | "Create a bookmark reader doc record." 27 | (append (bookmark-make-record-default nil t 1) 28 | (list (cons 'page (reader-current-doc-pagenumber)) 29 | (cons 'scale (reader-current-doc-scale-value)) 30 | (cons 'hscroll (window-hscroll)) 31 | (cons 'vscroll (window-vscroll)) 32 | '(handler . reader-bookmark-jump)))) 33 | 34 | ;;;###autoload 35 | (defun reader-bookmark-jump (bookmark) 36 | "Handles BOOKMARK for record type returned by `reader-bookmark-make-record'." 37 | (let ((page (bookmark-prop-get bookmark 'page)) 38 | (file (bookmark-prop-get bookmark 'filename)) 39 | (scale (bookmark-prop-get bookmark 'scale)) 40 | (hscroll (bookmark-prop-get bookmark 'hscroll)) 41 | (vscroll (bookmark-prop-get bookmark 'vscroll))) 42 | (bookmark-default-handler bookmark) 43 | (when (file-exists-p file) 44 | (switch-to-buffer (current-buffer)) 45 | (unless (derived-mode-p 'reader-mode) 46 | (reader-mode)) 47 | (reader-goto-page page) 48 | (reader-doc-scale-page scale) 49 | (reader--center-page) 50 | (set-window-hscroll nil hscroll) 51 | (set-window-vscroll nil vscroll)))) 52 | 53 | (put 'reader-bookmark-jump 'bookmark-handler-type "Reader") 54 | 55 | (provide 'reader-bookmark) 56 | ;;; reader-bookmark.el ends here 57 | -------------------------------------------------------------------------------- /test/vm/wayland.scm: -------------------------------------------------------------------------------- 1 | ;; Guix system configuration with Wayland, for testing purposes. 2 | 3 | ;; Copyright (C) 2025 Tushar 4 | 5 | ;; This program is free software; you can redistribute it and/or modify 6 | ;; it under the terms of the GNU General Public License as published by 7 | ;; the Free Software Foundation, either version 3 of the License, or 8 | ;; (at your option) any later version. 9 | 10 | ;; This program is distributed in the hope that it will be useful, 11 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | ;; GNU General Public License for more details. 14 | 15 | ;; You should have received a copy of the GNU General Public License 16 | ;; along with this program. If not, see . 17 | 18 | (use-modules (gnu) 19 | (gnu packages) 20 | (gnu packages base) 21 | (gnu packages terminals) 22 | (gnu services xorg) 23 | (gnu services sddm) 24 | (gnu packages pdf)) 25 | 26 | (use-service-modules desktop) 27 | (use-package-modules bootloaders emacs wm pdf) 28 | 29 | (operating-system 30 | (host-name "waylandvm") 31 | 32 | (users (cons (user-account 33 | (name "user") 34 | (group "users") 35 | (supplementary-groups '("wheel" "netdev" 36 | "audio" "video"))) 37 | %base-user-accounts)) 38 | 39 | (packages (append (list 40 | sway 41 | foot 42 | emacs-pgtk 43 | gnu-make 44 | mupdf) 45 | %base-packages)) 46 | 47 | (services 48 | (append (list (service sddm-service-type 49 | (sddm-configuration 50 | (auto-login-user "user") 51 | (auto-login-session "sway.desktop")))) 52 | (modify-services %desktop-services 53 | (delete gdm-service-type)))) 54 | 55 | 56 | (bootloader (bootloader-configuration 57 | (bootloader grub-efi-bootloader) 58 | (targets '("/boot/efi")))) 59 | 60 | (file-systems (append 61 | (list (file-system 62 | (device (file-system-label "root")) 63 | (mount-point "/") 64 | (type "ext4")) 65 | (file-system 66 | (device (file-system-label "boot-efi")) 67 | (mount-point "/boot/efi") 68 | (type "vfat"))) 69 | %base-file-systems))) 70 | -------------------------------------------------------------------------------- /test/vm/x.scm: -------------------------------------------------------------------------------- 1 | ;; Guix system configuration with X11, for testing purposes. 2 | 3 | ;; Copyright (C) 2025 Tushar 4 | 5 | ;; This program is free software; you can redistribute it and/or modify 6 | ;; it under the terms of the GNU General Public License as published by 7 | ;; the Free Software Foundation, either version 3 of the License, or 8 | ;; (at your option) any later version. 9 | 10 | ;; This program is distributed in the hope that it will be useful, 11 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | ;; GNU General Public License for more details. 14 | 15 | ;; You should have received a copy of the GNU General Public License 16 | ;; along with this program. If not, see . 17 | 18 | (use-modules (gnu) 19 | (gnu packages) 20 | (gnu packages base) 21 | (gnu packages xorg) 22 | (gnu services xorg) 23 | (gnu packages pdf)) 24 | 25 | (use-service-modules desktop xorg) 26 | (use-package-modules bootloaders emacs wm xorg pdf) 27 | 28 | (operating-system 29 | (host-name "x11vm") 30 | 31 | (users (cons (user-account 32 | (name "user") 33 | (group "users") 34 | (supplementary-groups '("wheel" "netdev" 35 | "audio" "video"))) 36 | %base-user-accounts)) 37 | 38 | (packages (append (list 39 | fluxbox 40 | xrandr 41 | xterm 42 | emacs 43 | gnu-make 44 | mupdf) 45 | %base-packages)) 46 | 47 | (services 48 | (append (list (service slim-service-type 49 | (slim-configuration 50 | (auto-login? #t) 51 | (default-user "user") 52 | (xorg-configuration 53 | (xorg-configuration (resolutions '((1920 1080)))))))) 54 | (modify-services %desktop-services 55 | (delete gdm-service-type)))) 56 | 57 | 58 | (bootloader (bootloader-configuration 59 | (bootloader grub-efi-bootloader) 60 | (targets '("/boot/efi")))) 61 | 62 | (file-systems (append 63 | (list (file-system 64 | (device (file-system-label "root")) 65 | (mount-point "/") 66 | (type "ext4")) 67 | (file-system 68 | (device (file-system-label "boot-efi")) 69 | (mount-point "/boot/efi") 70 | (type "vfat"))) 71 | %base-file-systems))) 72 | -------------------------------------------------------------------------------- /render/render-theme.c: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2025 Divya Ranjan Pattanaik 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "render-theme.h" 18 | #include "elisp-helpers.h" 19 | #include "render-core.h" 20 | #include "render-threads.h" 21 | 22 | /** 23 | * Toggle dark theme rendering for the current document page. 24 | * 25 | * Inverts the `invert` flag in the DocState, re-renders the current 26 | * page in a background thread, waits for it to finish, and updates 27 | * the Emacs overlay with the new image. 28 | * 29 | * @param env Emacs module environment. 30 | * @param nargs Argument count (unused). 31 | * @param args Argument values (unused). 32 | * @param data Additional data (unused). 33 | * Return: EMACS_T on success, EMACS_NIL if no DocState is available. 34 | */ 35 | 36 | emacs_value 37 | emacs_set_dark_theme(emacs_env *env, ptrdiff_t nargs, emacs_value *args, 38 | void *data) 39 | { 40 | (void)data; 41 | (void)nargs; 42 | (void)args; 43 | DocState *doc_state = get_doc_state_ptr(env); 44 | emacs_value current_doc_overlay = get_current_doc_overlay(env); 45 | EmacsWinState *win_state = get_win_state_ptr(env, current_doc_overlay); 46 | if (doc_state && win_state) 47 | { 48 | doc_state->invert ^= 1; 49 | CachedPage *cp = win_state->current_cached_page; 50 | DrawThreadArgs *draw_args = malloc(sizeof(DrawThreadArgs)); 51 | draw_args->doc_state = doc_state; 52 | draw_args->win_state = win_state; 53 | draw_args->cp = cp; 54 | submit_job(draw_page_thread, draw_args, &g_thread_pool); 55 | 56 | // Wait for the thread to signal before displaying 57 | pthread_mutex_lock(&cp->mutex); 58 | pthread_cond_wait(&cp->cond, &cp->mutex); 59 | pthread_mutex_unlock(&cp->mutex); 60 | 61 | display_img_to_overlay(env, win_state, cp->img_data, 62 | cp->img_size, current_doc_overlay); 63 | } 64 | else 65 | { 66 | return EMACS_NIL; 67 | } 68 | 69 | return EMACS_T; 70 | } 71 | -------------------------------------------------------------------------------- /doc/notes.org: -------------------------------------------------------------------------------- 1 | #+TITLE: Reader’s Rendering Functions 2 | 3 | * PDF 4 | We have a struct =PDFState= that represents the state that the current PDF is in, includes the context, page numbers and other data. We initialize this =PDFState= struct manually, thus storing it in heap. 5 | 6 | =load_pdf= is a simple function that loads a few things into the =PDFState= struct that will later on get used in rendering, such as the context, document handlers, number of pages and so on. 7 | 8 | We also have =load_pages= that loads the current =page_number= that is set in the =PDFState= struct and the ones following and preceding it. Here “loading” simply means doing =fz_load_page=. 9 | 10 | =render_page= is the main function that does the rendering. It conducts the following operations in order: 11 | 12 | - if the context or doc or page number is invalid, throw an error 13 | - if the =current_svg_data= has something, then =free= it, and then set it to =NULL=. 14 | - Then, do =load_pages= on the =page_number= that was provided as argument. 15 | - Get the bounding box for the page and its dimensions. 16 | - Create buffers for each page. 17 | - Create outputs for each page. 18 | - Create svg device for each page. 19 | - Run the page through each of the devices. 20 | - Close and drop the device 21 | - Close the output to finalize the buffer content 22 | - Allocate memory for storing the =*_svg_data= 23 | - Copy the data from the buffers into =*_svg_data= 24 | - Cleanup 25 | 26 | - =emacs_2_c_string= is simply a helper function to convert between Elisp strings and C strings. 27 | 28 | - =emacs_load_pdf= takes a pointer to an =emacs_env= which would be an Elisp string to a file path, and then it will do: 29 | 30 | - =clean_up_svg_data=: Cleans any previous SVG data. 31 | 32 | - =create_buffers=: Create =fz_buffer= 33 | 34 | - =create_outputs=: Create =fz_output= 35 | 36 | - =drop_all_buffers=: Drops all =fz_buffer= 37 | 38 | - =drop_all_outputs=: Drops all =fz_output= 39 | 40 | - =drop_all_pages=: Drops all =fz_device= 41 | 42 | - =close_all_outputs=: Drops all =fz_output= 43 | 44 | - =close_all_devices=: Drops all =fz_device= 45 | 46 | - =load_pdf= the file. 47 | - =render_page= the current page: 48 | - convert the =svg_data= into an Emacs string. 49 | - Create a new buffer and switch to it. 50 | - Do Emacs’ =create_image= on the =svg_string= 51 | - Then do =insert-image= to render the SVG in the buffer. 52 | 53 | =emacs_next_page= simply looks at the =current_page_number= in =PDFState= and if there is a next page, it gets the next page’s data and renders it in the buffer, and if it’s the last page, then it just stops. It also always renders the next to next page’s data. 54 | -------------------------------------------------------------------------------- /reader-saveplace.el: -------------------------------------------------------------------------------- 1 | ;;; reader-saveplace.el --- Saveplace integration with emacs-reader -*- lexical-binding: t; -*- 2 | 3 | ;; Copyright (C) 2025 Divya Ranjan Pattanaik 4 | ;; Copyright (C) 2025 Tushar 5 | 6 | ;; This program is free software; you can redistribute it and/or modify 7 | ;; it under the terms of the GNU General Public License as published by 8 | ;; the Free Software Foundation, either version 3 of the License, or 9 | ;; (at your option) any later version. 10 | 11 | ;; This program is distributed in the hope that it will be useful, 12 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | ;; GNU General Public License for more details. 15 | 16 | ;; You should have received a copy of the GNU General Public License 17 | ;; along with this program. If not, see . 18 | 19 | ;;; Commentary: 20 | 21 | ;; Bookmarks need to be stored inside a vector due to hard-coded logic 22 | ;; within `save-place--normalize-alist'. Specifically, it performs 23 | ;; operations on an element assuming it's a list, and this leads to 24 | ;; issues when we try to use it like a bookmark. 25 | 26 | ;;; Acknowledgements: 27 | 28 | ;; `saveplace-pdf-view' by Nicolai Singh was used 29 | ;; for reference. 30 | 31 | ;;; Code: 32 | 33 | (require 'bookmark) 34 | (require 'saveplace) 35 | (require 'reader-bookmark) 36 | 37 | ;;;###autoload 38 | (defun reader--saveplace-find-file (orig-fun &rest args) 39 | "Restores saved place in `reader-mode' buffers or calls ORIG-FUN with ARGS. 40 | 41 | Advice around `save-place-find-file'. See also `reader--saveplace-to-alist'." 42 | (or save-place-loaded (save-place-load-alist-from-file)) 43 | (if (derived-mode-p 'reader-mode) 44 | (if-let* ((place (assoc buffer-file-name save-place-alist)) 45 | (bookmark (aref (cdr place) 0))) ; get back the bookmark 46 | (reader-bookmark-jump bookmark)) 47 | (apply orig-fun args))) 48 | 49 | ;;;###autoload 50 | (defun reader--saveplace-to-alist (orig-fun &rest args) 51 | "Saves place in `reader-mode' buffers or calls ORIG-FUN with ARGS. 52 | 53 | Advice around `save-place-to-alist'. See also `reader--saveplace-find-file'." 54 | (if (derived-mode-p 'reader-mode) 55 | (when-let* ((filename buffer-file-name) 56 | (bookmark-record (reader-bookmark-make-record)) 57 | (bookmark (cons "reader-saveplace" bookmark-record))) 58 | (setq save-place-alist 59 | (assoc-delete-all filename save-place-alist)) 60 | ;; store bookmark inside a vector 61 | (push (cons filename (vector bookmark)) save-place-alist)) 62 | (apply orig-fun args))) 63 | 64 | (provide 'reader-saveplace) 65 | ;;; reader-saveplace.el ends here 66 | -------------------------------------------------------------------------------- /render/elisp-helpers.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2025 Divya Ranjan Pattanaik 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #ifndef EMACS_HELPERS_H 18 | #define EMACS_HELPERS_H 19 | 20 | #include "emacs-module.h" 21 | #include "mupdf-helpers.h" 22 | #include "render-core.h" 23 | #include 24 | #include 25 | 26 | #define EMACS_NIL env->intern(env, "nil") 27 | #define EMACS_T env->intern(env, "t") 28 | #define EMACS_CURR_WIN \ 29 | env->funcall(env, env->intern(env, "selected-window"), 0, NULL); 30 | 31 | bool 32 | elisp_2_c_str(emacs_env *env, emacs_value value, char **buffer, size_t *size); 33 | void 34 | provide(emacs_env *env, const char *value); 35 | void 36 | register_module_func(emacs_env *env, 37 | emacs_value (*module_func)(emacs_env *env, ptrdiff_t nargs, 38 | emacs_value *args, void *data), 39 | char *symbol, int min_args, int max_args, char *docstring); 40 | emacs_value 41 | data2elisp_image(emacs_env *env, EmacsWinState *win_state, char *img_data, 42 | size_t img_size); 43 | 44 | DocState * 45 | init_doc_state_ptr(emacs_env *env); 46 | DocState * 47 | get_doc_state_ptr(emacs_env *env); 48 | EmacsWinState * 49 | init_win_state_ptr(emacs_env *env, DocState *doc_state, emacs_value window); 50 | EmacsWinState * 51 | get_win_state_ptr(emacs_env *env, emacs_value overlay); 52 | void 53 | reset_win_state(EmacsWinState *win_state); 54 | void 55 | set_current_page_number(emacs_env *env, int page); 56 | void 57 | set_current_render_status(emacs_env *env); 58 | void 59 | set_current_pagecount(emacs_env *env, DocState *state); 60 | emacs_value 61 | init_overlay(emacs_env *env, emacs_value window); 62 | emacs_value 63 | get_current_doc_overlay(emacs_env *env); 64 | void 65 | emacs_message(emacs_env *env, char *str); 66 | void 67 | permanent_buffer_local_var(emacs_env *env, char *symbol); 68 | 69 | void 70 | display_img_to_overlay(emacs_env *env, EmacsWinState *win_state, char *img_data, 71 | size_t img_size, emacs_value buffer_overlay); 72 | emacs_value 73 | outline2plist(emacs_env *env, fz_outline *node); 74 | 75 | #endif 76 | -------------------------------------------------------------------------------- /CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | List of all the people who contributed to The Emacs Reader. For more 2 | information on what is included, visit 3 | www.gnu.org/prep/maintain/html_node/Legally-Significant.html#Legally-Significant 4 | 5 | * Legally Significant Contributions 6 | 7 | Divya Ranjan Pattanaik : 8 | 9 | - wrote or added to reader.el, reader-outline.el. reader-saveplace.el, 10 | mupdf-helpers.c, render-theme.c, render-core.c, elisp-helpers.c, and 11 | render-threads.c. 12 | - wrote Makefile. 13 | - wrote README.org 14 | 15 | Tushar : 16 | 17 | - changed the reader-center-page in reader.el to accommodate edge 18 | cases. 19 | - fixed several errors in centering and scrolling in reader.el for the 20 | v0.2.0 release 21 | - added bookmark and saveplace feature for v0.2.2 22 | - fixed autoloading issues 23 | - refactored reader.el significantly for readability and extensibility 24 | - refactored mouse wheel scrolling in reader.el 25 | - refactored the page centering logic in reader.el for v0.2.6 26 | - implemented the elisp side reader-dark-mode 27 | - refactored reader's keymap in reader.el 28 | - refactored the scrolling logic in reader.el for v0.2.7 29 | - cleaned up older documentation and handled renaming in PR #98 30 | - refactored the command queuening mechanism in PR #98 31 | - added mwheel functionality to new scaling mechanism in PR #98 32 | - added development environment configurations in PR #98 33 | - refactored button interface of reader-outline.el 34 | - renaming functions properly in reader-outline.el and newer reader.el functions. 35 | - updated docstrings in both C and Elisp modules for v0.3.0 36 | - added guix system configurations in test/vm/x11.scm and 37 | test/vm/wayland.scm. 38 | - updated README.org for clarification, typos, also added some 39 | sections to it. 40 | - fixed reader-outline.el when original source buffer is killed. 41 | 42 | prom (Codeberg user): 43 | - fixed and updated support for MS Windows in the Makefile. 44 | - updated README.org with MS Windows instructions. 45 | 46 | * Other Contributions (Not Legally Significant) 47 | 48 | shuxiao9058 (Codeberg user): 49 | 50 | - fixed the MacOS port for the build system in Makefile (PR #66) 51 | 52 | idilip (Codeberg user): 53 | 54 | - implemented a basic presentation mode in reader.el for v0.3.0 (PR #100) 55 | 56 | 57 | 58 | * highlighting settings 59 | # Local Variables: 60 | # mode: org 61 | # eval: (highlight-regexp ".*:" 'custom-group-tag-1) 62 | # eval: (highlight-regexp (rx (or "wrote" "changed" "fixed" "added" "refactored" "implemented" "cleaned" "renaming" "updated")) 'compilation-warning) 63 | # eval: (highlight-regexp (rx (or (seq "v" (one-or-more (any num)) nonl (one-or-more (any num)) nonl (one-or-more (any num))) (seq "PR #" (one-or-more (any num))))) 'success) 64 | # End: 65 | -------------------------------------------------------------------------------- /doc/18-05-notes.org: -------------------------------------------------------------------------------- 1 | #+TITLE: Part III: Multi-Threading 2 | * Core Refactoring & Additional Formats 3 | 4 | + *Render Core Refactor:* The biggest architectural shift is the move from a ~render-pdf~ specific system to a more general ~render-core~. This aims to support multiple document formats beyond PDF. 5 | + *C/Elisp Separation:* A clear separation of concerns between C and Elisp code was implemented. Many helper functions were moved from C to Elisp, improving maintainability. 6 | + =PdfState->DocState=: A ~DocState~ struct was introduced to hold document-related information, centralizing state management. 7 | 8 | * Scrolling & Navigation 9 | 10 | + *Extensive Scrolling Improvements:* A huge amount of work went into scrolling functionality: 11 | * *Screenful Scrolling:* Added screenful scrolling (scrolling by pages/screens). 12 | * *Continuous Scrolling:* Implemented continuous scrolling. 13 | * *Keybindings:* Added numerous keybindings for scrolling (up, down, page up, page down, continuous scrolling). 14 | * *Scrollable Functions:* Added optional amount arguments to scroll functions. 15 | * *Edge Case Handling:* Fixed edge cases in page navigation and scrolling. 16 | * *Scroll to Bottom:* Fixed scrolling to the bottom of the previous page. 17 | * *Scroll Up/Down Functionality* Added functionality to scroll pages up and down. 18 | + *Page Navigation:* Improved page navigation and handling, including centering after navigation. 19 | 20 | * Scaling & Zooming 21 | 22 | + *Scaling Factor Management:* Implemented proper scaling factor management, storing it within the ~DocState~. 23 | + *Zoom Support:* Added basic zoom support. 24 | + *Window Resizing:* The window size is now adjusted to match the ~read-pdf-mode~ one. 25 | + *Consistent Scaling:* Scaling is now consistent when changing pages. 26 | 27 | * Documentation & Code Quality 28 | 29 | + *Extensive Documentation:* Added documentation to many C and Elisp functions. 30 | + *Code Style:* Improved code style with indentation and consistent naming schemes. 31 | + *Error Handling:* Improved error handling in module functions. 32 | + *CONTRIBUTORS File:* Updated the CONTRIBUTORS file format and 33 | added contributors. 34 | 35 | * Build System & Dependencies 36 | 37 | + *Makefile:* Updated the Makefile to rely on the in-tree 38 | ~emacs-module.h~. 39 | + Made the build be cross-platform. 40 | 41 | * Integration with Emacs 42 | 43 | + Added feature to save pages of document from native Emacs boomarks. 44 | + Added feature to save the page when Emacs was closed and reopen it (=saveplace=). 45 | 46 | * What Lies Ahead for v0.3.0 47 | 48 | + Lay the foundations for multi-threading in the backend. 49 | + Work on persistent errors in centering of the page and scrolling. 50 | + Make the package ready for ELPA: 51 | + Remove the submodule as distributions package latest MuPDF. 52 | + Copyright assignments 53 | + Tentative features: 54 | + Basic text selection and search support 55 | + Table of Contents with =imenu= integration. 56 | -------------------------------------------------------------------------------- /render/render-core.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2025 Divya Ranjan Pattanaik 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #ifndef RENDER_CORE_H 18 | #define RENDER_CORE_H 19 | 20 | #include "emacs-module.h" 21 | #include 22 | #include 23 | 24 | #define MINRES 18 25 | #define MAXRES 850 26 | #define MAX_CACHE_SIZE 11 27 | #define MAX_CACHE_WINDOW_SIZE (MAX_CACHE_SIZE / 2) 28 | 29 | typedef enum 30 | { 31 | PAGE_STATUS_EMPTY, 32 | PAGE_STATUS_RENDERING, 33 | PAGE_STATUS_READY, 34 | PAGE_STATUS_ERROR 35 | } PageStatus; 36 | 37 | typedef struct 38 | { 39 | int page_num; 40 | fz_display_list *display_list; 41 | fz_pixmap *pixmap; 42 | int imgw, imgh; 43 | char *img_data; 44 | size_t img_size; 45 | PageStatus status; 46 | pthread_mutex_t mutex; 47 | pthread_cond_t cond; 48 | } CachedPage; 49 | 50 | typedef struct 51 | { 52 | fz_context *ctx; 53 | fz_locks_context locks; 54 | fz_document *doc; 55 | CachedPage **cached_pages_pool; 56 | char *path; 57 | int pagecount; 58 | fz_rect page_bbox; 59 | fz_outline *outline; 60 | int invert; 61 | } DocState; 62 | 63 | typedef struct 64 | { 65 | DocState *doc_state; 66 | float resolution; 67 | CachedPage *cache_window[MAX_CACHE_SIZE]; 68 | int current_window_index; 69 | CachedPage *current_cached_page; 70 | int current_page_number; 71 | int rotate; 72 | } EmacsWinState; 73 | 74 | int 75 | load_page_dl(DocState *state, CachedPage *cp); 76 | void * 77 | draw_page_thread(void *arg); 78 | void 79 | build_cache_window(DocState *doc_state, EmacsWinState *win_state, int n); 80 | bool 81 | slide_cache_window_forward(DocState *state, EmacsWinState *win_state); 82 | bool 83 | slide_cache_window_backward(DocState *state, EmacsWinState *win_state); 84 | 85 | // Emacs module functions 86 | emacs_value 87 | emacs_load_doc(emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data); 88 | emacs_value 89 | emacs_doc_window_create(emacs_env *env, ptrdiff_t nargs, emacs_value *args, 90 | void *data); 91 | emacs_value 92 | emacs_doc_window_close(emacs_env *env, ptrdiff_t nargs, emacs_value *args, 93 | void *data); 94 | emacs_value 95 | emacs_next_page(emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data); 96 | emacs_value 97 | emacs_prev_page(emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data); 98 | emacs_value 99 | emacs_first_page(emacs_env *env, ptrdiff_t nargs, emacs_value *args, 100 | void *data); 101 | emacs_value 102 | emacs_last_page(emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data); 103 | emacs_value 104 | emacs_goto_page(emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data); 105 | emacs_value 106 | emacs_doc_scale_page(emacs_env *env, ptrdiff_t nargs, emacs_value *args, 107 | void *data); 108 | emacs_value 109 | emacs_doc_rotate_doc(emacs_env *env, ptrdiff_t nargs, emacs_value *args, 110 | void *data); 111 | 112 | #endif // RENDER_CORE_H 113 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | ### Makefile for Emacs Reader’s dynamic module 2 | ## 3 | ## Copyright (C) 2025 Divya Ranjan Pattanaik 4 | ## Copyright (C) 2025 prom 5 | ## 6 | ## This program is free software; you can redistribute it and/or modify 7 | ## it under the terms of the GNU General Public License as published by 8 | ## the Free Software Foundation, either version 3 of the License, or 9 | ## (at your option) any later version. 10 | ## 11 | ## This program is distributed in the hope that it will be useful, 12 | ## but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | ## GNU General Public License for more details. 15 | ## 16 | ## You should have received a copy of the GNU General Public License 17 | ## along with this program. If not, see . 18 | 19 | # Detect platforms 20 | OS_NAME := $(shell uname) 21 | HAVE_GUIX := $(shell command -v guix >/dev/null 2>&1 && echo yes || echo no) 22 | HAVE_NIX := $(shell command -v nix >/dev/null 2>&1 && echo yes || echo no) 23 | ifneq ($(filter MINGW%, $(OS_NAME)),) 24 | HAVE_MINGW64 := yes 25 | else 26 | HAVE_MINGW64 := no 27 | endif 28 | USE_PKGCONFIG := yes 29 | 30 | ifeq ($(HAVE_GUIX),yes) 31 | $(info Guix detected: skipping pkg-config checks.) 32 | USE_PKGCONFIG := no 33 | else ifeq ($(HAVE_NIX),yes) 34 | $(info Nix detected: skipping pkg-config checks.) 35 | USE_PKGCONFIG := no 36 | else ifeq ($(OS_NAME),Darwin) 37 | $(info macOS detected: skipping pkg-config and using Homebrew for MuPDF paths.) 38 | USE_PKGCONFIG := no 39 | else ifeq ($(HAVE_MINGW64), yes) 40 | $(info MinGW64 detected: assuming dll is located in $(MINGW_PREFIX)/bin.) 41 | endif 42 | 43 | ifeq ($(OS_NAME),Darwin) 44 | SO := dylib 45 | else ifeq ($(HAVE_MINGW64),yes) 46 | SO := dll 47 | else 48 | SO := so 49 | endif 50 | 51 | # Compiler and base flags 52 | CC := gcc 53 | CFLAGS += -Wall -Wextra -fPIC 54 | LDFLAGS := 55 | 56 | ifeq ($(OS_NAME),Darwin) 57 | CFLAGS += -DMACOS 58 | LDFLAGS += -dynamiclib 59 | else ifeq ($(HAVE_MINGW64),yes) 60 | CFLAGS += -DWIN32 -pthread 61 | LDFLAGS += -shared -lpthread -L$$MINGW_PREFIX/bin 62 | else 63 | CFLAGS += -DLINUX -pthread 64 | LDFLAGS += -shared -lpthread 65 | endif 66 | 67 | # Required MuPDF version 68 | REQUIRED_VERSION := 1.26.0 69 | 70 | # --- MuPDF detection and flags --- 71 | ifeq ($(USE_PKGCONFIG),yes) 72 | PKG_EXISTS := $(shell pkg-config --exists mupdf && echo yes || echo no) 73 | ifeq ($(PKG_EXISTS),no) 74 | $(error "MuPDF not found via pkg-config. Please install it or set PKG_CONFIG_PATH.") 75 | endif 76 | 77 | MUPDF_VERSION := $(shell pkg-config --modversion mupdf) 78 | VER_OK := $(shell [ "$$(printf '%s\n' $(REQUIRED_VERSION) $(MUPDF_VERSION) | sort -V | head -n1)" = "$(REQUIRED_VERSION)" ] && echo yes || echo no) 79 | ifeq ($(VER_OK),no) 80 | $(error "MuPDF version $(MUPDF_VERSION) too old. Require ≥ $(REQUIRED_VERSION).") 81 | endif 82 | 83 | CFLAGS += $(shell pkg-config --cflags mupdf) 84 | LDFLAGS += $(shell pkg-config --libs mupdf) 85 | else ifeq ($(OS_NAME),Darwin) 86 | # macOS manual detection via brew 87 | BREW_PREFIX := $(shell brew --prefix mupdf 2>/dev/null) 88 | ifeq ($(BREW_PREFIX),) 89 | $(error "MuPDF not found via Homebrew. Run: brew install mupdf") 90 | endif 91 | MUPDF_VERSION := $(shell grep -o '[0-9][^"]*' $(BREW_PREFIX)/include/mupdf/fitz/version.h | head -n1) 92 | VER_OK := $(shell [ "$$(printf '%s\n' $(REQUIRED_VERSION) $(MUPDF_VERSION) | sort -V | head -n1)" = "$(REQUIRED_VERSION)" ] && echo yes || echo no) 93 | ifeq ($(VER_OK),no) 94 | $(error "MuPDF version $(MUPDF_VERSION) too old. Require ≥ $(REQUIRED_VERSION).") 95 | endif 96 | CFLAGS += -I$(BREW_PREFIX)/include 97 | LDFLAGS += -L$(BREW_PREFIX)/lib -lmupdf 98 | else 99 | # Generic fallback for Guix/Nix 100 | CFLAGS += -DMUPDF_NO_PKGCONFIG 101 | LDFLAGS += -lmupdf 102 | endif 103 | 104 | # --- Build Rules --- 105 | LIB_NAME := render-core.$(SO) 106 | SRCS := render/elisp-helpers.c render/mupdf-helpers.c render/render-threads.c render/render-core.c render/render-theme.c 107 | OBJS := $(SRCS:%.c=%.o) 108 | 109 | .PHONY: all clean 110 | 111 | all: $(LIB_NAME) 112 | 113 | $(LIB_NAME): $(OBJS) 114 | $(CC) -o $@ $^ $(LDFLAGS) 115 | 116 | %.o: %.c 117 | $(CC) $(CFLAGS) -c $< -o $@ 118 | 119 | clean: 120 | rm -f $(OBJS) $(LIB_NAME) 121 | -------------------------------------------------------------------------------- /reader-outline.el: -------------------------------------------------------------------------------- 1 | ;;; reader-outline.el --- imenu and outline-mode integration for the emacs-reader -*- lexical-binding: t; -*- 2 | 3 | ;; Copyright (C) 2025 Divya Ranjan Pattanaik 4 | ;; Copyright (C) 2025 Tushar 5 | 6 | ;; This program is free software; you can redistribute it and/or modify 7 | ;; it under the terms of the GNU General Public License as published by 8 | ;; the Free Software Foundation, either version 3 of the License, or 9 | ;; (at your option) any later version. 10 | 11 | ;; This program is distributed in the hope that it will be useful, 12 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | ;; GNU General Public License for more details. 15 | 16 | ;; You should have received a copy of the GNU General Public License 17 | ;; along with this program. If not, see . 18 | 19 | ;;; Commentary: 20 | 21 | ;;; Code: 22 | 23 | (require 'reader) 24 | (require 'imenu) 25 | (require 'outline) 26 | 27 | ;;; Imenu 28 | 29 | ;;;###autoload 30 | (defun reader--outline-make-imenu-entry (plist) 31 | "Convert one outline PLIST to an imenu entry." 32 | (let* ((title (plist-get plist :title)) 33 | (page (plist-get plist :page)) 34 | (children (plist-get plist :children))) 35 | (if children 36 | (cons title 37 | (mapcar #'reader--outline-make-imenu-entry children)) 38 | (cons title page)))) 39 | 40 | ;;;###autoload 41 | (defun reader--outline-imenu-create-index () 42 | "Turn `reader-current-doc-outline' into an imenu index." 43 | (if reader-current-doc-outline 44 | (mapcar #'reader--outline-make-imenu-entry 45 | reader-current-doc-outline) 46 | (error "Document lacks a proper outline!"))) 47 | 48 | ;;;###autoload 49 | (defun reader--outline-imenu-goto (name page) 50 | "Switch to PAGE, ignores the NAME argument. 51 | 52 | Just wraps `reader-goto-page' for imenu compatibility." 53 | (reader-goto-page page)) 54 | 55 | ;;; Outline 56 | 57 | (defvar-local reader-outline--doc-buffername nil 58 | "Name of the document buffer whose outline was generated.") 59 | 60 | (defvar-local reader-outline--doc-window nil 61 | "The window from where the outline was generated.") 62 | 63 | ;;;###autoload 64 | (defun reader-outline-show () 65 | "Show the document outline in a separate buffer. 66 | 67 | The outline buffer inherits it's name from the original 68 | document it was created from." 69 | (interactive) 70 | (unless (derived-mode-p 'reader-mode) 71 | (user-error "Not in a reader-mode buffer")) 72 | (unless reader-current-doc-outline 73 | (user-error "This document has no outline")) 74 | (let* ((outline-data reader-current-doc-outline) 75 | (source-buffer (current-buffer)) 76 | (bufname (format "*Outline of %s*" (buffer-name source-buffer)))) 77 | (with-current-buffer (get-buffer-create bufname) 78 | (when-let* ((emptyp (= 0 (buffer-size))) 79 | (inhibit-read-only t)) 80 | (reader-outline-mode) 81 | (setq reader-outline--doc-buffername (buffer-name source-buffer)) 82 | (reader--outline-insert-outline outline-data 1) 83 | (goto-char (point-min)))) 84 | (pop-to-buffer bufname))) 85 | 86 | (defun reader--outline-insert-outline (outline level) 87 | "Recursively insert OUTLINE entries at LEVEL. 88 | 89 | Each heading title is its own clickable button." 90 | (dolist (entry outline) 91 | (let ((title (plist-get entry :title)) 92 | (page (1+ (plist-get entry :page))) ; MuPDF does 0-indexing 93 | (children (plist-get entry :children))) 94 | ;; This cannot be part of label (title) because that will 95 | ;; obscure the outline TAB bindings with button bindings. 96 | (insert (concat (make-string level ?*) " ")) 97 | (insert-text-button 98 | title 99 | 'reader-page page 100 | 'action #'reader-outline-goto-entry 101 | 'follow-link t 102 | 'help-echo "Jump to section.") 103 | (insert "\n") 104 | (if children 105 | (reader--outline-insert-outline children (1+ level)))))) 106 | 107 | (defun reader-outline-select-doc-window () 108 | "Display and switch to the original document's window." 109 | (interactive) 110 | (select-window (if (window-valid-p reader-outline--doc-window) 111 | reader-outline--doc-window 112 | (get-buffer-window reader-outline--doc-buffername)))) 113 | 114 | (defvar-keymap reader-outline-mode-map 115 | :doc "Keymap for `reader-outline-mode'" 116 | "p" #'previous-line 117 | "n" #'next-line 118 | "o" #'reader-outline-select-doc-window 119 | "q" #'quit-window 120 | "RET" #'reader-outline-visit-page 121 | "M-RET" #'reader-outline-visit-page) 122 | 123 | (define-derived-mode reader-outline-mode outline-mode "Emacs Reader Outline" 124 | "Major mode for navigating document outlines." 125 | (setq buffer-read-only t) 126 | (setq-local outline-regexp "^\\*+ ") 127 | (use-local-map reader-outline-mode-map)) 128 | 129 | (defun reader-outline-goto-entry (button) 130 | "Shared logic to jump to an outline BUTTON." 131 | (let ((page (button-get button 'reader-page))) 132 | (unless (numberp page) 133 | (user-error "Invalid outline entry: no page info")) 134 | (reader-outline-select-doc-window) 135 | (reader-goto-page page window))) 136 | 137 | (defun reader-outline-visit-page () 138 | "Jump to the page at point in the associated reader buffer." 139 | (interactive) 140 | (save-excursion 141 | (end-of-line) ; This is done to make sure the we always have a 142 | (backward-char) ; button at point. 143 | (reader-outline-goto-entry (button-at (point))))) 144 | 145 | (provide 'reader-outline) 146 | ;;; reader-outline.el ends here 147 | -------------------------------------------------------------------------------- /render/render-threads.c: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2025 Divya Ranjan Pattanaik 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "render-threads.h" 18 | ThreadPool g_thread_pool; 19 | 20 | /** 21 | * Initialize the job queue. 22 | * 23 | * Sets head and tail to NULL and initializes the mutex and condition variable. 24 | * 25 | * @param queue Pointer to the JobQueue to initialize. 26 | */ 27 | 28 | void 29 | job_queue_init(JobQueue *queue) 30 | { 31 | queue->head = queue->tail = NULL; 32 | pthread_mutex_init(&queue->q_mutex, NULL); 33 | pthread_cond_init(&queue->q_cond, NULL); 34 | } 35 | 36 | /** 37 | * Destroy the job queue. 38 | * 39 | * Destroys the associated mutex and condition variable. 40 | * 41 | * @param queue Pointer to the JobQueue to destroy. 42 | */ 43 | 44 | void 45 | job_queue_destroy(JobQueue *queue) 46 | { 47 | pthread_mutex_destroy(&queue->q_mutex); 48 | pthread_cond_destroy(&queue->q_cond); 49 | } 50 | 51 | /** 52 | * Push a job into the job queue. 53 | * 54 | * Appends the job to the end of the queue and signals waiting threads. 55 | * 56 | * @param queue Pointer to the JobQueue. 57 | * @param job Pointer to the ThreadJob to enqueue. 58 | */ 59 | 60 | void 61 | job_queue_push(JobQueue *queue, ThreadJob *job) 62 | { 63 | job->next = NULL; 64 | pthread_mutex_lock(&queue->q_mutex); 65 | if (queue->tail) 66 | queue->tail->next = job; 67 | else 68 | queue->head = job; 69 | queue->tail = job; 70 | pthread_cond_signal(&queue->q_cond); 71 | pthread_mutex_unlock(&queue->q_mutex); 72 | } 73 | 74 | /** 75 | * Pop a job from the job queue. 76 | * 77 | * Blocks until a job is available, then removes and returns it. 78 | * 79 | * @param queue Pointer to the JobQueue. 80 | * @return Pointer to the next ThreadJob. 81 | */ 82 | 83 | ThreadJob * 84 | job_queue_pop(JobQueue *queue) 85 | { 86 | pthread_mutex_lock(&queue->q_mutex); 87 | while (!queue->head || queue->head == NULL) // Waiting for work 88 | pthread_cond_wait(&queue->q_cond, &queue->q_mutex); 89 | ThreadJob *job = queue->head; 90 | queue->head = job->next; 91 | if (!queue->head) // If there's no next job, set NULL 92 | queue->tail = NULL; 93 | pthread_mutex_unlock(&queue->q_mutex); 94 | return job; 95 | } 96 | 97 | /** 98 | * Worker thread routine for the thread pool. 99 | * 100 | * Continuously fetches and runs jobs from the job queue, using a 101 | * leader/follower pattern to manage scheduling. Terminates on receiving a job 102 | * with a NULL function. 103 | * 104 | * @param arg Pointer to the ThreadPool. 105 | * @return NULL on termination. 106 | */ 107 | 108 | void * 109 | thread_routine(void *arg) 110 | { 111 | ThreadPool *pool = (ThreadPool *)arg; 112 | 113 | while (1) 114 | { 115 | // Try to become the leader 116 | pthread_mutex_lock(&pool->leader_mutex); 117 | while (pool->leader_exists) 118 | { 119 | pthread_cond_wait(&pool->leader_cond, 120 | &pool->leader_mutex); 121 | } 122 | 123 | // Become leader 124 | pool->leader_exists = 1; 125 | pthread_mutex_unlock(&pool->leader_mutex); 126 | 127 | // Fetch a task 128 | ThreadJob *job = job_queue_pop(&pool->job_queue); 129 | 130 | if (job == NULL) 131 | { 132 | fprintf(stderr, "The job points to NULL!!!\n"); 133 | } 134 | 135 | // Hand off leadership 136 | pthread_mutex_lock(&pool->leader_mutex); 137 | pool->leader_exists = 0; 138 | pthread_cond_signal(&pool->leader_cond); 139 | pthread_mutex_unlock(&pool->leader_mutex); 140 | 141 | if (!job->func) 142 | { 143 | free(job); 144 | break; 145 | } 146 | 147 | job->func(job->arg); 148 | } 149 | 150 | free(arg); 151 | return NULL; 152 | } 153 | 154 | /** 155 | * Initialize the thread pool. 156 | * 157 | * Initializes the leader lock, job queue, and spawns worker threads. 158 | * 159 | * @param pool Pointer to the ThreadPool to initialize. 160 | */ 161 | 162 | void 163 | threadpool_init(ThreadPool *pool) 164 | { 165 | pool->leader_exists = 0; 166 | pthread_mutex_init(&pool->leader_mutex, NULL); 167 | pthread_cond_init(&pool->leader_cond, NULL); 168 | job_queue_init(&pool->job_queue); 169 | 170 | for (int i = 0; i < MAX_POOL_SIZE; i++) 171 | pthread_create(&pool->threads[i], NULL, thread_routine, pool); 172 | } 173 | 174 | /** 175 | * Shutdown the thread pool. 176 | * 177 | * Joins all threads and destroys the job queue and synchronization primitives. 178 | * 179 | * @param pool Pointer to the ThreadPool to shut down. 180 | */ 181 | 182 | void 183 | threadpool_shutdown(ThreadPool *pool) 184 | { 185 | fprintf(stderr, 186 | "Joining %d threads and shutting down the thread pool...\n", 187 | MAX_POOL_SIZE); 188 | for (int i = 0; i < MAX_POOL_SIZE; i++) 189 | pthread_join(pool->threads[i], NULL); 190 | fprintf(stderr, "Destroying the thread job queue..\n"); 191 | job_queue_destroy(&pool->job_queue); 192 | pthread_mutex_destroy(&pool->leader_mutex); 193 | pthread_cond_destroy(&pool->leader_cond); 194 | } 195 | 196 | /** 197 | * Submit a job to the thread pool. 198 | * 199 | * Wraps the given function and argument into a ThreadJob and pushes it to the 200 | * queue. 201 | * 202 | * @param func Function pointer representing the job. 203 | * @param arg Argument to pass to the job function. 204 | * @param pool Pointer to the ThreadPool to submit the job to. 205 | */ 206 | 207 | void 208 | submit_job(void *(*func)(void *arg), void *arg, ThreadPool *pool) 209 | { 210 | ThreadJob *job = (ThreadJob *)malloc(sizeof(*job)); 211 | job->func = func; 212 | job->arg = arg; 213 | job_queue_push(&pool->job_queue, job); 214 | } 215 | -------------------------------------------------------------------------------- /render/mupdf-helpers.c: -------------------------------------------------------------------------------- 1 | // Helper functions that complement the MuPDF C API 2 | 3 | // 4 | // Copyright (C) 2025 Divya Ranjan Pattanaik 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | 19 | #include "mupdf-helpers.h" 20 | #include "render-core.h" 21 | #include 22 | 23 | pthread_mutex_t g_mupdf_mutex[FZ_LOCK_MAX]; 24 | 25 | /** 26 | * doc_page_width - Provide integer width of the current document 27 | * @state: Pointer to DocState 28 | * Return: Integer width 29 | */ 30 | 31 | int 32 | doc_page_width(EmacsWinState *win_state) 33 | { 34 | CachedPage *cp = win_state->current_cached_page; 35 | int width = cp->imgw; 36 | return width; 37 | } 38 | 39 | /** 40 | * doc_page_height - Provide integer height of the current document 41 | * @state: Pointer to DocState 42 | * Return: Integer height 43 | */ 44 | 45 | int 46 | doc_page_height(EmacsWinState *win_state) 47 | { 48 | CachedPage *cp = win_state->current_cached_page; 49 | int height = cp->imgh; 50 | return height; 51 | } 52 | 53 | /** 54 | * reset_doc_state - Reset all fields of a DocState to their initial values. 55 | * @state: Pointer to the DocState to be reset. 56 | * 57 | */ 58 | 59 | void 60 | reset_doc_state(DocState *state) 61 | { 62 | fprintf(stderr, "Resetting the existing DocState\n"); 63 | *state = (DocState){ 64 | .ctx = NULL, 65 | .locks = NULL, 66 | .doc = NULL, 67 | .cached_pages_pool = NULL, 68 | .page_bbox = 69 | { 70 | .x0 = 0.0f, 71 | .y0 = 0.0f, 72 | }, 73 | .path = NULL, 74 | .pagecount = 0, 75 | .outline = NULL, 76 | .invert = 0}; 77 | } 78 | 79 | void 80 | fail(const char *msg) 81 | { 82 | fprintf(stderr, "%s\n", msg); 83 | abort(); 84 | } 85 | 86 | void 87 | lock_mutex(void *user, int lock) 88 | { 89 | pthread_mutex_t *mutexes = (pthread_mutex_t *)user; 90 | if (pthread_mutex_lock(&mutexes[lock]) != 0) 91 | fail("pthread_mutex_lock()"); 92 | } 93 | 94 | void 95 | unlock_mutex(void *user, int lock) 96 | { 97 | pthread_mutex_t *mutexes = (pthread_mutex_t *)user; 98 | if (pthread_mutex_unlock(&mutexes[lock]) != 0) 99 | fail("pthread_mutex_unlock()"); 100 | } 101 | 102 | /** 103 | * Initialize the main MuPDF context with thread-safe locking. 104 | * 105 | * Sets up mutexes for MuPDF's internal locking, assigns them to the 106 | * document state's lock structure, and creates a new `fz_context'. 107 | * Also registers default document handlers. 108 | * 109 | * @param state Pointer to the DocState to initialize. 110 | * Return: EXIT_SUCCESS on success, EXIT_FAILURE on error. 111 | */ 112 | 113 | int 114 | init_main_ctx(DocState *state) 115 | { 116 | for (int i = 0; i < FZ_LOCK_MAX; ++i) 117 | { 118 | pthread_mutex_init(&g_mupdf_mutex[i], NULL); 119 | } 120 | state->locks.user = g_mupdf_mutex; 121 | state->locks.lock = lock_mutex; 122 | state->locks.unlock = unlock_mutex; 123 | state->ctx = fz_new_context(NULL, &state->locks, FZ_STORE_DEFAULT); 124 | fz_register_document_handlers(state->ctx); 125 | 126 | if (!state->ctx) 127 | { 128 | fprintf(stderr, "Cannot create MuPDF context\n"); 129 | return EXIT_FAILURE; 130 | } 131 | 132 | return EXIT_SUCCESS; 133 | } 134 | 135 | /** 136 | * Load fz_document using MuPDF. 137 | * 138 | * Opens the document at `state->path', loads its outline and page count, 139 | * and stores them in the DocState. Handles errors via MuPDF's exception 140 | * mechanism. 141 | * 142 | * @param state Pointer to the DocState with initialized context and path. 143 | * Return: EXIT_SUCCESS on success, EXIT_FAILURE on failure. 144 | */ 145 | 146 | int 147 | load_mupdf_doc(DocState *state) 148 | { 149 | 150 | fz_try(state->ctx) 151 | { 152 | state->doc = fz_open_document(state->ctx, state->path); 153 | state->outline = fz_load_outline(state->ctx, state->doc); 154 | state->pagecount = fz_count_pages(state->ctx, state->doc); 155 | } 156 | fz_catch(state->ctx) 157 | { 158 | fprintf(stderr, "Could not open document\n"); 159 | fz_drop_context(state->ctx); 160 | return EXIT_FAILURE; 161 | } 162 | 163 | return EXIT_SUCCESS; 164 | } 165 | 166 | /** 167 | * Free resources associated with a CachedPage. 168 | * 169 | * Drops the display list and frees any associated image data 170 | * if the page was marked as ready. Marks the page as empty. 171 | * 172 | * @param state Document state containing the MuPDF context. 173 | * @param cp Pointer to the CachedPage to be freed. 174 | */ 175 | 176 | void 177 | free_cached_page(DocState *state, CachedPage *cp) 178 | { 179 | if (cp->status != PAGE_STATUS_READY) 180 | return; // already evicted or never loaded 181 | 182 | cp->status = PAGE_STATUS_EMPTY; 183 | fz_drop_display_list(state->ctx, cp->display_list); 184 | cp->display_list = NULL; 185 | free(cp->img_data); 186 | cp->img_data = NULL; 187 | cp->img_size = 0; 188 | } 189 | 190 | /** 191 | * Free all ready pages in the document's cache window. 192 | * 193 | * Iterates through the cache window and frees pages marked as ready. 194 | * Resets the cache window pointer afterward. 195 | * 196 | * @param state Pointer to the current DocState. 197 | */ 198 | 199 | void 200 | free_cache_window(DocState *doc_state, EmacsWinState *win_state) 201 | { 202 | fprintf(stderr, "Freeing the cache window for current document...\n"); 203 | for (int i = 0; i < MAX_CACHE_SIZE; i++) 204 | { 205 | if (win_state->cache_window[i] 206 | && win_state->cache_window[i]->status == PAGE_STATUS_READY) 207 | free_cached_page(doc_state, win_state->cache_window[i]); 208 | } 209 | *win_state->cache_window = NULL; 210 | } 211 | 212 | /** 213 | * Free the entire cached pages pool for the document. 214 | * 215 | * Destroys all mutexes and condition variables in the pool, 216 | * then frees the underlying memory. 217 | * 218 | * @param state Pointer to the current DocState. 219 | */ 220 | 221 | void 222 | free_cached_pages_pool(DocState *state) 223 | { 224 | fprintf(stderr, "Freeing the entire cached pages pool for current " 225 | "document...\n"); 226 | for (int i = 0; i < state->pagecount; i++) 227 | { 228 | pthread_mutex_destroy(&state->cached_pages_pool[i]->mutex); 229 | pthread_cond_destroy(&state->cached_pages_pool[i]->cond); 230 | } 231 | free(state->cached_pages_pool[0]); 232 | free(state->cached_pages_pool); 233 | } 234 | -------------------------------------------------------------------------------- /README.org: -------------------------------------------------------------------------------- 1 | #+TITLE: The GNU Emacs Reader 2 | #+OPTIONS: toc:nil 3 | 4 | #+begin_src org :exports none 5 | Copyright (C) 2025 Divya Ranjan Pattanaik 6 | Copyright (C) 2025 Tushar 7 | Copyright (C) 2025 prom 8 | 9 | This program is free software; you can redistribute it and/or modify 10 | it under the terms of the GNU General Public License as published by 11 | the Free Software Foundation, either version 3 of the License, or (at 12 | your option) any later version. 13 | 14 | This program is distributed in the hope that it will be useful, but 15 | WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | General Public License for more details. 18 | 19 | You should have received a copy of the GNU General Public License 20 | along with this program. If not, see . 21 | #+end_src 22 | 23 | [[file:extras/emacs-reader-logo.png]] 24 | 25 | An all-in-one document reader for GNU Emacs, supporting all [[* Supported Formats][major document formats]]. This package intends to take from =doc-view=, =nov.el=, and =pdf-tools= and make them better. And as such, it is effectively a *drop-in replacement* for them 26 | 27 | * Screencast 28 | [[https://codeberg.org/divyaranjan/emacs-reader/raw/commit/9d62d26fe4ae63e5cecf57bc399b20f7feefb620/extras/emacs-reader-2025-05-14_04.32.41.gif]] 29 | 30 | * Supported Formats 31 | The Emacs Reader (via MuPDF) can open all the formats below. 32 | 33 | ** Well-supported Formats 34 | + PDF 35 | + EPUB 36 | + MOBI 37 | + FB2 38 | + XPS/OpenXPS 39 | + CBZ 40 | 41 | ** Office Document Formats 42 | These formats below are not really for document reading, and as such while they are supported by MuPDF and can be opened fine, it’s just not going to be that good of an experience. It should only be used for quickly checking the textual contents of the document, and certainly cannot be edited inside Emacs. (You may use LibreOffice for that.) 43 | 44 | *** Open Document Formats (LibreOffice) 45 | + ODT 46 | + ODS 47 | + ODP 48 | + ODG 49 | 50 | *** Proprietary Micro$oft Formats 51 | Using these formats is heavily discouraged, you should /always/ prefer the above formats from LibreOffice (Which can also you help you edit these formats if you need to). But since MuPDF does come with some very minimal support for these proprietary formats as well, they can also be viewed: 52 | 53 | + DOCX 54 | + PPTX 55 | + XLSX 56 | 57 | * Dependencies 58 | The only thing this package depends on is =mupdf=, at minimum =v1.26.0=. 59 | 60 | * Installation 61 | For now, until the package has been published to GNU ELPA, the only way to install and use it is through locally cloning the repo and building it. This is different across platforms: 62 | 63 | ** GNU/Linux 64 | On GNU/Linux all you need is: =gcc= and =make=. Then you can simply install through the Emacs’ built-in =package-vc= or the [[https://github.com/radian-software/straight.el][straight]] package manager. The built-in =package-vc= still has some quirks, but here are the recipes for both: 65 | 66 | - =use-package= with =package-vc=: 67 | #+begin_src emacs-lisp 68 | (setq package-vc-allow-build-commands t) 69 | (use-package reader 70 | :vc (:url "https://codeberg.org/divyaranjan/emacs-reader" 71 | :make "all")) 72 | #+end_src 73 | 74 | - =use-package= with =straight= 75 | #+begin_src emacs-lisp 76 | (use-package reader 77 | :straight '(reader :type git :host codeberg :repo "divyaranjan/emacs-reader" 78 | :files ("*.el" "render-core.so") 79 | :pre-build ("make" "all"))) 80 | #+end_src 81 | 82 | *** GNU Guix 83 | Using the GNU Guix package manager, you can get emacs-reader through the [[https://codeberg.org/divyaranjan/divya-lambda][divya-lambda]] Guix channel. Follow the instructions there to add the Guix channel to your configuration. Then all that remains to do is, 84 | #+begin_src bash 85 | guix install emacs-reader 86 | #+end_src 87 | 88 | This will get the latest release of emacs-reader. However, if you want to get latest features, bug fixes (and bugs!) to help us with testing emacs-reader, you should use the master branch. You can instruct Guix to get it for you, like so, 89 | #+begin_src bash 90 | guix install emacs-reader --with-branch=emacs-reader=master 91 | #+end_src 92 | 93 | You can also upgrade an already installed package with, 94 | #+begin_src bash 95 | guix upgrade emacs-reader --with-branch=emacs-reader=master 96 | #+end_src 97 | 98 | You may replace the branch name as you need. 99 | 100 | *** Nix 101 | Follow the instructions [[https://codeberg.org/divyaranjan/emacs-reader/issues/115][here]]. 102 | 103 | ** MacOS 104 | Since MacOS’ package manager Homebrew already has the latest version of MuPDF (1.26.0), you don’t need the submodule at all. You just need to do: 105 | #+begin_src sh 106 | brew install gcc 107 | brew install make 108 | brew install mupdf 109 | #+end_src 110 | 111 | And then use the straight or package-vc recipe from the GNU/Linux section. 112 | 113 | ** Windows 114 | With Windows, you need MSYS2 toolchain, first install MSYS2, then choose one of the environment that MSYS2 provided, on a modern 115 | 64bit Windows system, you want either =MINGW64= or =UCRT64=. If you never try MSYS2 before, we recommend =MINGW64= since this is the 116 | environment that used to build the official GNU/Emacs' Windows version. 117 | 118 | The following steps assume you use =MINGW64=: 119 | 120 | First install the build dependencies: 121 | #+begin_src shell 122 | pacman -S make mingw-w64-x86_64-gcc git pkg-config 123 | #+end_src 124 | 125 | Then you need install libmupdf, unfortunately right now MSYS2's repo only has MuPDF 1.24.3, so you need this [[https://github.com/msys2/MINGW-packages/pull/24550][PR]], 126 | there are 2 ways to use this PR: 127 | 128 | 1. Download the pre-compiled package from the PR's CI, then use =pacman -U= to install the package file. 129 | 2. Clone the PR, goto the folder =mingw-w64-mupdf= then run command =makepkg -s= to compile MuPDF, and then use =pacman -U= to install the package file. 130 | 131 | After that, you can run =git clone https://codeberg.org/divyaranjan/emacs-reader.git= and then: 132 | #+begin_src sh 133 | make all 134 | #+end_src 135 | 136 | ** Manual 137 | This section is about how to install this package manually. Intended to be used by developers. 138 | 139 | After cloning the repository, follow the instructions from the previous section to install dependencies on your respective operating system. 140 | 141 | Then, you run =make= in the git repository, as noted earlier this may take a few depending on if it is fetching and building =mupdf=. 142 | 143 | After this, you add the path to emacs-reader git repository to =load-path=, 144 | #+begin_src emacs-lisp 145 | (add-to-list 'load-path "/path/to/emacs-reader") 146 | #+end_src 147 | 148 | You can also utilize =use-package= to do the same, 149 | #+begin_src emacs-lisp 150 | (use-package reader 151 | :vc t 152 | :load-path "/path/to/emacs-reader") 153 | #+end_src 154 | 155 | To test emacs-reader in a default Emacs config, use something like: 156 | #+begin_src shell 157 | emacs -q -L . -l reader.el 158 | #+end_src 159 | This command adds the current directory to path, and loads =reader.el=. 160 | 161 | This will not work for testing auto loading though. You can try using =package-vc-install-from-checkout= to test that. [[https://codeberg.org/attachments/2555c252-0977-484e-b369-38b18a321a48][This video]] demonstrates how to do that. 162 | 163 | * Key Bindings 164 | - =n= for going to next page 165 | - =p= for going to previous page 166 | - =C-n= for scrolling down. 167 | - =C-p= for scrolling up. 168 | - =C-b= for scrolling left. 169 | - =C-f= for scrolling right. 170 | - =Q= for closing the Emacs Reader buffer. 171 | - =M-<= for going to the first page. 172 | - =M->= for going to the last page. 173 | - =M-g g= for going to a particular page. 174 | - =M-v= or =Page Up= for scrolling to the top of the page. 175 | - =C-v= or =Page Down= for scrolling to the end of the page. 176 | - =SPC=, =S-SPC= , and =DEL= make the above two commands keep scrolling the pages. 177 | - ===, =+=, and =C-= for zooming into the page. 178 | - =-= and =C-= for zooming out of the page. 179 | - =H= to make the page fit the height of the current window. 180 | - =W= to make the page fit the width of the current window. 181 | 182 | * How It Works 183 | This package is entirely distinct from =DocView= and =pdf-tools= in both its architecture and implementation. It leverages Emacs’ dynamic/native modules which allows it to interoperate with other programming languages outside of its Emacs Lisp environment. 184 | 185 | Thus, we rely on the efficient MuPDF library as a shared object with which our dynamic modules work. All the tasks that require manual memory management, efficiently dealing with the rendered pages, and so on are delegated to the C backend, and Emacs takes care of exclusively what it’s good at: displaying produced pages, buffer management, and all round integration with the rest of Emacs. 186 | 187 | For understanding how dynamic modules work within Emacs, please consult the following article I wrote: 188 | 189 | https://www.phimulambda.org/blog/emacs-dynamic-module.html 190 | 191 | * Live Streams 192 | 193 | I have been streaming the development of this package on [[https://tv.dyne.org/c/phimulambda/][my PeerTube channel: (phi (mu (lambda)))]] 194 | 195 | Here are the recordings of the streams: 196 | 197 | - [[https://tv.dyne.org/w/8W8o4fWz94bMYVMUWExkX7][Part I: Introduction]] 198 | - [[https://tv.dyne.org/w/fmJnktiZMjrUKJU2s8Pxkq][Part II: Making Overlays Centered and Zoomable]] 199 | - [[https://tv.dyne.org/w/fsHrNnwYYnnYweArgtBHSe][Part III: Multi-Threading]] 200 | 201 | The streams happen on *Sundays, biweekly at around 5:30 PM UTC*. Follow the channel on Peertube or my [[https://mathstodon.xyz/@divyaranjan][Mastodon]] to be notified when I stream. You can also find some stream notes [[file:doc/][here]]. 202 | 203 | If you wish to join the discussion for the package, you should join the IRC channel =#phi-mu-lambda= on [[https://libera.chat/][Libera]]. 204 | 205 | * License 206 | Unless another license is listed, all files in emacs-reader are licensed under the GNU General Public License version 3 (or at your option), any later version. See [[file:LICENSE][LICENSE]] and [[file:CONTRIBUTORS][CONTRIBUTORS]] for further details. 207 | 208 | The logo of the project was made by Divya Ranjan Pattanaik and is shared under [[http://creativecommons.org/licenses/by-sa/4.0/][CC-BY-SA-4.0]]. The logo uses the following artworks from GNU: 209 | 210 | - [[https://www.gnu.org/graphics/heckert_gnu.html][A Bold GNU Head by Aurélio A. Heckert]] 211 | - [[https://commons.wikimedia.org/wiki/File:Emacs_512.png][Icon for Emacs 23 by Kentaro Ohkouchi]] 212 | 213 | The interesting history of different Emacs logos is outlined by Luis Fernandes, in his article on [[https://www.ee.torontomu.ca/~elf/emacs/logo/][The Design of the Emacs Logo]]. 214 | -------------------------------------------------------------------------------- /render/elisp-helpers.c: -------------------------------------------------------------------------------- 1 | // Helper functions that complement the C API of the Emacs Module 2 | 3 | // 4 | // Copyright (C) 2025 Divya Ranjan Pattanaik 5 | // Copyright (C) 2025 Tushar 6 | // 7 | // This program is free software: you can redistribute it and/or modify 8 | // it under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 3 of the License, or 10 | // any later version. 11 | // 12 | // This program is distributed in the hope that it will be useful, 13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with this program. If not, see . 19 | 20 | #include "elisp-helpers.h" 21 | #include "emacs-module.h" 22 | #include "render-core.h" 23 | 24 | /** 25 | * elisp_2_c_str - Convert an Elisp string to a C string. 26 | * @env: Pointer (of type `emacs_env') to the environment of the Emacs runtime 27 | * @value: The value of the Elisp string that is to be converted. It will only 28 | * the value (in Elisp, (symbol-value str)) of the string, not the symbol. 29 | * @buffer: The C character array that is going to store the converted string. 30 | * @size: Pointer to the length of the string after being converted, as 31 | * type size_t. 32 | * 33 | * Return: true on success, false on error 34 | */ 35 | 36 | bool 37 | elisp_2_c_str(emacs_env *env, emacs_value value, char **buffer, size_t *size) 38 | { 39 | ptrdiff_t buffer_size; 40 | if (!env->copy_string_contents(env, value, NULL, &buffer_size)) 41 | return false; 42 | assert(env->non_local_exit_check(env) == emacs_funcall_exit_return); 43 | assert(buffer_size > 0); 44 | *buffer = malloc((size_t)buffer_size); 45 | if (*buffer == NULL) 46 | { 47 | env->non_local_exit_signal(env, env->intern(env, "memory-full"), 48 | env->intern(env, "nil")); 49 | return false; 50 | } 51 | ptrdiff_t old_buffer_size = buffer_size; 52 | if (!env->copy_string_contents(env, value, *buffer, &buffer_size)) 53 | { 54 | free(*buffer); 55 | *buffer = NULL; 56 | return false; 57 | } 58 | assert(env->non_local_exit_check(env) == emacs_funcall_exit_return); 59 | assert(buffer_size == old_buffer_size); 60 | *size = (size_t)(buffer_size - 1); 61 | return true; 62 | } 63 | 64 | /** 65 | * provide - Calls the Elisp (provide) function to provide a feature to the 66 | * module. 67 | * @env: Pointer (of type `emacs_env') to the environment of the Emacs runtime 68 | * @value: String of the symbol that is to be provid-ed. 69 | * 70 | * It doesn’t store the symbol or value of the feature anywhere, only calls the 71 | * provide function with the symbol from the string. 72 | * 73 | * It’s equivalent to doing the following in Elisp: 74 | * (provide 'feature) 75 | */ 76 | 77 | void 78 | provide(emacs_env *env, const char *value) 79 | { 80 | emacs_value Qvalue = env->intern(env, value); 81 | emacs_value Qprovide = env->intern(env, "provide"); 82 | emacs_value args[] = { Qvalue }; 83 | 84 | env->funcall(env, Qprovide, 1, args); 85 | } 86 | 87 | /** 88 | * register_module_func - Register a function from the dynamic module into the 89 | * Emacs environment. It makes the function available to be directly usable 90 | * from Emacs as any other Elisp function. 91 | * @env: Pointer to the Emacs environment for the runtime (emacs_env). 92 | * @module_func: Pointer to the function (emacs_value) that needs to be 93 | registered. 94 | * @symbol: The symbol for which the function is to be registered. 95 | * @min_args: The minimum number of arguments this function must be provided 96 | * with. 97 | * @max_args: The maximum number of arguments this function can take. 98 | * @docstring: The string which would act as the docstring for the module 99 | * function. Equivalent to the docstring in Elisp functions, and visible from 100 | * C-h f. 101 | * 102 | * The @module_func must be not only compile-able but also it must respect the 103 | * Elisp runtime of Emacs, any sort of undefined or unpredictable behavior would 104 | * not be found during compile-time, but rather would result in a segfault of 105 | * Emacs. 106 | * 107 | * Returns: nothing 108 | */ 109 | 110 | void 111 | register_module_func(emacs_env *env, 112 | emacs_value (*module_func)(emacs_env *env, ptrdiff_t nargs, 113 | emacs_value *args, void *data), 114 | char *symbol, int min_args, int max_args, char *docstring) 115 | { 116 | 117 | emacs_value elisp_func_symbol = env->intern(env, symbol); 118 | emacs_value elisp_func = env->make_function( 119 | env, min_args, max_args, module_func, docstring, NULL); 120 | 121 | emacs_value elisp_func_args[2] = { elisp_func_symbol, elisp_func }; 122 | env->funcall(env, env->intern(env, "fset"), 2, elisp_func_args); 123 | } 124 | 125 | /** 126 | * data2elisp_image - Create an Elisp image object from raw image data 127 | * @env: Emacs environment pointer 128 | * @img_data: Image data that is to be rendered as image, should usually be from 129 | * the DocState. 130 | * @img_size: The size of the image data that is going to be rendered, should 131 | * usually be from the DocState. 132 | * 133 | * One needs to be extremely about handling the image data, and make sure it 134 | * later gets dropped and freed accordingly. 135 | * 136 | * Returns: The Elisp image object, which will be a specific plist, and can be 137 | * rendered in Emacs with `insert-image' or other means. 138 | 139 | */ 140 | 141 | emacs_value 142 | data2elisp_image(emacs_env *env, EmacsWinState *win_state, char *img_data, 143 | size_t img_size) 144 | { 145 | emacs_value image_width 146 | = env->make_integer(env, doc_page_width(win_state)); 147 | emacs_value image_height 148 | = env->make_integer(env, doc_page_height(win_state)); 149 | emacs_value img_data_string 150 | = env->make_unibyte_string(env, img_data, img_size); 151 | emacs_value image_args[7] = { 152 | img_data_string, env->intern(env, "pbm"), 153 | env->intern(env, "t"), env->intern(env, ":width"), 154 | image_width, env->intern(env, ":height"), 155 | image_height, 156 | }; 157 | 158 | emacs_value image_data = env->funcall( 159 | env, env->intern(env, "create-image"), 7, image_args); 160 | 161 | return image_data; 162 | } 163 | 164 | /** 165 | * init_doc_state_ptr - Initialize the DocState and expose it to Elisp. 166 | * @env: The Emacs environment pointer. 167 | * 168 | * Return: A pointer to the current `docstate` (or null if the symbol is unbound 169 | * or not a valid user pointer.). 170 | */ 171 | 172 | DocState * 173 | init_doc_state_ptr(emacs_env *env) 174 | { 175 | DocState *state = malloc(sizeof(DocState)); 176 | // Create a user pointer and expose it to Emacs in a buffer-local 177 | emacs_value user_ptr = env->make_user_ptr(env, NULL, state); 178 | emacs_value doc_state_ptr_sym 179 | = env->intern(env, "reader-current-doc-state-ptr"); 180 | env->funcall(env, env->intern(env, "set"), 2, 181 | (emacs_value[]){ doc_state_ptr_sym, user_ptr }); 182 | return state; 183 | } 184 | 185 | /** 186 | * get_doc_state_ptr - Retrieve the DocState pointer stored in Elisp. 187 | * @env: The Emacs environment pointer. 188 | * 189 | * Return: A pointer to the current `DocState` (or NULL if the symbol is unbound 190 | * or not a valid user pointer.). 191 | */ 192 | 193 | DocState * 194 | get_doc_state_ptr(emacs_env *env) 195 | { 196 | emacs_value ptr_sym = env->intern(env, "reader-current-doc-state-ptr"); 197 | emacs_value ptr 198 | = env->funcall(env, env->intern(env, "symbol-value"), 1, &ptr_sym); 199 | DocState *state = env->get_user_ptr(env, ptr); 200 | return state; 201 | } 202 | 203 | EmacsWinState * 204 | init_win_state_ptr(emacs_env *env, DocState *doc_state, emacs_value window) 205 | { 206 | EmacsWinState *win_state = malloc((sizeof(EmacsWinState))); 207 | reset_win_state(win_state); 208 | win_state->doc_state = doc_state; 209 | // Create a user pointer 210 | emacs_value win_state_usr_ptr 211 | = env->make_user_ptr(env, NULL, win_state); 212 | 213 | // Get the overlay window parameter 214 | emacs_value overlay = env->funcall( 215 | env, env->intern(env, "window-parameter"), 2, 216 | (emacs_value[]){ window, env->intern(env, "overlay") }); 217 | 218 | // Set the overlay property for the EmacsWinState user pointer 219 | env->funcall(env, env->intern(env, "overlay-put"), 3, 220 | (emacs_value[]){ overlay, env->intern(env, "win-state"), 221 | win_state_usr_ptr }); 222 | return win_state; 223 | } 224 | 225 | EmacsWinState * 226 | get_win_state_ptr(emacs_env *env, emacs_value overlay) 227 | { 228 | emacs_value ptr = env->funcall( 229 | env, env->intern(env, "overlay-get"), 2, 230 | (emacs_value[]){ overlay, env->intern(env, "win-state") }); 231 | if (ptr == NULL) 232 | emacs_message( 233 | env, 234 | "Selected window doesn't have a pointer to EmacsWinState."); 235 | EmacsWinState *win_state = env->get_user_ptr(env, ptr); 236 | return win_state; 237 | } 238 | 239 | void 240 | reset_win_state(EmacsWinState *win_state) 241 | { 242 | *win_state = (EmacsWinState){ 243 | .resolution = 72.0, 244 | .rotate = 0, 245 | .current_page_number = 0, 246 | .current_window_index = 0, 247 | .current_cached_page = NULL, 248 | }; 249 | } 250 | 251 | void 252 | set_current_page_number(emacs_env *env, int page) 253 | { 254 | page += 1; // Exposed number shouldn't be 0-indexed 255 | emacs_value curr_win = EMACS_CURR_WIN; 256 | env->funcall(env, env->intern(env, "set-window-parameter"), 3, 257 | (emacs_value[]){ curr_win, env->intern(env, "page"), 258 | env->make_integer(env, page) }); 259 | env->funcall(env, env->intern(env, "set"), 2, 260 | (emacs_value[]){ 261 | env->intern(env, "reader--recent-pagenumber-fallback"), 262 | env->make_integer(env, page) }); 263 | } 264 | 265 | /** 266 | * set_current_render_status - Mark the buffer’s render status as true. 267 | * @env: The Emacs environment pointer. 268 | * 269 | * Sets the Elisp variable `doc-render-status` to `t` in the current buffer, 270 | * indicating that the image rendering is up to date. 271 | */ 272 | 273 | void 274 | set_current_render_status(emacs_env *env) 275 | { 276 | emacs_value render_status_var 277 | = env->intern(env, "reader-current-doc-render-status"); 278 | env->funcall( 279 | env, env->intern(env, "set"), 2, 280 | (emacs_value[]){ render_status_var, env->intern(env, "t") }); 281 | } 282 | 283 | /** 284 | * set_current_pagecount - Expose the document’s total page count to Elisp. 285 | * @env: The Emacs environment pointer. 286 | * @state: Pointer to the `DocState` containing the pagecount. 287 | * 288 | * Sets the Elisp variable `current-doc-pagecount` in the current buffer to the 289 | * number of pages the document has. 290 | */ 291 | 292 | void 293 | set_current_pagecount(emacs_env *env, DocState *state) 294 | { 295 | emacs_value pagecount_args[2] 296 | = { env->intern(env, "reader-current-doc-pagecount"), 297 | env->make_integer(env, state->pagecount) }; 298 | env->funcall(env, env->intern(env, "set"), 2, pagecount_args); 299 | } 300 | 301 | /** 302 | * init_overlay - Create and register an overlay covering the whole buffer. 303 | * @env: The Emacs environment pointer. 304 | * 305 | * Makes an overlay spanning the entire buffer. Stores the overlay object in the 306 | * Elisp variable `reader-current-doc-overlay` for later use. 307 | */ 308 | 309 | emacs_value 310 | init_overlay(emacs_env *env, emacs_value window) 311 | { 312 | emacs_value start 313 | = env->funcall(env, env->intern(env, "point-min"), 0, NULL); 314 | emacs_value end 315 | = env->funcall(env, env->intern(env, "point-max"), 0, NULL); 316 | emacs_value overlay 317 | = env->funcall(env, env->intern(env, "make-overlay"), 2, 318 | (emacs_value[]){ start, end }); 319 | env->funcall( 320 | env, env->intern(env, "overlay-put"), 3, 321 | (emacs_value[]){ overlay, env->intern(env, "window"), window }); 322 | env->funcall( 323 | env, env->intern(env, "set-window-parameter"), 3, 324 | (emacs_value[]){ window, env->intern(env, "overlay"), overlay }); 325 | 326 | return overlay; 327 | } 328 | 329 | /** 330 | * get_current_doc_overlay - Retrieve the stored overlay object for the 331 | * document as a window parameter. 332 | * @env: The Emacs environment pointer. 333 | * 334 | * Return: The Elisp overlay object, or an unbound value if not set. 335 | */ 336 | 337 | emacs_value 338 | get_current_doc_overlay(emacs_env *env) 339 | { 340 | 341 | emacs_value curr_win = EMACS_CURR_WIN; 342 | emacs_value current_overlay = env->funcall( 343 | env, env->intern(env, "window-parameter"), 2, 344 | (emacs_value[]){ curr_win, env->intern(env, "overlay") }); 345 | return current_overlay; 346 | } 347 | 348 | /** 349 | * emacs_message - Print a message in Emacs with the given string 350 | * @env: The Emacs environment pointer. 351 | * @str: Null-terminated C string containing the message. 352 | */ 353 | 354 | void 355 | emacs_message(emacs_env *env, char *str) 356 | { 357 | emacs_value el_string = env->make_string(env, str, strlen(str)); 358 | env->funcall(env, env->intern(env, "message"), 1, &el_string); 359 | } 360 | 361 | /** 362 | * permanent_buffer_local_var: Sets a buffer local variable and makes it 363 | * permanently local so that it doesn’t get overridden 364 | * @env: The Emacs environment pointer. 365 | * @symbol: The symbol of the variable to be set 366 | */ 367 | 368 | void 369 | permanent_buffer_local_var(emacs_env *env, char *symbol) 370 | { 371 | emacs_value el_symbol = env->intern(env, symbol); 372 | env->funcall(env, env->intern(env, "make-variable-buffer-local"), 1, 373 | &el_symbol); 374 | env->funcall(env, env->intern(env, "set"), 2, 375 | (emacs_value[]){ el_symbol, EMACS_NIL }); 376 | 377 | env->funcall(env, env->intern(env, "put"), 3, 378 | (emacs_value[]){ el_symbol, 379 | env->intern(env, "permanent-local"), 380 | EMACS_T }); 381 | } 382 | 383 | /** 384 | * Display image data in an Emacs overlay. 385 | * 386 | * Converts raw image data into an Emacs image spec and sets it as the 387 | * `display` property of the given overlay. Clears the image cache to 388 | * ensure the image is rendered fresh. 389 | * 390 | * @param env Emacs module environment. 391 | * @param state Document state (used by image conversion). 392 | * @param img_data Pointer to raw image bytes (e.g., PNG). 393 | * @param img_size Size of the image data. 394 | * @param buffer_overlay Emacs overlay to attach the image to. 395 | */ 396 | 397 | void 398 | display_img_to_overlay(emacs_env *env, EmacsWinState *win_state, char *img_data, 399 | size_t img_size, emacs_value buffer_overlay) 400 | { 401 | emacs_value elisp_img 402 | = data2elisp_image(env, win_state, img_data, img_size); 403 | emacs_value overlay_put_args[3] 404 | = { buffer_overlay, env->intern(env, "display"), elisp_img }; 405 | env->funcall(env, env->intern(env, "overlay-put"), 3, overlay_put_args); 406 | env->funcall(env, env->intern(env, "clear-image-cache"), 0, NULL); 407 | } 408 | 409 | /** 410 | * Convert a fz_outline tree to an Emacs plist structure. 411 | * 412 | * Recursively traverses the outline linked list and builds a nested 413 | * plist representation for Emacs: each node becomes a plist with 414 | * `:title`, `:page`, and optionally `:children` keys. 415 | * 416 | * Stores the result in `reader-current-doc-outline` and returns it. 417 | * 418 | * @param env Emacs module environment. 419 | * @param node Root of the fz_outline tree (from MuPDF). 420 | * Return: Emacs Lisp list of plists representing the outline. 421 | */ 422 | 423 | emacs_value 424 | outline2plist(emacs_env *env, fz_outline *node) 425 | { 426 | emacs_value outline_plist = EMACS_NIL; 427 | if (!node) 428 | { 429 | return outline_plist; 430 | } 431 | 432 | while (node) 433 | { 434 | if (!node->title) 435 | { 436 | node = node->next; 437 | continue; 438 | } 439 | 440 | /* Build the base plist: (:title TITLE :page PAGE) */ 441 | emacs_value node_title 442 | = env->make_string(env, node->title, strlen(node->title)); 443 | emacs_value node_page = env->make_integer(env, node->page.page); 444 | emacs_value base_args[] 445 | = { env->intern(env, ":title"), node_title, 446 | env->intern(env, ":page"), node_page }; 447 | emacs_value node_plist 448 | = env->funcall(env, env->intern(env, "list"), 4, base_args); 449 | 450 | /* If there are children, recurse and append as :children key */ 451 | if (node->down) 452 | { 453 | emacs_value children = outline2plist(env, node->down); 454 | emacs_value child_pair_args[] 455 | = { env->intern(env, ":children"), children }; 456 | emacs_value children_pair = env->funcall( 457 | env, env->intern(env, "list"), 2, child_pair_args); 458 | /* Append the (:children CHILDREN) onto this node's 459 | * plist */ 460 | node_plist = env->funcall( 461 | env, env->intern(env, "append"), 2, 462 | (emacs_value[]){ node_plist, children_pair }); 463 | } 464 | 465 | /* Cons this node_plist onto our accumulator */ 466 | outline_plist = env->funcall( 467 | env, env->intern(env, "cons"), 2, 468 | (emacs_value[]){ node_plist, outline_plist }); 469 | node = node->next; 470 | } 471 | 472 | /* Reverse to preserve original document order */ 473 | outline_plist = env->funcall(env, env->intern(env, "nreverse"), 1, 474 | &outline_plist); 475 | 476 | /* Store in reader-current-doc-outline and return */ 477 | env->funcall( 478 | env, env->intern(env, "set"), 2, 479 | (emacs_value[]){ env->intern(env, "reader-current-doc-outline"), 480 | outline_plist }); 481 | return outline_plist; 482 | } 483 | -------------------------------------------------------------------------------- /reader.el: -------------------------------------------------------------------------------- 1 | ;;; reader.el --- General-purpose Document Reader -*- lexical-binding: t; -*- 2 | 3 | ;; Copyright (C) 2025 Divya Ranjan Pattanaik 4 | ;; Copyright (C) 2025 Tushar 5 | 6 | ;; Author: Divya Ranjan Pattanaik 7 | ;; Keywords: lisp, files, tools 8 | ;; Version: 0.3.2 9 | ;; Package-Requires: ((emacs "26.1")) 10 | ;; URL: https://codeberg.org/divyaranjan/emacs-reader 11 | 12 | ;; This program is free software; you can redistribute it and/or modify 13 | ;; it under the terms of the GNU General Public License as published by 14 | ;; the Free Software Foundation, either version 3 of the License, or 15 | ;; (at your option) any later version. 16 | 17 | ;; This program is distributed in the hope that it will be useful, 18 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 20 | ;; GNU General Public License for more details. 21 | 22 | ;; You should have received a copy of the GNU General Public License 23 | ;; along with this program. If not, see . 24 | 25 | ;;; Commentary: 26 | 27 | ;; This package provides a general purpose document reader within 28 | ;; Emacs by leveraging the use of dynamic modules. It primarily 29 | ;; relies on MuPDF to do the rendering, and Emacs Lisp’s native image 30 | ;; displaying capabilities to view the rendered images and manipulate them. 31 | 32 | ;;; Code: 33 | 34 | (require 'image) 35 | (require 'render-core) 36 | 37 | (defgroup reader nil 38 | "Group for Reader’s customizations." 39 | :prefix "reader-" 40 | :group 'custom) 41 | 42 | (defcustom reader-enlarge-factor 1.25 43 | "The fractional amount by which the page would be enlarged." 44 | :group 'reader 45 | :type 'number) 46 | 47 | (defcustom reader-shrink-factor 0.75 48 | "The fractional amount by which the page would be shrinked." 49 | :group 'reader 50 | :type 'number) 51 | 52 | (defcustom reader-default-fit 'reader-fit-to-height 53 | "The default fitting for documents." 54 | :group 'reader 55 | :type '(radio (function-item reader-fit-to-height) 56 | (function-item reader-fit-to-width))) 57 | 58 | (defvar-local reader--recent-scale-fallback 1.0 59 | "Previous scaling factor applied to the document.") 60 | 61 | ;; Setting of `auto-mode-list' fails if not autoloaded. 62 | ;;;###autoload 63 | (defconst reader-supported-formats (list "pdf" "epub" "mobi" 64 | "fb2" "xps" "cbz" 65 | "docx""pptx" "xlsx" 66 | "odt" "ods" "odp" "odg") 67 | "File formats supported by the document reader.") 68 | 69 | (defun reader-current-doc-overlay (&optional window) 70 | "Selected window (or if specified, WINDOW) parameter for overlay that is to be operated on." 71 | (window-parameter (or window (selected-window)) 'overlay)) 72 | 73 | (defun reader-current-doc-pagenumber (&optional window) 74 | "Page number of WINDOW (defaults to selected window)." 75 | (window-parameter (or window (selected-window)) 'page)) 76 | 77 | (defun reader-current-doc-scale-value (&optional window) 78 | "Scaling factor of WINDOW (defaults to selected window)." 79 | (or (window-parameter window 'scale) reader--recent-scale-fallback)) 80 | 81 | ;; We queue some commands because the user is expected to use the 82 | ;; commands repeatedly, such as by simply spamming a key. If we don't 83 | ;; queue the commands, Emacs may start skipping intermediate commands. 84 | 85 | (defvar reader--command-queue nil 86 | "Queue of reader commands to be executed sequentially.") 87 | 88 | (defun reader--process-command-queue () 89 | "Process the next command in the queue, ensuring UI updates." 90 | (when-let* ((cmd (pop reader--command-queue)) 91 | (delay 0.0001)) 92 | (funcall cmd) 93 | (redisplay) 94 | (run-with-idle-timer delay nil #'reader--process-command-queue))) 95 | 96 | (defun reader--enqueue-command (cmd args) 97 | "Add CMD with ARGS to the queue and start processing if needed." 98 | (push (apply #'apply-partially cmd args) reader--command-queue) 99 | (unless (or (active-minibuffer-window) 100 | (memq #'reader--process-command-queue post-command-hook)) 101 | (add-hook 'post-command-hook #'reader--process-command-queue))) 102 | 103 | (defmacro reader--define-queue-command (name arglist docstring interactive &rest body) 104 | "Define NAME as a reader command. 105 | Also define a necessary non-queue function. 106 | 107 | Much like `defun', except that ARGLIST, DOCSTRING, and INTERACTIVE are required. 108 | 109 | The reader--non-queue-NAME function is simply defined as a function with body BODY. 110 | The reader-NAME command is simply a wrapper around `reader--enqueue-command' with 111 | reader--non-queue-NAME as the argument." 112 | (declare (indent defun) 113 | (doc-string 3)) 114 | (let* ((name (symbol-name name)) 115 | (non-queue-function-name (concat "reader--non-queue-" name)) 116 | (queue-function-name (concat "reader-" name))) 117 | `(progn 118 | 119 | (defun ,(intern non-queue-function-name) ,arglist 120 | ,(format "%s 121 | 122 | This is the actual function, see `%s' for the interactive version." 123 | docstring queue-function-name) 124 | ,(add-to-list 'body 'progn)) 125 | 126 | (defun ,(intern queue-function-name) ,arglist 127 | ,(format "%s 128 | 129 | This is the queuing function, see `%s' for the actual definition." 130 | docstring non-queue-function-name) 131 | ,interactive 132 | (reader--enqueue-command #',(intern non-queue-function-name) 133 | ,(remq '&optional (add-to-list 'arglist 'list))))))) 134 | 135 | ;;;###autoload 136 | (defun reader-open-doc (document) 137 | "Open DOCUMENT for viewing. 138 | 139 | This function calls the module function `reader-dyn--load-doc' from the 140 | dynamic module to render the first page and displays it in a new buffer. 141 | 142 | The only formats that can be opened `reader-supported-formats', any 143 | other file format will simply not show up as a candidate." 144 | (interactive (let* ((regexp (concat "\\." (regexp-opt reader-supported-formats t) "$")) 145 | (file (read-file-name 146 | "Open document: " 147 | nil nil t nil 148 | (lambda (f) 149 | (or (file-directory-p f) 150 | (string-match-p regexp f)))))) 151 | (list file))) 152 | (switch-to-buffer (create-file-buffer document)) 153 | (insert "\n") 154 | (reader-dyn--load-doc (expand-file-name document)) 155 | (reader-mode)) 156 | 157 | (reader--define-queue-command next-page () 158 | "Go to the next page of the document." 159 | (interactive) 160 | (if-let* ((status (reader-dyn--next-page))) 161 | (force-mode-line-update t) 162 | status)) 163 | 164 | (reader--define-queue-command previous-page () 165 | "Go to the previous page of the document." 166 | (interactive) 167 | (if-let* ((status (reader-dyn--prev-page))) 168 | (force-mode-line-update t) 169 | status)) 170 | 171 | (defun reader-first-page () 172 | "Go to the first page of the document." 173 | (interactive) 174 | (reader-dyn--first-page) 175 | (reader--center-page) 176 | (force-mode-line-update t)) 177 | 178 | (defun reader-last-page () 179 | "Go to the last page of the document." 180 | (interactive) 181 | (reader-dyn--last-page) 182 | (reader--center-page) 183 | (force-mode-line-update t)) 184 | 185 | (defun reader-goto-page (n) 186 | "Go to page number N in the current document." 187 | (interactive "nGoto page: ") 188 | (reader-dyn--goto-page (- n 1)) ; MuPDF does 0-indexing 189 | (reader--center-page)) 190 | 191 | (defun reader--get-current-doc-image-size (&optional window) 192 | "Get the dimensions of the selected window (or if specified WINDOW) page." 193 | (let* ((cdr-image (cdr (overlay-get (reader-current-doc-overlay window) 'display))) 194 | (width (plist-get cdr-image :width)) 195 | (height (plist-get cdr-image :height))) 196 | (cons width height))) 197 | 198 | (defun reader-doc-scale-page (factor) 199 | "Scales the page by a given FACTOR. 200 | 201 | It also updates `reader--recent-scale-fallback' and `scale' property of 202 | selected window to reflect the new scale." 203 | (reader-dyn--scale-page factor) 204 | (setq reader--recent-scale-fallback factor) 205 | (set-window-parameter nil 'scale factor)) 206 | 207 | (defun reader-enlarge-size (&optional scaling-factor) 208 | "Enlarge the size of the current page by the `reader-enlarge-factor'. 209 | 210 | Optionally scale it by the SCALING-FACTOR. Scales on selected 211 | window." 212 | (interactive (list (float 213 | (* (reader-current-doc-scale-value) reader-enlarge-factor)))) 214 | (reader-doc-scale-page scaling-factor) 215 | (reader--center-page)) 216 | 217 | (defun reader-shrink-size (&optional scaling-factor) 218 | "Shrink the size of the current page by the `reader-shrink-factor'. 219 | 220 | Optionally scale it by the SCALING-FACTOR. Scales on selected 221 | window." 222 | (interactive (list (float 223 | (* (reader-current-doc-scale-value) reader-shrink-factor)))) 224 | (reader-doc-scale-page scaling-factor) 225 | (reader--center-page)) 226 | 227 | (defun reader-reset-size () 228 | "Reset the size of the current page to 1.0." 229 | (reader-doc-scale-page 1.0) 230 | (reader--center-page)) 231 | 232 | (defun reader-fit-to-height () 233 | "Scale the current page in the selected window to fit its height." 234 | (interactive) 235 | (let* ((image-height (cdr (reader--get-current-doc-image-size))) 236 | (pixel-window-height (window-pixel-height)) 237 | (unscaled-height (/ image-height (reader-current-doc-scale-value))) 238 | (scaling-factor (/ pixel-window-height unscaled-height))) 239 | (reader-doc-scale-page scaling-factor) 240 | (reader--center-page) 241 | (reader--set-window-vscroll nil 0))) 242 | 243 | (defun reader-fit-to-width () 244 | "Scale the current page in the selected window to fit its width." 245 | (interactive) 246 | (let* ((image-width (car (reader--get-current-doc-image-size))) 247 | (pixel-window-width (window-pixel-width)) 248 | (unscaled-width (/ image-width (reader-current-doc-scale-value))) 249 | (scaling-factor (/ pixel-window-width unscaled-width))) 250 | (reader-doc-scale-page scaling-factor) 251 | (reader--center-page))) 252 | 253 | (defun reader--get-pixel-per-col (&optional window) 254 | "Get the no of pixels per column for WINDOW." 255 | (/ (window-pixel-width window) (window-body-width window))) 256 | 257 | ;; We need to do this because scrolling is possible in one direction 258 | ;; (downwards) indefinitely. 259 | 260 | (defun reader--set-window-vscroll (window vscroll &optional pixels-p) 261 | "Set amount by which WINDOW should be scrolled vertically to VSCROLL. 262 | 263 | If setting VSCROLL makes the document page's top disappear, it sets the 264 | maximum vertical scroll possible without doing that. 265 | 266 | If PIXELS-P is non-nil, VSCROLL is considered to be in pixels. 267 | Also see `set-window-vscroll'." 268 | (let* ((image-height (cdr (reader--get-current-doc-image-size window))) 269 | (pixel-window-height (window-pixel-height window)) 270 | (window-height (window-body-height window)) 271 | (pixel-per-col (/ pixel-window-height window-height)) 272 | (pixel-vscroll (* pixel-per-col vscroll)) 273 | (max-pixel-vscroll (- image-height pixel-window-height)) 274 | (corrected-pixel-vscroll (min pixel-vscroll max-pixel-vscroll)) 275 | (corrected-vscroll (/ corrected-pixel-vscroll pixel-per-col))) 276 | (set-window-vscroll window 277 | (if pixels-p corrected-pixel-vscroll corrected-vscroll) 278 | pixels-p))) 279 | 280 | ;; Most of the scrolling functions here exist because of our handling 281 | ;; of centering in `reader--center-page'. 282 | 283 | (defun reader--get-prefix-width (&optional window) 284 | "Get the line prefix width set by `reader--center-page'. 285 | 286 | For WINDOW (or selected window if not specified)." 287 | (car 288 | (plist-get 289 | (cdr (overlay-get (reader-current-doc-overlay window) 'line-prefix)) 290 | :width))) 291 | 292 | (defun reader--right-most-window-hscroll (window) 293 | "Get the maximum horizontal scroll value for WINDOW. 294 | 295 | This position is at the rightmost point." 296 | (let* ((image-width (car (reader--get-current-doc-image-size window))) 297 | (line-prefix-width (reader--get-prefix-width window)) 298 | (pixel-window-width (window-pixel-width window)) 299 | (max-ncol (round (/ (max line-prefix-width 300 | (- image-width pixel-window-width)) 301 | (reader--get-pixel-per-col window))))) 302 | max-ncol)) 303 | 304 | (defun reader--set-window-hscroll (window ncol &optional unconstrained) 305 | "Set number of columns WINDOW is scrolled from left margin to NCOL. 306 | 307 | If setting NCOL makes the document page disappear, it sets the maximum 308 | horizontal scroll possible without doing that. If UNCONSTRAINED is 309 | non-nil, it allows setting NCOL even if it makes the page disappear. 310 | 311 | See also `set-window-hscroll'." 312 | (let* ((line-prefix-width (reader--get-prefix-width window)) 313 | (pixel-per-col (reader--get-pixel-per-col window)) 314 | (calibrated-ncol (round (- (/ line-prefix-width pixel-per-col) ncol))) 315 | (max-ncol (reader--right-most-window-hscroll window)) 316 | (ncol (if unconstrained 317 | calibrated-ncol 318 | (min calibrated-ncol max-ncol)))) 319 | (set-window-hscroll window ncol) 320 | (reader--window-hscroll window))) 321 | 322 | (defun reader--window-hscroll (&optional window) 323 | "Return the number of columns by which WINDOW is scrolled from left margin. 324 | WINDOW must be a live window and defaults to the selected one. 325 | 326 | This correctly handles the prefix width set by reader documents and does 327 | not return the actual horizontal scroll value; for that, see 328 | `window-hscroll'." 329 | (let* ((line-prefix-width (reader--get-prefix-width window)) 330 | (pixel-per-col (reader--get-pixel-per-col window)) 331 | (hscroll (round (- (/ line-prefix-width pixel-per-col) (window-hscroll window))))) 332 | hscroll)) 333 | 334 | ;; We need this hack involving line-prefix because Emacs' scrolling is 335 | ;; idiosyncratic, and doesn't allow arbitrary scrolling in every 336 | ;; direction. 337 | (defun reader--center-page (&optional window) 338 | "Center the document with respect to WINDOW. 339 | 340 | If WINDOW is omitted defaults to selected window." 341 | (let* ((overlay (reader-current-doc-overlay window)) 342 | (window-width (window-body-width window t)) 343 | (doc-image-width (car (reader--get-current-doc-image-size window))) 344 | (max-left-offset (max 0 (- window-width doc-image-width))) 345 | (overlay-offset `(space :width (,max-left-offset))) 346 | (pixel-per-col (reader--get-pixel-per-col window)) 347 | (doc-left-offset (- window-width doc-image-width)) 348 | (doc-center-offset (/ doc-left-offset 2)) 349 | (scroll-offset (round (/ doc-center-offset pixel-per-col)))) 350 | ;; Add prefix so that the page is at the leftmost point of the window. 351 | (overlay-put (reader-current-doc-overlay window) 'line-prefix overlay-offset) 352 | ;; scroll window back to the center of the doc 353 | (reader--set-window-hscroll window scroll-offset t))) 354 | 355 | (defun reader-scroll-up (&optional amount) 356 | "Scroll up the current page by AMOUNT (1 by default)." 357 | (interactive "p") 358 | (or amount (setq amount 1)) 359 | (let* ((prev-scroll (window-vscroll)) 360 | (vscroll (- prev-scroll amount))) 361 | (- prev-scroll (reader--set-window-vscroll nil vscroll)))) 362 | 363 | (defun reader-scroll-down (&optional amount) 364 | "Scroll down the current page by AMOUNT (1 by default)." 365 | (interactive "p") 366 | (or amount (setq amount 1)) 367 | (let* ((prev-scroll (window-vscroll)) 368 | (vscroll (+ prev-scroll amount))) 369 | (- (reader--set-window-vscroll nil vscroll) prev-scroll))) 370 | 371 | (defun reader-scroll-up-screenful () 372 | "Scroll up the current page by a screenful." 373 | (interactive) 374 | (let ((amount (- (window-body-height) 375 | next-screen-context-lines))) 376 | (when (= 0 (reader-scroll-up amount)) 377 | (message "Beginning of page")))) 378 | 379 | (defun reader-scroll-down-screenful () 380 | "Scroll down the current page by a screenful." 381 | (interactive) 382 | (let ((amount (- (window-body-height) 383 | next-screen-context-lines))) 384 | (when (= 0 (reader-scroll-down amount)) 385 | (message "End of page")))) 386 | 387 | (defun reader-scroll-left (&optional amount) 388 | "Scroll to the left of the current page by AMOUNT (or 1). 389 | 390 | Only scrolls when the document page width is larger then the window width." 391 | (interactive "p") 392 | (or amount (setq amount 1)) 393 | (when-let* (((< (window-pixel-width) (car (reader--get-current-doc-image-size)))) 394 | (prev-scroll (reader--window-hscroll)) 395 | (hscroll (+ prev-scroll amount))) 396 | (- (reader--set-window-hscroll nil hscroll) prev-scroll))) 397 | 398 | (defun reader-scroll-right (&optional amount) 399 | "Scroll to the right of the current page by AMOUNT (or 1). 400 | 401 | Only scrolls when the document page width is larger then the window width." 402 | (interactive "p") 403 | (or amount (setq amount 1)) 404 | (when-let* (((< (window-pixel-width) (car (reader--get-current-doc-image-size)))) 405 | (prev-scroll (reader--window-hscroll)) 406 | (hscroll (- prev-scroll amount))) 407 | (- prev-scroll (reader--set-window-hscroll nil hscroll)))) 408 | 409 | (defun reader-scroll-left-most () 410 | "Scroll to the left most point of the current page. 411 | 412 | Only scrolls when the document page width is larger then the window width." 413 | (interactive) 414 | (when (< (window-pixel-width) (car (reader--get-current-doc-image-size))) 415 | (reader--set-window-hscroll nil 0))) 416 | 417 | (defun reader-scroll-right-most () 418 | "Scroll to the right most point of the current page. 419 | 420 | Only scrolls when the document page width is larger then the window width." 421 | (interactive) 422 | (when (< (window-pixel-width) (car (reader--get-current-doc-image-size))) 423 | ;; We use `set-window-hscroll' here because we need to go the right 424 | ;; most point directly, bypassing `'reader--set-window-hscroll' checks. 425 | (set-window-hscroll window (reader--right-most-window-hscroll)))) 426 | 427 | (reader--define-queue-command scroll-up-or-prev-page (&optional amount) 428 | "Scroll up the current page by AMOUNT (or 1), otherwise switch to the previous page." 429 | (interactive "p") 430 | (or amount (setq amount 1)) 431 | (when-let* (((and (= 0 (reader-scroll-up amount)) 432 | (reader--non-queue-previous-page))) ; if succeeds 433 | (image-height (cdr (reader--get-current-doc-image-size))) 434 | (pixel-window-height (window-pixel-height)) 435 | (bottom-most-scroll-pixel 436 | (- image-height pixel-window-height))) 437 | (reader--set-window-vscroll nil bottom-most-scroll-pixel t))) 438 | 439 | (reader--define-queue-command scroll-down-or-next-page (&optional amount) 440 | "Scroll down the current page by AMOUNT (or 1), otherwise switch to the next page." 441 | (interactive "p") 442 | (or amount (setq amount 1)) 443 | (when (and (= 0 (reader-scroll-down amount)) 444 | (reader--non-queue-next-page)) ; if succeeds 445 | (reader--set-window-vscroll nil 0))) 446 | 447 | (reader--define-queue-command scroll-up-screenful-or-prev-page () 448 | "Scroll up the current page by screenful, otherwise switch to the previous page." 449 | (interactive) 450 | (let ((scroll (- (window-body-height) 451 | next-screen-context-lines))) 452 | (reader--non-queue-scroll-up-or-prev-page scroll))) 453 | 454 | (reader--define-queue-command scroll-down-screenful-or-next-page () 455 | "Scroll down the current page by screenful, otherwise switch to the next page." 456 | (interactive) 457 | (let ((scroll (- (window-body-height) 458 | next-screen-context-lines))) 459 | (reader--non-queue-scroll-down-or-next-page scroll))) 460 | 461 | (reader--define-queue-command mwheel-scroll-up (event) 462 | "Scroll up or switch to the previous page, but also handle mouse EVENT. 463 | 464 | See also `reader-non-queue-scroll-up-or-prev-page'." 465 | (interactive "e") 466 | (let* ((event-type (car event)) 467 | (amount (pcase event-type 468 | ('wheel-up 1) 469 | ('double-wheel-up 2) 470 | ('triple-wheel-up 3))) 471 | (scrolled-window (car (cadr event)))) 472 | (with-selected-window scrolled-window 473 | (reader--non-queue-scroll-up-or-prev-page amount)))) 474 | 475 | (reader--define-queue-command mwheel-scroll-down (event) 476 | "Scroll down or switch to the next page, but also handle mouse EVENT. 477 | 478 | See also `reader--non-queue-scroll-down-or-next-page'." 479 | (interactive "e") 480 | (let* ((event-type (car event)) 481 | (amount (pcase event-type 482 | ('wheel-down 1) 483 | ('double-wheel-down 2) 484 | ('triple-wheel-down 3))) 485 | (scrolled-window (car (cadr event)))) 486 | (with-selected-window scrolled-window 487 | (reader--non-queue-scroll-down-or-next-page amount)))) 488 | 489 | (defun reader-mwheel-scroll-left (event) 490 | "Scroll to the left, but also handle mouse EVENT. 491 | 492 | See also `reader-scroll-left'." 493 | (interactive "e") 494 | (let* ((event-type (car event)) 495 | (amount (pcase event-type 496 | ('S-wheel-up 1) 497 | ('S-double-wheel-up 2) 498 | ('S-triple-wheel-up 3))) 499 | (scrolled-window (car (cadr event)))) 500 | (with-selected-window scrolled-window 501 | (reader-scroll-left amount)))) 502 | 503 | (defun reader-mwheel-scroll-right (event) 504 | "Scroll to the right, but also handle mouse EVENT. 505 | 506 | See also `reader-scroll-right'." 507 | (interactive "e") 508 | (let* ((event-type (car event)) 509 | (amount (pcase event-type 510 | ('S-wheel-down 1) 511 | ('S-double-wheel-down 2) 512 | ('S-triple-wheel-down 3))) 513 | (scrolled-window (car (cadr event)))) 514 | (with-selected-window scrolled-window 515 | (reader-scroll-right amount)))) 516 | 517 | (defun reader-mwheel-enlarge-size (event) 518 | "Enlarge the current page, but also handle mouse EVENT. 519 | 520 | See also `reader-enlarge-size'." 521 | (interactive "e") 522 | (let* ((event-type (car event)) 523 | (scaling-factor (pcase event-type 524 | ('C-wheel-up reader-enlarge-factor) 525 | ('C-double-wheel-up (+ reader-enlarge-factor 0.1)) 526 | ('C-triple-wheel-up (+ reader-enlarge-factor 0.2)))) 527 | (scrolled-window (car (cadr event)))) 528 | (with-selected-window scrolled-window 529 | (reader-enlarge-size 530 | (* scaling-factor (reader-current-doc-scale-value)))))) 531 | 532 | (defun reader-mwheel-shrink-size (event) 533 | "Shrink the current page, but also handle mouse EVENT. 534 | 535 | See also `reader-shrink-size'." 536 | (interactive "e") 537 | (let* ((event-type (car event)) 538 | (scaling-factor (pcase event-type 539 | ('C-wheel-down reader-shrink-factor) 540 | ('C-double-wheel-down (- reader-shrink-factor 0.1)) 541 | ('C-triple-wheel-down (- reader-shrink-factor 0.2)))) 542 | (scrolled-window (car (cadr event)))) 543 | (with-selected-window scrolled-window 544 | (reader-shrink-size 545 | (* scaling-factor (reader-current-doc-scale-value)))))) 546 | 547 | (defun reader-rotate-clockwise () 548 | "Rotate all pages of the current document by 90 degrees, clockwise." 549 | (interactive) 550 | (reader-dyn--rotate-doc 90) 551 | (reader--center-page)) 552 | 553 | (defun reader-rotate-counter-clockwise () 554 | "Rotate all pages of the current document by 90 degrees, counter-clockwise." 555 | (interactive) 556 | (reader-dyn--rotate-doc -90) 557 | (reader--center-page)) 558 | 559 | (defun reader--clear-doc-memory () 560 | "Clear document memory if we are in `reader-mode'. 561 | 562 | Intended for use in `kill-buffer-hook'." 563 | (when (derived-mode-p 'reader-mode) 564 | (reader-dyn--close-doc))) 565 | (add-hook 'kill-buffer-hook 'reader--clear-doc-memory) 566 | 567 | (defun reader-close-doc () 568 | "Close the current document, also prompt the user for confirmation." 569 | (interactive) 570 | (when (yes-or-no-p "Are you sure you want to close the current document?") 571 | (kill-buffer (current-buffer)))) 572 | 573 | (defun reader-refresh-doc-buffer (&optional ignore-auto noconfirm preserve-modes) 574 | "Refresh the buffer document with file on disk. 575 | 576 | It reloads the entire document while preserving the previous state. 577 | The args IGNORE-AUTO, NOCONFIRM and PRESERVE-MODES are ignored and are 578 | simply to satisfy the template for `revert-buffer-function'. 579 | This function is replaced as `revert-buffer-function' for `reader-mode' buffers." 580 | (interactive) 581 | (when buffer-file-name 582 | (let ((page (reader-current-doc-pagenumber)) 583 | (scale (reader-current-doc-scale-value window))) 584 | (remove-overlays) 585 | (reader--render-buffer) 586 | (if reader-dark-mode 587 | (reader-dark-mode 1)) 588 | (reader-doc-scale-page scale) 589 | (reader-goto-page page) 590 | (reader--center-page)))) 591 | 592 | (defun reader--render-buffer () 593 | "Render the document file current buffer is associated with." 594 | (interactive) 595 | (if-let* ((file (buffer-file-name (current-buffer)))) 596 | (when (file-exists-p file) 597 | (reader-dyn--load-doc file)) 598 | (message "No file associated with buffer."))) 599 | 600 | ;; We have an overlay per window, since we (naturally) need to be able 601 | ;; show different pages on different windows. 602 | ;; 603 | ;; The window knows (as a window parameter): 604 | ;; * Which overlay it belongs to. 605 | ;; * Which page number it's currently displaying. 606 | ;; * What the current scale is. 607 | ;; 608 | ;; The overlay knows (as an overlay property): 609 | ;; * Which window it belongs to. 610 | ;; * user pointer to the underlying EmacsWinState from the native 611 | ;; module. 612 | ;; 613 | ;; Window and overlay need to know each other for efficient lookup. 614 | 615 | (defun reader--manage-window-overlays () 616 | "Manage the creation and deletion of window overlays as needed. 617 | 618 | It is hooked to `window-configuration-change-hook' to keep detecting." 619 | (let ((overlays (car (overlay-lists))) 620 | (windows (get-buffer-window-list (current-buffer) nil t))) 621 | (mapcar #'reader--window-close-function overlays) 622 | (mapcar #'reader--window-create-function windows))) 623 | 624 | (defun reader--window-create-function (window) 625 | "Create window overlay for WINDOW." 626 | (unless (window-parameter window 'overlay) 627 | (let* ((last-win-page (window-parameter (old-selected-window) 'page)) 628 | (last-win-scale (window-parameter (old-selected-window) 'scale)) 629 | (page (or last-win-page reader--recent-pagenumber-fallback)) 630 | (scale (or last-win-scale reader--recent-scale-fallback))) 631 | (reader-dyn--window-create window) 632 | (set-window-parameter window 'page last-win-page) 633 | (with-selected-window window 634 | (reader-goto-page page) 635 | (reader-doc-scale-page scale) 636 | (reader--center-page))))) 637 | 638 | (defun reader--window-close-function (overlay) 639 | "Properly close the window belonging to OVERLAY." 640 | (let ((window (overlay-get overlay 'window))) 641 | (unless (window-valid-p window) 642 | (reader-dyn--window-close overlay)))) 643 | 644 | ;; We explicitly bind default keys because relying on the rebinding 645 | ;; mechanism can lead to them not being bound at all if users have 646 | ;; overridden the defaults with other commands. 647 | (defvar-keymap reader-mode-map 648 | :doc "Keymap for `reader-mode'." 649 | "n" #'reader-next-page 650 | "p" #'reader-previous-page 651 | 652 | "C-p" #'reader-scroll-up-or-prev-page 653 | "C-n" #'reader-scroll-down-or-next-page 654 | " " #'reader-scroll-up-or-prev-page 655 | " " #'reader-scroll-down-or-next-page 656 | " " #'reader-scroll-down-or-next-page 657 | " " #'reader-scroll-up-or-prev-page 658 | 659 | "" #'reader-mwheel-scroll-up 660 | "" #'reader-mwheel-scroll-down 661 | 662 | "S-" #'reader-mwheel-scroll-left 663 | "S-" #'reader-mwheel-scroll-right 664 | 665 | "C-v" #'reader-scroll-down-screenful 666 | "M-v" #'reader-scroll-up-screenful 667 | " " #'reader-scroll-up-screenful 668 | " " #'reader-scroll-down-screenful 669 | 670 | "SPC" #'reader-scroll-down-screenful-or-next-page 671 | "DEL" #'reader-scroll-up-screenful-or-prev-page 672 | "S-SPC" #'reader-scroll-up-screenful-or-prev-page 673 | 674 | "C-f" #'reader-scroll-right 675 | "C-b" #'reader-scroll-left 676 | " " #'reader-scroll-right 677 | " " #'reader-scroll-left 678 | 679 | "C-e" #'reader-scroll-right-most 680 | "C-a" #'reader-scroll-left-most 681 | " " #'reader-scroll-right-most 682 | " " #'reader-scroll-left-most 683 | 684 | "M-<" #'reader-first-page 685 | "M->" #'reader-last-page 686 | " " #'reader-first-page 687 | " " #'reader-last-page 688 | 689 | "M-g g" #'reader-goto-page 690 | "M-g M-g" #'reader-goto-page 691 | " " #'reader-goto-page 692 | 693 | "=" #'reader-enlarge-size 694 | "+" #'reader-enlarge-size 695 | "C-" #'reader-mwheel-enlarge-size 696 | 697 | "-" #'reader-shrink-size 698 | "C-" #'reader-mwheel-shrink-size 699 | 700 | "0" #'reader-reset-size 701 | 702 | "H" #'reader-fit-to-height 703 | "W" #'reader-fit-to-width 704 | 705 | "r" #'reader-rotate-clockwise 706 | "R" #'reader-rotate-counter-clockwise 707 | 708 | "" #'reader-presentation-mode 709 | 710 | "o" #'reader-outline-show 711 | 712 | "Q" #'reader-close-doc) 713 | 714 | ;;;###autoload 715 | (define-derived-mode reader-mode special-mode "Emacs Reader" 716 | "Major mode for viewing documents in The Emacs Reader. 717 | 718 | Keybindings: 719 | \\{reader-mode-map}" 720 | :group 'reader 721 | 722 | (unless (and buffer-file-name 723 | (file-exists-p buffer-file-name) 724 | (file-regular-p buffer-file-name) 725 | (file-readable-p buffer-file-name)) 726 | (message "Reader did not open the document: %s is not a valid file" 727 | (or buffer-file-name "")) 728 | (kill-buffer (current-buffer))) 729 | 730 | (setq-local buffer-read-only t 731 | global-linum-mode nil 732 | cursor-type 'hollow 733 | display-line-numbers-mode nil 734 | ;; messes up centering(line-prefix) otherwise, the 735 | ;; default value is 8, so we keep it at that. 736 | left-fringe-width 8) 737 | (set-buffer-modified-p nil) 738 | (blink-cursor-mode 0) 739 | (auto-revert-mode 1) 740 | (setq-local revert-buffer-function #'reader-refresh-doc-buffer) 741 | 742 | ;; Disable `pixel-scroll-precision-mode' locally because it doesn't 743 | ;; work nicely with `reader-mode'. 744 | (when (bound-and-true-p pixel-scroll-precision-mode) 745 | (setq-local pixel-scroll-precision-mode nil)) 746 | 747 | (setq-local bookmark-make-record-function 748 | #'reader-bookmark-make-record) 749 | 750 | (unless reader-current-doc-render-status 751 | (reader--render-buffer)) 752 | 753 | (setq-local imenu-create-index-function #'reader--outline-imenu-create-index 754 | imenu-default-goto-function #'reader--outline-imenu-goto 755 | imenu-submenus-on-top nil 756 | imenu-sort-function nil 757 | imenu-auto-rescan t) 758 | 759 | (use-local-map reader-mode-map) 760 | (setq major-mode 'reader-mode) 761 | (setq mode-name "Emacs Reader") 762 | (run-hooks 'reader-mode-hook) 763 | 764 | (funcall reader-default-fit) 765 | (add-hook 'window-size-change-functions #'reader--center-page nil t) 766 | (add-hook 'window-configuration-change-hook #'reader--manage-window-overlays nil t)) 767 | 768 | (defun reader-mode-line () 769 | "Set custom mode-line interface when reading documents." 770 | (setq-local mode-line-position 771 | '(" P" (:eval (number-to-string (reader-current-doc-pagenumber))) 772 | "/" (:eval (number-to-string reader-current-doc-pagecount))))) 773 | 774 | (add-hook 'reader-mode-hook #'reader-mode-line) 775 | (add-hook 'reader-mode-hook #'imenu-add-menubar-index) 776 | 777 | (define-minor-mode reader-dark-mode 778 | "Toggle dark-mode for current reader document." 779 | :lighter " Dark" 780 | (when (eq major-mode 'reader-mode) 781 | (if reader-dark-mode 782 | (reader-dyn--set-dark-theme) 783 | (reader-dyn--redisplay-doc)) 784 | (reader-doc-scale-page (reader-current-doc-scale-value)))) 785 | 786 | (define-globalized-minor-mode reader-global-dark-mode reader-dark-mode reader-dark-mode) 787 | 788 | (define-minor-mode reader-presentation-mode 789 | "Toggle presentation view for current reader document." 790 | :lighter "" 791 | (cond (reader-presentation-mode 792 | (setq-local mode-line-format nil) 793 | (reader-fit-to-height)) 794 | ((kill-local-variable 'mode-line-format)))) 795 | 796 | ;; see `reader-saveplace' for details. 797 | ;;;###autoload 798 | (advice-add 'save-place-find-file-hook :around #'reader--saveplace-find-file) 799 | 800 | ;;;###autoload 801 | (advice-add 'save-place-to-alist :around #'reader--saveplace-to-alist) 802 | 803 | ;;;###autoload 804 | (dolist (pattern reader-supported-formats) 805 | (add-to-list 'auto-mode-alist (cons (concat "\\." pattern "\\'") 'reader-mode))) 806 | 807 | (provide 'reader) 808 | ;;; reader.el ends here. 809 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /render/render-core.c: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2025 Divya Ranjan Pattanaik 3 | // Copyright (C) 2025 Tushar 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | #include "render-core.h" 19 | #include "elisp-helpers.h" 20 | #include "emacs-module.h" 21 | #include "mupdf-helpers.h" 22 | #include "render-theme.h" 23 | #include "render-threads.h" 24 | 25 | int plugin_is_GPL_compatible; 26 | 27 | /** 28 | * Load and cache the display list for a page. 29 | * 30 | * If the page is empty, sets its status to rendering, loads the page, 31 | * computes its bounding box, and generates a display list. Uses a 32 | * cloned MuPDF context for thread safety. 33 | * 34 | * @param state Pointer to the current DocState. 35 | * @param cp Pointer to the CachedPage to load. 36 | * Return: EXIT_SUCCESS on success (errors are rethrown via MuPDF). 37 | */ 38 | 39 | int 40 | load_page_dl(DocState *state, CachedPage *cp) 41 | { 42 | fz_page *loaded_page = NULL; 43 | fz_context *ctx = fz_clone_context(state->ctx); 44 | 45 | fz_drop_display_list(ctx, cp->display_list); 46 | if (cp->status == PAGE_STATUS_EMPTY) 47 | { 48 | cp->status = PAGE_STATUS_RENDERING; 49 | fz_try(ctx) 50 | { 51 | loaded_page 52 | = fz_load_page(ctx, state->doc, cp->page_num); 53 | state->page_bbox = fz_bound_page(ctx, loaded_page); 54 | cp->display_list = fz_new_display_list_from_page( 55 | state->ctx, loaded_page); 56 | } 57 | fz_always(ctx) 58 | { 59 | fz_drop_page(state->ctx, loaded_page); 60 | loaded_page = NULL; 61 | } 62 | fz_catch(ctx) fz_rethrow(ctx); 63 | } 64 | 65 | fz_drop_context(ctx); 66 | return EXIT_SUCCESS; 67 | } 68 | 69 | /** 70 | * Thread function to render a page and encode it as a PNM image. 71 | * 72 | * Uses the page's display list to generate a pixmap, optionally inverts 73 | * and gamma-corrects it, then encodes it to PNM and stores it in 74 | * `cp->img_data'. Updates image dimensions and status, and signals 75 | * completion via a condition variable. 76 | * 77 | * @param arg Pointer to DrawThreadArgs (contains DocState and CachedPage). 78 | * Return: NULL (result is stored in CachedPage). 79 | */ 80 | 81 | void * 82 | draw_page_thread(void *arg) 83 | { 84 | fz_output *out = NULL; 85 | fz_buffer *buf = NULL; 86 | fz_matrix ctm; 87 | 88 | DrawThreadArgs *args = (DrawThreadArgs *)arg; 89 | DocState *doc_state = args->doc_state; 90 | EmacsWinState *win_state = args->win_state; 91 | CachedPage *cp = args->cp; 92 | 93 | fz_context *ctx = fz_clone_context(doc_state->ctx); 94 | 95 | ctm = fz_transform_page(doc_state->page_bbox, win_state->resolution, 96 | win_state->rotate); 97 | cp->imgh = 0; 98 | cp->imgw = 0; 99 | 100 | fz_try(ctx) 101 | { 102 | if (cp->display_list == NULL) 103 | { 104 | fprintf(stderr, "Display list of page %d is empty\n", 105 | cp->page_num); 106 | } 107 | cp->pixmap = fz_new_pixmap_from_display_list( 108 | ctx, cp->display_list, ctm, fz_device_rgb(ctx), 0); 109 | if (doc_state->invert) 110 | { 111 | fz_invert_pixmap_luminance(ctx, cp->pixmap); 112 | fz_gamma_pixmap(ctx, cp->pixmap, 1 / 1.4f); 113 | } 114 | cp->imgh = fz_pixmap_height(ctx, cp->pixmap); 115 | cp->imgw = fz_pixmap_width(ctx, cp->pixmap); 116 | } 117 | fz_catch(ctx) cp->status = PAGE_STATUS_ERROR; 118 | 119 | fz_try(ctx) 120 | { 121 | buf = fz_new_buffer(ctx, 1024); 122 | out = fz_new_output_with_buffer(ctx, buf); 123 | fz_write_pixmap_as_pnm(ctx, out, cp->pixmap); 124 | fz_drop_pixmap(ctx, 125 | cp->pixmap); // Drop the pixmap after using it 126 | cp->pixmap = NULL; 127 | } 128 | fz_catch(ctx) 129 | { 130 | fz_close_output(ctx, out); 131 | fz_drop_output(ctx, out); 132 | fz_drop_buffer(ctx, buf); 133 | } 134 | 135 | fz_close_output(ctx, out); 136 | 137 | // Reset the pre-existing memory that we were pointing to 138 | free(cp->img_data); 139 | cp->img_data = NULL; 140 | cp->img_size = 0; 141 | 142 | // Prepare for assigning data from fz_buffer 143 | cp->img_size = buf->len; 144 | cp->img_data = (char *)malloc(cp->img_size); 145 | 146 | if (cp->img_data == NULL) 147 | { 148 | fprintf(stderr, "Could not allocate memory for image data\n"); 149 | fz_close_output(ctx, out); 150 | fz_drop_buffer(ctx, buf); 151 | return NULL; 152 | } 153 | 154 | // Copy the data and null-terminate 155 | memcpy(cp->img_data, buf->data, cp->img_size); 156 | 157 | fz_drop_output(ctx, out); 158 | fz_drop_buffer(ctx, buf); 159 | fz_drop_context(ctx); 160 | 161 | pthread_mutex_lock(&cp->mutex); 162 | cp->status = PAGE_STATUS_READY; 163 | pthread_cond_signal(&cp->cond); 164 | pthread_mutex_unlock(&cp->mutex); 165 | 166 | free(args); 167 | return NULL; 168 | } 169 | 170 | /** 171 | * Build a sliding cache window around the given page. 172 | * 173 | * Determines a window of pages centered around page `n', clears any 174 | * previously rendered pages, loads display lists for empty ones, and 175 | * submits rendering jobs. Waits for the current page to be fully cached. 176 | * 177 | * @param state Pointer to the current DocState. 178 | * @param n Page number to center the cache window around. 179 | */ 180 | 181 | void 182 | build_cache_window(DocState *doc_state, EmacsWinState *win_state, int n) 183 | { 184 | int start, end; 185 | int pagecount = doc_state->pagecount; 186 | 187 | if (n < MAX_CACHE_WINDOW_SIZE) 188 | { 189 | start = 0; 190 | end = n + MAX_CACHE_WINDOW_SIZE; 191 | if (end >= pagecount) 192 | end = pagecount - 1; 193 | } 194 | else if (n > (pagecount - 1) - MAX_CACHE_WINDOW_SIZE) 195 | { 196 | end = pagecount - 1; 197 | start = n - MAX_CACHE_WINDOW_SIZE; 198 | if (start < 0) 199 | start = 0; 200 | } 201 | else 202 | { 203 | start = n - MAX_CACHE_WINDOW_SIZE; 204 | end = n + MAX_CACHE_WINDOW_SIZE; 205 | } 206 | 207 | win_state->current_page_number = n; 208 | win_state->current_window_index = n - start; 209 | 210 | for (int i = 0; i < MAX_CACHE_SIZE; ++i) 211 | { 212 | int idx = start + i; 213 | if (idx < pagecount && idx <= end) 214 | { 215 | CachedPage *cp = doc_state->cached_pages_pool[idx]; 216 | win_state->cache_window[i] = cp; 217 | 218 | if (cp->status == PAGE_STATUS_READY) 219 | { 220 | free_cached_page(doc_state, 221 | win_state->cache_window[i]); 222 | } 223 | 224 | if (cp->status == PAGE_STATUS_EMPTY) 225 | { 226 | load_page_dl(doc_state, cp); 227 | DrawThreadArgs *draw_args 228 | = malloc(sizeof(DrawThreadArgs)); 229 | draw_args->doc_state = doc_state; 230 | draw_args->win_state = win_state; 231 | draw_args->cp = cp; 232 | submit_job(draw_page_thread, draw_args, 233 | &g_thread_pool); 234 | } 235 | } 236 | else 237 | { 238 | win_state->cache_window[i] = NULL; 239 | } 240 | } 241 | 242 | // Wait for the current page's cache to be ready if it isn't 243 | while (win_state->cache_window[win_state->current_window_index]->status 244 | != PAGE_STATUS_READY) 245 | fprintf(stderr, "Waiting for page %d to be ready\n", 246 | win_state->cache_window[win_state->current_window_index] 247 | ->page_num); 248 | win_state->current_cached_page 249 | = win_state->cache_window[win_state->current_window_index]; 250 | } 251 | 252 | /** 253 | * Slide the cache window forward by one page. 254 | * 255 | * Advances to the next page, shifts the cache window if within bounds, 256 | * reuses or frees cached pages, and spawns rendering jobs as needed. 257 | * Falls back to full rebuild if near document edges. Waits until the 258 | * new current page is ready. 259 | * 260 | * @param state Pointer to the current DocState. 261 | * Return: true if sliding succeeded, false if at end of document. 262 | */ 263 | 264 | bool 265 | slide_cache_window_forward(DocState *doc_state, EmacsWinState *win_state) 266 | { 267 | int n = ++win_state->current_page_number; 268 | int pagecount = doc_state->pagecount; 269 | 270 | if (n >= pagecount) 271 | { 272 | fprintf(stderr, 273 | "slide_cache_window_right: cannot slide past end (page " 274 | "%d)\n", 275 | n); 276 | return false; 277 | } 278 | 279 | if (n - MAX_CACHE_WINDOW_SIZE > 0 280 | && n + MAX_CACHE_WINDOW_SIZE < pagecount) 281 | { 282 | // Free the leftmost page in the cache window 283 | if (win_state->cache_window[0] != NULL 284 | && win_state->cache_window[0]->status == PAGE_STATUS_READY) 285 | { 286 | free_cached_page(doc_state, win_state->cache_window[0]); 287 | } 288 | memmove( 289 | &win_state->cache_window[0], &win_state->cache_window[1], 290 | sizeof(win_state->cache_window[0]) * (MAX_CACHE_SIZE - 1)); 291 | 292 | CachedPage *cp 293 | = doc_state->cached_pages_pool[n + MAX_CACHE_WINDOW_SIZE]; 294 | win_state->cache_window[MAX_CACHE_SIZE - 1] = cp; 295 | if (cp->status == PAGE_STATUS_EMPTY) 296 | { 297 | load_page_dl(doc_state, cp); 298 | DrawThreadArgs *draw_args 299 | = malloc(sizeof(DrawThreadArgs)); 300 | draw_args->doc_state = doc_state; 301 | draw_args->win_state = win_state; 302 | draw_args->cp = cp; 303 | submit_job(draw_page_thread, draw_args, &g_thread_pool); 304 | } 305 | win_state->current_window_index = MAX_CACHE_WINDOW_SIZE; 306 | } 307 | else 308 | { 309 | build_cache_window(doc_state, win_state, n); 310 | } 311 | 312 | // Wait for the current page's cache to be ready if it isn't 313 | while (win_state->cache_window[win_state->current_window_index]->status 314 | != PAGE_STATUS_READY) 315 | fprintf(stderr, "Waiting for page %d to be ready\n", 316 | win_state->cache_window[win_state->current_window_index] 317 | ->page_num); 318 | win_state->current_cached_page 319 | = win_state->cache_window[win_state->current_window_index]; 320 | 321 | return true; 322 | } 323 | 324 | /** 325 | * Slide the cache window backward by one page. 326 | * 327 | * Moves to the previous page, shifts the cache window if within bounds, 328 | * frees or reuses cached pages, and triggers rendering if needed. 329 | * Falls back to a full rebuild near document start. Waits until the 330 | * new current page is ready. 331 | * 332 | * @param state Pointer to the current DocState. 333 | * Return: true if sliding succeeded, false if at start of document. 334 | */ 335 | 336 | bool 337 | slide_cache_window_backward(DocState *doc_state, EmacsWinState *win_state) 338 | { 339 | int n = --win_state->current_page_number; 340 | int pagecount = doc_state->pagecount; 341 | 342 | if (n < 0) 343 | { 344 | fprintf( 345 | stderr, 346 | "slide_window_left: cannot slide past start (page %d)\n", 347 | win_state->current_page_number); 348 | return false; 349 | } 350 | 351 | if (n - MAX_CACHE_WINDOW_SIZE > 0 352 | && n + MAX_CACHE_WINDOW_SIZE < pagecount) 353 | { 354 | // Free the rightmost page in the cache window 355 | if (win_state->cache_window[MAX_CACHE_SIZE - 1] != NULL 356 | && win_state->cache_window[MAX_CACHE_SIZE - 1]->status 357 | == PAGE_STATUS_READY) 358 | { 359 | free_cached_page( 360 | doc_state, 361 | win_state->cache_window[MAX_CACHE_SIZE - 1]); 362 | } 363 | memmove( 364 | &win_state->cache_window[1], &win_state->cache_window[0], 365 | sizeof(win_state->cache_window[0]) * (MAX_CACHE_SIZE - 1)); 366 | CachedPage *cp 367 | = doc_state->cached_pages_pool[n - MAX_CACHE_WINDOW_SIZE]; 368 | win_state->cache_window[0] = cp; 369 | if (cp->status == PAGE_STATUS_EMPTY) 370 | { 371 | load_page_dl(doc_state, cp); 372 | DrawThreadArgs *draw_args 373 | = malloc(sizeof(DrawThreadArgs)); 374 | draw_args->doc_state = doc_state; 375 | draw_args->win_state = win_state; 376 | draw_args->cp = cp; 377 | submit_job(draw_page_thread, draw_args, &g_thread_pool); 378 | } 379 | win_state->current_window_index = MAX_CACHE_WINDOW_SIZE; 380 | } 381 | else 382 | { 383 | build_cache_window(doc_state, win_state, n); 384 | } 385 | 386 | // Wait for the current page's cache to be ready if it isn't 387 | while (win_state->cache_window[win_state->current_window_index]->status 388 | != PAGE_STATUS_READY) 389 | fprintf(stderr, "Waiting for page %d to be ready\n", 390 | win_state->cache_window[win_state->current_window_index] 391 | ->page_num); 392 | win_state->current_cached_page 393 | = win_state->cache_window[win_state->current_window_index]; 394 | 395 | return true; 396 | } 397 | 398 | /** 399 | * emacs_load_doc - Load a document from Emacs, initialize state, and render 400 | * first page. 401 | * @env: The Emacs environment pointer. 402 | * @nargs: Number of arguments passed from Elisp (should be 1). 403 | * @args: Array of Elisp argument values; args[0] is the file path string. 404 | * @data: User-supplied callback data (ignored). 405 | * 406 | * Return: Elisp `t` on completion (`nil` otherwise). 407 | */ 408 | 409 | emacs_value 410 | emacs_load_doc(emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data) 411 | { 412 | (void)nargs; 413 | (void)data; 414 | size_t str_length = 0; 415 | 416 | emacs_value curr_win = EMACS_CURR_WIN; 417 | emacs_value current_doc_overlay = init_overlay(env, curr_win); 418 | DocState *doc_state = init_doc_state_ptr(env); 419 | EmacsWinState *win_state = init_win_state_ptr(env, doc_state, curr_win); 420 | 421 | if (!doc_state || !win_state) 422 | { 423 | emacs_message(env, 424 | "Document cannot be loaded into memory due to " 425 | "unsupported format or some other reason."); 426 | return EMACS_NIL; 427 | } 428 | 429 | reset_doc_state(doc_state); 430 | reset_win_state(win_state); 431 | 432 | if (!elisp_2_c_str(env, args[0], &doc_state->path, &str_length)) 433 | { 434 | emacs_message(env, 435 | "Failed to convert Emacs string to C string."); 436 | return EMACS_NIL; 437 | } 438 | 439 | init_main_ctx(doc_state); // Creates mupdf context with locks 440 | load_mupdf_doc(doc_state); // Opens the doc and sets pagecount 441 | outline2plist(env, doc_state->outline); 442 | 443 | doc_state->cached_pages_pool = malloc( 444 | doc_state->pagecount * sizeof(*doc_state->cached_pages_pool)); 445 | CachedPage *block = calloc(doc_state->pagecount, sizeof *block); 446 | 447 | for (int i = 0; i < doc_state->pagecount; ++i) 448 | { 449 | doc_state->cached_pages_pool[i] = &block[i]; 450 | doc_state->cached_pages_pool[i]->page_num = i; 451 | pthread_mutex_init(&doc_state->cached_pages_pool[i]->mutex, 452 | NULL); 453 | pthread_cond_init(&doc_state->cached_pages_pool[i]->cond, NULL); 454 | doc_state->cached_pages_pool[i]->status = PAGE_STATUS_EMPTY; 455 | } 456 | 457 | build_cache_window(doc_state, win_state, 458 | win_state->current_page_number); 459 | set_current_pagecount(env, doc_state); 460 | set_current_page_number(env, win_state->current_page_number); 461 | set_current_render_status(env); 462 | 463 | CachedPage *cp = win_state->current_cached_page; 464 | 465 | // Wait until getting a signal from render threads 466 | pthread_mutex_lock(&cp->mutex); 467 | while (cp->status != PAGE_STATUS_READY) 468 | pthread_cond_wait(&cp->cond, &cp->mutex); 469 | pthread_mutex_unlock(&cp->mutex); 470 | 471 | display_img_to_overlay(env, win_state, cp->img_data, cp->img_size, 472 | current_doc_overlay); 473 | return EMACS_T; 474 | } 475 | 476 | /** 477 | * Redisplay the current document page in Emacs. 478 | * 479 | * Resets visual state (no rotation/inversion), re-renders the current 480 | * cached page in a background thread, waits for completion, and updates 481 | * the image in the associated Emacs overlay. 482 | * 483 | * @param env Emacs module environment. 484 | * @param nargs Argument count (unused). 485 | * @param args Argument values (unused). 486 | * @param data Additional data (unused). 487 | * Return: EMACS_T on success, EMACS_NIL if state is not available. 488 | */ 489 | 490 | emacs_value 491 | emacs_redisplay_doc(emacs_env *env, ptrdiff_t nargs, emacs_value *args, 492 | void *data) 493 | { 494 | (void)nargs; 495 | (void)args; 496 | (void)data; 497 | 498 | DocState *doc_state = get_doc_state_ptr(env); 499 | emacs_value current_doc_overlay = get_current_doc_overlay(env); 500 | EmacsWinState *win_state = get_win_state_ptr(env, current_doc_overlay); 501 | 502 | if (doc_state && win_state) 503 | { 504 | doc_state->invert = 0; 505 | win_state->rotate = 0; 506 | CachedPage *cp = win_state->current_cached_page; 507 | DrawThreadArgs *draw_args = malloc(sizeof(DrawThreadArgs)); 508 | draw_args->doc_state = doc_state; 509 | draw_args->win_state = win_state; 510 | draw_args->cp = cp; 511 | submit_job(draw_page_thread, draw_args, &g_thread_pool); 512 | 513 | pthread_mutex_lock(&cp->mutex); 514 | pthread_cond_wait(&cp->cond, &cp->mutex); 515 | pthread_mutex_unlock(&cp->mutex); 516 | display_img_to_overlay(env, win_state, cp->img_data, 517 | cp->img_size, current_doc_overlay); 518 | } 519 | else 520 | { 521 | return EMACS_NIL; 522 | } 523 | 524 | return EMACS_T; 525 | } 526 | 527 | /** 528 | * Close the currently loaded document and free all resources. 529 | * 530 | * Frees the cache window and cached pages pool, drops the outline, 531 | * document, and MuPDF context, resets the DocState, and frees it. 532 | * 533 | * @param env Emacs module environment. 534 | * @param nargs Argument count (unused). 535 | * @param args Argument values (unused). 536 | * @param data Additional data (unused). 537 | * Return: EMACS_T after successful cleanup. 538 | */ 539 | 540 | emacs_value 541 | emacs_close_doc(emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data) 542 | { 543 | (void)nargs; 544 | (void)args; 545 | (void)data; 546 | 547 | DocState *state = get_doc_state_ptr(env); 548 | emacs_value overlay = get_current_doc_overlay(env); 549 | EmacsWinState *win_state = get_win_state_ptr(env, overlay); 550 | free_cache_window(state, win_state); 551 | free_cached_pages_pool(state); 552 | fz_drop_outline(state->ctx, state->outline); 553 | fz_drop_document(state->ctx, state->doc); 554 | fz_drop_context(state->ctx); 555 | reset_doc_state(state); 556 | free(state); 557 | return EMACS_T; 558 | } 559 | 560 | /** 561 | * emacs_next_page - Move to and display the next page in the overlay. 562 | * @env: The Emacs environment pointer. 563 | * @nargs: (ignored). 564 | * @args: (ignored). 565 | * @data: (ignored). 566 | * 567 | * Return: Elisp `t` on completion, `nil` otherwise. 568 | */ 569 | 570 | emacs_value 571 | emacs_next_page(emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data) 572 | { 573 | (void)nargs; 574 | (void)args; 575 | (void)data; 576 | DocState *doc_state = get_doc_state_ptr(env); 577 | emacs_value current_doc_overlay = get_current_doc_overlay(env); 578 | EmacsWinState *win_state = get_win_state_ptr(env, current_doc_overlay); 579 | 580 | if (doc_state && win_state) 581 | { 582 | if (win_state->current_page_number 583 | == (doc_state->pagecount - 1)) 584 | { 585 | emacs_message(env, "Already last page!"); 586 | return EMACS_NIL; 587 | } 588 | 589 | // Get the pointer for the next CachedPage in the window 590 | CachedPage *next_cp 591 | = win_state 592 | ->cache_window[win_state->current_window_index + 1]; 593 | 594 | if (next_cp->status != PAGE_STATUS_READY) 595 | load_page_dl(doc_state, next_cp); 596 | 597 | DrawThreadArgs *draw_args = malloc(sizeof(DrawThreadArgs)); 598 | draw_args->doc_state = doc_state; 599 | draw_args->win_state = win_state; 600 | draw_args->cp = next_cp; 601 | submit_job(draw_page_thread, draw_args, &g_thread_pool); 602 | 603 | // Wait for the thread to signal before displaying 604 | pthread_mutex_lock(&next_cp->mutex); 605 | pthread_cond_wait(&next_cp->cond, &next_cp->mutex); 606 | pthread_mutex_unlock(&next_cp->mutex); 607 | display_img_to_overlay(env, win_state, next_cp->img_data, 608 | next_cp->img_size, current_doc_overlay); 609 | slide_cache_window_forward(doc_state, win_state); 610 | set_current_page_number(env, win_state->current_page_number); 611 | return EMACS_T; 612 | } 613 | else 614 | { 615 | return EMACS_NIL; 616 | } 617 | 618 | return EMACS_T; 619 | } 620 | 621 | /** 622 | * emacs_prev_page - Move to and display the previous page in the overlay. 623 | * @env: The Emacs environment pointer. 624 | * @nargs: (ignored). 625 | * @args: (ignored). 626 | * @data: (ignored). 627 | * 628 | * Return: Elisp `t` if page moved, `nil` if already at first page (and warn). 629 | */ 630 | 631 | emacs_value 632 | emacs_prev_page(emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data) 633 | { 634 | (void)nargs; 635 | (void)args; 636 | (void)data; 637 | DocState *doc_state = get_doc_state_ptr(env); 638 | emacs_value current_doc_overlay = get_current_doc_overlay(env); 639 | EmacsWinState *win_state = get_win_state_ptr(env, current_doc_overlay); 640 | 641 | if (doc_state && win_state) 642 | { 643 | if (win_state->current_page_number == 0) 644 | { 645 | emacs_message(env, "Already first page!"); 646 | return EMACS_NIL; 647 | } 648 | 649 | CachedPage *prev_cp 650 | = win_state 651 | ->cache_window[win_state->current_window_index - 1]; 652 | 653 | if (prev_cp->status != PAGE_STATUS_READY) 654 | load_page_dl(doc_state, prev_cp); 655 | 656 | DrawThreadArgs *draw_args = malloc(sizeof(DrawThreadArgs)); 657 | draw_args->doc_state = doc_state; 658 | draw_args->win_state = win_state; 659 | draw_args->cp = prev_cp; 660 | submit_job(draw_page_thread, draw_args, &g_thread_pool); 661 | 662 | pthread_mutex_lock(&prev_cp->mutex); 663 | pthread_cond_wait(&prev_cp->cond, &prev_cp->mutex); 664 | pthread_mutex_unlock(&prev_cp->mutex); 665 | display_img_to_overlay(env, win_state, prev_cp->img_data, 666 | prev_cp->img_size, current_doc_overlay); 667 | slide_cache_window_backward(doc_state, win_state); 668 | set_current_page_number(env, win_state->current_page_number); 669 | } 670 | else 671 | { 672 | return EMACS_NIL; 673 | } 674 | 675 | return EMACS_T; 676 | } 677 | 678 | /** 679 | * emacs_first_page - Jump to and display the first page of the document. 680 | * @env: The Emacs environment pointer. 681 | * @nargs: (ignored). 682 | * @args: (ignored). 683 | * @data: (ignored). 684 | * 685 | * Return: Elisp `t` on success, `nil` if already at the first page (and warn). 686 | */ 687 | 688 | emacs_value 689 | emacs_first_page(emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data) 690 | { 691 | (void)nargs; 692 | (void)args; 693 | (void)data; 694 | DocState *doc_state = get_doc_state_ptr(env); 695 | emacs_value current_doc_overlay = get_current_doc_overlay(env); 696 | EmacsWinState *win_state = get_win_state_ptr(env, current_doc_overlay); 697 | 698 | if (doc_state && win_state) 699 | { 700 | 701 | if (win_state->current_page_number == 0) 702 | { 703 | emacs_message(env, "Already first page!"); 704 | return EMACS_NIL; 705 | } 706 | 707 | win_state->current_page_number = 0; 708 | set_current_page_number(env, win_state->current_page_number); 709 | build_cache_window(doc_state, win_state, 710 | win_state->current_page_number); 711 | CachedPage *first_cp = win_state->current_cached_page; 712 | display_img_to_overlay(env, win_state, first_cp->img_data, 713 | first_cp->img_size, current_doc_overlay); 714 | } 715 | else 716 | { 717 | return EMACS_NIL; 718 | } 719 | 720 | return EMACS_T; 721 | } 722 | 723 | /** 724 | * emacs_last_page - Jump to and display the last page of the document. 725 | * @env: The Emacs environment pointer. 726 | * @nargs: (ignored). 727 | * @args: (ignored). 728 | * @data: (ignored). 729 | * 730 | * Return: Elisp `t` on success, `nil` if already at the last page (and warn). 731 | */ 732 | 733 | emacs_value 734 | emacs_last_page(emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data) 735 | { 736 | (void)nargs; 737 | (void)args; 738 | (void)data; 739 | DocState *doc_state = get_doc_state_ptr(env); 740 | emacs_value current_doc_overlay = get_current_doc_overlay(env); 741 | EmacsWinState *win_state = get_win_state_ptr(env, current_doc_overlay); 742 | 743 | if (doc_state && win_state) 744 | { 745 | if (win_state->current_page_number == doc_state->pagecount - 1) 746 | { 747 | emacs_message(env, "Already the last page!"); 748 | return EMACS_NIL; 749 | } 750 | 751 | win_state->current_page_number = doc_state->pagecount - 1; 752 | set_current_page_number(env, win_state->current_page_number); 753 | build_cache_window(doc_state, win_state, 754 | win_state->current_page_number); 755 | CachedPage *last_cp = win_state->current_cached_page; 756 | display_img_to_overlay(env, win_state, last_cp->img_data, 757 | last_cp->img_size, current_doc_overlay); 758 | } 759 | else 760 | { 761 | return EMACS_NIL; 762 | } 763 | 764 | return EMACS_T; 765 | } 766 | 767 | /** 768 | * emacs_goto_page - Jump to a specific page number and display it. 769 | * @env: The Emacs environment pointer. 770 | * @nargs: Number of Elisp args (should be 1). 771 | * @args: Array of Elisp argument values; args[0] is desired page index. 772 | * @data: (ignored). 773 | * 774 | * Return: Elisp `t` on success or out-of-bounds (always `t`), otherwise emits a 775 | * bounds warning. 776 | */ 777 | 778 | emacs_value 779 | emacs_goto_page(emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data) 780 | { 781 | (void)nargs; 782 | (void)data; 783 | int page_number = env->extract_integer(env, args[0]); 784 | DocState *doc_state = get_doc_state_ptr(env); 785 | emacs_value current_doc_overlay = get_current_doc_overlay(env); 786 | EmacsWinState *win_state = get_win_state_ptr(env, current_doc_overlay); 787 | 788 | if (doc_state && win_state) 789 | { 790 | if (page_number >= 0 791 | && page_number <= (doc_state->pagecount - 1)) 792 | { 793 | win_state->current_page_number = page_number; 794 | set_current_page_number(env, 795 | win_state->current_page_number); 796 | build_cache_window(doc_state, win_state, 797 | win_state->current_page_number); 798 | CachedPage *cp = win_state->current_cached_page; 799 | display_img_to_overlay(env, win_state, cp->img_data, 800 | cp->img_size, 801 | current_doc_overlay); 802 | } 803 | else 804 | { 805 | emacs_message(env, 806 | "Provided page number is out of bounds!"); 807 | return EMACS_NIL; 808 | } 809 | } 810 | else 811 | { 812 | return EMACS_NIL; 813 | } 814 | 815 | return EMACS_T; 816 | } 817 | 818 | /** 819 | * emacs_doc_change_page_size - Scale the displayed image to a new size. 820 | * @env: The Emacs environment pointer. 821 | * @nargs: Number of Elisp args (should be 1). 822 | * @args: Array of Elisp argument values; args[0] is the float scale factor. 823 | * @data: (ignored). 824 | * 825 | * Return: Elisp `t` on completion, `nil` otherwise. 826 | */ 827 | 828 | emacs_value 829 | emacs_doc_scale_page(emacs_env *env, ptrdiff_t nargs, emacs_value *args, 830 | void *data) 831 | { 832 | (void)nargs; 833 | (void)data; 834 | DocState *doc_state = get_doc_state_ptr(env); 835 | emacs_value current_doc_overlay = get_current_doc_overlay(env); 836 | EmacsWinState *win_state = get_win_state_ptr(env, current_doc_overlay); 837 | float scale_factor = env->extract_float(env, args[0]); 838 | 839 | if (doc_state && win_state) 840 | { 841 | DrawThreadArgs *draw_args = malloc(sizeof(DrawThreadArgs)); 842 | draw_args->doc_state = doc_state; 843 | draw_args->win_state = win_state; 844 | draw_args->cp = win_state->current_cached_page; 845 | double new_res = fz_clamp(scale_factor * 72, MINRES, MAXRES); 846 | win_state->resolution = new_res; 847 | 848 | if (draw_args->cp->status != PAGE_STATUS_READY) 849 | load_page_dl(doc_state, draw_args->cp); 850 | submit_job(draw_page_thread, draw_args, &g_thread_pool); 851 | pthread_mutex_lock(&win_state->current_cached_page->mutex); 852 | pthread_cond_wait(&win_state->current_cached_page->cond, 853 | &win_state->current_cached_page->mutex); 854 | pthread_mutex_unlock(&win_state->current_cached_page->mutex); 855 | 856 | display_img_to_overlay(env, win_state, 857 | win_state->current_cached_page->img_data, 858 | win_state->current_cached_page->img_size, 859 | current_doc_overlay); 860 | } 861 | else 862 | { 863 | emacs_message(env, "Not a valid document, or you are not in an " 864 | "Emacs Reader buffer!"); 865 | return EMACS_NIL; 866 | } 867 | 868 | return EMACS_T; 869 | } 870 | 871 | /** 872 | * emacs_doc_rotate - rotate the displayed image by rotation angle. 873 | * @env: The Emacs environment pointer. 874 | * @nargs: Number of Elisp args (should be 1). 875 | * @args: Array of Elisp argument values, args[0] is the angle (in degrees). 876 | * @data: (ignored). 877 | * 878 | * Return: Elisp `t` on completion, `nil` otherwise. 879 | */ 880 | 881 | emacs_value 882 | emacs_doc_rotate(emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data) 883 | { 884 | (void)nargs; 885 | (void)data; 886 | DocState *doc_state = get_doc_state_ptr(env); 887 | emacs_value current_doc_overlay = get_current_doc_overlay(env); 888 | EmacsWinState *win_state = get_win_state_ptr(env, current_doc_overlay); 889 | int rotation_deg = env->extract_integer(env, args[0]); 890 | if (doc_state && win_state) 891 | { 892 | win_state->rotate += rotation_deg; 893 | DrawThreadArgs *draw_args = malloc(sizeof(DrawThreadArgs)); 894 | draw_args->doc_state = doc_state; 895 | draw_args->win_state = win_state; 896 | draw_args->cp = win_state->current_cached_page; 897 | 898 | if (draw_args->cp->status != PAGE_STATUS_READY) 899 | load_page_dl(doc_state, draw_args->cp); 900 | 901 | submit_job(draw_page_thread, draw_args, &g_thread_pool); 902 | 903 | // Wait for the thread to signal before displaying 904 | pthread_mutex_lock(&win_state->current_cached_page->mutex); 905 | pthread_cond_wait(&win_state->current_cached_page->cond, 906 | &win_state->current_cached_page->mutex); 907 | pthread_mutex_unlock(&win_state->current_cached_page->mutex); 908 | display_img_to_overlay(env, win_state, 909 | win_state->current_cached_page->img_data, 910 | win_state->current_cached_page->img_size, 911 | current_doc_overlay); 912 | } 913 | else 914 | { 915 | return EMACS_NIL; 916 | } 917 | return EMACS_T; 918 | } 919 | 920 | emacs_value 921 | emacs_doc_window_create(emacs_env *env, ptrdiff_t nargs, emacs_value *args, 922 | void *data) 923 | { 924 | (void)nargs; 925 | (void)data; 926 | emacs_value win = args[0]; 927 | DocState *doc_state = get_doc_state_ptr(env); 928 | init_overlay(env, win); 929 | init_win_state_ptr(env, doc_state, win); 930 | return EMACS_T; 931 | } 932 | 933 | emacs_value 934 | emacs_doc_window_close(emacs_env *env, ptrdiff_t nargs, emacs_value *args, 935 | void *data) 936 | { 937 | (void)nargs; 938 | (void)data; 939 | emacs_value overlay = args[0]; 940 | DocState *doc_state = get_doc_state_ptr(env); 941 | EmacsWinState *win_state = get_win_state_ptr(env, overlay); 942 | if (win_state) 943 | free(win_state); 944 | env->funcall(env, env->intern(env, "delete-overlay"), 1, &overlay); 945 | return EMACS_T; 946 | } 947 | 948 | // Entrypoint for the dynamic module 949 | int 950 | emacs_module_init(struct emacs_runtime *runtime) 951 | { 952 | emacs_env *env = runtime->get_environment(runtime); 953 | if (!env) 954 | { 955 | fprintf(stderr, "Failed to get Emacs environment.\n"); 956 | return 1; 957 | } 958 | 959 | // Registrations for the required functions and variables 960 | 961 | register_module_func( 962 | env, emacs_load_doc, "reader-dyn--load-doc", 1, 1, 963 | "Loads a DOC to be rendered in Emacs. It is wrapped around the " 964 | "Elisp " 965 | "function `reader-open-doc'. The function does the following:\n 1. " 966 | "Allocates and resets a new DocState\n 2. Attempts to open the " 967 | "document " 968 | "through the internal (non-registered) `load_mupdf_doc'.\n 3. " 969 | "Exposes " 970 | "the total page count to Elisp\n 4. Create a bufer-local " 971 | "overlay " 972 | "through `init_overlay'\n 5. Calls the main `render_page' function " 973 | "to " 974 | "render the current page and its adjacent ones.\n 6. Converts the " 975 | "raw PPM data to " 976 | "an Emacs image object and displays it in the overlay through " 977 | "`overlay-put'.\n 7. Wraps the C pointer for DocState as an user " 978 | "pointer " 979 | "and stores it in `reader-current-doc-state-ptr'."); 980 | 981 | register_module_func( 982 | env, emacs_redisplay_doc, "reader-dyn--redisplay-doc", 0, 0, 983 | "Redisplays the document at the current page and scale."); 984 | register_module_func(env, emacs_close_doc, "reader-dyn--close-doc", 0, 985 | 0, 986 | "Frees the DocState in memory and all other " 987 | "artifacts related to the current document."); 988 | register_module_func( 989 | env, emacs_next_page, "reader-dyn--next-page", 0, 0, 990 | "Loads and renders the next page of the document. It is wrapped " 991 | "around " 992 | "the Elisp function `reader-next-page'. Since DocState stores PPM " 993 | "data " 994 | "for the previous and next page, all this does is render the data " 995 | "for " 996 | "the next page that was rendered and stored in memory previously."); 997 | 998 | register_module_func( 999 | env, emacs_prev_page, "reader-dyn--prev-page", 0, 0, 1000 | "Loads and renders the previous page of the document. It is " 1001 | "wrapped " 1002 | "around the Elisp function `reader-prev-page'. Since DocState " 1003 | "stores " 1004 | "image data for the previous and next page, all this does is " 1005 | "render " 1006 | "the " 1007 | "data for the previous page that was rendered and stored in memory " 1008 | "previously."); 1009 | 1010 | register_module_func(env, emacs_first_page, "reader-dyn--first-page", 0, 1011 | 0, 1012 | "Loads and renders the first page of the " 1013 | "document. It is wrapped around " 1014 | "`reader-first-page'. It calls `render_pages' " 1015 | "with 0 as the argument, " 1016 | "since MuPDF does 0-indexing."); 1017 | 1018 | register_module_func( 1019 | env, emacs_last_page, "reader-dyn--last-page", 0, 0, 1020 | "Loads and renders the last page of the document. It is " 1021 | "wrapped around `reader-last-page'. It calls " 1022 | "`render_pages' with (pagecount - 1) as the argument"); 1023 | 1024 | register_module_func( 1025 | env, emacs_goto_page, "reader-dyn--goto-page", 1, 1, 1026 | "Loads and renders the N page number. It is wrapped around " 1027 | "`reader-goto-page'. It calls `render_pages' with N - 1 as the " 1028 | "argument"); 1029 | 1030 | register_module_func( 1031 | env, emacs_doc_scale_page, "reader-dyn--scale-page", 1, 1, 1032 | "Scales the current page of the document by a given FACTOR. It " 1033 | "multiplies the FACTOR with the :width, :height and :scale " 1034 | "properties of " 1035 | "the image, and then renders the scaled image through " 1036 | "`overlay-put'."); 1037 | 1038 | register_module_func(env, emacs_set_dark_theme, 1039 | "reader-dyn--set-dark-theme", 0, 0, 1040 | "Sets the current document to have a dark theme. " 1041 | "It simply inverts the pixmap."); 1042 | 1043 | register_module_func(env, emacs_doc_rotate, "reader-dyn--rotate-doc", 1, 1044 | 1, "Rotates the page by the given DEGREE."); 1045 | 1046 | register_module_func( 1047 | env, emacs_doc_window_create, "reader-dyn--window-create", 1, 1, 1048 | "Function to initialize window parameters for EmacsWinState."); 1049 | register_module_func(env, emacs_doc_window_close, 1050 | "reader-dyn--window-close", 1, 1, 1051 | "Function to free EmacsWinState."); 1052 | 1053 | // Register buffer-local variables. 1054 | permanent_buffer_local_var(env, "reader-current-doc-pagecount"); 1055 | permanent_buffer_local_var(env, "reader-current-doc-render-status"); 1056 | permanent_buffer_local_var(env, "reader-current-doc-state-ptr"); 1057 | permanent_buffer_local_var(env, "reader-current-doc-outline"); 1058 | permanent_buffer_local_var(env, "reader--recent-pagenumber-fallback"); 1059 | 1060 | // Provide the current dynamic module as a feature to Emacs 1061 | provide(env, "render-core"); 1062 | 1063 | // Initialize the global thread pool 1064 | threadpool_init(&g_thread_pool); 1065 | fprintf(stderr, "reader: %d threads have been initialized.\n", 1066 | MAX_POOL_SIZE); 1067 | 1068 | fprintf(stderr, 1069 | "reader: dynamic module has been loaded successfully.\n"); 1070 | 1071 | return 0; 1072 | } 1073 | --------------------------------------------------------------------------------