JFLib

doc_io#

conservative DOCX interchange and bounded file I/O -- crate root lib/doc_io/lib.rs

Conservative DOCX interchange for the initial document model. New native library code.
Unrepresentable content is rejected before exposing an editable document. No VBA support.

doc_io crate root#

  • enum Error Failure with the unsupported part/element included for a useful UI explanation.

    • Io
    • Limit
    • Invalid
    • Archive(archive::Error)
    • Xml(xml::Error)
    • Unsupported(String)
    • Model(doc_core::Error)
  • fn encode_docx(d: &Document) -> Result<Vec<u8>, Error> Serialize a validated document to a deterministic DOCX package. Sources are native bibliography custom XML; citations are CITATION fields with cached display text. Footnotes and endnotes use their standard parts and continuous decimal numbering.

  • fn decode_docx(b: &[u8]) -> Result<Document, Error> Read the initial editable DOCX profile. Unknown package parts, layout, formatting, relationships, fields and source fields are rejected, never silently discarded. Full Word interoperability is deliberately not claimed by this early codec.

  • fn read_file(path: &str, limit: usize) -> Result<Vec<u8>, Error> Bounded whole-file read; refuses oversized files before allocation, including short reads.

  • fn load_docx(path: &str) -> Result<Document, Error> Load a DOCX without altering the caller's current editing session on failure.

  • fn save_docx(path: &str, d: &Document) -> Result<(), Error> Encode completely before the platform's temporary-file/rename write.

doc_io/bibliography.rs#

Source: lib/doc_io/bibliography.rs

Shared Word bibliography XML codec: used by DOCX and standalone source lists.
  • fn encode_sources(sources: &[Source]) -> Result<Vec<u8>, Error> Encode supported sources as Word Sources.xml, with document-local jf<ID> tags. Input IDs must be unique and nonzero. Output is UTF-8, without external resources.

  • fn decode_sources(bytes: &[u8]) -> Result<Vec<Source>, Error> Decode a complete standalone Word source list. External tags are validated but remapped to sequential IDs; use Edit::ImportSources to allocate identities in an existing document. Unrepresented fields/types abort the whole import; no partial or silent content import. Read with the limits encode_sources writes with (8 MiB, 250000 elements), so every list it encodes decodes again.

  • fn load_sources(path: &str) -> Result<Vec<Source>, Error> Load a bounded standalone Word bibliography XML file (at most 8 MiB, what save_sources may write).

  • fn save_sources(path: &str, sources: &[Source]) -> Result<(), Error> Export a source list using the platform's temporary-file/rename write.

doc_io/bibtex.rs#

Source: lib/doc_io/bibtex.rs

Bounded, explicit Unicode BibTeX interchange subset. New native library code.
Syntax reference: Oren Patashnik, BibTeXing, https://texdoc.org/serve/btxdoc/0.
This is a metadata codec, not a TeX interpreter or a BibLaTeX style processor.
  • fn decode_bibtex(bytes: &[u8]) -> Result<Vec<Source>, Error> Decode a bounded Unicode BibTeX subset (@book, @article, @online and web @misc). Values may be braced, quoted or numeric. Names use Family, Given, single-token family names, or one braced corporation. UTF-8 and BOM-marked UTF-16 are accepted. Entry keys are validated and remapped to sequential IDs, not retained as metadata. Unsupported fields, TeX commands, case protection, macros and suffixes abort the entire import. Limits: 4 MiB input, 1024 sources, 64 authors, 4096 bytes per scalar, 2 MiB retained model. ASCII field whitespace follows BibTeX normalization.

  • fn encode_bibtex(sources: &[Source]) -> Result<Vec<u8>, Error> Encode the representable Source subset as deterministic UTF-8 BibTeX. Keys are jf<ID>; IDs must be nonzero, unique and below 0x7fff_ffff. Separate middle names, external IDs, language, short titles and other unmapped metadata are errors. Export validates the entire list and refuses values whose meaning/spacing would change. Unicode is emitted directly; no TeX commands, resource loading or execution.

