Skip to main content

qualia_client_core/view_host/
mod.rs

1//! App-global entity-view session composition (desktop-wide, not browser-only).
2//!
3//! Pure filter/layout from `qualia_core_db::entity_view`; this module binds storage + session.
4
5mod session;
6
7pub use session::{
8    morph_flatten, morph_spatialize, project_library_for_observer, project_web_locus, MorphMode,
9    ViewSession,
10};
11
12use qualia_core_db::entity_view::{Circumstance, EntityId, ObserverStatus, PresentationLevel};
13use serde::{Deserialize, Serialize};
14use std::sync::Mutex;
15
16/// Process-wide session for webizen-desktop (shell, studio, browser share one).
17static SESSION: Mutex<Option<ViewSession>> = Mutex::new(None);
18
19/// Builder — sets session.
20pub fn with_session<R>(f: impl FnOnce(&mut ViewSession) -> R) -> R {
21    let mut g = SESSION.lock().unwrap_or_else(|e| e.into_inner());
22    if g.is_none() {
23        *g = Some(ViewSession::default());
24    }
25    f(g.as_mut().expect("session just set"))
26}
27
28/// Gets session-snapshot.
29pub fn get_session_snapshot() -> ViewSession {
30    with_session(|s| s.clone())
31}
32
33/// Sets observer.
34pub fn set_observer(status: ObserverStatus) {
35    with_session(|s| s.observer = status);
36}
37
38/// Sets presentation-level.
39pub fn set_presentation_level(level: u8) {
40    with_session(|s| s.presentation_level = PresentationLevel::from_u8(level));
41}
42
43/// Selects an entity.
44pub fn select_entity(entity_id: u64) {
45    with_session(|s| {
46        s.selection.clear();
47        s.selection.push(EntityId::from_raw(entity_id));
48    });
49}
50
51/// Select by URI/DID/asset (stable EntityId via from_uri); also sets attention_url.
52pub fn select_entity_uri(uri: &str) {
53    let id = EntityId::from_uri(uri);
54    with_session(|s| {
55        s.selection.clear();
56        s.selection.push(id);
57        s.attention_url = Some(uri.to_string());
58    });
59}
60
61/// Clears the selection.
62pub fn clear_selection() {
63    with_session(|s| {
64        s.selection.clear();
65        s.attention_url = None;
66    });
67}
68
69/// Set circumstance (role / audience / quorum / environment / evaluatory).
70pub fn set_circumstance(c: Circumstance) {
71    with_session(|s| s.circumstance = c);
72}
73
74/// DTO for Tauri / studio JSON.
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct ProjectLibraryRequest {
77    pub storage_path: String,
78    pub section: Option<String>,
79    pub observer: Option<String>,
80    pub presentation_level: Option<u8>,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct ProjectWebLocusRequest {
85    pub url: String,
86    pub observer: Option<String>,
87}
88
89/// Parses observer.
90pub fn parse_observer(s: &str) -> ObserverStatus {
91    match s.trim().to_ascii_lowercase().as_str() {
92        "peer" => ObserverStatus::Peer,
93        "guardian" => ObserverStatus::Guardian,
94        "steward" => ObserverStatus::Steward,
95        "public" | "anonymous" => ObserverStatus::Public,
96        "instrument" | "agent" => ObserverStatus::Instrument,
97        "auditor" => ObserverStatus::Auditor,
98        _ => ObserverStatus::Principal,
99    }
100}
101
102/// Project library from disk path for given observer (updates session).
103pub fn project_library_json(
104    storage_path: &str,
105    section: Option<&str>,
106    observer: ObserverStatus,
107    level: PresentationLevel,
108) -> Result<serde_json::Value, String> {
109    with_session(|s| {
110        s.observer = observer;
111        s.presentation_level = level;
112        let result = project_library_for_observer(storage_path, section, observer, level)?;
113        s.last_projection = Some(result.clone());
114        s.morph_mode = MorphMode::Both;
115        serde_json::to_value(&result).map_err(|e| e.to_string())
116    })
117}
118
119/// `project-web-locus` as JSON.
120pub fn project_web_locus_json(
121    url: &str,
122    observer: ObserverStatus,
123) -> Result<serde_json::Value, String> {
124    with_session(|s| {
125        s.observer = observer;
126        let card = project_web_locus(url, observer);
127        if let Some(id) = card.get("entity_id").and_then(|v| v.as_u64()) {
128            s.selection.clear();
129            s.selection.push(EntityId::from_raw(id));
130        }
131        s.attention_url = Some(url.to_string());
132        Ok(card)
133    })
134}
135
136/// `morph` as JSON.
137pub fn morph_json(mode: &str) -> Result<serde_json::Value, String> {
138    with_session(|s| {
139        let Some(ref proj) = s.last_projection else {
140            return Err("no projection yet - call view_project_library first".into());
141        };
142        match mode.trim().to_ascii_lowercase().as_str() {
143            "flatten" | "flat" => {
144                s.morph_mode = MorphMode::Flatten;
145                Ok(morph_flatten(proj))
146            }
147            "spatialize" | "spatial" | "scene" => {
148                s.morph_mode = MorphMode::Spatialize;
149                Ok(morph_spatialize(proj))
150            }
151            "both" => {
152                s.morph_mode = MorphMode::Both;
153                serde_json::to_value(proj).map_err(|e| e.to_string())
154            }
155            _ => Err(format!(
156                "unknown morph mode '{mode}' (flatten|spatialize|both)"
157            )),
158        }
159    })
160}
161
162/// Nearest scene node in last projection by normalized (x,y) in 0..1 (controller pick).
163/// Returns entity_id when found; also updates selection.
164pub fn pick_scene_node_at(nx: f64, ny: f64, max_dist: f64) -> Option<u64> {
165    with_session(|s| {
166        let proj = s.last_projection.as_ref()?;
167        let mut best: Option<(f64, u64)> = None;
168        for n in &proj.scene_nodes {
169            if n.entity_id == 0 {
170                continue;
171            }
172            let dx = n.x - nx;
173            let dy = n.y - ny;
174            let d = (dx * dx + dy * dy).sqrt();
175            if d <= max_dist {
176                if best.map(|(bd, _)| d < bd).unwrap_or(true) {
177                    best = Some((d, n.entity_id));
178                }
179            }
180        }
181        let id = best.map(|(_, id)| id)?;
182        s.selection.clear();
183        s.selection.push(EntityId::from_raw(id));
184        Some(id)
185    })
186}