Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Apps/ORIXMaps/Sources/Search/SearchModel.swift10// Module : Search11// Repository : https://git.spboucher.ai/orix-maps12// Created : 2026-11-2513// Last Modified : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import Observation90import ORIXGeoCore91import ORIXMapRenderer92import ORIXMapStyle93import ORIXPrivacy94import ORIXSearch9596/// Offline search over the installed regions: suggestions while typing, full search, categories, reverse geocoding.97@Observable98final class SearchModel {99 private(set) var results: [SearchResult] = []100 private(set) var corrections: [TermCorrection] = []101 private(set) var matchedCategory: PlaceCategory?102 private(set) var isSearching = false103 /// Text of the query the current results answer.104 private(set) var answeredQuery = ""105 /// Regions whose search index is open, with the date of their data.106 private(set) var indexes: [SearchIndexInfo] = []107108 @ObservationIgnored private let engine = SearchEngine()109 @ObservationIgnored private var task: Task<Void, Never>?110 @ObservationIgnored private weak var map: MapController?111112 private static let log = PrivacyLog(category: "search")113114 init(map: MapController) { self.map = map }115116 var hasIndex: Bool { !indexes.isEmpty }117118 /// Opens the indexes of the installed regions and closes those of removed ones.119 func setRegions(_ regions: [MapRegion]) {120 Task { [engine] in121 await engine.closeAll()122 for r in regions {123 guard let url = r.searchURL else { continue }124 do { _ = try await engine.openIndex(at: url) } catch { Self.log.error("search index of \(r.id) not opened: \(String(describing: error))") }125 }126 self.indexes = await engine.openIndexes127 }128 }129130 /// Runs a query, cancelling the previous one. `full` = the user pressed Search (more results, typo correction).131 func update(text: String, full: Bool) {132 task?.cancel()133 let query = text.trimmingCharacters(in: .whitespacesAndNewlines)134 guard !query.isEmpty else { clear(); return }135 let focus = map?.camera.center, viewport = map?.visibleBounds136 isSearching = true137 task = Task { [engine] in138 // Typing: wait a moment so that every keystroke does not start a search.139 if !full { try? await Task.sleep(for: .milliseconds(120)) }140 guard !Task.isCancelled else { return }141 let response: SearchResponse?142 if full { response = try? await engine.search(SearchQuery(text: query, mode: .full, focus: focus, viewport: viewport, limit: 30)) }143 else { response = try? await engine.suggest(query, focus: focus, viewport: viewport, limit: 10) }144 guard !Task.isCancelled else { return }145 var list = response?.results ?? []146 // A typed coordinate is always a valid answer, even with no index.147 if let c = CoordinateText.parse(query), !list.contains(where: { $0.kind == .coordinate }) { list.insert(.coordinate(c), at: 0) }148 self.results = list149 self.corrections = response?.corrections ?? []150 self.matchedCategory = response?.matchedCategory151 self.answeredQuery = query152 self.isSearching = false153 if full { self.drawResults() }154 }155 }156157 /// Places of a category around the centre of the map.158 func search(category: PlaceCategory) {159 task?.cancel()160 let focus = map?.camera.center, viewport = map?.visibleBounds161 isSearching = true162 task = Task { [engine] in163 let found = (try? await engine.pointsOfInterest(categories: [category], focus: focus, viewport: viewport, limit: 40)) ?? []164 guard !Task.isCancelled else { return }165 self.results = found166 self.corrections = []167 self.matchedCategory = category168 self.answeredQuery = ""169 self.isSearching = false170 self.drawResults()171 }172 }173174 /// Places of several categories around the centre of the map, nearest first (Explorer).175 func explore(_ categories: Set<PlaceCategory>) async -> [SearchResult] {176 let focus = map?.camera.center177 let found = (try? await engine.pointsOfInterest(categories: categories, focus: focus, viewport: nil, limit: 60)) ?? []178 return found.filter { !$0.name.isEmpty || $0.category == .viewpoint }.sorted { ($0.distance ?? .infinity) < ($1.distance ?? .infinity) }179 }180181 func clear() {182 task?.cancel()183 results = []; corrections = []; matchedCategory = nil; answeredQuery = ""; isSearching = false184 map?.setOverlay(OverlayID.searchResults, features: [])185 }186187 private func drawResults() {188 let features = results.filter { $0.kind == .poi || $0.kind == .address }.map { OverlayFeature(.point($0.coordinate), properties: ["title": .string($0.name), "id": .string($0.id)]) }189 map?.setOverlay(OverlayID.searchResults, features: features)190 if results.count > 1, let box = BoundingBox(enclosing: results.prefix(15).map(\.coordinate)) { map?.fit(box.expanded(byMeters: 150), maxZoom: 16) }191 }192193 /// The nearest address, street or place of a coordinate, from the installed regions only.194 func reverse(_ c: Coordinate) async -> ReverseGeocodeResult? {195 guard hasIndex, case .found(let r)? = try? await engine.reverseGeocode(c, maxDistance: 120) else { return nil }196 return r197 }198199 /// A point of interest of the index matching a feature tapped on the map (same name within 60 m), to show its address and category.200 func lookup(name: String, near c: Coordinate) async -> SearchResult? {201 guard hasIndex, let response = try? await engine.search(SearchQuery(text: name, mode: .full, focus: c, limit: 5)) else { return nil }202 return response.results.first { Geodesy.fastDistance($0.coordinate, c) < 60 }203 }204}205206extension SearchResult {207 var symbol: String {208 switch kind {209 case .coordinate: "scope"210 case .place: placeType?.symbolName ?? "building.2"211 case .poi: category?.symbolName ?? "mappin"212 case .street: streetClass?.symbolName ?? "road.lanes"213 case .address: "house"214 }215 }216217 func selection(language: String) -> PlaceSelection {218 var subtitle = secondaryLine219 if kind == .poi, let category { subtitle = [category.label(languageCode: language), subtitle].filter { !$0.isEmpty }.joined(separator: " · ") }220 return PlaceSelection(title: name, subtitle: subtitle.isEmpty ? nil : subtitle, coordinate: coordinate, origin: kind == .coordinate ? .coordinates : .search, category: category?.rawValue)221 }222}223