doc_io/clipboard.rs#

Source: lib/doc_io/clipboard.rs

Bounded rich clipboard interchange. New native code, no assembly counterpart.
RTF control syntax follows Microsoft's RTF specification; this is a supported profile,
not a general RTF file editor. Internal structured fragments use the DOCX codec instead.
  • fn clipboard_rtf_encode(d: &Document) -> Result<Vec<u8>, Error> Encode body paragraphs as RTF 1 with explicit resolved character formatting, RGB colors, paragraph alignment, twip spacing/indents and Unicode. Hard paragraphs and soft breaks remain distinct. Fields and note anchors become their visible text; source/note metadata and style identities are not transferred. Font families and effective formatting remain. Use DOCX for a structured internal copy including the style graph. CRLF and lone CR inside text normalize to a single soft break. The output is bounded to 16 MiB and color tables to 1024 entries.

  • fn clipboard_html_encode(d: &Document) -> Result<Vec<u8>, Error> Encode a raw UTF-8 HTML clipboard fragment with inline CSS for resolved character and paragraph formatting. No CF_HTML envelope is included: that belongs to the platform clipboard layer. Font families use escaped CSS names; fields/anchors become visible text and source/note metadata stays in the private DOCX format. The result is bounded to 16 MiB. Floating tables carry versioned exact anchors plus CSS float fallback; page units are twips. Raised and lowered text shows its script size in font-size and keeps its nominal size, in half points, in data-jf-size (clipboard_html_decode reads it back).

  • fn clipboard_rtf_decode(bytes: &[u8]) -> Result<Document, Error> Decode the bounded RTF clipboard profile into validated, directly formatted paragraphs. Accepts group-scoped formatting, Windows single-byte text (874/1250–1258), Unicode/surrogate escapes, colors, relative line spacing, twip paragraph metrics, font family names and cached field results. Language, style identities and metadata map to model defaults. Unknown ignorable destinations are skipped; unsupported visible content (including pictures, lists and objects), unsupported encodings or typography and malformed input are rejected atomically. Only direct formatting is read: implicit Normal-style/default-character properties in metadata are not resolved and fall back to RTF defaults (12pt, automatic color). Other named-style references are rejected. This profile is intended for resolved rich selections. Rectangular and nested table grids, row/column merges, headers, fills and cell borders are read. Limits: 16 MiB input, 2 MiB expanded text, 64 groups, 1024 colors, 256 fonts, 4M tokens.

doc_io/html_import.rs#

Source: lib/doc_io/html_import.rs

  • fn clipboard_html_decode(bytes:&[u8])->Result<Document,Error> Decode a UTF-8 HTML clipboard fragment into editable paragraphs and nested tables. Handles inline text/CSS, table grids, merged cells, headers, borders and table positions. JFLib's versioned data attributes retain exact twip anchors and document page settings, and data-jf-size the nominal size of raised and lowered text. Input is bounded to 16 MiB, 2 MiB text, 64 element levels and eight table levels. Active content and metadata are ignored; external resources are never requested.

doc_io/fragment.rs#

Source: lib/doc_io/fragment.rs

Versioned, self-contained clipboard transport. Payload is the validated native DOCX profile.
  • fn encode_document_fragment(fragment: &DocumentFragment) -> Result<Vec<u8>, Error> Encode a rich selection for application/x-jfgui-docx-fragment. The version prefix prevents future fragment semantics from being interpreted as the current model.

  • fn decode_document_fragment(bytes: &[u8]) -> Result<DocumentFragment, Error> Decode bounded clipboard data without mutating the receiving document. Unknown versions, unsupported DOCX content and invalid source/note references are rejected atomically.

  • fn clipboard_display_fragment( fragment: &DocumentFragment, context: &Document, ) -> Result<Document, Error> Materialize field results for external text formats using the originating document. In particular a bibliography-only selection and note numbers must use the source context, even though the native fragment carries only selected references.

