ctb_formats_pan/
functions.rs

1/* SPDX-License-Identifier: MIT */
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7Permission is hereby granted, free of charge, to any person obtaining a copy of
8this software and associated documentation files (the “Software”), to deal in
9the Software without restriction, including without limitation the rights to
10use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11the Software, and to permit persons to whom the Software is furnished to do so,
12subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in all
15copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23SOFTWARE.
24*/
25
26//! Comprehensive Panorama built-in functions library.
27
28#[allow(
29    unused_imports,
30    clippy::wildcard_imports,
31    reason = "Standard workspace module prelude"
32)]
33use crate::utilities::*;
34
35/// Context passed to Panorama built-in functions that query database or environment state.
36#[derive(Debug, Clone, Default)]
37pub struct PanFunctionContext<'a> {
38    pub databasename: &'a str,
39    pub current_form: &'a str,
40}
41
42/// Returns `iftrue` when `cond` is true, otherwise `iffalse`.
43#[must_use]
44pub fn q(cond: bool, iftrue: &str, iffalse: &str) -> String {
45    if cond {
46        iftrue.to_string()
47    } else {
48        iffalse.to_string()
49    }
50}
51
52/// Returns a system or runtime information value for the given query key.
53#[must_use]
54pub fn info(key: &str, context: &PanFunctionContext<'_>) -> String {
55    match key.to_ascii_lowercase().as_str() {
56        "panoramafolder" => String::new(),
57        "databasename" => {
58            if context.databasename.is_empty() {
59                "Programming Reference".to_string()
60            } else {
61                context.databasename.to_string()
62            }
63        }
64        "scratchmemory" => "1048576".to_string(),
65        "modifiers" => String::new(),
66        "formname" => context.current_form.to_string(),
67        "found" => "true".to_string(),
68        "empty" => "false".to_string(),
69        "windowrectangle" => "0,0,800,600".to_string(),
70        "windowoptions" => String::new(),
71        "mouse" => "100,100".to_string(),
72        "buttonrectangle" => "0,0,100,100".to_string(),
73        _ => String::new(),
74    }
75}
76
77/// Formats a folder path ensuring a trailing separator.
78#[must_use]
79pub fn folderpath(path: &str) -> String {
80    if path.is_empty() {
81        String::new()
82    } else if path.ends_with(':') || path.ends_with('/') {
83        path.to_string()
84    } else {
85        format!("{path}:")
86    }
87}
88
89/// Checks whether a folder exists.
90#[must_use]
91pub fn folderexists(_folder: &str, _sub: &str) -> bool {
92    false
93}
94
95/// Returns the Panorama directory or subdirectory path.
96#[must_use]
97pub fn panoramafolder(_sub: &str) -> String {
98    String::new()
99}
100
101/// Lists files within a directory matching a pattern/type.
102#[must_use]
103pub fn listfiles(_folder: &str, _file_type: &str) -> String {
104    String::new()
105}
106
107/// Extracts text between `start_tag` and `end_tag` for the N-th occurrence (1-indexed).
108#[must_use]
109pub fn tagdata(
110    text: &str,
111    start_tag: &str,
112    end_tag: &str,
113    occurrence: usize,
114) -> String {
115    if occurrence == 0 || start_tag.is_empty() {
116        return String::new();
117    }
118
119    let mut cursor = 0usize;
120    let mut count = 0usize;
121
122    while cursor < text.len() {
123        let Some(rel_start) =
124            text.get(cursor..).and_then(|sub| sub.find(start_tag))
125        else {
126            break;
127        };
128        let tag_start = cursor.saturating_add(rel_start);
129        let content_start = tag_start.saturating_add(start_tag.len());
130        count = count.saturating_add(1);
131
132        if count == occurrence {
133            let Some(rest) = text.get(content_start..) else {
134                return String::new();
135            };
136            if end_tag.is_empty() {
137                return rest.to_string();
138            }
139            if let Some(rel_end) = rest.find(end_tag) {
140                if let Some(sub) = rest.get(..rel_end) {
141                    return sub.to_string();
142                }
143                return String::new();
144            }
145            return rest.to_string();
146        }
147
148        cursor = content_start;
149    }
150
151    String::new()
152}
153
154/// Extracts all matches between `start_tag` and `end_tag`, joined by delim.
155#[must_use]
156pub fn tagarray(
157    text: &str,
158    start_tag: &str,
159    end_tag: &str,
160    delim: &str,
161) -> String {
162    if start_tag.is_empty() {
163        return String::new();
164    }
165
166    let mut results = Vec::new();
167    let mut cursor = 0usize;
168
169    while cursor < text.len() {
170        let Some(rel_start) =
171            text.get(cursor..).and_then(|sub| sub.find(start_tag))
172        else {
173            break;
174        };
175        let tag_start = cursor.saturating_add(rel_start);
176        let content_start = tag_start.saturating_add(start_tag.len());
177        let Some(rest) = text.get(content_start..) else {
178            break;
179        };
180
181        if end_tag.is_empty() {
182            results.push(rest.to_string());
183            break;
184        }
185
186        if let Some(rel_end) = rest.find(end_tag) {
187            let matched = match rest.get(..rel_end) {
188                Some(sub) => sub,
189                None => "",
190            };
191            results.push(matched.to_string());
192            cursor = content_start
193                .saturating_add(rel_end)
194                .saturating_add(end_tag.len());
195        } else {
196            results.push(rest.to_string());
197            break;
198        }
199    }
200
201    results.join(delim)
202}
203
204/// Extracts parameter attributes like `NAME="..."` or `NAME=...` from tagged parameter lines.
205#[must_use]
206pub fn tagparameterarray(params: &str, prefix: &str, delim: &str) -> String {
207    let mut results = Vec::new();
208    for line in params.split('\n') {
209        let trimmed = line.trim();
210        if let Some(idx) = trimmed.find(prefix) {
211            let rest = match trimmed.get(idx.saturating_add(prefix.len())..) {
212                Some(sub) => sub.trim(),
213                None => "",
214            };
215            if let Some(quoted) = rest.strip_prefix('"') {
216                if let Some(end_q) = quoted.find('"') {
217                    let sub = match quoted.get(..end_q) {
218                        Some(s) => s,
219                        None => "",
220                    };
221                    results.push(sub.to_string());
222                } else {
223                    results.push(quoted.to_string());
224                }
225            } else {
226                let unquoted = match rest.split_whitespace().next() {
227                    Some(u) => u,
228                    None => "",
229                };
230                results.push(unquoted.to_string());
231            }
232        }
233    }
234    results.join(delim)
235}
236
237/// Replaces all occurrences of `find` with `replacement` in `text`.
238#[must_use]
239pub fn replace(text: &str, find: &str, replacement: &str) -> String {
240    text.replace(find, replacement)
241}
242
243/// Replaces multiple target patterns with their replacements.
244#[must_use]
245pub fn replacemultiple(
246    text: &str,
247    find_list: &str,
248    repl_list: &str,
249    delim: &str,
250) -> String {
251    let finds: Vec<&str> = find_list.split(delim).collect();
252    let repls: Vec<&str> = repl_list.split(delim).collect();
253
254    let mut current = text.to_string();
255    for (i, find) in finds.iter().enumerate() {
256        if find.is_empty() {
257            continue;
258        }
259        let repl = match repls.get(i) {
260            Some(&r) => r,
261            None => "",
262        };
263        current = current.replace(find, repl);
264    }
265    current
266}
267
268/// Returns a newline carriage return string.
269#[must_use]
270pub fn cr() -> &'static str {
271    "\n"
272}
273
274/// Checks whether the running OS is Windows.
275#[must_use]
276pub fn oswindows() -> bool {
277    false
278}
279
280/// Formats a menu definition string.
281#[must_use]
282pub fn menu(name: &str) -> String {
283    format!("MENU:{name};")
284}
285
286/// Formats menu items string.
287#[must_use]
288pub fn menuitems(items: &str) -> String {
289    items.to_string()
290}
291
292/// Formats a checked array menu.
293#[must_use]
294pub fn checkedarraymenu(array: &str, checked_item: &str) -> String {
295    let mut items = Vec::new();
296    for item in array.split('\n') {
297        if item.is_empty() {
298            continue;
299        }
300        if item.eq_ignore_ascii_case(checked_item) {
301            items.push(format!("√{item}"));
302        } else {
303            items.push(item.to_string());
304        }
305    }
306    items.join(";")
307}
308
309/// Formats a column menu.
310#[must_use]
311pub fn columnmenu(name: &str) -> String {
312    format!("COLUMN:{name};")
313}
314
315/// Standard Panorama view menu definition.
316#[must_use]
317pub fn standardviewmenu() -> String {
318    "View:Data;Design;".to_string()
319}
320
321/// Standard Panorama edit menu definition.
322#[must_use]
323pub fn standardeditmenu() -> String {
324    "Edit:Undo;Cut;Copy;Paste;Clear;Select All;".to_string()
325}
326
327/// Standard Panorama fields menu definition.
328#[must_use]
329pub fn standardfieldsmenu() -> String {
330    "Fields:New Field;Delete Field;".to_string()
331}
332
333/// Standard Panorama search menu definition.
334#[must_use]
335pub fn standardsearchmenu() -> String {
336    "Search:Find;Find Next;Select;".to_string()
337}
338
339/// Standard Panorama sort menu definition.
340#[must_use]
341pub fn standardsortmenu() -> String {
342    "Sort:Sort Up;Sort Down;".to_string()
343}
344
345/// Standard Panorama math menu definition.
346#[must_use]
347pub fn standardmathmenu() -> String {
348    "Math:Total;Average;Count;".to_string()
349}
350
351/// Standard Panorama setup menu definition.
352#[must_use]
353pub fn standardsetupmenu() -> String {
354    "Setup:Database Options;".to_string()
355}
356
357/// Standard Panorama text menu definition.
358#[must_use]
359pub fn standardtextmenu() -> String {
360    "Text:Font;Size;Style;".to_string()
361}
362
363/// Look up a value from a database document.
364#[must_use]
365pub fn lookup(
366    document: &crate::parser::PanDocument,
367    key_field: &str,
368    key_val: &str,
369    result_field: &str,
370    default_val: &str,
371) -> String {
372    if let Some(data) = document.data.as_ref() {
373        for record in &data.records {
374            let match_found = record.fields.iter().any(|f| {
375                f.field_name.eq_ignore_ascii_case(key_field)
376                    && f.value
377                        .to_display_string()
378                        .trim()
379                        .eq_ignore_ascii_case(key_val.trim())
380            });
381            if match_found {
382                if let Some(res_field) = record
383                    .fields
384                    .iter()
385                    .find(|f| f.field_name.eq_ignore_ascii_case(result_field))
386                {
387                    return res_field.value.to_display_string();
388                }
389            }
390        }
391    }
392    default_val.to_string()
393}
394
395#[cfg(test)]
396#[allow(
397    clippy::panic,
398    clippy::expect_used,
399    clippy::unwrap_used,
400    clippy::unwrap_in_result,
401    clippy::panic_in_result_fn,
402    clippy::indexing_slicing,
403    clippy::arithmetic_side_effects,
404    reason = "Standard repository test boilerplate"
405)]
406mod tests {
407    use ctb_utilities::anyhow::ensure;
408
409    use super::*;
410
411    #[crate::ctb_test]
412    fn test_q() -> anyhow::Result<()> {
413        ensure!(q(true, "yes", "no") == "yes");
414        ensure!(q(false, "yes", "no") == "no");
415        Ok(())
416    }
417
418    #[crate::ctb_test]
419    fn test_tagdata() -> anyhow::Result<()> {
420        let xml = "<p>First</p><p>Second</p>";
421        ensure!(tagdata(xml, "<p>", "</p>", 1) == "First");
422        ensure!(tagdata(xml, "<p>", "</p>", 2) == "Second");
423        ensure!(tagdata(xml, "<p>", "</p>", 3).is_empty());
424        Ok(())
425    }
426
427    #[crate::ctb_test]
428    fn test_tagarray() -> anyhow::Result<()> {
429        let xml = "<item>A</item><item>B</item>";
430        ensure!(tagarray(xml, "<item>", "</item>", ",") == "A,B");
431        Ok(())
432    }
433
434    #[crate::ctb_test]
435    fn test_replacemultiple() -> anyhow::Result<()> {
436        let text = "Hello World";
437        let res = replacemultiple(text, "Hello,World", "Hi,Earth", ",");
438        ensure!(res == "Hi Earth");
439        Ok(())
440    }
441}