Skip to main content

atmos/os_lib/web_engine/
omnibox.rs

1// src/os_lib/web_engine/omnibox.rs - Omnibox (Smart Address Bar) Suggestions & Bookmarks
2#![allow(dead_code)]
3
4extern crate alloc;
5use alloc::string::String;
6use alloc::vec::Vec;
7
8/// Omnibox 候補の種別
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum OmniboxItemKind {
11    /// ブックマーク(お気に入り登録済み)
12    Bookmark,
13    /// 閲覧履歴
14    History,
15    /// Web 検索候補 (DuckDuckGo)
16    Search,
17}
18
19impl OmniboxItemKind {
20    pub fn badge_label(&self) -> &'static str {
21        match self {
22            OmniboxItemKind::Bookmark => "Bookmark",
23            OmniboxItemKind::History => "History",
24            OmniboxItemKind::Search => "Search",
25        }
26    }
27
28    pub fn icon_char(&self) -> &'static str {
29        match self {
30            OmniboxItemKind::Bookmark => "*",
31            OmniboxItemKind::History => ">",
32            OmniboxItemKind::Search => "?",
33        }
34    }
35}
36
37/// Omnibox サジェスト項目
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct OmniboxItem {
40    pub title: String,
41    pub url: String,
42    pub kind: OmniboxItemKind,
43}
44
45/// ブックマーク項目
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Bookmark {
48    pub title: String,
49    pub url: String,
50}
51
52/// 閲覧履歴項目
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct HistoryEntry {
55    pub title: String,
56    pub url: String,
57    pub visit_count: u32,
58}
59
60/// Omnibox サジェスト・ブックマーク・履歴管理エンジン(純粋ロジック)
61#[derive(Debug, Clone)]
62pub struct OmniboxEngine {
63    pub bookmarks: Vec<Bookmark>,
64    pub history: Vec<HistoryEntry>,
65}
66
67impl Default for OmniboxEngine {
68    fn default() -> Self {
69        Self::new()
70    }
71}
72
73impl OmniboxEngine {
74    pub fn new() -> Self {
75        let mut engine = Self {
76            bookmarks: Vec::new(),
77            history: Vec::new(),
78        };
79
80        // デフォルトの組み込みブックマーク
81        engine.add_bookmark("AtmOS Home", "http://localhost/home");
82        // そのほかの既定のブックマークはサイト別の対応が決める(`site_hooks::default_bookmarks`)。
83        for (title, url) in super::site_hooks::hooks().default_bookmarks() {
84            engine.add_bookmark(title, url);
85        }
86
87        engine
88    }
89
90    /// ブックマーク追加(既に同一 URL があればタイトル更新して true を返す)
91    pub fn add_bookmark(&mut self, title: &str, url: &str) -> bool {
92        let clean_url = url.trim();
93        if clean_url.is_empty() {
94            return false;
95        }
96
97        if let Some(existing) = self.bookmarks.iter_mut().find(|b| urls_match(&b.url, clean_url)) {
98            existing.title = title.trim().into();
99            return false;
100        }
101
102        self.bookmarks.push(Bookmark {
103            title: title.trim().into(),
104            url: clean_url.into(),
105        });
106        true
107    }
108
109    /// ブックマーク削除
110    pub fn remove_bookmark(&mut self, url: &str) -> bool {
111        let clean_url = url.trim();
112        let initial_len = self.bookmarks.len();
113        self.bookmarks.retain(|b| !urls_match(&b.url, clean_url));
114        self.bookmarks.len() < initial_len
115    }
116
117    /// ブックマーク登録状態の確認
118    pub fn is_bookmarked(&self, url: &str) -> bool {
119        let clean = url.trim();
120        self.bookmarks.iter().any(|b| urls_match(&b.url, clean))
121    }
122
123    /// ブックマーク登録のトグル(未登録なら追加、登録済みなら削除)
124    pub fn toggle_bookmark(&mut self, title: &str, url: &str) -> bool {
125        if self.is_bookmarked(url) {
126            self.remove_bookmark(url);
127            false
128        } else {
129            self.add_bookmark(title, url);
130            true
131        }
132    }
133
134    /// ページ訪問履歴を記録
135    pub fn record_visit(&mut self, title: &str, url: &str) {
136        let clean_url = url.trim();
137        if clean_url.is_empty() || clean_url == "about:blank" {
138            return;
139        }
140
141        // 既存エントリがあれば最前列に移動してカウント増加
142        if let Some(pos) = self.history.iter().position(|h| h.url == clean_url) {
143            let mut entry = self.history.remove(pos);
144            entry.visit_count = entry.visit_count.saturating_add(1);
145            if !title.trim().is_empty() {
146                entry.title = title.trim().into();
147            }
148            self.history.insert(0, entry);
149            return;
150        }
151
152        // 新規エントリを先頭に挿入
153        self.history.insert(0, HistoryEntry {
154            title: title.trim().into(),
155            url: clean_url.into(),
156            visit_count: 1,
157        });
158
159        // 履歴上限(最新 100 件)
160        if self.history.len() > 100 {
161            self.history.truncate(100);
162        }
163    }
164
165    /// 入力クエリに対する統合サジェスト候補を生成
166    ///
167    /// 優先順位:
168    /// 1. ブックマーク(タイトルまたは URL にクエリが含まれるもの)
169    /// 2. 閲覧履歴(訪問回数および直近順)
170    /// 3. Web 検索候補 (DuckDuckGo サジェスト)
171    pub fn get_suggestions(
172        &self,
173        query: &str,
174        search_suggestions: &[String],
175        max_items: usize,
176    ) -> Vec<OmniboxItem> {
177        let q = query.trim().to_ascii_lowercase();
178        let mut results = Vec::new();
179
180        if q.is_empty() {
181            // 空クエリ時は主要ブックマークを提示
182            for b in self.bookmarks.iter().take(max_items) {
183                results.push(OmniboxItem {
184                    title: b.title.clone(),
185                    url: b.url.clone(),
186                    kind: OmniboxItemKind::Bookmark,
187                });
188            }
189            return results;
190        }
191
192        // 先頭の語(`yt <query>` など)による直接のサジェスト(サイト別の対応)。
193        if let Some((title, url)) = super::site_hooks::hooks().omnibox_prefix_suggestion(&q) {
194            results.push(OmniboxItem {
195                title,
196                url,
197                kind: OmniboxItemKind::Search,
198            });
199        }
200
201        // 1. ブックマーク検索
202        for b in &self.bookmarks {
203            let t_lower = b.title.to_ascii_lowercase();
204            let u_lower = b.url.to_ascii_lowercase();
205            if t_lower.contains(&q) || u_lower.contains(&q) {
206                results.push(OmniboxItem {
207                    title: b.title.clone(),
208                    url: b.url.clone(),
209                    kind: OmniboxItemKind::Bookmark,
210                });
211                if results.len() >= max_items {
212                    return results;
213                }
214            }
215        }
216
217        // 2. 閲覧履歴検索(ブックマークと重複しないもの)
218        for h in &self.history {
219            let t_lower = h.title.to_ascii_lowercase();
220            let u_lower = h.url.to_ascii_lowercase();
221            if (t_lower.contains(&q) || u_lower.contains(&q))
222                && !results.iter().any(|r| r.url == h.url) {
223                    let disp_title = if h.title.is_empty() {
224                        h.url.clone()
225                    } else {
226                        h.title.clone()
227                    };
228                    results.push(OmniboxItem {
229                        title: disp_title,
230                        url: h.url.clone(),
231                        kind: OmniboxItemKind::History,
232                    });
233                    if results.len() >= max_items {
234                        return results;
235                    }
236                }
237        }
238
239        // 3. Web 検索サジェスト
240        for s in search_suggestions {
241            if !results.iter().any(|r| r.title.eq_ignore_ascii_case(s)) {
242                let search_url = super::site_hooks::hooks().search_suggestion_url(s);
243                results.push(OmniboxItem {
244                    title: s.clone(),
245                    url: search_url,
246                    kind: OmniboxItemKind::Search,
247                });
248                if results.len() >= max_items {
249                    return results;
250                }
251            }
252        }
253
254        results
255    }
256}
257
258/// URL の末尾スラッシュの違いを許容して比較
259fn urls_match(u1: &str, u2: &str) -> bool {
260    let s1 = u1.trim().trim_end_matches('/');
261    let s2 = u2.trim().trim_end_matches('/');
262    s1.eq_ignore_ascii_case(s2)
263}