doc_io/exchange.rs#

Source: lib/doc_io/exchange.rs

Format dispatch for standalone bibliography exchange; codecs remain independent of the app.
  • enum BibliographyFormat Supported standalone source-list formats. Each codec has an explicit editable subset.
    • WordXml
    • Ris
    • Bibtex

impl BibliographyFormat

  • fn from_path(path: &str) -> Result<Self, Error> Select by filename extension, case-insensitively; never guess from malformed content.

  • fn extension(self) -> &'static str Default filename extension without a dot.

  • fn decode_bibliography(bytes: &[u8], format: BibliographyFormat) -> Result<Vec<Source>, Error> Decode one complete source list. Errors never return a partially decoded list.

  • fn encode_bibliography( sources: &[Source], format: BibliographyFormat, ) -> Result<Vec<u8>, Error> Encode all records before any file is touched; unrepresentable metadata is an error.

  • fn load_bibliography(path: &str) -> Result<Vec<Source>, Error> Load a bounded source file, choosing the codec from its extension.

  • fn save_bibliography(path: &str, sources: &[Source]) -> Result<(), Error> Save through the platform's temporary-file/rename writer after complete encoding.

doc_io/library.rs#

Source: lib/doc_io/library.rs

Native source-library persistence: strict XML, optimistic conflict detection and recovery.
New shared functionality; no user-profile policy or application UI belongs in this layer.
  • fn encode_source_library(library: &SourceLibrary) -> Result<Vec<u8>, Error> Encode the native version-one source library, preserving source IDs and their high-water mark.

  • fn decode_source_library(bytes: &[u8]) -> Result<SourceLibrary, Error> Decode the complete native source-library format; future versions and unknown data fail closed.

  • enum LibraryStoreError Persistent-library failures distinguish stale content, a held lock and codec rejection.

    • Io -- A path could not be inspected, read, backed up or atomically replaced.
    • Busy -- The cooperative lock could not be acquired (busy or unavailable).
    • Conflict -- The file has changed since this store's successful open, reload or save.
    • Codec(Error) -- The current file, backup or proposed model is outside the supported native format.
  • struct LibraryStore A validated source library and the exact file snapshot used for optimistic concurrency. Opening and reloading never write. Saving uses a sibling lock and atomic platform writes.

  • struct LibraryRecovery A recovery preview with exact current-file and backup snapshots, safe to keep across a dialog. Restoring fails if either reviewed file changes before the caller confirms the operation.

impl LibraryRecovery

  • fn library(&self) -> &SourceLibrary The planned restored model, retaining the greater ID high-water mark of valid current XML.
  • fn restore(&self) -> Result<LibraryStore, LibraryStoreError> Restore the reviewed backup under the library lock, preserving replaced bytes in .damaged.

impl LibraryStore

  • fn open(path: &str) -> Result<Self, LibraryStoreError> Open an existing valid library, or an empty in-memory library when the path is absent. A malformed existing file is an error and is never replaced by an empty model.
  • fn library(&self) -> &SourceLibrary The last successfully opened, reloaded or saved library.
  • fn path(&self) -> &str The configured native library filename.
  • fn save(&mut self, library: &SourceLibrary) -> Result<(), LibraryStoreError> Validate fully, acquire the sibling lock, compare the original bytes, then save atomically. An existing valid version is backed up to .bak before replacement; backup failure aborts.
  • fn reload(&mut self) -> Result<(), LibraryStoreError> Read and validate the current file; on any failure this store keeps its previous state.
  • fn restore_backup(&mut self) -> Result<(), LibraryStoreError> Restore the validated .bak only if the current file still matches this store's snapshot. The replaced bytes are retained in .damaged; the good .bak is never overwritten.
  • fn inspect_backup(path: &str) -> Result<SourceLibrary, LibraryStoreError> Read a backup for review without changing the current file or creating any paths.
  • fn prepare_recovery(path: &str) -> Result<LibraryRecovery, LibraryStoreError> Read a valid backup and current bytes for explicit recovery, including malformed current XML. This read-only preview can later restore exactly those reviewed snapshots.
  • fn restore_backup_if(&mut self, expected: &SourceLibrary) -> Result<(), LibraryStoreError> Restore only the backup model the caller previously inspected; changes return Conflict.
  • fn recover(path: &str) -> Result<Self, LibraryStoreError> Recover from a malformed current file by restoring a validated .bak under the same lock. Current bytes are retained in .damaged before replacement; neither an unreadable nor an oversized current file is overwritten because an exact comparison cannot be established. Valid current XML retains its ID high-water mark. A malformed file cannot supply that mark.
  • fn recover_if_backup( path: &str, expected: &SourceLibrary, ) -> Result<Self, LibraryStoreError> Recover only the backup model the caller previously inspected, preventing a stale preview.

