625 lines · 27.6 KB · SwiftRaw
// Cotton Notes, the writing app (notes-new-ios): what the phone asks the// core (`notes.*`, `shapes.md`) and the shapes it is// answered in. The phone decides nothing: order, titles, previews, dates,// tags, spans, what a button does, the words and the colours are the core's.// Offsets are UTF-16 code units, as NSString counts.#if os(iOS)import CottonKitimport CottonValuesimport CottonWritingimport Foundationimport UIKit/// A word of Cotton Notes' line set (`kits/shell/lines/notes.json`).func notesLine(_ path: String, _ fills: [String: String] = [:]) -> String { ShellLines.line("notes", path, fills) }/// One row of a list.struct NotesRow: Decodable, Equatable, Sendable, Identifiable { var id: String var title: String? var preview: String var previewLines: Int var date: String var archived: Bool var binned: Bool var editedAt: String? var tags: [String] /// Pinned in THIS list (drawn on top, with the pin), and pinned in Notes (CONTRACT.md §2). var pinned: Bool var pinnedInNotes: Bool /// The checklist's ticked and all boxes (no line for a note with none). var checklist: Checklist? /// The first picture's media key, for the thumbnail. var thumbnail: String? /// Written by an assistant: drawn quietly marked. var byAssistant: Bool /// `note`, or `page`: a web page an assistant made, read in the sealed reader (CONTRACT.md §13). var kind: String var page: Page? /// A page's file (its media key for `media.ensure`), or why it cannot open here. struct Page: Decodable, Equatable, Sendable { var key: String? var bytes: Int? var refused: String? } struct Checklist: Decodable, Equatable, Sendable { var done: Int var total: Int } private struct Thumbnail: Decodable { var key: String? } enum CodingKeys: String, CodingKey { case id, title, preview, date, archived, binned, tags, pinned, checklist, thumbnail, kind, page case previewLines = "preview_lines" case editedAt = "edited_at" case pinnedInNotes = "pinned_in_notes" case byAssistant = "by_assistant" } init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = try c.decode(String.self, forKey: .id) title = try c.decodeIfPresent(String.self, forKey: .title) preview = try c.decodeIfPresent(String.self, forKey: .preview) ?? "" previewLines = try c.decodeIfPresent(Int.self, forKey: .previewLines) ?? 2 date = try c.decodeIfPresent(String.self, forKey: .date) ?? "" archived = try c.decodeIfPresent(Bool.self, forKey: .archived) ?? false binned = try c.decodeIfPresent(Bool.self, forKey: .binned) ?? false editedAt = try c.decodeIfPresent(String.self, forKey: .editedAt) tags = (try? c.decodeIfPresent([String].self, forKey: .tags)) ?? [] pinned = try c.decodeIfPresent(Bool.self, forKey: .pinned) ?? false pinnedInNotes = try c.decodeIfPresent(Bool.self, forKey: .pinnedInNotes) ?? false checklist = try c.decodeIfPresent(Checklist.self, forKey: .checklist) thumbnail = try c.decodeIfPresent(Thumbnail.self, forKey: .thumbnail)?.key byAssistant = try c.decodeIfPresent(Bool.self, forKey: .byAssistant) ?? false kind = try c.decodeIfPresent(String.self, forKey: .kind) ?? "note" page = try c.decodeIfPresent(Page.self, forKey: .page) }}/// One list (`notes.list`).struct NotesList: Decodable, Equatable, Sendable { var view: String var tag: String? var heading: String var rows: [NotesRow] var countWords: String? var empty: String? var searchHint: String var compose: String /// While the assistant wrote anything, Notes' one tap to it: a quiet line above the rows (CONTRACT.md §13). var assistant: ToAssistant? struct ToAssistant: Decodable, Equatable, Sendable { var label: String var count: Int var list: NotesListAsk } enum CodingKeys: String, CodingKey { case view, tag, heading, rows, empty, compose, assistant case countWords = "count_words" case searchHint = "search_hint" }}/// A picture a text shows, by its address: the media key it draws from, or/// the words for one not on this phone.struct NotePicture: Decodable, Equatable, Sendable { var key: String? var missing: String?}/// A file a note carries that is not one of its pictures (CONTRACT.md section 15), as the core says it: its/// name, what it is and its size (`about`), how it opens (`page`, `note`, `pdf`, `picture`, `elsewhere`, or nil/// until it is here), its media key, whether this copy holds it (`here`), or why it cannot open.struct NoteFile: Decodable, Equatable, Sendable, Identifiable { var id: String var record: String? var name: String var format: String? var about: String? var opens: String? var mime: String? var bytes: Int64? var key: String? var here: Bool var refused: String? var label: String?}/// A note opened, made or saved (`notes.open`, `notes.new`, `notes.edit`,/// `notes.tag`, `notes.picture`).struct NoteText: Decodable, Equatable, Sendable { var id: String var text: String var title: String? var pictures: [String: NotePicture] /// The files it carries, in its order (only `notes.open` says them). var files: [NoteFile] var archived: Bool? var binned: Bool? var hint: String? var selection: WritingSelection? /// Pinned in Notes (top of every list). var pinnedInNotes: Bool enum CodingKeys: String, CodingKey { case id, text, title, pictures, files, archived, binned, hint, selection case pinnedInNotes = "pinned_in_notes" } init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = try c.decode(String.self, forKey: .id) text = try c.decode(String.self, forKey: .text) title = try c.decodeIfPresent(String.self, forKey: .title) pictures = (try? c.decodeIfPresent([String: NotePicture].self, forKey: .pictures)) ?? [:] files = (try? c.decodeIfPresent([NoteFile].self, forKey: .files)) ?? [] archived = try c.decodeIfPresent(Bool.self, forKey: .archived) binned = try c.decodeIfPresent(Bool.self, forKey: .binned) hint = try c.decodeIfPresent(String.self, forKey: .hint) selection = try c.decodeIfPresent(WritingSelection.self, forKey: .selection) pinnedInNotes = try c.decodeIfPresent(Bool.self, forKey: .pinnedInNotes) ?? false }}/// What an archive, bin, restore or delete answered.struct NotesMoved: Decodable, Equatable, Sendable { var said: String?}/// A tag, for the Tag key's choices (`notes.tags`, flattened).struct NotesTag: Decodable, Equatable, Sendable, Identifiable { var tag: String var name: String var count: Int var depth: Int var children: [NotesTag] var id: String { tag } var flattened: [NotesTag] { [self] + children.flatMap(\.flattened) }}/// The looks, the typefaces and their bounds, and the buttons (`notes.themes`).struct NotesThemes: Decodable, Equatable, Sendable { struct Theme: Decodable, Equatable, Sendable, Identifiable { var id: String var name: String var light: WritingTheme.Colours var dark: WritingTheme.Colours func writing(dark: Bool) -> WritingTheme { WritingTheme(id: id, name: name, dark: dark, colours: dark ? self.dark : light) } } struct Font: Decodable, Equatable, Sendable, Identifiable { var id: String var name: String } struct Range: Decodable, Equatable, Sendable { var min: Double var max: Double var step: Double var values: [Double] { guard step > 0, max >= min else { return [min] } return stride(from: min, through: max + step / 2, by: step).map { ($0 * 100).rounded() / 100 } } } struct Width: Decodable, Equatable, Sendable { var value: Double var name: String } struct Button: Decodable, Equatable, Sendable { var action: WritingAction var label: String } struct Key: Decodable, Equatable, Sendable { var key: String var label: String } var themes: [Theme] var fonts: [Font] var fontSize: Range var lineHeight: Range var lineWidths: [Width] var formatting: [Button] var bar: [Key] var shortcuts: [Shortcut]? var keyboard: Keyboard? var words: [String: String] /// The chosen ink's id, and the inks for the chooser (CONTRACT §10 "Ink"); a core without them offers none. var ink: String? var inks: [Ink]? /// What a new copy starts with (`kits/notes/writing.json` `defaults`): what Look's Reset writes back. var defaults: Defaults? struct Defaults: Decodable, Equatable, Sendable { var lightTheme: String var darkTheme: String var font: String var fontSize: Double var lineHeight: Double var lineWidth: Double var hideMarks: Bool var ink: String? enum CodingKeys: String, CodingKey { case font, ink case lightTheme = "light_theme" case darkTheme = "dark_theme" case fontSize = "font_size" case lineHeight = "line_height" case lineWidth = "line_width" case hideMarks = "hide_marks" } } /// One ink: its name, and its accent and selection tint in each appearance, for the chooser's swatch. struct Ink: Decodable, Equatable, Sendable, Identifiable { struct Colours: Decodable, Equatable, Sendable { var accent: String var selection: String? } var id: String var name: String var light: Colours var dark: Colours } /// The keys in the keyboard's place, as the kit arranges them: the bar's left and right keys, the grid row by row, /// and the slim row under it. A cell's words are its button's, else the bar's, else the kit's own. struct Keyboard: Decodable, Equatable, Sendable { struct Named: Decodable, Equatable, Sendable { var key: String var label: String } struct Sides: Decodable, Equatable, Sendable { var left: [Named] var right: [Named] } struct Cell: Decodable, Equatable, Sendable { var key: String var label: String? var grey: Bool? var action: WritingAction? var hold: [Cell]? } struct Foot: Decodable, Equatable, Sendable { var left: Named? var right: Named? } var bar: Sides? var grid: [[Cell]] var foot: Foot? /// What the format key says while the grid stands: it takes the phone back to the letters. var letters: String? /// And what it shows then (ABC), drawn as letters on the key. var lettersFace: String? enum CodingKeys: String, CodingKey { case bar, grid, foot, letters case lettersFace = "letters_face" } } /// A hardware keyboard's shortcut: its keys (`primary`, `shift`, `alt`, then the key), and the button or command it presses. struct Shortcut: Decodable, Equatable, Sendable { var keys: [String] var action: WritingAction? var command: String? } enum CodingKeys: String, CodingKey { case themes, fonts, formatting, bar, words, shortcuts, keyboard, ink, inks, defaults case fontSize = "font_size" case lineHeight = "line_height" case lineWidths = "line_widths" } func word(_ name: String) -> String { words[name] ?? name }}/// The look and type chosen (`notes.settings`).struct NotesSettingsChosen: Decodable, Equatable, Sendable { var lightTheme: String var darkTheme: String var light: WritingTheme.Colours var dark: WritingTheme.Colours var font: String var fontSize: Double var lineHeight: Double var lineWidth: Double /// Marks hidden away from the cursor (the default), or always drawn dim. var hideMarks: Bool /// The person's ink (CONTRACT §10 "Ink"): `light` and `dark` already come in it. var ink: String? enum CodingKeys: String, CodingKey { case light, dark, font, ink case hideMarks = "hide_marks" case lightTheme = "light_theme" case darkTheme = "dark_theme" case fontSize = "font_size" case lineHeight = "line_height" case lineWidth = "line_width" } /// The type as Notes sets it: the core's `sans` in Figtree, code in JetBrains Mono. @MainActor var type: WritingType { WritingType(face: NotesLook.face(font), size: fontSize, lineHeight: lineHeight, width: lineWidth, code: WritingFonts.hasFigtree ? "jetbrains" : "mono") } /// The look the screens draw with: the core's chosen theme for this appearance, the type and whether marks hide. @MainActor func look(dark: Bool) -> WritingLook { WritingLook(theme: WritingTheme(id: dark ? darkTheme : lightTheme, name: "", dark: dark, colours: dark ? self.dark : light), type: type, hideMarks: hideMarks) }}/// What an import brought in, in the core's words.struct NotesImported: Decodable, Equatable, Sendable { var said: String}/// A file handed to `notes.import`: where it lies on the phone, and its path/// inside what was picked.struct NoteImportFile: Encodable, Equatable, Sendable { var path: String var name: String}/// A setting sent back: a look's or a face's id, or a number.enum NotesSetting: Encodable, Sendable, Equatable { case text(String) case number(Double) case flag(Bool) func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer() switch self { case .text(let s): try c.encode(s) case .number(let n): try c.encode(n) case .flag(let b): try c.encode(b) } }}/// What the Notes screens ask of the core.struct NotesBook: Sendable { let core: any CottonCalling private struct Id: Encodable { let id: String } private struct ListAsk: Encodable { let view: String; let tag: String?; let list: String?; let search: String?; let zone: String } private struct NewAsk: Encodable { let tag: String? } private struct OpenAsk: Encodable { let id: String; let cursor: Int? } private struct EditAsk: Encodable { let id: String; let text: String; let cursor: Int? } private struct TagAsk: Encodable { let id: String; let tag: String } private struct PictureAsk: Encodable { let id: String; let path: String; let mime: String; let filename: String; let text: String; let selection: WritingSelection } private struct FileAsk: Encodable { let note: String; let id: String } private struct Import: Encodable { let files: [NoteImportFile] } private struct Empty: Encodable {} private struct Tags: Decodable { let tags: [NotesTag] } /// The writing rule as Notes asks it: every drawing with the `hide_marks` the settings say. func rules(hideMarks: Bool) -> any WritingRules { NotesWritingRules(core: core, hideMarks: hideMarks) } func list(_ ask: NotesListAsk, search: String?) async throws -> NotesList { try await core.call("notes.list", ListAsk(view: ask.view, tag: ask.tag, list: ask.list, search: search, zone: TimeZone.current.identifier), as: NotesList.self) } func new(tag: String?) async throws -> NoteText { try await core.call("notes.new", NewAsk(tag: tag), as: NoteText.self) } func open(_ id: String) async throws -> NoteText { try await core.call("notes.open", OpenAsk(id: id, cursor: nil), as: NoteText.self) } func edit(_ id: String, text: String, cursor: Int?) async throws -> NoteText { try await core.call("notes.edit", EditAsk(id: id, text: text, cursor: cursor), as: NoteText.self) } func tag(_ id: String, _ tag: String) async throws -> NoteText { try await core.call("notes.tag", TagAsk(id: id, tag: tag), as: NoteText.self) } func picture(_ id: String, file: URL, mime: String, text: String, selection: NSRange) async throws -> NoteText { try await core.call("notes.picture", PictureAsk(id: id, path: file.path, mime: mime, filename: file.lastPathComponent, text: text, selection: WritingSelection(selection)), as: NoteText.self) } /// One file the note carries, its row fetched from the object when this copy does not hold it (`notes.file`). func file(note: String, id: String) async throws -> NoteFile { try await core.call("notes.file", FileAsk(note: note, id: id), as: NoteFile.self) } /// `archive`, `unarchive`, `bin`, `restore` (deleting for good is `remove`, asked first). func move(_ id: String, _ act: String) async throws -> NotesMoved { try await core.call("notes.\(act)", Id(id: id), as: NotesMoved.self) } func tags() async throws -> [NotesTag] { try await core.call("notes.tags", Empty(), as: Tags.self).tags.flatMap(\.flattened) } func themes() async throws -> NotesThemes { try await core.call("notes.themes", Empty(), as: NotesThemes.self) } func settings(_ change: [String: NotesSetting] = [:]) async throws -> NotesSettingsChosen { try await core.call("notes.settings", change, as: NotesSettingsChosen.self) } func bringIn(_ files: [NoteImportFile]) async throws -> NotesImported { try await core.call("notes.import", Import(files: files), as: NotesImported.self) } /// A picture's file on this phone, fetched when it is not here yet. func picturePath(key: String) async -> URL? { guard let path = try? await PhotosMediaSource(core: core).ensure(key), !path.isEmpty else { return nil } return URL(fileURLWithPath: path) }}/// The writing surface's questions, asked of the core's writing rule.struct NotesWritingRules: WritingRules { let core: any CottonCalling var hideMarks = true private struct Style: Encodable { let text: String; let cursor: Int?; let hide_marks: Bool } /// `zone`: the phone's time zone, for the keys that write a date (Today). private struct Format: Encodable { let text: String; let selection: WritingSelection; let action: WritingAction; let hide_marks: Bool let zone = TimeZone.current.identifier } private struct Empty: Encodable {} private struct Tags: Decodable { let tags: [NotesTag] } func style(_ text: String, cursor: Int?) async throws -> WritingStyled { try await core.call("notes.style", Style(text: text, cursor: cursor, hide_marks: hideMarks), as: WritingStyled.self) } func press(_ ask: WritingAsk) async throws -> WritingChange { try await core.call("notes.format", Format(text: ask.text, selection: WritingSelection(start: ask.start, end: ask.end), action: ask.action, hide_marks: hideMarks), as: WritingChange.self) } /// The tags to offer while one is typed: the core's tags, most used first, /// those that begin with what is typed. func tags(_ prefix: String) async throws -> [WritingTagOffer] { let all = try await core.call("notes.tags", Empty(), as: Tags.self).tags.flatMap(\.flattened) let typed = prefix.lowercased() return all.filter { typed.isEmpty || ($0.tag.lowercased().hasPrefix(typed) && $0.tag.lowercased() != typed) } .sorted { $0.count > $1.count }.prefix(12).map { WritingTagOffer(tag: $0.tag, label: $0.tag, count: $0.count) } } /// As the core writes a tag (`phone::notes::hashtag`): `#work`, `#two words#`. func written(_ tag: String) -> String { tag.contains(" ") ? "#\(tag)#" : "#\(tag)" }}/// A note's pictures: drawn from this phone's copy of each photo; a new one/// kept by the core and written into the text.final class NotesWritingMedia: WritingMedia, @unchecked Sendable { let book: NotesBook let id: String private let lock = NSLock() private var known: [String: NotePicture] = [:] init(book: NotesBook, id: String) { self.book = book self.id = id } /// The addresses the core said in its last answer for this note. func learn(_ pictures: [String: NotePicture]) { lock.lock() known.merge(pictures) { _, new in new } lock.unlock() } /// What the core said of a picture's address. func picture(_ src: String) -> NotePicture? { lock.lock() defer { lock.unlock() } return known[src] } private func key(_ src: String) -> String? { picture(src)?.key } func image(_ src: String, width: CGFloat) async -> UIImage? { guard let key = key(src), let url = await book.picturePath(key: key) else { return nil } return await NotesPictures.image(at: url, width: width) } /// The core keeps the picture as a photo, writes it into the text after /// the cursor's line and saves the note. func add(_ file: URL, text: String, selection: NSRange) async throws -> WritingChange { let answer = try await book.picture(id, file: file, mime: "image/jpeg", text: text, selection: selection) learn(answer.pictures) return WritingChange(text: answer.text, selection: answer.selection) }}enum NotesPictures { /// A picture's file, drawn no wider than `width` points on this screen. static func image(at url: URL, width: CGFloat) async -> UIImage? { await Task.detached(priority: .userInitiated) { guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil } let pixels = max(1, Int(width * 3)) let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: pixels] guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil } return UIImage(cgImage: image) }.value }}enum NotesBooks { /// Each key's drawing in Notes' own set (`WritingMarks`), by the key's name. static let icons: [String: String] = [ "bullet": "bullets", "numbered": "numbers", "check": "check", "highlight": "highlight", "code": "code", "link": "link", "divider": "divider", "indent": "indent", "outdent": "outdent", "move_up": "up", "move_down": "down", "quote": "quote", "return": "return", "table": "table", "bold": "bold", "italic": "italic", "underline": "underline", "strike": "strike", "code_block": "code_block", "note_link": "note_link", "fold": "fold", "undo": "undo", "redo": "redo", "tag": "hash", "picture": "picture", "hide_keyboard": "hide", "format": "format", "keyboard": "keyboard", ] /// Whether this app is Cotton Notes (or Notes Dev). static var isNotes: Bool { FlavourManifest.current?.flavour.hasPrefix("notes") == true } /// The surface's keys, as Android's `NotesModel.keys`. The bar (DECISIONS.md "The bar"): undo, redo, #, [[, /// picture, hide keyboard, formatting. The formatting keys in the decided order: headings, bold, italic, /// underline, strike, highlight, code, link, bullet, numbered, to-do, quote, table, divider, indent, outdent, /// move up, move down, fold. Each wears Notes' own drawing; a heading its level's letters. static func words(_ themes: NotesThemes, hint: String?) -> WritingWords { // The bar and the panel as the core orders them; the keyboard key is the formatting key's face while the panel // stands (the kit's letters word, ABC, when it says one). func barKey(_ key: NotesThemes.Key) -> WritingKey { WritingKey(id: key.key, label: key.label, icon: icons[key.key] ?? key.key) } var bar = themes.keyboard?.bar.map { sides in (sides.left + [NotesThemes.Keyboard.Named(key: "gap", label: "")] + sides.right).map { NotesThemes.Key(key: $0.key, label: $0.label) }.map(barKey) } ?? themes.bar.map(barKey) let face = themes.keyboard?.lettersFace bar.append(WritingKey(id: "keyboard", label: themes.keyboard?.letters ?? notesLine("bar.keyboard"), glyph: face, icon: face == nil ? "keyboard" : nil, style: face == nil ? nil : "bold")) func id(_ action: WritingAction) -> String { action.fields["level"]?.number.map { "\(action.name)\(Int($0))" } ?? action.name } let panel = themes.formatting.map { button -> WritingKey in let name = button.action.name let level = button.action.fields["level"]?.number.map { Int($0) } let id = id(button.action) let group = switch name { case "heading", "paragraph": "headings" case "bold", "italic", "underline", "strike", "highlight", "code", "code_block", "link": "marks" case "bullet", "numbered", "check", "quote", "table", "divider": "blocks" default: "lines" } return WritingKey(id: id, label: button.label, glyph: name == "heading" ? "H\(level ?? 1)" : nil, icon: name == "heading" ? nil : icons[name] ?? name, style: name == "heading" ? "bold" : nil, group: group, action: button.action) } // The grid, when the kit lays one: each cell its button's words and drawing, held cells their offers. func cell(_ c: NotesThemes.Keyboard.Cell) -> WritingKey { let button = c.action.flatMap { a in panel.first { $0.id == id(a) } } // A cell's words: its button's, else its own line (`format.<key>`). var key = button ?? WritingKey(id: c.key, label: c.label ?? notesLine("format.\(c.key)"), icon: icons[c.key] ?? c.key, action: c.action) key.id = c.key if let label = c.label { key.label = label } key.grey = c.grey key.hold = c.hold?.map(cell) return key } let grid = themes.keyboard?.grid.map { $0.map(cell) } ?? [] let foot = [themes.keyboard?.foot?.left, themes.keyboard?.foot?.right].compactMap { $0 }.map { cell(NotesThemes.Keyboard.Cell(key: $0.key, label: $0.label)) } // A hardware keyboard's shortcuts, as the core names them (`primary` is ⌘). let shortcuts: [WritingShortcut] = (themes.shortcuts ?? []).compactMap { shortcut in guard let key = shortcut.keys.last, let does = shortcut.action.map(id) ?? shortcut.command else { return nil } return WritingShortcut(key: key, ctrl: shortcut.keys.contains("primary"), shift: shortcut.keys.contains("shift"), alt: shortcut.keys.contains("alt") || shortcut.keys.contains("option"), does: does) } var words: [String: String] = [ "add_row": notesLine("format.table_row_add"), "add_column": notesLine("format.table_column_add"), "remove_row": notesLine("format.table_row_remove"), "remove_column": notesLine("format.table_column_remove"), "keyboard": notesLine("bar.keyboard"), "open": notesLine("writer.open"), ] words["hint"] = hint ?? notesLine("writer.hint") return WritingWords(bar: bar, panel: panel, shortcuts: shortcuts, words: words, grid: grid, foot: foot) }}#endif#if os(iOS)/// The navigation words, from the notes line set.enum NotesNav { static var back: String { notesLine("nav.back") } static var more: String { notesLine("nav.more") } static var share: String { notesLine("nav.share") } static var settings: String { notesLine("nav.settings") } static var close: String { notesLine("nav.close") }}#endif