1#![allow(dead_code)]
3
4extern crate alloc;
5use alloc::format;
6use alloc::string::{String, ToString};
7use alloc::vec::Vec;
8
9#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum GoogleUrlType {
12 Home,
14 Search {
16 query: String,
17 start: usize,
18 },
19 Redirect {
21 target_url: String,
22 },
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct GoogleSearchResultItem {
28 pub title: String,
30 pub target_url: String,
32 pub display_url: String,
34 pub snippet: String,
36}
37
38impl GoogleSearchResultItem {
39 pub fn new(title: String, target_url: String, display_url: String, snippet: String) -> Self {
40 Self {
41 title,
42 target_url,
43 display_url,
44 snippet,
45 }
46 }
47
48 pub fn domain(&self) -> String {
50 let u = if !self.display_url.is_empty() {
51 &self.display_url
52 } else {
53 &self.target_url
54 };
55 let stripped = u
56 .strip_prefix("https://")
57 .or_else(|| u.strip_prefix("http://"))
58 .or_else(|| u.strip_prefix("//"))
59 .unwrap_or(u);
60 let host = stripped.split('/').next().unwrap_or(stripped);
61 let host = host.split('?').next().unwrap_or(host);
62 let host = host.strip_prefix("www.").unwrap_or(host);
63 host.to_string()
64 }
65
66 pub fn breadcrumb(&self) -> String {
68 let u = if !self.display_url.is_empty() {
69 &self.display_url
70 } else {
71 &self.target_url
72 };
73 let stripped = u
74 .strip_prefix("https://")
75 .or_else(|| u.strip_prefix("http://"))
76 .or_else(|| u.strip_prefix("//"))
77 .unwrap_or(u);
78 let mut parts = stripped.split('/').filter(|p| !p.is_empty());
79 let first = parts.next().unwrap_or("");
80 let domain = first.strip_prefix("www.").unwrap_or(first);
81 let mut bc = domain.to_string();
82 for p in parts.take(2) {
83 let clean_p = p.split('?').next().unwrap_or(p);
84 if !clean_p.is_empty() {
85 bc.push_str(" › ");
86 bc.push_str(clean_p);
87 }
88 }
89 if bc.is_empty() {
90 self.domain()
91 } else {
92 bc
93 }
94 }
95
96 pub fn favicon_letter(&self) -> char {
98 let dom = self.domain();
99 dom.chars()
100 .find(|c| c.is_alphanumeric())
101 .map(|c| c.to_ascii_uppercase())
102 .unwrap_or('G')
103 }
104
105 pub fn is_https(&self) -> bool {
107 self.target_url.starts_with("https://") || self.target_url.starts_with("//")
108 }
109}
110
111#[derive(Debug, Clone, PartialEq, Eq, Default)]
113pub struct GoogleKnowledgeCard {
114 pub title: String,
115 pub subtitle: String,
116 pub description: String,
117 pub attributes: Vec<(String, String)>,
118 pub source_url: String,
119 pub source_name: String,
120}
121
122impl GoogleKnowledgeCard {
123 pub fn is_empty(&self) -> bool {
124 self.title.is_empty() && self.description.is_empty()
125 }
126}
127
128#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct GoogleSearchPage {
131 pub query: String,
132 pub results: Vec<GoogleSearchResultItem>,
133 pub total_results_text: String,
134 pub search_time_sec: String,
135 pub knowledge: Option<GoogleKnowledgeCard>,
136 pub related_searches: Vec<String>,
137 pub start_offset: usize,
138}
139
140pub fn is_google_host(host: &str) -> bool {
143 let h = host.to_ascii_lowercase();
144 let clean_h = h.split(':').next().unwrap_or(&h);
145 clean_h == "google.com"
146 || clean_h == "www.google.com"
147 || clean_h == "google.co.jp"
148 || clean_h == "www.google.co.jp"
149 || clean_h == "m.google.com"
150 || clean_h == "encrypted.google.com"
151}
152
153pub fn parse_google_url(url: &str) -> Option<GoogleUrlType> {
156 let clean = url.trim();
157 if !clean.contains("google.com") && !clean.contains("google.co.jp") {
158 return None;
159 }
160
161 if clean.contains("/url?") {
163 if let Some(target) = extract_google_redirect_target(clean) {
164 return Some(GoogleUrlType::Redirect { target_url: target });
165 }
166 }
167
168 if clean.contains("/search") {
170 let q = extract_query_param(clean, "q").unwrap_or_default();
171 let start_str = extract_query_param(clean, "start").unwrap_or_default();
172 let start = start_str.parse::<usize>().unwrap_or(0);
173 return Some(GoogleUrlType::Search { query: q, start });
174 }
175
176 let without_scheme = clean
178 .strip_prefix("https://")
179 .or_else(|| clean.strip_prefix("http://"))
180 .unwrap_or(clean);
181 let parts: Vec<&str> = without_scheme.splitn(2, '/').collect();
182 let path = if parts.len() > 1 { parts[1] } else { "" };
183 let clean_path = path.split('?').next().unwrap_or(path);
184
185 if clean_path.is_empty() || clean_path == "webhp" {
186 if clean.contains("?q=") || clean.contains("&q=") {
188 let q = extract_query_param(clean, "q").unwrap_or_default();
189 let start = extract_query_param(clean, "start")
190 .and_then(|s| s.parse::<usize>().ok())
191 .unwrap_or(0);
192 return Some(GoogleUrlType::Search { query: q, start });
193 }
194 return Some(GoogleUrlType::Home);
195 }
196
197 None
198}
199
200pub fn extract_google_redirect_target(url: &str) -> Option<String> {
203 let path = url.split('?').next().unwrap_or(url);
204 if !path.ends_with("/url") && !url.contains("/url?") {
205 return None;
206 }
207 if let Some(q_val) = extract_query_param(url, "q") {
208 if !q_val.is_empty() {
209 return Some(q_val);
210 }
211 }
212 if let Some(url_val) = extract_query_param(url, "url") {
213 if !url_val.is_empty() {
214 return Some(url_val);
215 }
216 }
217 None
218}
219
220pub fn extract_query_param(url: &str, param: &str) -> Option<String> {
223 let query_part = url.split('?').nth(1)?;
224 for pair in query_part.split('&') {
225 let mut kv = pair.splitn(2, '=');
226 let key = kv.next()?;
227 if key == param {
228 let val = kv.next().unwrap_or("");
229 return Some(url_decode(val));
230 }
231 }
232 None
233}
234
235pub fn url_encode(input: &str) -> String {
238 let mut out = String::new();
239 for b in input.bytes() {
240 match b {
241 b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
242 out.push(b as char);
243 }
244 b' ' => out.push('+'),
245 _ => {
246 out.push_str(&format!("%{:02X}", b));
247 }
248 }
249 }
250 out
251}
252
253pub fn url_decode(input: &str) -> String {
256 let mut bytes = Vec::new();
257 let raw = input.as_bytes();
258 let mut i = 0;
259 while i < raw.len() {
260 if raw[i] == b'+' {
261 bytes.push(b' ');
262 i += 1;
263 } else if raw[i] == b'%' && i + 2 < raw.len() {
264 let h1 = raw[i + 1];
265 let h2 = raw[i + 2];
266 if let (Some(n1), Some(n2)) = (hex_val(h1), hex_val(h2)) {
267 bytes.push((n1 << 4) | n2);
268 i += 3;
269 } else {
270 bytes.push(raw[i]);
271 i += 1;
272 }
273 } else {
274 bytes.push(raw[i]);
275 i += 1;
276 }
277 }
278 String::from_utf8(bytes).unwrap_or_else(|_| input.to_string())
279}
280
281fn hex_val(b: u8) -> Option<u8> {
282 match b {
283 b'0'..=b'9' => Some(b - b'0'),
284 b'a'..=b'f' => Some(b - b'a' + 10),
285 b'A'..=b'F' => Some(b - b'A' + 10),
286 _ => None,
287 }
288}
289
290pub fn html_escape(input: &str) -> String {
293 let mut out = String::with_capacity(input.len());
294 for c in input.chars() {
295 match c {
296 '&' => out.push_str("&"),
297 '<' => out.push_str("<"),
298 '>' => out.push_str(">"),
299 '"' => out.push_str("""),
300 '\'' => out.push_str("'"),
301 _ => out.push(c),
302 }
303 }
304 out
305}
306
307pub fn strip_html_tags(input: &str) -> String {
310 let mut out = String::with_capacity(input.len());
311 let mut in_tag = false;
312 for c in input.chars() {
313 if c == '<' {
314 in_tag = true;
315 } else if c == '>' {
316 in_tag = false;
317 } else if !in_tag {
318 out.push(c);
319 }
320 }
321 let res = out
322 .replace(" ", " ")
323 .replace("&", "&")
324 .replace("<", "<")
325 .replace(">", ">")
326 .replace(""", "\"")
327 .replace("'", "'")
328 .replace("·", "·");
329 res.split_whitespace().collect::<Vec<_>>().join(" ")
330}
331
332pub fn parse_google_results(html: &str) -> Vec<GoogleSearchResultItem> {
335 let mut items = Vec::new();
336
337 let mut search_pos = 0;
341 while let Some(h3_start) = html.get(search_pos..).unwrap_or("").find("<h3") {
342 let abs_h3 = search_pos + h3_start;
343 search_pos = abs_h3 + 3;
344
345 let Some(tag_close) = html.get(abs_h3..).unwrap_or("").find('>') else { continue };
347 let content_start = abs_h3 + tag_close + 1;
348 let Some(h3_end) = html.get(content_start..).unwrap_or("").find("</h3>") else { continue };
349 let raw_title = html.get(content_start..content_start + h3_end).unwrap_or("");
350 let title = strip_html_tags(raw_title);
351 if title.is_empty() || title == "Featured snippet" || title == "People also ask" {
352 continue;
353 }
354
355 let check_window_start = html.ceil_char_boundary(abs_h3.saturating_sub(800));
357 let before_h3 = html.get(check_window_start..abs_h3).unwrap_or("");
358 let Some(a_pos) = before_h3.rfind("<a ") else { continue };
359 let a_snippet = before_h3.get(a_pos..).unwrap_or("");
360 let Some(href_pos) = a_snippet.find("href=\"") else { continue };
361 let href_start = href_pos + 6;
362 let Some(href_end) = a_snippet.get(href_start..).unwrap_or("").find('"') else { continue };
363 let raw_href = a_snippet.get(href_start..href_start + href_end).unwrap_or("");
364
365 let target_url = if raw_href.starts_with("/url?") {
367 extract_google_redirect_target(raw_href).unwrap_or_else(|| raw_href.to_string())
368 } else if raw_href.starts_with('/') {
369 format!("https://www.google.com{}", raw_href)
370 } else {
371 raw_href.to_string()
372 };
373
374 if !target_url.starts_with("http://") && !target_url.starts_with("https://") {
375 continue;
376 }
377 if target_url.contains("google.com/search") || target_url.contains("accounts.google.com") {
378 continue;
379 }
380
381 let after_h3_start = content_start + h3_end + 5;
383 let after_window_end = html.floor_char_boundary(after_h3_start + 1200);
384 let after_h3 = html.get(after_h3_start..after_window_end).unwrap_or("");
385
386 let snippet = extract_snippet_from_block(after_h3);
387 let display_url = target_url.clone();
388
389 let item = GoogleSearchResultItem::new(title, target_url, display_url, snippet);
390 if !items.iter().any(|existing: &GoogleSearchResultItem| existing.target_url == item.target_url) {
391 items.push(item);
392 }
393 }
394
395 items
396}
397
398fn extract_snippet_from_block(block: &str) -> String {
400 if let Some(div_pos) = block.find("class=\"VwiC3b") {
402 if let Some(close_tag) = block.get(div_pos..).unwrap_or("").find('>') {
403 let start = div_pos + close_tag + 1;
404 if let Some(end) = block.get(start..).unwrap_or("").find("</div>") {
405 let s = strip_html_tags(block.get(start..start + end).unwrap_or(""));
406 if !s.is_empty() {
407 return s;
408 }
409 }
410 }
411 }
412 for tag in &["<span class=\"aCOpRe\">", "<div class=\"s\">", "<span class=\"st\">"] {
414 if let Some(p) = block.find(tag) {
415 let start = p + tag.len();
416 if let Some(end) = block.get(start..).unwrap_or("").find('<') {
417 let s = strip_html_tags(block.get(start..start + end).unwrap_or(""));
418 if s.len() > 15 {
419 return s;
420 }
421 }
422 }
423 }
424 let plain = strip_html_tags(block);
426 if plain.len() > 20 {
427 let max_len = plain.floor_char_boundary(160);
428 plain.get(..max_len).unwrap_or("").to_string()
429 } else {
430 String::new()
431 }
432}
433
434pub fn parse_google_page(html: &str, query: &str, start_offset: usize) -> GoogleSearchPage {
437 let results = parse_google_results(html);
438 let knowledge = parse_google_knowledge_card(html, query);
439 let related = parse_google_related_searches(html);
440
441 let total_results_text = if results.is_empty() {
442 "約 0 件".to_string()
443 } else {
444 "約 12,800,000 件".to_string()
445 };
446 let search_time_sec = "0.24".to_string();
447
448 GoogleSearchPage {
449 query: query.to_string(),
450 results,
451 total_results_text,
452 search_time_sec,
453 knowledge,
454 related_searches: related,
455 start_offset,
456 }
457}
458
459pub fn parse_google_knowledge_card(html: &str, query: &str) -> Option<GoogleKnowledgeCard> {
462 if let Some(calc_pos) = html.find("class=\"qv3Wpe\"") {
464 if let Some(close_tag) = html.get(calc_pos..).unwrap_or("").find('>') {
465 let start = calc_pos + close_tag + 1;
466 if let Some(end) = html.get(start..).unwrap_or("").find("</span>") {
467 let ans = strip_html_tags(html.get(start..start + end).unwrap_or(""));
468 if !ans.is_empty() {
469 return Some(GoogleKnowledgeCard {
470 title: ans,
471 subtitle: format!("計算結果: {}", query),
472 description: "Google 電卓機能による即時計算".into(),
473 attributes: Vec::new(),
474 source_url: String::new(),
475 source_name: "Google Calculator".into(),
476 });
477 }
478 }
479 }
480 }
481
482 let kg_pos = html.find("data-attrid=\"title\"")
484 .or_else(|| html.find("class=\"kp-title\""));
485 if let Some(kg_pos) = kg_pos {
486 if let Some(close_tag) = html.get(kg_pos..).unwrap_or("").find('>') {
487 let start = kg_pos + close_tag + 1;
488 let end_pattern = if html.get(kg_pos..).unwrap_or("").starts_with("class=\"kp-title\"") { "</" } else { "</div>" };
489 if let Some(end) = html.get(start..).unwrap_or("").find(end_pattern) {
490 let title = strip_html_tags(html.get(start..start + end).unwrap_or(""));
491 if !title.is_empty() {
492 let subtitle = if let Some(sub_pos) = html.find("class=\"kp-subtitle\"") {
493 if let Some(c) = html.get(sub_pos..).unwrap_or("").find('>') {
494 let s = sub_pos + c + 1;
495 html.get(s..).unwrap_or("").find("</").map(|e| strip_html_tags(html.get(s..s + e).unwrap_or(""))).unwrap_or_default()
496 } else {
497 String::new()
498 }
499 } else {
500 "ナレッジグラフ".into()
501 };
502
503 let desc = if let Some(desc_pos) = html.find("class=\"kp-desc\"") {
504 if let Some(c) = html.get(desc_pos..).unwrap_or("").find('>') {
505 let s = desc_pos + c + 1;
506 html.get(s..).unwrap_or("").find("</").map(|e| strip_html_tags(html.get(s..s + e).unwrap_or(""))).unwrap_or_default()
507 } else {
508 String::new()
509 }
510 } else {
511 format!("{} に関する Google ナレッジパネル情報", query)
512 };
513
514 return Some(GoogleKnowledgeCard {
515 title,
516 subtitle,
517 description: desc,
518 attributes: Vec::new(),
519 source_url: String::new(),
520 source_name: "Google Knowledge Graph".into(),
521 });
522 }
523 }
524 }
525 }
526
527 if query.contains('+') || query.contains('-') || query.contains('*') || query.contains('/') {
529 if let Some(ans) = try_eval_simple_calc(query) {
530 return Some(GoogleKnowledgeCard {
531 title: ans.clone(),
532 subtitle: format!("{} =", query.trim()),
533 description: "AtmOS 内蔵計算エンジンによる即時回答".into(),
534 attributes: Vec::new(),
535 source_url: String::new(),
536 source_name: "Google Calculator".into(),
537 });
538 }
539 }
540
541 None
542}
543
544fn try_eval_simple_calc(expr: &str) -> Option<String> {
546 let clean: String = expr.chars().filter(|c| !c.is_whitespace()).collect();
547 if let Some(pos) = clean.find('+') {
548 let left: i64 = clean.get(..pos).unwrap_or("").parse().ok()?;
549 let right: i64 = clean.get(pos + 1..).unwrap_or("").parse().ok()?;
550 return Some((left + right).to_string());
551 }
552 if let Some(pos) = clean.rfind('-') {
553 if pos > 0 {
554 let left: i64 = clean.get(..pos).unwrap_or("").parse().ok()?;
555 let right: i64 = clean.get(pos + 1..).unwrap_or("").parse().ok()?;
556 return Some((left - right).to_string());
557 }
558 }
559 if let Some(pos) = clean.find('*') {
560 let left: i64 = clean.get(..pos).unwrap_or("").parse().ok()?;
561 let right: i64 = clean.get(pos + 1..).unwrap_or("").parse().ok()?;
562 return Some((left * right).to_string());
563 }
564 if let Some(pos) = clean.find('/') {
565 let left: i64 = clean.get(..pos).unwrap_or("").parse().ok()?;
566 let right: i64 = clean.get(pos + 1..).unwrap_or("").parse().ok()?;
567 if right != 0 {
568 return Some((left / right).to_string());
569 }
570 }
571 None
572}
573
574pub fn parse_google_related_searches(html: &str) -> Vec<String> {
577 let mut rel = Vec::new();
578 let mut pos = 0;
579 while let Some(find_pos) = html.get(pos..).unwrap_or("").find("class=\"s3v9rd") {
580 let abs_pos = pos + find_pos;
581 pos = abs_pos + 10;
582 if let Some(close_tag) = html.get(abs_pos..).unwrap_or("").find('>') {
583 let start = abs_pos + close_tag + 1;
584 if let Some(end) = html.get(start..).unwrap_or("").find("</div>") {
585 let text = strip_html_tags(html.get(start..start + end).unwrap_or(""));
586 if text.len() > 3 && text.len() < 40 && !rel.contains(&text) {
587 rel.push(text);
588 if rel.len() >= 6 {
589 break;
590 }
591 }
592 }
593 }
594 }
595 rel
596}
597
598pub fn get_mock_google_results(query: &str) -> Vec<GoogleSearchResultItem> {
601 let q = query.to_lowercase();
602 let mut items = Vec::new();
603
604 if q.contains("rust") {
605 items.push(GoogleSearchResultItem::new(
606 "Rust Programming Language".into(),
607 "https://www.rust-lang.org/".into(),
608 "https://www.rust-lang.org".into(),
609 "A language empowering everyone to build reliable and efficient software. Performance, reliability, productivity.".into(),
610 ));
611 items.push(GoogleSearchResultItem::new(
612 "The Rust Programming Language - The Rust Book".into(),
613 "https://doc.rust-lang.org/book/".into(),
614 "https://doc.rust-lang.org › book".into(),
615 "The Rust Programming Language, affectionately nicknamed 'the book,' will give you an overview of the language from first principles.".into(),
616 ));
617 items.push(GoogleSearchResultItem::new(
618 "Rust (プログラミング言語) - Wikipedia".into(),
619 "https://ja.wikipedia.org/wiki/Rust_(%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0%E8%A8%80%E8%AA%9E)".into(),
620 "https://ja.wikipedia.org › wiki › Rust_(プログラミング言語)".into(),
621 "Rust(ラスト)は、性能、メモリ安全性、安全な並行性を目指して設計されたマルチパラダイムの汎用プログラミング言語である。".into(),
622 ));
623 } else if q.contains("atmos") || q.contains("sugimura") {
624 items.push(GoogleSearchResultItem::new(
625 "AtmOS - Bare-Metal ARM64 Operating System".into(),
626 "https://www.sugi-lab.net/".into(),
627 "https://www.sugi-lab.net".into(),
628 "AtmOS: 自作ベアメタル ARM64 オペレーティングシステム。独自 Web エンジン、H.264 デコーダ、ファイルシステムを完全内蔵。".into(),
629 ));
630 items.push(GoogleSearchResultItem::new(
631 "Sugimura Laboratory (杉村研究室)".into(),
632 "https://www.sugi-lab.net/research".into(),
633 "https://www.sugi-lab.net › research".into(),
634 "コンピュータアーキテクチャ・組み込みOS・ネットワークに関する研究と教育を行っています。".into(),
635 ));
636 } else if q.contains("youtube") {
637 items.push(GoogleSearchResultItem::new(
638 "YouTube - ホーム".into(),
639 "https://www.youtube.com/".into(),
640 "https://www.youtube.com".into(),
641 "YouTube でお気に入りの動画や音楽を楽しみ、オリジナルのコンテンツをアップロードして友だちや家族、世界中の人たちと共有しましょう。".into(),
642 ));
643 items.push(GoogleSearchResultItem::new(
644 "YouTube (AtmOS ベアメタル再生テスト)".into(),
645 "https://www.youtube.com/watch?v=aqz-KE-bpKQ".into(),
646 "https://www.youtube.com › watch".into(),
647 "Big Buck Bunny - H.264 / AAC ベアメタルデコーダによるリアルタイム同期動画再生テスト。".into(),
648 ));
649 } else {
650 items.push(GoogleSearchResultItem::new(
651 format!("{} に関する情報と最新ニュース", query),
652 format!("https://example.com/search?q={}", url_encode(query)),
653 format!("https://example.com › {}", url_encode(query)),
654 format!("{} についての包括的な解説、公式ドキュメント、最新のトピックと関連情報をまとめてお届けします。", query),
655 ));
656 items.push(GoogleSearchResultItem::new(
657 format!("{} の概要と詳細解説 - Web Encyclopedia", query),
658 format!("https://ja.wikipedia.org/wiki/{}", url_encode(query)),
659 format!("https://ja.wikipedia.org › wiki › {}", url_encode(query)),
660 format!("フリー百科事典による {} の定義、歴史、特徴、および主要なトピックの解説です。", query),
661 ));
662 items.push(GoogleSearchResultItem::new(
663 format!("{} 公式リソース・リファレンスガイド", query),
664 format!("https://www.sugi-lab.net/search?q={}", url_encode(query)),
665 "https://www.sugi-lab.net".into(),
666 format!("AtmOS 独自 Web エンジンによって高速かつ安全にインデックスされた {} の公式検索結果です。", query),
667 ));
668 }
669
670 items
671}
672
673pub fn generate_google_home_html() -> String {
676 r#"<!DOCTYPE html>
677<html>
678<head>
679<meta charset="utf-8">
680<title>Google</title>
681<style>
682body {
683 background-color: #202124;
684 color: #bdc1c6;
685 font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
686 margin: 0;
687 padding: 0;
688 display: flex;
689 flex-direction: column;
690 min-height: 100vh;
691}
692.header-nav {
693 display: flex;
694 justify-content: flex-end;
695 padding: 16px 24px;
696 gap: 16px;
697 font-size: 13px;
698}
699.nav-link {
700 color: #e8eaed;
701 text-decoration: none;
702}
703.nav-link:hover {
704 text-decoration: underline;
705}
706.center-container {
707 display: flex;
708 flex-direction: column;
709 align-items: center;
710 justify-content: center;
711 flex: 1;
712 padding-bottom: 120px;
713}
714.logo-wrap {
715 margin-bottom: 28px;
716 user-select: none;
717}
718.g-logo {
719 font-size: 72px;
720 font-weight: bold;
721 letter-spacing: -2px;
722}
723.c-blue { color: #4285F4; }
724.c-red { color: #EA4335; }
725.c-yellow { color: #FBBC05; }
726.c-green { color: #34A853; }
727
728.search-box-wrap {
729 width: 100%;
730 max-width: 584px;
731 margin-bottom: 28px;
732}
733.search-form {
734 display: flex;
735 align-items: center;
736 background-color: #202124;
737 border: 1px solid #5f6368;
738 border-radius: 24px;
739 padding: 10px 16px;
740 box-shadow: 0 1px 6px rgba(0, 0, 0, 0.28);
741}
742.search-icon {
743 color: #9aa0a6;
744 margin-right: 12px;
745 font-size: 16px;
746}
747.search-input {
748 flex: 1;
749 background: transparent;
750 border: none;
751 color: #e8eaed;
752 font-size: 16px;
753 outline: none;
754}
755.buttons-wrap {
756 display: flex;
757 gap: 12px;
758}
759.btn-action {
760 background-color: #303134;
761 border: 1px solid #303134;
762 color: #e8eaed;
763 padding: 10px 16px;
764 border-radius: 4px;
765 font-size: 14px;
766 cursor: pointer;
767 text-decoration: none;
768}
769.btn-action:hover {
770 border: 1px solid #5f6368;
771}
772.footer-bar {
773 background-color: #171717;
774 padding: 14px 24px;
775 font-size: 14px;
776 color: #9aa0a6;
777 border-top: 1px solid #212327;
778 display: flex;
779 justify-content: space-between;
780}
781</style>
782</head>
783<body>
784<div class="header-nav">
785 <a href="https://www.google.com/search?q=AtmOS" class="nav-link">AtmOS Web</a>
786 <a href="https://www.youtube.com/" class="nav-link">YouTube</a>
787 <a href="https://duckduckgo.com/" class="nav-link">DuckDuckGo</a>
788</div>
789
790<div class="center-container">
791 <div class="logo-wrap">
792 <span class="g-logo">
793 <span class="c-blue">G</span><span class="c-red">o</span><span class="c-yellow">o</span><span class="c-blue">g</span><span class="c-green">l</span><span class="c-red">e</span>
794 </span>
795 </div>
796
797 <div class="search-box-wrap">
798 <form class="search-form" action="https://www.google.com/search" method="GET">
799 <span class="search-icon">🔍</span>
800 <input type="text" name="q" class="search-input" placeholder="" autofocus autocomplete="off">
801 </form>
802 </div>
803
804 <div class="buttons-wrap">
805 <button class="btn-action" onclick="document.forms[0].submit()">Google 検索</button>
806 <a href="https://www.google.com/search?q=AtmOS+Raspberry+Pi" class="btn-action">I'm Feeling Lucky</a>
807 </div>
808</div>
809
810<div class="footer-bar">
811 <div>日本 • AtmOS Bare-Metal OS (ARM64)</div>
812 <div>プライバシー • 規約 • 設定</div>
813</div>
814</body>
815</html>"#
816 .to_string()
817}
818
819pub fn generate_google_page_html(page: &GoogleSearchPage) -> String {
822 let q_escaped = html_escape(&page.query);
823 let q_encoded = url_encode(&page.query);
824
825 let mut cards_html = String::new();
826
827 if let Some(ref kg) = page.knowledge {
829 let kg_title = html_escape(&kg.title);
830 let kg_subtitle = html_escape(&kg.subtitle);
831 let kg_desc = html_escape(&kg.description);
832 let mut attrs_html = String::new();
833 for (k, v) in &kg.attributes {
834 attrs_html.push_str(&format!(
835 r#"<div class="kg-attr-row"><span class="kg-attr-k">{}</span>: <span class="kg-attr-v">{}</span></div>"#,
836 html_escape(k),
837 html_escape(v)
838 ));
839 }
840 cards_html.push_str(&format!(
841 r#"<div class="knowledge-card">
842 <div class="kg-header">
843 <div class="kg-title">{title}</div>
844 <div class="kg-subtitle">{subtitle}</div>
845 </div>
846 <div class="kg-desc">{desc}</div>
847 <div class="kg-attrs">{attrs}</div>
848 <div class="kg-source">情報提供: {source}</div>
849</div>"#,
850 title = kg_title,
851 subtitle = kg_subtitle,
852 desc = kg_desc,
853 attrs = attrs_html,
854 source = html_escape(&kg.source_name),
855 ));
856 }
857
858 if page.results.is_empty() {
860 cards_html.push_str(&format!(
861 r#"<div class="no-results">
862 <div style="font-size: 18px; color: #e8eaed; margin-bottom: 12px;">「{}」に一致する情報は見つかりませんでした。</div>
863 <ul style="color: #9aa0a6; line-height: 1.6;">
864 <li>キーワードに誤字・脱字がないか確認します。</li>
865 <li>別のキーワードを試してみます。</li>
866 <li>より一般的なキーワードを指定します。</li>
867 </ul>
868</div>"#,
869 q_escaped
870 ));
871 } else {
872 for item in &page.results {
873 let t_escaped = html_escape(&item.title);
874 let s_escaped = html_escape(&item.snippet);
875 let target_url = html_escape(&item.target_url);
876 let bc_escaped = html_escape(&item.breadcrumb());
877 let fav_letter = item.favicon_letter();
878
879 cards_html.push_str(&format!(
880 r#"<div class="result-card">
881 <div class="site-header">
882 <span class="favicon-pill">{fav}</span>
883 <span class="breadcrumb">{bc}</span>
884 </div>
885 <div class="title-wrap">
886 <a href="{url}" class="result-title">{title}</a>
887 </div>
888 <div class="snippet">{snippet}</div>
889</div>"#,
890 fav = fav_letter,
891 bc = bc_escaped,
892 url = target_url,
893 title = t_escaped,
894 snippet = s_escaped,
895 ));
896 }
897 }
898
899 let mut related_html = String::new();
901 if !page.related_searches.is_empty() {
902 let mut pills = String::new();
903 for rel in &page.related_searches {
904 pills.push_str(&format!(
905 r#"<a href="https://www.google.com/search?q={u}" class="related-pill">🔍 {t}</a>"#,
906 u = url_encode(rel),
907 t = html_escape(rel)
908 ));
909 }
910 related_html = format!(
911 r#"<div class="related-section">
912 <div class="related-title">関連する検索キーワード</div>
913 <div class="related-pills">{pills}</div>
914</div>"#,
915 pills = pills
916 );
917 }
918
919 let cur_page = (page.start_offset / 10) + 1;
921 let mut pager_html = String::new();
922 pager_html.push_str("<div class=\"pager-wrap\">");
923 for p in 1..=5 {
924 let p_start = (p - 1) * 10;
925 if p == cur_page {
926 pager_html.push_str(&format!(r#"<span class="pager-item active">{}</span>"#, p));
927 } else {
928 pager_html.push_str(&format!(
929 r#"<a href="https://www.google.com/search?q={}&start={}" class="pager-item">{}</a>"#,
930 q_encoded, p_start, p
931 ));
932 }
933 }
934 pager_html.push_str("</div>");
935
936 format!(
937 r#"<!DOCTYPE html>
938<html>
939<head>
940<meta charset="utf-8">
941<title>{q} - Google 検索</title>
942<style>
943body {{
944 background-color: #202124;
945 color: #bdc1c6;
946 font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
947 margin: 0;
948 padding: 0;
949}}
950.top-bar {{
951 background-color: #202124;
952 border-bottom: 1px solid #303134;
953 padding: 12px 24px;
954 display: flex;
955 align-items: center;
956 position: sticky;
957 top: 0;
958 z-index: 100;
959}}
960.logo-small {{
961 font-size: 24px;
962 font-weight: bold;
963 letter-spacing: -1px;
964 text-decoration: none;
965 margin-right: 28px;
966}}
967.c-blue {{ color: #4285F4; }}
968.c-red {{ color: #EA4335; }}
969.c-yellow {{ color: #FBBC05; }}
970.c-green {{ color: #34A853; }}
971
972.search-box {{
973 flex: 1;
974 max-width: 650px;
975 background-color: #303134;
976 border-radius: 24px;
977 padding: 8px 18px;
978 display: flex;
979 align-items: center;
980}}
981.search-box-input {{
982 flex: 1;
983 background: transparent;
984 border: none;
985 color: #e8eaed;
986 font-size: 15px;
987 outline: none;
988}}
989.search-box-btn {{
990 background: transparent;
991 border: none;
992 color: #8ab4f8;
993 font-size: 16px;
994 cursor: pointer;
995}}
996.meta-info {{
997 max-width: 652px;
998 margin: 12px auto 8px 180px;
999 font-size: 13px;
1000 color: #9aa0a6;
1001}}
1002.main-col {{
1003 max-width: 652px;
1004 margin-left: 180px;
1005 padding-bottom: 60px;
1006}}
1007.knowledge-card {{
1008 background-color: #303134;
1009 border: 1px solid #3c4043;
1010 border-radius: 12px;
1011 padding: 18px;
1012 margin-bottom: 24px;
1013}}
1014.kg-title {{
1015 font-size: 26px;
1016 font-weight: bold;
1017 color: #e8eaed;
1018 margin-bottom: 4px;
1019}}
1020.kg-subtitle {{
1021 font-size: 14px;
1022 color: #9aa0a6;
1023 margin-bottom: 12px;
1024}}
1025.kg-desc {{
1026 font-size: 14px;
1027 line-height: 1.6;
1028 color: #e8eaed;
1029 margin-bottom: 12px;
1030}}
1031.kg-source {{
1032 font-size: 12px;
1033 color: #9aa0a6;
1034 border-top: 1px solid #3c4043;
1035 padding-top: 8px;
1036}}
1037.result-card {{
1038 margin-bottom: 28px;
1039}}
1040.site-header {{
1041 display: flex;
1042 align-items: center;
1043 gap: 8px;
1044 margin-bottom: 4px;
1045}}
1046.favicon-pill {{
1047 display: inline-flex;
1048 align-items: center;
1049 justify-content: center;
1050 width: 22px;
1051 height: 22px;
1052 background-color: #3c4043;
1053 color: #e8eaed;
1054 border-radius: 50%;
1055 font-size: 11px;
1056 font-weight: bold;
1057}}
1058.breadcrumb {{
1059 font-size: 13px;
1060 color: #dadce0;
1061}}
1062.title-wrap {{
1063 margin-bottom: 4px;
1064}}
1065.result-title {{
1066 color: #8ab4f8;
1067 font-size: 19px;
1068 line-height: 1.35;
1069 text-decoration: none;
1070}}
1071.result-title:hover {{
1072 text-decoration: underline;
1073}}
1074.snippet {{
1075 font-size: 14px;
1076 line-height: 1.58;
1077 color: #bdc1c6;
1078}}
1079.related-section {{
1080 margin-top: 36px;
1081 border-top: 1px solid #3c4043;
1082 padding-top: 20px;
1083}}
1084.related-title {{
1085 font-size: 18px;
1086 font-weight: bold;
1087 color: #e8eaed;
1088 margin-bottom: 14px;
1089}}
1090.related-pills {{
1091 display: flex;
1092 flex-wrap: wrap;
1093 gap: 10px;
1094}}
1095.related-pill {{
1096 background-color: #303134;
1097 color: #e8eaed;
1098 padding: 8px 14px;
1099 border-radius: 20px;
1100 font-size: 14px;
1101 text-decoration: none;
1102}}
1103.related-pill:hover {{
1104 background-color: #3c4043;
1105}}
1106.pager-wrap {{
1107 display: flex;
1108 gap: 14px;
1109 margin-top: 40px;
1110 align-items: center;
1111}}
1112.pager-item {{
1113 color: #8ab4f8;
1114 font-size: 15px;
1115 text-decoration: none;
1116 padding: 6px 12px;
1117 border-radius: 4px;
1118}}
1119.pager-item.active {{
1120 background-color: #303134;
1121 color: #ffffff;
1122 font-weight: bold;
1123}}
1124</style>
1125</head>
1126<body>
1127<div class="top-bar">
1128 <a href="https://www.google.com/" class="logo-small">
1129 <span class="c-blue">G</span><span class="c-red">o</span><span class="c-yellow">o</span><span class="c-blue">g</span><span class="c-green">l</span><span class="c-red">e</span>
1130 </a>
1131 <form class="search-box" action="https://www.google.com/search" method="GET">
1132 <input type="text" name="q" class="search-box-input" value="{q}">
1133 <input type="submit" value="🔍" class="search-box-btn">
1134 </form>
1135</div>
1136
1137<div class="meta-info">
1138 {total} ({time} 秒)
1139</div>
1140
1141<div class="main-col">
1142 {cards}
1143 {related}
1144 {pager}
1145</div>
1146</body>
1147</html>"#,
1148 q = q_escaped,
1149 total = page.total_results_text,
1150 time = page.search_time_sec,
1151 cards = cards_html,
1152 related = related_html,
1153 pager = pager_html
1154 )
1155}
1156
1157pub fn get_mock_suggestions(query: &str) -> Vec<String> {
1160 let q = query.trim().to_ascii_lowercase();
1161 if q.is_empty() {
1162 return Vec::new();
1163 }
1164
1165 static DICTIONARY: &[&str] = &[
1166 "google",
1167 "google search",
1168 "google maps",
1169 "google translate",
1170 "rust",
1171 "rust programming",
1172 "rust lang",
1173 "rust cargo",
1174 "rust compiler",
1175 "raspberry pi",
1176 "raspberry pi 3b",
1177 "raspberry pi 4",
1178 "raspberry pi os",
1179 "operating system",
1180 "os kernel development",
1181 "atmos",
1182 "atmos operating system",
1183 "atmos web engine",
1184 "atmos browser",
1185 "youtube",
1186 "duckduckgo",
1187 "calculator",
1188 ];
1189
1190 let mut suggestions = Vec::new();
1191 for &entry in DICTIONARY {
1192 if entry.starts_with(&q) && entry != q {
1193 suggestions.push(entry.to_string());
1194 }
1195 }
1196 for &entry in DICTIONARY {
1197 if !entry.starts_with(&q) && entry.contains(&q) && entry != q && !suggestions.iter().any(|s| s == entry) {
1198 suggestions.push(entry.to_string());
1199 }
1200 }
1201 suggestions
1202}
1203