doc_io/preservation.rs#

Source: lib/doc_io/preservation.rs

Bounded OPC inspection and original-byte preservation for foreign Word documents.
New native library code. Unrepresented content is never exposed as an editable model.
The package itself (content types, relationships, part names) is archive::opc's.
  • enum DocxMode Whether the entire document is represented by the editable model.

    • Editable -- Every supported package component has passed the strict editable codec.
    • Preserved -- The original package is retained; the text excerpt is not an editable conversion.
  • struct DocxReport Deterministic inspection results for a bounded, structurally checked DOCX package.

    • mode: DocxMode -- Editing capability; preservation does not imply rendering or editing compatibility.
    • main_part: String -- Main document part resolved through the package relationship.
    • part_count: usize -- Number of ZIP parts, including content types and relationships.
    • diagnostics: Vec<String> -- Human-readable reasons and feature descriptions, capped at 64 distinct entries.
    • preview_truncated: bool -- The reading excerpt reached its independent paragraph or text limit.
  • struct DocxFile A DOCX session retaining its exact original archive alongside an optional full model. Unknown features remain intact; individually proven text leaves may be edited without model conversion. Saving without edits returns the original bytes, including compression, ordering, metadata, images, fields and unknown extension parts.

impl DocxFile

  • fn open(bytes: &[u8]) -> Result<Self, Error> Inspect a conventional, unencrypted DOCX with bounded ZIP/XML processing. Macro-enabled main parts or VBA payloads are rejected. External relationships are retained as data only; this library never follows links or executes embedded content.
  • fn load(path: &str) -> Result<Self, Error> Read and inspect a file, refusing archives over 32 MiB before allocation.
  • fn document(&self) -> Option<&Document> Entire editable document, or None when any unsupported content must be preserved.
  • fn preview(&self) -> &[String] Main-story plain-text excerpt, excluding separate headers, footers and note parts. This deliberately does not claim layout fidelity. Field instructions, deleted revisions and unsupported alternate representations are omitted; cached visible field text and table-cell paragraphs may be included.
  • fn report(&self) -> &DocxReport Original package's capability and compatibility diagnostics.
  • fn text_runs(&self) -> &[crate::DocxTextRun] Safe individual text leaves in the preserved main story and related headers, footers, footnotes and endnotes. Parts resolve through OPC relationships and content types. Signed/protected packages, fields, revisions and content controls are not editable; a complex field or tracked revision disables its whole containing story part.
  • fn replace_text( &mut self, index: usize, expected: &str, replacement: &str, ) -> Result<(), Error> Replace exactly one eligible text leaf, verifying its current text first. Paragraph/run structure and every other package payload remain unchanged.
  • fn dirty(&self) -> bool Whether preserved text differs from the last saved checkpoint.
  • fn revision(&self) -> u64 Monotonic preserved-text revision, including successful undo and redo operations. Saving and replacing text with identical text leave the revision unchanged.
  • fn mark_saved(&mut self) Establish the saved checkpoint after a successful save, retaining undo history.
  • fn undo(&mut self) -> bool Undo the most recent preserved text edit, within the bounded history.
  • fn redo(&mut self) -> bool Redo the next preserved text edit.
  • fn can_undo(&self) -> bool Whether an earlier preserved text edit is available.
  • fn can_redo(&self) -> bool Whether an undone preserved text edit is available.
  • fn encode(&self, document: Option<&Document>) -> Result<Vec<u8>, Error> Produce original bytes for unchanged content, or serialize a changed fully represented model. Passing a model to a preservation-only session is an error. None saves preserved text edits if present, otherwise copies the original exactly.
  • fn save(&self, path: &str, document: Option<&Document>) -> Result<(), Error> Encode before atomic temporary-file/rename writing; a failed edit cannot overwrite a destination. Copying a preserved document retains every original archive byte.

