Files

629 lines
22 KiB
Ziran

// Date arithmetic and per-day documents moved from Harmony's original Diary.
// File effects belong to the host; this bundle has no OS or database access.
//
// A day's document keeps Harmony's version 1:
// {"version":1,"date":"YYYY-MM-DD","text":"...","photos":[...]}. The text is
// the entry, in Markdown, and the only source of truth: its photos are embed
// lines (diary_markdown.zi). "photos" lists the Diary files the text embeds,
// for older versions, which show those photos below the entry.
#import "json_scan"
#import, file "diary_view.zi";
#import, file "diary_date.zi";
#import, file "diary_markdown.zi";
#import "std/text"
#import "vec"
#import "byte_text_linux"
#import, file "diary_types.zi";
#import "kryon/app_context"
#import "kryon/app_protocol"
#import "date_parse"
#import, file "diary_history.zi";
#import, file "diary_spelling_mask.zi";
#import, file "diary_ui_types.zi";
#import, file "diary_wire.zi";
ReadDiaryFile :: (name: string) -> DiaryFileResult {
data := DocumentRead(name)
status := DocumentStatus()
return DiaryFileResult.{.data = data, .missing = status == DOCUMENT_MISSING,
.succeeded = status != DOCUMENT_ERROR}
}
DiaryClock :: () -> string {
seconds := cast(s64)AppNow() + cast(s64)AppLocalOffset()
date := CivilFromUnix(seconds)
buffer: [19]u8
unused WriteIsoDay(seconds, buffer[:10])
buffer[10] = cast(u8)32
unused DateWriteDigits(buffer[:], 11, date.hour, 2)
buffer[13] = cast(u8)58
unused DateWriteDigits(buffer[:], 14, date.minute, 2)
buffer[16] = cast(u8)58
unused DateWriteDigits(buffer[:], 17, date.second, 2)
out: Vec(u8)
BuilderPrint(*out, "%", TextFromBytes(buffer[:]))
return BuilderFinish(out)
}
Today :: () -> Date {
clock := DiaryClock()
if clock.count < 10 {
return Date.{}
}
return ParseDate(clock[:10])
}
Filename :: (date: Date) -> string {
out: Vec(u8)
BuilderPrint(*out, "%.json", ISO(date))
return BuilderFinish(out)
}
Decode :: (value: string, at: s32) -> string {
bytes: Vec(u8)
for index: 0..value.count {
if !VecPush(bytes, cast(u8)0) {
VecFree(bytes);
return ""
}
}
count := ReadStringText(value, at, VecSlice(bytes, 0, bytes.count))
if count < 0 {
VecFree(bytes);
return ""
}
out: Vec(u8)
BuilderPrint(*out, "%", TextFromBytes(VecSlice(bytes, 0, count)))
VecFree(bytes)
return BuilderFinish(out)
}
Json :: (out: *Vec(u8), value: string) {
BuilderPrint(out, "\"")
for index: 0..value.count - 1 {
byte := value[index]
if byte == cast(u8)34 {
BuilderPrint(out, "\\\"")
}
else if byte == cast(u8)92 {
BuilderPrint(out, "\\\\")
}
else if byte == cast(u8)10 {
BuilderPrint(out, "\\n")
}
else if byte == cast(u8)13 {
BuilderPrint(out, "\\r")
}
else if byte == cast(u8)9 {
BuilderPrint(out, "\\t")
}
else if byte < cast(u8)32 {
BuilderPrint(out, " ")
}
else {
BuilderPrint(out, "%", value[index:index + 1])
}
}
BuilderPrint(out, "\"")
}
Document :: (message: DiaryMessage) -> string {
out: Vec(u8)
BuilderPrint(*out, "{\"version\":1,\"date\":")
Json(*out, ISO(Date.{message.year, message.month, message.day}))
BuilderPrint(*out, ",\"text\":")
Json(*out, message.text)
BuilderPrint(*out, ",\"photos\":")
PhotoMirror(*out, message.text)
BuilderPrint(*out, "}")
return BuilderFinish(out)
}
// The "photos" list older versions show: each Diary file the text embeds,
// once, in the order the text first names it. Photos of the media library
// are no Diary files; older versions show their embed lines as text.
PhotoMirror :: (out: *Vec(u8), text: string) {
BuilderPrint(out, "[")
written: s32 = 0
embed := DiaryEmbedNext(text, 0)
while embed.valid {
file := DiaryEmbedTarget(text, embed)
first := !embed.library
earlier := DiaryEmbedNext(text, 0)
while first && earlier.valid && earlier.start < embed.start {
if !earlier.library && DiaryEmbedTarget(text, earlier) == file {
first = false
}
earlier = DiaryEmbedNext(text, earlier.end)
}
if first {
if written > 0 {
BuilderPrint(out, ",")
}
BuilderPrint(out, "{\"file\":")
Json(out, file)
BuilderPrint(out, ",\"name\":")
Json(out, DiaryEmbedAlt(text, embed))
BuilderPrint(out, "}")
written += 1
}
embed = DiaryEmbedNext(text, embed.end)
}
BuilderPrint(out, "]")
}
// Photos an older version attached as Diary files and the text does not
// embed yet, as embed lines after the text, in the document's order. Only
// the text in memory changes: viewing a day writes nothing, and its first
// real edit saves the embeds.
Migrated :: (text: string, document: string) -> string {
rows := FieldAt(document, 0, "photos")
result := text
for index: cast(s32)0..ArrayCount(document, rows) - 1 {
row := ElementAt(document, rows, index)
file := Decode(document, FieldAt(document, row, "file"))
if DiaryEmbedReferences(result, file) {
continue
}
destination: Vec(u8)
BuilderPrint(*destination, "diary:%", file)
line := DiaryEmbedLine(BuilderFinish(destination),
Decode(document, FieldAt(document, row, "name")))
result = DiaryEmbedAppend(result, line)
}
return result
}
// Puts the photo the host named, a library photo it just added or a Diary
// file, on its own line at the caret: one edit, saved at once. The caret
// starts at the end of a day's entry, so without a click the photo follows
// the text.
AttachPhoto :: (message: DiaryMessage) -> DiaryMessage {
line := DiaryEmbedLine(message.attachment_file, message.attachment_name)
if !OnOrBefore(Date.{message.year, message.month, message.day}, Today()) ||
message.load_error || DiaryEmbedAt(line, 0).end != cast(s32)line.count {
message.succeeded = false
return message
}
edit := DiaryEmbedInsertion(message.text, message.cursor, line)
message.action = DIARY_EDIT
message.edit_start = edit.start
message.edit_end = edit.end
message.replacement = edit.replacement
message = Apply(message)
message.replacement = ""
// An entry that cannot save keeps the photo and saves with its next edit.
message = Save(message)
return message
}
Load :: (message: DiaryMessage, date: Date) -> DiaryMessage {
if !OnOrBefore(date, Today()) {
message.succeeded = false;
return message
}
loaded := ReadDiaryFile(Filename(date))
message.year = date.year
message.month = date.month
message.day = date.day
message.text = ""
message.document = loaded.data
message.cursor = 0
message.anchor = 0
message.load_error = !loaded.succeeded
message.saved = true
if loaded.missing {
message.load_error = false;
return message
}
version := ReadNumber(loaded.data, FieldAt(loaded.data, 0, "version"))
day := Decode(loaded.data, FieldAt(loaded.data, 0, "date"))
text := FieldAt(loaded.data, 0, "text")
if !version.valid || version.value != 1.0 || day != ISO(date) || text < 0 ||
loaded.data[text] != cast(u8)34 ||
ArrayCount(loaded.data, FieldAt(loaded.data, 0, "photos")) < 0 ||
Space(loaded.data, ValueEnd(loaded.data, 0, 0)) != loaded.data.count {
message.load_error = true
return message
}
rows := FieldAt(loaded.data, 0, "photos")
for index: cast(s32)0..ArrayCount(loaded.data, rows) - 1 {
row := ElementAt(loaded.data, rows, index)
file := Decode(loaded.data, FieldAt(loaded.data, row, "file"))
label := FieldAt(loaded.data, row, "name")
if !DiaryFileNameValid(file) || label < 0 || loaded.data[label] != cast(u8)34 {
message.load_error = true
return message
}
}
message.text = Migrated(Decode(loaded.data, text), loaded.data)
message.cursor = cast(s32)message.text.count
message.anchor = message.cursor
return message
}
Save :: (message: DiaryMessage) -> DiaryMessage {
if message.load_error || !OnOrBefore(Date.{message.year, message.month, message.day}, Today()) {
message.succeeded = false;
return message
}
if message.saved {
return message
}
message.document = Document(message)
message.saved = DocumentWrite(Filename(Date.{message.year, message.month, message.day}),
message.document)
message.succeeded = message.saved
return message
}
Apply :: (message: DiaryMessage) -> DiaryMessage {
message.succeeded = true
if message.action == DIARY_ROUTE {
message.succeeded = true
return message
}
if message.action == DIARY_LOAD {
date := Date.{message.year, message.month, message.day}
if !Valid(date) {
date = Today()
}
return Load(message, date)
}
if message.action == DIARY_SAVE {
return Save(message)
}
if message.action == DIARY_ATTACH {
return AttachPhoto(message)
}
if message.action == DIARY_EDIT {
if !OnOrBefore(Date.{message.year, message.month, message.day}, Today()) ||
message.load_error || message.edit_start < 0 ||
message.edit_end < message.edit_start || message.edit_end > message.text.count {
message.succeeded = false
return message
}
out: Vec(u8)
BuilderPrint(*out, "%", message.text[0:message.edit_start])
BuilderPrint(*out, "%", message.replacement)
BuilderPrint(*out, "%", message.text[message.edit_end:message.text.count])
message.text = BuilderFinish(out)
message.cursor = message.edit_start + cast(s32)message.replacement.count
message.anchor = message.cursor
message.saved = false
return message
}
if message.action != DIARY_CONTROL {
message.succeeded = false;
return message
}
if message.control == 29013 {
clock := DiaryClock()
if message.load_error || message.calendar || clock.count < 16 {
message.succeeded = false
return message
}
stamp: Vec(u8)
BuilderPrint(*stamp, "**%**", clock[11:16])
message.replacement = BuilderFinish(stamp)
message.edit_start = ifx message.cursor < message.anchor then message.cursor else message.anchor
message.edit_end = ifx message.cursor > message.anchor then message.cursor else message.anchor
message.action = DIARY_EDIT
return Apply(message)
}
if message.control == 29003 {
message.calendar = !message.calendar
message.month_year = message.year
message.month_number = message.month
} else if message.control == 29011 || message.control == 29012 {
previous_year := message.month_year
previous_month := message.month_number
message.month_number += ifx message.control == 29011 then -1 else 1
if message.month_number < 1 {
message.month_number = 12;
message.month_year -= 1
}
if message.month_number > 12 {
message.month_number = 1;
message.month_year += 1
}
if !OnOrBefore(Date.{message.month_year, message.month_number, 1}, Today()) {
message.month_year = previous_year
message.month_number = previous_month
message.succeeded = false;
return message
}
} else {
before := message
date := Date.{before.year, before.month, before.day}
if message.control == 29001 {
date = Next(date, -1)
}
else if message.control == 29002 {
date = Next(date, 1)
}
else if message.control == 29004 {
date = Today()
}
else if message.control >= 29101 && message.control <= 29131 {
date = Date.{message.month_year, message.month_number, message.control - 29100}
} else {
message.succeeded = false;
return message
}
if !OnOrBefore(date, Today()) {
message.succeeded = false
return message
}
message = Save(message)
if !message.saved && !message.load_error {
return message
}
message = Load(message, date)
message.calendar = false
}
if message.calendar {
if !Valid(Date.{message.month_year, message.month_number, 1}) {
message.succeeded = false
message.calendar = false
return message
}
message.month_days = Days(message.month_year, message.month_number)
message.month_weekday = Weekday(Date.{message.month_year, message.month_number, 1})
for day: cast(s32)0..cast(s32)31 {
message.marks[day] = cast(u8)0
}
for day: cast(s32)1..Days(message.month_year, message.month_number) {
file := ReadDiaryFile(Filename(Date.{message.month_year, message.month_number, day}))
text := FieldAt(file.data, 0, "text")
has_text := text >= 0 && text + 1 < file.data.count && file.data[text + 1] != cast(u8)34
message.marks[day] = ifx has_text ||
ArrayCount(file.data, FieldAt(file.data, 0, "photos")) > 0 then cast(u8)1 else cast(u8)0
}
}
return message
}
entry: DiaryMessage;
editor: DiaryUiFrame;
loaded: bool;
document_scope: string;
document_revision: string;
history: DiaryHistory;
photo_waiting: bool;
photo_day: Date;
spelling_sent: string;
spelling_day: Date;
spelling_notice_until: float64;
DiarySpellingNotice :: (key: string) {
editor.spelling_notice = key
spelling_notice_until = editor.now + 6.0
}
DiarySpellingPollService :: () {
if !editor.spelling_busy || !AppSupports("text.correct.poll") { return }
result := AppService("text.correct.poll", "")
if !DiaryWireBool(result, "finished") { return }
editor.spelling_busy = false
same_day := entry.year == spelling_day.year && entry.month == spelling_day.month &&
entry.day == spelling_day.day
if !same_day { return }
notice := DiaryWireString(result, FieldAt(result, 0, "notice"))
if notice != "" {
DiarySpellingNotice(notice)
return
}
if entry.text != spelling_sent {
DiarySpellingNotice("diary_spelling_error")
return
}
corrected := DiarySpellingRestored(entry.text, DiaryWireString(result, FieldAt(result, 0, "text")))
if corrected == "" && entry.text != "" {
DiarySpellingNotice("diary_spelling_error")
return
}
if corrected == entry.text {
DiarySpellingNotice("diary_spelling_none")
return
}
edit := DiaryHistoryEdit(entry.text, corrected)
entry.action = DIARY_EDIT
entry.edit_start = edit.start
entry.edit_end = edit.end
entry.replacement = edit.replacement
entry = Apply(entry)
entry.replacement = ""
editor.save_at = editor.now
DiaryHistoryObserve(*history, entry.year, entry.month, entry.day, entry.text, editor.now, false)
}
DiarySpellingRequest :: () {
if !editor.spelling_requested || editor.spelling_busy || !AppSupports("text.correct.start") { return }
result := AppService("text.correct.start", DiarySpellingMasked(entry.text))
notice := DiaryWireString(result, FieldAt(result, 0, "notice"))
if notice != "" {
DiarySpellingNotice(notice)
return
}
editor.spelling_busy = DiaryWireBool(result, "busy")
if editor.spelling_busy {
spelling_sent = entry.text
spelling_day = Date.{entry.year, entry.month, entry.day}
editor.spelling_notice = ""
}
}
DiaryEnsureLoaded :: () {
if !loaded {
entry = Apply(DiaryMessage.{.action = DIARY_LOAD})
loaded = entry.succeeded
}
}
DiaryRefreshPosition :: (position: s32, text: string) -> s32 {
at := ifx position > text.count then cast(s32)text.count else position
while at > 0 && at < text.count && DiaryContinuationByte(text[at]) {
at -= 1
}
return at
}
DiaryObserveDocuments :: (refresh: bool) {
if !AppSupports("document.revision") {
return
}
revision := AppService("document.revision", "")
if revision == "" || revision == document_revision {
return
}
separator := revision.count - 1
while separator >= 0 && revision[separator] != cast(u8)58 {
separator -= 1
}
if separator <= 0 {
return
}
scope := revision[:separator]
if document_scope != "" && scope != document_scope {
// Keep the selected date, but never save or carry editor state from
// another account into it.
date := Date.{entry.year, entry.month, entry.day}
entry = Apply(DiaryMessage.{.action = DIARY_LOAD, .year = date.year,
.month = date.month, .day = date.day})
loaded = entry.succeeded
editor = DiaryUiFrame.{}
DiaryHistoryClear(*history)
photo_waiting = false
spelling_sent = ""
document_scope = scope
document_revision = revision
return
}
document_scope = scope
if !refresh || (loaded && !entry.saved) {
// Leave the revision pending while typing or retrying a failed save.
return
}
document_revision = revision
if !loaded {
return
}
fresh := Load(entry, Date.{entry.year, entry.month, entry.day})
// A manifest and its chunks may arrive on different sync pages. Keep
// the current text until a later committed revision makes it readable.
if fresh.load_error || (fresh.document == entry.document && !entry.load_error) {
return
}
fresh.cursor = DiaryRefreshPosition(entry.cursor, fresh.text)
fresh.anchor = DiaryRefreshPosition(entry.anchor, fresh.text)
if fresh.text != entry.text {
DiaryHistoryClear(*history)
}
entry = fresh
}
DiaryHistoryApply :: (redo: bool) {
changed := ifx redo then DiaryHistoryRedo(*history) else DiaryHistoryUndo(*history)
if !changed { return }
edit := DiaryHistoryEdit(entry.text, history.current)
entry.action = DIARY_EDIT
entry.edit_start = edit.start
entry.edit_end = edit.end
entry.replacement = edit.replacement
entry = Apply(entry)
entry.replacement = ""
editor.save_at = editor.now
}
DiaryPicked :: (result: string) {
status := DiaryWireString(result, FieldAt(result, 0, "status"))
photo_waiting = status == "pending"
if status != "done" {
editor.photo_error = status == "failed"
return
}
if entry.year != photo_day.year || entry.month != photo_day.month || entry.day != photo_day.day {
return
}
entry.action = DIARY_ATTACH
entry.attachment_file = DiaryWireString(result, FieldAt(result, 0, "destination"))
entry.attachment_name = DiaryWireString(result, FieldAt(result, 0, "name"))
entry = Apply(entry)
editor.photo_error = !entry.succeeded
}
#program_export "DiaryMain"
Main :: () -> s32 {
mode := AppMode()
if mode == APP_IDENTIFY {
AppIdentity("inbe.diary")
AppDescribe("Diary", "S1.8rr:M5 3H19V21H5ZM8 7H16M8 11H16M8 15H13")
return APP_PROTOCOL
}
if mode == APP_COMMAND {
DiaryObserveDocuments(false)
entry = Apply(DiaryMessageDecode(AppCommand()))
loaded = entry.year > 0
AppReply(DiaryMessageEncode(entry))
return 0
}
if mode == APP_SAVE {
DiaryObserveDocuments(false)
if loaded { entry = Save(entry) }
AppReply(DiaryMessageEncode(entry))
return ifx !loaded || entry.saved || entry.load_error then 0 else 1
}
if mode != APP_FRAME { return 0 }
DiaryObserveDocuments(true)
DiaryEnsureLoaded()
bounds := AppBounds()
editor.session = AppSession()
editor.width = cast(s32)bounds.width
editor.height = cast(s32)(bounds.y + bounds.height)
editor.origin_x = cast(s32)bounds.x
editor.origin_y = cast(s32)bounds.y
editor.scale = AppScale()
editor.font = AppFont()
editor.now = AppAreaInput().now_seconds
editor.input = AppAreaInput()
editor.link_color = ifx AppDark() then cast(u32)0x9bc5e8ff else cast(u32)0x286d9cff
editor.muted_color = ifx AppDark() then cast(u32)0xaaaeb3ff else cast(u32)0x62686eff
editor.can_undo = history.undo_count > 0
editor.can_redo = history.redo_count > 0
editor.photo_requested = false
editor.undo_requested = false
editor.redo_requested = false
editor.spelling_requested = false
if editor.now >= spelling_notice_until { editor.spelling_notice = "" }
DiarySpellingPollService()
editor.clipboard_write = false
if photo_waiting && AppSupports("media.pick.status") {
DiaryPicked(AppService("media.pick.status", ""))
}
entry.action = DIARY_FRAME
entry = DiaryView(entry, editor, Today())
editor = DiaryObservedFrame()
if entry.action != DIARY_FRAME { entry = Apply(entry) }
if editor.undo_requested { DiaryHistoryApply(false) }
if editor.redo_requested { DiaryHistoryApply(true) }
DiarySpellingRequest()
if editor.photo_requested && AppSupports("media.pick") {
entry = Save(entry)
if entry.saved {
photo_day = Date.{entry.year, entry.month, entry.day}
DiaryPicked(AppService("media.pick", AppLocale("diary_attach_photo")))
}
}
if editor.clipboard_write {
unused ClipboardCopy(editor.clipboard_text, 0)
}
if !entry.saved && editor.now >= editor.save_at { entry = Save(entry) }
if loaded && !entry.load_error {
DiaryHistoryObserve(*history, entry.year, entry.month, entry.day, entry.text, editor.now, true)
}
AppKeyboard(editor.focused)
return 0
}