use std::sync::atomic::{AtomicU64, Ordering};
use serde::{Deserialize, Serialize};
use super::{NativeDocumentSession, NativeHostError};
use crate::document_core::native_interaction::NativeTextPosition;
use crate::serializer::{ContentLossReport, SerializedDocument};
use crate::DocumentCore;
static NEXT_SAVE_TOKEN: AtomicU64 = AtomicU64::new(1);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NativeSaveFormat {
Hwp,
Hwpx,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum NativeSaveCaretPolicy {
StoredCore,
CurrentFocus,
HwpxSourceSettings,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct NativeSaveToken(u64);
impl NativeSaveToken {
pub fn as_u64(self) -> u64 {
self.0
}
pub fn from_raw(value: u64) -> Self {
Self(value)
}
}
#[derive(Debug)]
#[must_use = "persist bytes with their content-loss report before acknowledging the token"]
pub struct PreparedSave {
serialized: SerializedDocument,
revision: u64,
token: NativeSaveToken,
caret_policy: NativeSaveCaretPolicy,
caret_preserved_from_source: bool,
}
impl PreparedSave {
pub fn bytes(&self) -> &[u8] {
self.serialized.bytes()
}
pub fn content_loss(&self) -> &ContentLossReport {
self.serialized.content_loss()
}
pub fn revision(&self) -> u64 {
self.revision
}
pub fn token(&self) -> NativeSaveToken {
self.token
}
pub fn caret_policy(&self) -> NativeSaveCaretPolicy {
self.caret_policy
}
pub fn caret_saved(&self) -> bool {
self.caret_policy == NativeSaveCaretPolicy::CurrentFocus
}
pub fn caret_preserved_from_source(&self) -> bool {
self.caret_preserved_from_source
}
pub fn into_parts(self) -> (Vec<u8>, ContentLossReport, u64, NativeSaveToken) {
let (bytes, content_loss) = self.serialized.into_parts();
(bytes, content_loss, self.revision, self.token)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeSaveStatus {
pub revision: u64,
pub saved_revision: Option<u64>,
pub dirty: bool,
}
pub(super) struct PendingSaveCheckpoint {
token: NativeSaveToken,
revision: u64,
}
impl NativeDocumentSession {
pub fn is_dirty(&self) -> bool {
self.saved_revision != Some(self.revision())
}
pub fn prepare_save(
&mut self,
format: NativeSaveFormat,
) -> Result<PreparedSave, NativeHostError> {
let serialized = match format {
NativeSaveFormat::Hwp => self.core.export_hwp_with_adapter_snapshot_with_report()?,
NativeSaveFormat::Hwpx => self.core.export_hwpx_native_with_report()?,
};
self.retain_prepared_save(
serialized,
match format {
NativeSaveFormat::Hwp => NativeSaveCaretPolicy::StoredCore,
NativeSaveFormat::Hwpx => NativeSaveCaretPolicy::HwpxSourceSettings,
},
)
}
pub fn prepare_save_with_caret(
&mut self,
format: NativeSaveFormat,
focus: &NativeTextPosition,
) -> Result<PreparedSave, NativeHostError> {
if format != NativeSaveFormat::Hwp {
return Err(NativeHostError::Unsupported(
"current-focus persistence is supported only for HWP; use prepare_save for HWPX"
.into(),
));
}
self.core
.validate_native_text_position(focus)
.map_err(|error| NativeHostError::InvalidArgument(error.to_string()))?;
if !focus.cell_path.is_empty() {
return Err(NativeHostError::Unsupported(
"saved caret currently supports body text only".into(),
));
}
self.core
.check_native_interaction_support(focus)
.map_err(|error| NativeHostError::Unsupported(error.to_string()))?;
let lowered = self.core.prepare_hwp_export_snapshot();
let mut snapshot = lowered.document().clone();
DocumentCore::set_document_caret_position(
&mut snapshot,
focus.section as usize,
focus.paragraph as usize,
focus.scalar_offset as usize,
);
let serialized =
crate::serializer::serialize_document_with_report(&snapshot).map_err(|error| {
NativeHostError::Core(crate::HwpError::RenderError(error.to_string()))
})?;
self.retain_prepared_save(serialized, NativeSaveCaretPolicy::CurrentFocus)
}
pub fn acknowledge_save(
&mut self,
token: NativeSaveToken,
) -> Result<NativeSaveStatus, NativeHostError> {
let saved_revision = self.pending_save_revision(token)?;
self.pending_save = None;
self.saved_revision = Some(saved_revision);
Ok(self.native_save_status())
}
pub fn cancel_save(
&mut self,
token: NativeSaveToken,
) -> Result<NativeSaveStatus, NativeHostError> {
self.pending_save_revision(token)?;
self.pending_save = None;
Ok(self.native_save_status())
}
fn retain_prepared_save(
&mut self,
serialized: SerializedDocument,
caret_policy: NativeSaveCaretPolicy,
) -> Result<PreparedSave, NativeHostError> {
let caret_preserved_from_source = caret_policy == NativeSaveCaretPolicy::HwpxSourceSettings
&& self
.core
.document()
.hwpx_aux_entry("settings.xml")
.is_some();
let token = rhwp_codec_resource::atomic::try_update_u64(
&NEXT_SAVE_TOKEN,
Ordering::Relaxed,
Ordering::Relaxed,
|value| value.checked_add(1),
)
.map(NativeSaveToken)
.map_err(|_| NativeHostError::LimitExceeded("save token space exhausted".into()))?;
let revision = self.revision();
self.pending_save = Some(PendingSaveCheckpoint { token, revision });
Ok(PreparedSave {
serialized,
revision,
token,
caret_policy,
caret_preserved_from_source,
})
}
fn pending_save_revision(&self, token: NativeSaveToken) -> Result<u64, NativeHostError> {
self.pending_save
.as_ref()
.filter(|checkpoint| checkpoint.token == token)
.map(|checkpoint| checkpoint.revision)
.ok_or_else(|| {
NativeHostError::InvalidArgument(
"unknown, superseded or consumed save token".into(),
)
})
}
fn native_save_status(&self) -> NativeSaveStatus {
NativeSaveStatus {
revision: self.revision(),
saved_revision: self.saved_revision,
dirty: self.is_dirty(),
}
}
}