doc_io/preserved_text.rs#

Source: lib/doc_io/preserved_text.rs

Provenance-preserving edits of individual Word text leaves, independent of the model.
Original XML syntax, run properties and every unrelated package payload are retained.
  • struct DocxTextRun An individually editable text leaf in an original Word story part.
    • index: usize -- Stable zero-based identifier accepted by DocxFile::replace_text.
    • part: String -- Original OPC part path; shared headers are exposed only once.
    • story: DocxStory -- The containing story, resolved from the main part's relationship and content type.
    • note_id: Option<i64> -- OOXML note identity, not its rendered number. None for the main story and headers/footers.
    • paragraph: usize -- One-based XML paragraph number within this part, including table-cell paragraphs.
    • text: String -- Current decoded text. Run properties and paragraph structure are kept separately.

doc_io/ris.rs#

Source: lib/doc_io/ris.rs

Bounded RIS bibliography interchange. New native codec, no legacy counterpart.
Tag semantics: Clarivate RIS / primary Zotero RIS translator mapping; see public API scope.
  • fn decode_ris(bytes: &[u8]) -> Result<Vec<Source>, Error> Decode a complete bounded RIS list: BOOK/JOUR/ELEC, people in AU/A1 order, TI/T1 (BOOK: BT), PY/Y1 year only, PB/CY/ET, JOUR JF/JO/T2, ELEC T2, VL/IS/SP/EP (not ELEC), UR/DO, SN/ST/N1/LA and Y2 access date. UTF-8/BOM and BOM UTF-16, LF/CRLF and multiline values are accepted. Continuations strip one six-space indent; other continuation text is preserved with LF. ID is validated then remapped sequentially; use Edit::ImportSources for document IDs. No corporate/suffix inference, role conversion, abstract/keyword/attachment dropping, or publication-date truncation. Unknown or duplicate scalar tags abort the whole list. DOI occupies the URL only when a safe doi.org URL and any UR agree. LA is kept verbatim. Limits: 4 MiB encoded/decoded input, 4096 tags, 1024 records, 4096 bytes per field, 64 authors per record and 2 MiB retained model. No input causes filesystem/network access.

  • fn encode_ris(sources: &[Source]) -> Result<Vec<u8>, Error> Export deterministic UTF-8 RIS with CRLF and indented continuation lines. Only fields represented by decode_ris are accepted; source IDs are local and omitted. Corporate authors, separately stored middle names, external GUIDs, incompatible type-specific fields and non-year publication dates produce record/tag diagnostics. People with commas or outer whitespace in name components cannot be emitted faithfully. Validation includes decoding the complete result and model equality (except source IDs), so no partial output or silently omitted metadata is ever returned.

doc_io/preserved_stories.rs#

Source: lib/doc_io/preserved_stories.rs

Related Word stories resolved by OPC identity, never guessed from ZIP file names.
  • enum DocxStory The Word story containing an individually editable preserved text leaf.
    • Main -- Main document, including eligible table-cell paragraphs.
    • Header -- A section header part; multiple sections can share the same part.
    • Footer -- A section footer part.
    • Footnote -- A normal footnote (separator/continuation definitions are excluded).
    • Endnote -- A normal endnote (separator/continuation definitions are excluded).

Source: docs/API.md in the JFLib repository.