Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat(ios): iPhone and iPad app that keeps meeting records and listens to the room with live subtitles, notes and a Live Activity

wquguru8e3acfe5d447
diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.strings
index 17b1cb0..edfe665 100644
--- a/Resources/en.lproj/Localizable.strings
+++ b/Resources/en.lproj/Localizable.strings
@@ -174,6 +174,8 @@
"换后备 " = "Fallbacks ";
"无" = "none";
"AI 请求 %d 次 · 排队最久 %.2fs · token %d/%d" = "AI requests: %d · longest queue %.2fs · tokens %d/%d";
+
+/* DiagnosticsView */
"有人说话后,这里会显示每句话的耗时明细" = "Each sentence's timing shows here once someone speaks";
"这场会议 · %lld 分钟 · %lld 句 · 同声传译 %lld 次" = "This meeting · %lld min · sentences: %lld · interpreted: %lld";
"开始聆听后,这里会显示每句话的耗时明细" = "Once listening starts, the timing of every sentence shows here";
@@ -574,13 +576,29 @@
"本机不支持%@识别" = "This Mac can't recognize %@";
"请在系统设置 › 键盘 › 听写里添加%@,下载好后可用" = "Add %@ to Dictation in System Settings › Keyboard; it works once downloaded";
+/* RecordList */
+"今天" = "Today";
+"昨天" = "Yesterday";
+"本周" = "This Week";
+"不到 1 分钟" = "Under 1 min";
+"%lld 小时" = "%lld h";
+"%lld 小时 %lld 分" = "%lld h %lld min";
+"英语" = "English";
+"日语" = "Japanese";
+"中文" = "Chinese";
+"繁中" = "Trad. Chinese";
+"韩语" = "Korean";
+"西语" = "Spanish";
+"法语" = "French";
+"德语" = "German";
+"葡语" = "Portuguese";
+
/* RoomMic */
"没有可用的麦克风" = "No microphone available";
/* SessionStore */
"会议 %@" = "Meeting %@";
"未识别" = "Unidentified";
-"不到 1 分钟" = "Under 1 min";
/* SettingsWindow */
"语言" = "Language";
@@ -777,10 +795,13 @@
/* SpeakerID */
"说话人 %lld" = "Speaker %lld";
+
+/* SpeakerViews */
"没认出是谁:太短,或和已知的声音都不像" = "Not recognised: too short, or unlike the known voices";
"关掉说话人识别,记录里的名字一起收起" = "Turn off speaker identification; the names in your records are hidden too";
"Ling 从对话里认出,点一下可以改" = "Ling found this name in the conversation; click to change";
"改名字,或和别人合并" = "Rename, or merge with someone else";
+"改名字" = "Rename";
"不准?关掉" = "Wrong? Turn off";
"说了 %lld 句" = "%lld lines";
"是谁" = "Who";
@@ -897,9 +918,6 @@
"对方听到 %@" = "They hear %@";
"搜索" = "Search";
"没有找到“%@”" = "Nothing found for “%@”";
-"今天" = "Today";
-"昨天" = "Yesterday";
-"本周" = "This Week";
"收起更早的会议" = "Hide earlier meetings";
"更早的会议" = "Earlier meetings";
"只有录音" = "Recording only";
@@ -907,21 +925,10 @@
"转写中 %lld%%" = "%lld%%";
"翻译中" = "Translating";
"准备中" = "Preparing";
-"%lld 小时" = "%lld h";
-"%lld 小时 %lld 分" = "%lld h %lld min";
"显示原文件" = "Show Original File";
"在 Finder 中显示" = "Show in Finder";
"恢复自动标题" = "Restore Automatic Title";
"删除" = "Delete";
-"英语" = "English";
-"日语" = "Japanese";
-"中文" = "Chinese";
-"繁中" = "Trad. Chinese";
-"韩语" = "Korean";
-"西语" = "Spanish";
-"法语" = "French";
-"德语" = "German";
-"葡语" = "Portuguese";
"正在听,说话的内容会出现在这里" = "Listening; what's said will appear here";
"转出的文字会陆续出现在这里" = "The transcript will appear here as it's made";
"还没有文字记录" = "No transcript yet";
@@ -1041,3 +1048,28 @@
"录音太短了,请至少朗读 %lld 秒" = "Too short; read for at least %lld seconds";
"读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次" = "Read a bit slowly: your cloned voice would be just as slow. Record again at your usual pace";
"没听清录音内容,请换个安静的地方再录一次" = "Couldn't make out the recording; try again somewhere quiet";
+
+/* Debug */
+"导入录音或视频" = "Import a Recording or Video";
+
+/* RecordsView */
+"%lld 人" = "%lld people";
+
+/* RootView */
+"好" = "OK";
+"下一版就能用" = "Coming in the next version";
+"正在听 · %@" = "Listening · %@";
+"对方说和翻译成" = "They speak, and translate into";
+"%lld 人在说" = "%lld people talking";
+"纪要 · %lld 条新" = "Notes · %lld new";
+"开始说话后,字幕会出现在这里" = "Subtitles show up here once people start talking";
+"只看 %@ · %lld 段 · 再点一下取消" = "Only %@ · %lld turns · tap again to clear";
+"只看这个人;按住可改名字,或和别人合并" = "Shows only this person; press and hold to rename or merge";
+"正在准备…" = "Getting ready…";
+"请在设置里允许知了使用麦克风" = "Allow Cicada to use the microphone in Settings";
+"识别中断了,请重新开始听" = "Recognition stopped. Start listening again";
+
+/* SettingsView (iOS) */
+"在 Ling 开放平台点“创建令牌”,复制以 sk- 开头的那串。" = "On the Ling platform, click “Create token” and copy the string that starts with sk-.";
+"打开 Ling 开放平台 ↗" = "Open the Ling platform ↗";
+"Ling 提示此令牌无效,请检查是否复制完整,或重新创建一个" = "Ling says this token is invalid. Check that you copied all of it, or create a new one";
diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.strings
index 4492bf0..5c8f870 100644
--- a/Resources/ja.lproj/Localizable.strings
+++ b/Resources/ja.lproj/Localizable.strings
@@ -174,6 +174,8 @@
"换后备 " = "代替に切替 ";
"无" = "なし";
"AI 请求 %d 次 · 排队最久 %.2fs · token %d/%d" = "AI リクエスト %d回 · 最長待ち %.2fs · トークン %d/%d";
+
+/* DiagnosticsView */
"有人说话后,这里会显示每句话的耗时明细" = "誰かが話すと、ここに一文ごとの所要時間が表示されます";
"这场会议 · %lld 分钟 · %lld 句 · 同声传译 %lld 次" = "今回の会議 · %lld分 · %lld文 · 同時通訳 %lld回";
"开始聆听后,这里会显示每句话的耗时明细" = "聞き取りを開始すると、各文の所要時間がここに表示されます";
@@ -574,13 +576,29 @@
"本机不支持%@识别" = "このMacは%@の認識に対応していません";
"请在系统设置 › 键盘 › 听写里添加%@,下载好后可用" = "システム設定 › キーボード › 音声入力で %@ を追加してください。ダウンロード後に使えます";
+/* RecordList */
+"今天" = "今日";
+"昨天" = "昨日";
+"本周" = "今週";
+"不到 1 分钟" = "1分未満";
+"%lld 小时" = "%lld時間";
+"%lld 小时 %lld 分" = "%lld時間%lld分";
+"英语" = "英語";
+"日语" = "日本語";
+"中文" = "中国語";
+"繁中" = "繁体中文";
+"韩语" = "韓国語";
+"西语" = "スペイン語";
+"法语" = "フランス語";
+"德语" = "ドイツ語";
+"葡语" = "ポルトガル語";
+
/* RoomMic */
"没有可用的麦克风" = "使用できるマイクがありません";
/* SessionStore */
"会议 %@" = "会議 %@";
"未识别" = "未識別";
-"不到 1 分钟" = "1分未満";
/* SettingsWindow */
"语言" = "言語";
@@ -777,10 +795,13 @@
/* SpeakerID */
"说话人 %lld" = "話者 %lld";
+
+/* SpeakerViews */
"没认出是谁:太短,或和已知的声音都不像" = "誰か判別できません:短すぎるか、既知の声と似ていません";
"关掉说话人识别,记录里的名字一起收起" = "話者識別をオフにします(記録の名前も隠れます)";
"Ling 从对话里认出,点一下可以改" = "Ling が会話から見つけた名前です。クリックで変更";
"改名字,或和别人合并" = "名前を付ける、またはほかの人とまとめる";
+"改名字" = "名前を変更";
"不准?关掉" = "不正確?オフにする";
"说了 %lld 句" = "%lld 回発言";
"是谁" = "誰か";
@@ -897,9 +918,6 @@
"对方听到 %@" = "相手には%@で届きます";
"搜索" = "検索";
"没有找到“%@”" = "「%@」は見つかりません";
-"今天" = "今日";
-"昨天" = "昨日";
-"本周" = "今週";
"收起更早的会议" = "以前の会議を隠す";
"更早的会议" = "以前の会議";
"只有录音" = "録音のみ";
@@ -907,21 +925,10 @@
"转写中 %lld%%" = "文字起こし中 %lld%%";
"翻译中" = "翻訳中";
"准备中" = "準備中";
-"%lld 小时" = "%lld時間";
-"%lld 小时 %lld 分" = "%lld時間%lld分";
"显示原文件" = "元のファイルを表示";
"在 Finder 中显示" = "Finder で表示";
"恢复自动标题" = "自動タイトルに戻す";
"删除" = "削除";
-"英语" = "英語";
-"日语" = "日本語";
-"中文" = "中国語";
-"繁中" = "繁体中文";
-"韩语" = "韓国語";
-"西语" = "スペイン語";
-"法语" = "フランス語";
-"德语" = "ドイツ語";
-"葡语" = "ポルトガル語";
"正在听,说话的内容会出现在这里" = "聞き取り中。発言内容がここに表示されます";
"转出的文字会陆续出现在这里" = "文字起こしが順にここに表示されます";
"还没有文字记录" = "まだ文字起こしがありません";
@@ -1041,3 +1048,28 @@
"录音太短了,请至少朗读 %lld 秒" = "録音が短すぎます。%lld秒以上読み上げてください";
"读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次" = "読むのが少し遅いため、クローンの声も同じく遅くなります。普段の話す速さでもう一度録音してください";
"没听清录音内容,请换个安静的地方再录一次" = "録音を聞き取れませんでした。静かな場所でもう一度録音してください";
+
+/* Debug */
+"导入录音或视频" = "録音や動画を読み込む";
+
+/* RecordsView */
+"%lld 人" = "%lld 人";
+
+/* RootView */
+"好" = "OK";
+"下一版就能用" = "次のバージョンで使えます";
+"正在听 · %@" = "聞いています · %@";
+"对方说和翻译成" = "相手の言語と翻訳先";
+"%lld 人在说" = "%lld 人が話しています";
+"纪要 · %lld 条新" = "メモ · 新着 %lld 件";
+"开始说话后,字幕会出现在这里" = "話し始めると、ここに字幕が出ます";
+"只看 %@ · %lld 段 · 再点一下取消" = "%@ だけ · %lld か所 · もう一度タップで解除";
+"只看这个人;按住可改名字,或和别人合并" = "この人だけを表示。長押しで名前の変更や統合";
+"正在准备…" = "準備しています…";
+"请在设置里允许知了使用麦克风" = "設定で Cicada にマイクの使用を許可してください";
+"识别中断了,请重新开始听" = "認識が止まりました。もう一度聞き始めてください";
+
+/* SettingsView (iOS) */
+"在 Ling 开放平台点“创建令牌”,复制以 sk- 开头的那串。" = "Ling のプラットフォームで「トークンを作成」をクリックし、sk- で始まる文字列をコピーします。";
+"打开 Ling 开放平台 ↗" = "Ling プラットフォームを開く ↗";
+"Ling 提示此令牌无效,请检查是否复制完整,或重新创建一个" = "Ling がこのトークンは無効だと通知しました。全体をコピーできているか確認するか、新しく作成してください";
diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.strings
index 77cc868..d2080fe 100644
--- a/Resources/ko.lproj/Localizable.strings
+++ b/Resources/ko.lproj/Localizable.strings
@@ -174,6 +174,8 @@
"换后备 " = "대체 전환 ";
"无" = "없음";
"AI 请求 %d 次 · 排队最久 %.2fs · token %d/%d" = "AI 요청 %d회 · 최장 대기 %.2fs · token %d/%d";
+
+/* DiagnosticsView */
"有人说话后,这里会显示每句话的耗时明细" = "누군가 말하면 문장별 소요 시간이 여기에 표시돼요";
"这场会议 · %lld 分钟 · %lld 句 · 同声传译 %lld 次" = "이번 회의 · %lld분 · %lld문장 · 동시통역 %lld회";
"开始聆听后,这里会显示每句话的耗时明细" = "듣기를 시작하면 문장별 소요 시간이 여기에 표시됩니다";
@@ -574,13 +576,29 @@
"本机不支持%@识别" = "이 Mac에서는 %@ 인식을 지원하지 않습니다";
"请在系统设置 › 键盘 › 听写里添加%@,下载好后可用" = "시스템 설정 › 키보드 › 받아쓰기에서 %@을(를) 추가해 주세요. 다운로드 후 사용할 수 있습니다";
+/* RecordList */
+"今天" = "오늘";
+"昨天" = "어제";
+"本周" = "이번 주";
+"不到 1 分钟" = "1분 미만";
+"%lld 小时" = "%lld시간";
+"%lld 小时 %lld 分" = "%lld시간 %lld분";
+"英语" = "영어";
+"日语" = "일본어";
+"中文" = "중국어";
+"繁中" = "중국어(번체)";
+"韩语" = "한국어";
+"西语" = "스페인어";
+"法语" = "프랑스어";
+"德语" = "독일어";
+"葡语" = "포르투갈어";
+
/* RoomMic */
"没有可用的麦克风" = "사용할 수 있는 마이크가 없습니다";
/* SessionStore */
"会议 %@" = "회의 %@";
"未识别" = "미식별";
-"不到 1 分钟" = "1분 미만";
/* SettingsWindow */
"语言" = "언어";
@@ -777,10 +795,13 @@
/* SpeakerID */
"说话人 %lld" = "화자 %lld";
+
+/* SpeakerViews */
"没认出是谁:太短,或和已知的声音都不像" = "누군지 알 수 없어요: 너무 짧거나 알려진 목소리와 달라요";
"关掉说话人识别,记录里的名字一起收起" = "화자 인식을 꺼요(기록의 이름도 숨겨져요)";
"Ling 从对话里认出,点一下可以改" = "Ling이 대화에서 찾은 이름이에요. 클릭해서 바꿀 수 있어요";
"改名字,或和别人合并" = "이름을 바꾸거나 다른 사람과 합치기";
+"改名字" = "이름 바꾸기";
"不准?关掉" = "틀렸나요? 끄기";
"说了 %lld 句" = "%lld번 발언";
"是谁" = "누구인지";
@@ -897,9 +918,6 @@
"对方听到 %@" = "상대에게 %@로 들립니다";
"搜索" = "검색";
"没有找到“%@”" = "“%@” 검색 결과 없음";
-"今天" = "오늘";
-"昨天" = "어제";
-"本周" = "이번 주";
"收起更早的会议" = "이전 회의 숨기기";
"更早的会议" = "이전 회의";
"只有录音" = "녹음만 있음";
@@ -907,21 +925,10 @@
"转写中 %lld%%" = "받아쓰는 중 %lld%%";
"翻译中" = "번역 중";
"准备中" = "준비 중";
-"%lld 小时" = "%lld시간";
-"%lld 小时 %lld 分" = "%lld시간 %lld분";
"显示原文件" = "원본 파일 보기";
"在 Finder 中显示" = "Finder에서 보기";
"恢复自动标题" = "자동 제목으로 복원";
"删除" = "삭제";
-"英语" = "영어";
-"日语" = "일본어";
-"中文" = "중국어";
-"繁中" = "중국어(번체)";
-"韩语" = "한국어";
-"西语" = "스페인어";
-"法语" = "프랑스어";
-"德语" = "독일어";
-"葡语" = "포르투갈어";
"正在听,说话的内容会出现在这里" = "듣는 중입니다. 말한 내용이 여기에 표시됩니다";
"转出的文字会陆续出现在这里" = "받아쓴 내용이 여기에 차례로 나타납니다";
"还没有文字记录" = "아직 텍스트 기록이 없습니다";
@@ -1041,3 +1048,28 @@
"录音太短了,请至少朗读 %lld 秒" = "녹음이 너무 짧습니다. 최소 %lld초 이상 읽어 주세요";
"读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次" = "조금 느리게 읽어서 복제한 목소리도 똑같이 느려집니다. 평소 말하는 속도로 다시 녹음하세요";
"没听清录音内容,请换个安静的地方再录一次" = "녹음 내용을 알아듣지 못했습니다. 조용한 곳에서 다시 녹음하세요";
+
+/* Debug */
+"导入录音或视频" = "녹음 또는 동영상 가져오기";
+
+/* RecordsView */
+"%lld 人" = "%lld명";
+
+/* RootView */
+"好" = "확인";
+"下一版就能用" = "다음 버전에서 사용할 수 있어요";
+"正在听 · %@" = "듣는 중 · %@";
+"对方说和翻译成" = "상대 언어와 번역할 언어";
+"%lld 人在说" = "%lld명이 말하는 중";
+"纪要 · %lld 条新" = "회의록 · 새 항목 %lld개";
+"开始说话后,字幕会出现在这里" = "말하기 시작하면 여기에 자막이 나타납니다";
+"只看 %@ · %lld 段 · 再点一下取消" = "%@만 보기 · %lld개 구간 · 다시 탭하면 해제";
+"只看这个人;按住可改名字,或和别人合并" = "이 사람만 표시합니다. 길게 눌러 이름을 바꾸거나 합칩니다";
+"正在准备…" = "준비하는 중…";
+"请在设置里允许知了使用麦克风" = "설정에서 Cicada의 마이크 사용을 허용하세요";
+"识别中断了,请重新开始听" = "인식이 멈췄습니다. 다시 듣기를 시작하세요";
+
+/* SettingsView (iOS) */
+"在 Ling 开放平台点“创建令牌”,复制以 sk- 开头的那串。" = "Ling 개발자 플랫폼에서 “토큰 만들기”를 클릭하고 sk-로 시작하는 문자열을 복사하세요.";
+"打开 Ling 开放平台 ↗" = "Ling 개발자 플랫폼 열기 ↗";
+"Ling 提示此令牌无效,请检查是否复制完整,或重新创建一个" = "Ling에서 이 토큰이 유효하지 않다고 합니다. 전체를 복사했는지 확인하거나 새로 만드세요";
diff --git a/Resources/zh-Hans.lproj/Localizable.strings b/Resources/zh-Hans.lproj/Localizable.strings
index c5b3478..6b7cf4b 100644
--- a/Resources/zh-Hans.lproj/Localizable.strings
+++ b/Resources/zh-Hans.lproj/Localizable.strings
@@ -174,6 +174,8 @@
"换后备 " = "换后备 ";
"无" = "无";
"AI 请求 %d 次 · 排队最久 %.2fs · token %d/%d" = "AI 请求 %d 次 · 排队最久 %.2fs · token %d/%d";
+
+/* DiagnosticsView */
"有人说话后,这里会显示每句话的耗时明细" = "有人说话后,这里会显示每句话的耗时明细";
"这场会议 · %lld 分钟 · %lld 句 · 同声传译 %lld 次" = "这场会议 · %lld 分钟 · %lld 句 · 同声传译 %lld 次";
"开始聆听后,这里会显示每句话的耗时明细" = "开始聆听后,这里会显示每句话的耗时明细";
@@ -574,13 +576,29 @@
"本机不支持%@识别" = "本机不支持%@识别";
"请在系统设置 › 键盘 › 听写里添加%@,下载好后可用" = "请在系统设置 › 键盘 › 听写里添加%@,下载好后可用";
+/* RecordList */
+"今天" = "今天";
+"昨天" = "昨天";
+"本周" = "本周";
+"不到 1 分钟" = "不到 1 分钟";
+"%lld 小时" = "%lld 小时";
+"%lld 小时 %lld 分" = "%lld 小时 %lld 分";
+"英语" = "英语";
+"日语" = "日语";
+"中文" = "中文";
+"繁中" = "繁中";
+"韩语" = "韩语";
+"西语" = "西语";
+"法语" = "法语";
+"德语" = "德语";
+"葡语" = "葡语";
+
/* RoomMic */
"没有可用的麦克风" = "没有可用的麦克风";
/* SessionStore */
"会议 %@" = "会议 %@";
"未识别" = "未识别";
-"不到 1 分钟" = "不到 1 分钟";
/* SettingsWindow */
"语言" = "语言";
@@ -777,10 +795,13 @@
/* SpeakerID */
"说话人 %lld" = "说话人 %lld";
+
+/* SpeakerViews */
"没认出是谁:太短,或和已知的声音都不像" = "没认出是谁:太短,或和已知的声音都不像";
"关掉说话人识别,记录里的名字一起收起" = "关掉说话人识别,记录里的名字一起收起";
"Ling 从对话里认出,点一下可以改" = "Ling 从对话里认出,点一下可以改";
"改名字,或和别人合并" = "改名字,或和别人合并";
+"改名字" = "改名字";
"不准?关掉" = "不准?关掉";
"说了 %lld 句" = "说了 %lld 句";
"是谁" = "是谁";
@@ -897,9 +918,6 @@
"对方听到 %@" = "对方听到 %@";
"搜索" = "搜索";
"没有找到“%@”" = "没有找到“%@”";
-"今天" = "今天";
-"昨天" = "昨天";
-"本周" = "本周";
"收起更早的会议" = "收起更早的会议";
"更早的会议" = "更早的会议";
"只有录音" = "只有录音";
@@ -907,21 +925,10 @@
"转写中 %lld%%" = "转写中 %lld%%";
"翻译中" = "翻译中";
"准备中" = "准备中";
-"%lld 小时" = "%lld 小时";
-"%lld 小时 %lld 分" = "%lld 小时 %lld 分";
"显示原文件" = "显示原文件";
"在 Finder 中显示" = "在 Finder 中显示";
"恢复自动标题" = "恢复自动标题";
"删除" = "删除";
-"英语" = "英语";
-"日语" = "日语";
-"中文" = "中文";
-"繁中" = "繁中";
-"韩语" = "韩语";
-"西语" = "西语";
-"法语" = "法语";
-"德语" = "德语";
-"葡语" = "葡语";
"正在听,说话的内容会出现在这里" = "正在听,说话的内容会出现在这里";
"转出的文字会陆续出现在这里" = "转出的文字会陆续出现在这里";
"还没有文字记录" = "还没有文字记录";
@@ -1041,3 +1048,28 @@
"录音太短了,请至少朗读 %lld 秒" = "录音太短了,请至少朗读 %lld 秒";
"读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次" = "读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次";
"没听清录音内容,请换个安静的地方再录一次" = "没听清录音内容,请换个安静的地方再录一次";
+
+/* Debug */
+"导入录音或视频" = "导入录音或视频";
+
+/* RecordsView */
+"%lld 人" = "%lld 人";
+
+/* RootView */
+"好" = "好";
+"下一版就能用" = "下一版就能用";
+"正在听 · %@" = "正在听 · %@";
+"对方说和翻译成" = "对方说和翻译成";
+"%lld 人在说" = "%lld 人在说";
+"纪要 · %lld 条新" = "纪要 · %lld 条新";
+"开始说话后,字幕会出现在这里" = "开始说话后,字幕会出现在这里";
+"只看 %@ · %lld 段 · 再点一下取消" = "只看 %@ · %lld 段 · 再点一下取消";
+"只看这个人;按住可改名字,或和别人合并" = "只看这个人;按住可改名字,或和别人合并";
+"正在准备…" = "正在准备…";
+"请在设置里允许知了使用麦克风" = "请在设置里允许知了使用麦克风";
+"识别中断了,请重新开始听" = "识别中断了,请重新开始听";
+
+/* SettingsView (iOS) */
+"在 Ling 开放平台点“创建令牌”,复制以 sk- 开头的那串。" = "在 Ling 开放平台点“创建令牌”,复制以 sk- 开头的那串。";
+"打开 Ling 开放平台 ↗" = "打开 Ling 开放平台 ↗";
+"Ling 提示此令牌无效,请检查是否复制完整,或重新创建一个" = "Ling 提示此令牌无效,请检查是否复制完整,或重新创建一个";
diff --git a/Sources/LiveSubs/Voices.swift b/Sources/LiveSubs/Voices.swift
index 85c68a5..00cca06 100644
--- a/Sources/LiveSubs/Voices.swift
+++ b/Sources/LiveSubs/Voices.swift
@@ -174,6 +174,9 @@ enum VoiceReference {
// MARK: Pace
+ #if !CICADA_IOS
+ // Mac app only, with the voice recorder below: it scores with the speak test's tokens (SpeakTest.swift).
+
/// Ming copies the recording's pace into every sentence: a recital at 1.7 characters a second
/// made each sentence about 4× as long as the built-in voice says it. Below these (characters
/// for Chinese, Japanese and Korean, words otherwise, per second of speech) the clone is too
@@ -233,6 +236,7 @@ enum VoiceReference {
savedPace = (date, slow)
return slow
}
+ #endif
/// The passage to read, in the user's own language.
static func passage(for locale: String) -> String {
diff --git a/docs/ios-plan.md b/docs/ios-plan.md
new file mode 100644
index 0000000..3ed48f0
--- /dev/null
+++ b/docs/ios-plan.md
@@ -0,0 +1,96 @@
+# 知了 iPhone / iPad 版技术方案
+
+状态:设计稿已有(claude.ai 画布“知了 iOS 设计”,9 屏)。M0 已在 Mac 上完成(2026-11-04,worktree `../live-subs-ios-core`、分支 `ios-core`,还没提交):12 个文件能脱离 Mac app 单独通过类型检查,Mac 的 117 个测试通过,开发版放示例会议的字幕、翻译、纪要、诊断、录音和三种导出都正常,英文界面也看过。M1 也已完成(同一天,Xcode 27.2 / iOS 27.2 模拟器):共用的 13 个文件用 iOS SDK 编译通过;iPhone 和 iPad 模拟器里能读 Mac 生成的会议记录,列表、文字记录、纪要、搜索、设置都能显示,中文和英文界面都正常,iPad 上是双栏;Mac 的测试在 Xcode 27 的编译器下也通过。
+
+iPhone 和 iPad 拿不到其他 app 的声音,也不能往别的 app 的麦克风里送声音,所以 iOS 版不是 Mac 版的移植,而是“面对面会议 + 导入录音 + 会议记录”的随身版:
+
+- 用麦克风听会议室,实时双语字幕和纪要
+- 面对面同声传译:按住说话,从扬声器念出译文
+- 导入录音或视频,在本机转成双语记录
+- 会议记录:搜索、双语全文、纪要、原声回放、导出 Markdown / Word / SRT
+- 引导、设置、实时活动和灵动岛
+
+第一版不做:听其他 app 的声音(ReplayKit 广播扩展,单独做原型再说)、往会议里送语音、会议软件挂断时自动结束(iOS 看不到别的 app 用不用麦克风,只靠 10 分钟没人说话结束)。
+
+## 关键决策
+
+| 决策 | 选择 | 原因 |
+|---|---|---|
+| 最低系统 | iOS / iPadOS 26 | 只用 `SpeechAnalyzer` 和 Apple 本机翻译,不需要 Mac 上 14.4–15 那条 `SFSpeechRecognizer` 退路;设计稿按 iOS 26 的液态玻璃做 |
+| 代码放哪 | 同仓库 `ios/`,引擎和 Mac 共用 | 和 Windows 不同,这里是同一种语言、同一套系统框架,共用比照抄省事,也最能保证纪要提示词和记录格式一致 |
+| 怎样共用 | 文件级共用:`ios/shared-sources.txt` 列出 Mac 的源文件,iOS 构建直接把它们和 `ios/Sources` 编成一个模块 | 不用拆 SwiftPM 库:拆库要给跨模块的类型和成员都加 `public`,还要改测试,Mac 端改动太大。现在 Mac 端只是拆了几个文件、加了几处 `#if`。iOS 能编译以后再看要不要拆成库 |
+| 构建 | `ios/scripts/build.sh`:`xcrun --sdk iphonesimulator swiftc` 编译,自己拼 `.app`,`simctl install` | 沿用 Mac“不用 `.xcodeproj`、脚本拼包”的做法;根目录“不建 `.xcodeproj`”这条只管 Mac。真机签名如果脚本搞不定,再评估 `.xcodeproj`,先在这里记下 |
+| 界面 | SwiftUI,按设计稿;iPad 用 `NavigationSplitView` 三栏 | 设计稿是真相来源,颜色、文案沿用 Mac |
+| 文案 | 中文作 key,和 Mac 共用 `Resources/*.lproj/Localizable.strings` | Mac 是参照;有 iOS SDK 时 `scripts/strings.py` 会一起检查 iOS 构建 |
+| Ling key | app 沙盒里的 `ling-api-key` 文件,保护级别是第一次解锁后可读(`completeFileProtectionUntilFirstUserAuthentication`),不进备份 | 对应 Mac 的 0600 文件。不用 `complete`:锁屏时还在听,从操作按钮锁屏启动时也要读 key 才能出纪要 |
+| 记录同步 | 第一版不做;以后用 iCloud Drive 放同一份 `session.json` | 格式本来就逐字节一致,能直接共用 |
+
+## 能共用的代码
+
+`ios/scripts/typecheck.sh` 会把共用的文件和 `ios/Sources` 一起做类型检查,还会挡住 iOS 没有的框架导入(AppKit、CoreAudio、SwiftUI…)。现在没有 Xcode,只能用 `SDK=macosx` 跑。两种 `#if` 的用法:需要 AppKit 的用 `#if os(macOS)`;需要 Mac app 其他部分的用 `#if !CICADA_IOS`,iOS 构建会设这个标志。
+
+M0、M1 已经共用的 13 个文件,以及 M1 起要做的:
+
+| 文件 | 状态 |
+|---|---|
+| `Ling.swift`、`Notes.swift`、`HeardText.swift`、`MeetingEnd.swift`、`Localization.swift`、`Translator.swift` | 已共用。`LingCall` 从 `Diagnostics.swift` 搬进 `Ling.swift`,`appDisplayName` 从 `SettingsWindow.swift` 搬进 `Localization.swift`,`Translator.swift` 去掉了用不到的 AppKit 和 CoreAudio 导入;iOS 上 key 文件加了文件保护 |
+| `SessionStore.swift` | 已共用。记录格式、Markdown、SRT 两边一样。Word 导出靠 `NSAttributedString` 的 `.officeOpenXML`,这个只有 macOS 有,所以放在 `#if os(macOS)` 里;iOS 在 M3 写一个不靠第三方的最小 `.docx` 生成器(几个 XML 文件加一个不压缩的 zip,CRC32 自己算),做好后两端都换成它 |
+| `SpeakerID.swift` | 已共用。声纹、聚类、起名留在这里,界面拆到只给 Mac 用的 `SpeakerViews.swift` |
+| `Diagnostics.swift` | 已共用。记录器留在这里,设置里的诊断页拆到 `DiagnosticsView.swift` |
+| `AudioFiles.swift` | 新文件,从 `AudioRouter.swift` 原样搬来 `PCMConverter` 和 `AudioFileWriter` |
+| `RecordList.swift` | 新文件,会议列表的分组、标题、时间和时长,从 Mac 的 `Views.swift` 原样搬来 |
+| `Voices.swift` | 已共用。声音列表和参考音频共用;克隆用的录音器 `VoiceRecorder` 绑在 Mac 的输入设备上,放在 `#if !CICADA_IOS` 里,iOS 在 M3 自己写 |
+| `ios/Sources/Cicada/DevBuild.swift` | iOS 版的 `DevBuild` 和 `debugLog`,日志写在 app 容器的 Caches 里 |
+| `Recognition.swift`、`FileImport.swift` | 还没共用:这两个文件正在改,等改完提交后再搬。`SpeechAnalyzer` 部分共用,`SFSpeechRecognizer` 退路只留给 Mac |
+| `Settings.swift` 的 `AppSettings` | M2:拆成共用的听写和翻译设置,以及 Mac 独有的设置 |
+
+留在 Mac:`SystemAudioTap`、`AudioRouter`(Core Audio HAL)、`VirtualMic`、`SystemMic`、`MicUsers`、`Shortcuts`、`LoginItem`、`Updater` / `Updates` / `UpdateChecker`、所有窗口和菜单。
+
+iOS 新写:
+
+| 文件 | 作用 | 对应 Mac |
+|---|---|---|
+| `ios/Sources/Cicada/RoomListen.swift` | `AVAudioSession`(`.playAndRecord`、`.measurement`)+ `AVAudioEngine` 麦克风 → 共用的识别和翻译 | `RoomMic.swift`、`ListenEngine.swift` 的会议室部分 |
+| `FaceToFace.swift` | 按住说话 → Ming(有 key)或本机识别 + 翻译 → 扬声器;念的时候暂停听 | `SpeakEngine.swift` 去掉虚拟麦克风 |
+| `AppModel.swift` | 把引擎接到界面;调试命令 | `AppModel.swift` |
+| `Views/…` | 设计稿的 9 屏 | `Views.swift`、`NotesViews.swift`、`Onboarding.swift`… |
+| `LiveActivity/`(扩展) | 灵动岛和锁屏卡片,按钮走 App Intent,只能点按 | 无 |
+| `Intents.swift` | “开始听”给操作按钮、控制中心和 Siri | 无 |
+
+## 后台和权限
+
+- 正在听时开 `audio` 后台模式,锁屏也继续听;状态栏有橙点。Ling 和翻译请求在后台照常发。
+- 导入用 `BGContinuedProcessingTask`(iOS 26),切到别的 app 也继续转,系统显示进度。
+- 权限只问麦克风和语音识别,分别在第一次听和引导第一步时问;拒绝了,导入和会议记录照常能用。
+
+## 开发环境和验证
+
+- 装 Xcode 26(App Store,要 Apple ID),然后 `sudo xcode-select -s /Applications/Xcode.app/Contents/Developer`、`xcodebuild -downloadPlatform iOS`。模拟器不需要开发者账号;真机要在 Xcode 里登录 Apple ID。
+- `ios/scripts/build.sh` 编译模拟器版,`ios/scripts/run.sh` 装进 iPhone 和 iPad 模拟器并启动。
+- 调试通道:`ios/scripts/ctl.sh <命令>` 把命令写进 app 容器的 `Library/Caches/debug-command`,再发一个 Darwin 通知叫醒 app。命令名和 Mac 的 `AppModel.debugCommand` 一致。`simctl openurl` 打开 `cicada-dev://` 也行,但模拟器每次都要人点确认。日志在 app 容器的 `Library/Caches/livesubs-dev-debug.log`;截图用 `simctl io <设备> screenshot`,对照设计稿。
+- 听会议室在模拟器里用 Mac 的麦克风:`afplay Resources/sample/sample.m4a` 就能当输入。
+- 要人来验证的:真机麦克风、锁屏后台、灵动岛、外接键盘的右 ⌥、TestFlight 分发。
+
+## 里程碑
+
+| 阶段 | 产出 | 怎样算完成 |
+|---|---|---|
+| **M0 共用引擎**(已完成) | `ios/shared-sources.txt`、`ios/scripts/typecheck.sh`,第一批 12 个文件 | macOS SDK 下类型检查通过;Mac 的 `scripts/test.sh` 通过;开发版播 `sample.m4a`,字幕、纪要、录音、导出都正常;英文界面正常 |
+| **M1 跑起来**(已完成) | `ios/` 骨架、构建脚本、模拟器里能启动;会议记录列表和详情读 Mac 生成的 `session.json`;`scripts/strings.py` 也扫 `ios/` | iPhone 和 iPad 模拟器截图和设计稿对得上 |
+| **M2 听会议室** | 麦克风 → 字幕 → 纪要 → 存记录;引导、设置、Ling key | 模拟器里放示例会议,字幕和纪要跟上;生成的记录 Mac 能打开 |
+| **M3 说和导入** | 面对面同声传译、导入录音或视频、导出 | 导入 `sample.m4a` 得到和 Mac 一致的记录;按住说话能念出译文 |
+| **M4 能发布** | 实时活动和灵动岛、App Intents、四种界面语言、TestFlight;`scripts/changelog.py` 加 `(ios)` 分组 | 一台没装过的 iPhone 从 TestFlight 装上到第一次出字幕顺利走完 |
+
+## 风险
+
+1. **不用 `.xcodeproj` 能不能签真机、打 TestFlight 包**:模拟器肯定可以;真机要描述文件,扩展还要单独签。M1 先做出模拟器版,M4 前定方案,不行就只给 `ios/` 加一个最小的 `.xcodeproj`。
+2. **共用引擎拖累 Mac**:每次只搬几个文件,搬完跑 Mac 的测试和真机行为;搬的时候逻辑一行不改。
+3. **macOS SDK 的类型检查不够**:它只能证明共用的文件不依赖 Mac app 的其余部分;只有 macOS 才有的 Foundation 或 AVFoundation 接口(比如 `.officeOpenXML`)它查不出来,要等 Xcode 装好后用 iOS SDK 再跑一遍。
+4. **App Store 审核**:麦克风和语音识别的用途说明要写清楚;Ling key 由用户自己填,不涉及内购。
+5. **iPhone 内存**:`SpeechAnalyzer`、声纹模型和录音同时跑,在旧机型上要实测;不够就默认关说话人识别。
+
+## 发布时要一起改
+
+- `README.md`、`README.en.md` 的路线图,`docs/ROADMAP.md`、`docs/ROADMAP.zh-CN.md` 里“iPhone / iPad 暂不计划”那一行
+- 根目录 `AGENTS.md` 开头的平台列表(iOS 也会说,不只是听)
+- `site/` 的下载入口和 `site/changelog.json`
diff --git a/ios/AGENTS.md b/ios/AGENTS.md
new file mode 100644
index 0000000..bc1010e
--- /dev/null
+++ b/ios/AGENTS.md
@@ -0,0 +1,10 @@
+# AGENTS.md (iOS / iPadOS)
+
+The iPhone and iPad app: listens to the room with the microphone, interprets face to face through the speaker, imports recordings and keeps meeting records. It cannot hear other apps or speak into them. The root `AGENTS.md` applies too (Ling key, `LingClient`, no third-party dependencies, the Mac app as the reference, one `VERSION`). The plan is `docs/ios-plan.md`; the design canvas on claude.ai (知了 iOS 设计) is the source of truth for the UI.
+
+- iOS / iPadOS 26 and later, SwiftUI. Engines are the Mac's own files, listed in `ios/shared-sources.txt` and compiled into the iOS app; `ios/Sources` has the iOS side. Change a shared file and keep both working: `ios/scripts/typecheck.sh`, then `scripts/test.sh` and a Mac dev build.
+- Built by `ios/scripts/build.sh` with `xcrun swiftc`, no `.xcodeproj` until device signing proves it needs one. Needs full Xcode, not only the Command Line Tools.
+- The key: the `ling-api-key` file in the app container readable only after the first unlock (listening goes on while locked), excluded from backups; never UserDefaults, logs or exports.
+- UI text: the same Chinese keys and `Resources/*.lproj/Localizable.strings` as the Mac; reuse a Mac key where the feature is the same. `python3 scripts/strings.py` checks the iOS build too when Xcode is there.
+- Verify in the iPhone and iPad simulators: `ios/scripts/build.sh`, `ios/scripts/run.sh "<device>" [--seed <Mac meeting folders>]`, drive it with `ios/scripts/ctl.sh` (commands in `Debug.swift`), read `Library/Caches/livesubs-dev-debug.log` in the app container, `xcrun simctl io <device> screenshot` against the design; pass `-AppleLanguages "(zh-Hans)"` to `simctl launch` for Chinese. A real microphone, the lock screen, the Dynamic Island and TestFlight need a person.
+- Commits use the `(ios)` scope. `scripts/changelog.py` has no iOS group yet (M4 in the plan); until then such commits land under Mac.
diff --git a/ios/CLAUDE.md b/ios/CLAUDE.md
new file mode 100644
index 0000000..43c994c
--- /dev/null
+++ b/ios/CLAUDE.md
@@ -0,0 +1 @@
diff --git a/ios/LiveActivity/CicadaLive.swift b/ios/LiveActivity/CicadaLive.swift
new file mode 100644
index 0000000..2c805e8
--- /dev/null
+++ b/ios/LiveActivity/CicadaLive.swift
@@ -0,0 +1,110 @@
+import ActivityKit
+import SwiftUI
+import WidgetKit
+
+// The CicadaLive extension: draws ListenActivity (ios/Sources/Cicada/ListenActivity.swift) on the
+// lock screen and in the Dynamic Island. Built by ios/scripts/build.sh into PlugIns/CicadaLive.appex.
+
+@main
+struct CicadaLiveBundle: WidgetBundle {
+ var body: some Widget { ListenLiveActivity() }
+}
+
+private enum LiveInk {
+ static let ink = Color(red: 0x15 / 255, green: 0x17 / 255, blue: 0x1C / 255)
+ static let accent = Color(red: 0xE8 / 255, green: 0x55 / 255, blue: 0x2B / 255)
+ static let grey = Color(red: 0x5A / 255, green: 0x5F / 255, blue: 0x6B / 255)
+ static let ground = Color(red: 0xF3 / 255, green: 0xF4 / 255, blue: 0xF6 / 255)
+}
+
+private struct LiveLogo: View {
+ let size: CGFloat
+ private static let image = Bundle.main.path(forResource: "logo", ofType: "png").flatMap(UIImage.init(contentsOfFile:))
+
+ var body: some View {
+ Group {
+ if let image = Self.image { Image(uiImage: image).resizable().scaledToFill().scaleEffect(1.24) } else { LiveInk.accent }
+ }
+ .frame(width: size, height: size)
+ .clipShape(RoundedRectangle(cornerRadius: size / 4, style: .continuous))
+ }
+}
+
+/// The elapsed time, counting up from the start, ticked by the system.
+private struct Elapsed: View {
+ let since: Date
+ var body: some View {
+ Text(timerInterval: since...Date.distantFuture, countsDown: false)
+ .monospacedDigit()
+ }
+}
+
+struct ListenLiveActivity: Widget {
+ var body: some WidgetConfiguration {
+ ActivityConfiguration(for: ListenActivity.self) { context in
+ // Lock screen: the logo, 正在听 · time, the languages, and the newest line.
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(spacing: 10) {
+ LiveLogo(size: 34)
+ VStack(alignment: .leading, spacing: 1) {
+ HStack(spacing: 6) {
+ Circle().fill(LiveInk.accent).frame(width: 7, height: 7)
+ Text("正在听").font(.footnote.weight(.semibold)).foregroundStyle(LiveInk.accent)
+ Elapsed(since: context.attributes.startedAt).font(.footnote.weight(.semibold)).foregroundStyle(LiveInk.accent)
+ }
+ Text(verbatim: "\(String(localized: "会议室")) · \(context.attributes.pair)")
+ .font(.subheadline.weight(.semibold)).foregroundStyle(LiveInk.ink)
+ }
+ Spacer()
+ if context.state.people >= 2 {
+ Text(String(localized: "\(context.state.people) 人在说")).font(.caption).foregroundStyle(LiveInk.grey)
+ }
+ }
+ if !context.state.line.isEmpty {
+ Text(context.state.line).font(.callout).foregroundStyle(LiveInk.ink).lineLimit(2)
+ } else {
+ Text("开始说话后,字幕会出现在这里").font(.callout).foregroundStyle(LiveInk.grey)
+ }
+ }
+ .padding(16)
+ .activityBackgroundTint(LiveInk.ground.opacity(0.92))
+ .activitySystemActionForegroundColor(LiveInk.ink)
+ } dynamicIsland: { context in
+ DynamicIsland {
+ DynamicIslandExpandedRegion(.leading) {
+ HStack(spacing: 8) {
+ LiveLogo(size: 26)
+ Text("正在听").font(.footnote.weight(.semibold)).foregroundStyle(LiveInk.accent)
+ }
+ .padding(.leading, 4)
+ }
+ DynamicIslandExpandedRegion(.trailing) {
+ Elapsed(since: context.attributes.startedAt).font(.footnote.weight(.semibold))
+ .foregroundStyle(.white).frame(maxWidth: 64, alignment: .trailing).padding(.trailing, 4)
+ }
+ DynamicIslandExpandedRegion(.bottom) {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(context.state.line.isEmpty ? String(localized: "开始说话后,字幕会出现在这里") : context.state.line)
+ .font(.callout).foregroundStyle(.white).lineLimit(2)
+ Text(verbatim: "\(String(localized: "会议室")) · \(context.attributes.pair)")
+ .font(.caption2).foregroundStyle(.white.opacity(0.6))
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 4)
+ }
+ } compactLeading: {
+ HStack(spacing: 5) {
+ Circle().fill(LiveInk.accent).frame(width: 7, height: 7)
+ LiveLogo(size: 20)
+ }
+ } compactTrailing: {
+ Elapsed(since: context.attributes.startedAt)
+ .font(.caption.weight(.semibold)).foregroundStyle(LiveInk.accent)
+ .frame(maxWidth: 46)
+ } minimal: {
+ Circle().fill(LiveInk.accent).frame(width: 9, height: 9)
+ }
+ .keylineTint(LiveInk.accent)
+ }
+ }
+}
diff --git a/ios/LiveActivity/Info.plist b/ios/LiveActivity/Info.plist
new file mode 100644
index 0000000..df450e6
--- /dev/null
+++ b/ios/LiveActivity/Info.plist
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>en</string>
+ <key>CFBundleDisplayName</key>
+ <string>Cicada</string>
+ <key>CFBundleExecutable</key>
+ <string>CicadaLive</string>
+ <key>CFBundleIdentifier</key>
+ <string>com.wquguru.cicada.live</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>CicadaLive</string>
+ <key>CFBundlePackageType</key>
+ <string>XPC!</string>
+ <key>CFBundleShortVersionString</key>
+ <string>1.0.0</string>
+ <key>CFBundleVersion</key>
+ <string>1</string>
+ <key>CFBundleSupportedPlatforms</key>
+ <array>
+ <string>iPhoneSimulator</string>
+ </array>
+ <key>MinimumOSVersion</key>
+ <string>26.0</string>
+ <key>NSExtension</key>
+ <dict>
+ <key>NSExtensionPointIdentifier</key>
+ <string>com.apple.widgetkit-extension</string>
+ </dict>
+</dict>
+</plist>
diff --git a/ios/Resources/Info.plist b/ios/Resources/Info.plist
new file mode 100644
index 0000000..644340b
--- /dev/null
+++ b/ios/Resources/Info.plist
@@ -0,0 +1,70 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>en</string>
+ <key>CFBundleDisplayName</key>
+ <string>Cicada</string>
+ <key>CFBundleExecutable</key>
+ <string>Cicada</string>
+ <key>CFBundleIdentifier</key>
+ <string>com.wquguru.cicada</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleLocalizations</key>
+ <array>
+ <string>zh-Hans</string>
+ <string>zh-Hant</string>
+ <string>en</string>
+ <string>ja</string>
+ <string>ko</string>
+ </array>
+ <key>CFBundleName</key>
+ <string>Cicada</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>1.0.0</string>
+ <key>CFBundleVersion</key>
+ <string>1</string>
+ <key>CFBundleSupportedPlatforms</key>
+ <array>
+ <string>iPhoneSimulator</string>
+ </array>
+ <key>LSRequiresIPhoneOS</key>
+ <true/>
+ <key>MinimumOSVersion</key>
+ <string>26.0</string>
+ <key>UIDeviceFamily</key>
+ <array>
+ <integer>1</integer>
+ <integer>2</integer>
+ </array>
+ <key>NSMicrophoneUsageDescription</key>
+ <string>Cicada listens to the people in the room to show live translated subtitles and notes.</string>
+ <key>NSSpeechRecognitionUsageDescription</key>
+ <string>Cicada turns what is said in the room into text on this device.</string>
+ <key>NSSupportsLiveActivities</key>
+ <true/>
+ <key>UIBackgroundModes</key>
+ <array>
+ <string>audio</string>
+ </array>
+ <key>UILaunchScreen</key>
+ <dict/>
+ <key>UIApplicationSupportsIndirectInputEvents</key>
+ <true/>
+ <key>UISupportedInterfaceOrientations</key>
+ <array>
+ <string>UIInterfaceOrientationPortrait</string>
+ </array>
+ <key>UISupportedInterfaceOrientations~ipad</key>
+ <array>
+ <string>UIInterfaceOrientationPortrait</string>
+ <string>UIInterfaceOrientationPortraitUpsideDown</string>
+ <string>UIInterfaceOrientationLandscapeLeft</string>
+ <string>UIInterfaceOrientationLandscapeRight</string>
+ </array>
+</dict>
+</plist>
diff --git a/ios/Sources/Cicada/CicadaApp.swift b/ios/Sources/Cicada/CicadaApp.swift
new file mode 100644
index 0000000..4a4585b
--- /dev/null
+++ b/ios/Sources/Cicada/CicadaApp.swift
@@ -0,0 +1,220 @@
+import SwiftUI
+
+@main
+struct CicadaApp: App {
+ @StateObject private var model = AppModel()
+
+ var body: some Scene {
+ WindowGroup {
+ RootView()
+ .environmentObject(model)
+ .environmentObject(model.ling)
+ .environmentObject(model.notes)
+ .environmentObject(model.room)
+ .onOpenURL { model.open($0) }
+ .modifier(DevWindow(model: model))
+ }
+ }
+}
+
+enum AppTab: String { case records, settings, search }
+
+/// Settings the iOS app shares with the Mac by name (AppSettings in Settings.swift), so a record
+/// and its languages mean the same thing on both.
+enum Pref {
+ /// 对方说: "auto" or a `sourceLanguages` locale.
+ static let source = "sourceMode"
+ /// 翻译成: "system" or a `targetLanguages` code.
+ static let target = "target"
+ static let model = "aiModel"
+ /// 说话人识别.
+ static let voices = "speakerVoices"
+ /// 纪要语言: "mine" (the language meetings are translated into) or "source" (the meeting's own).
+ static let notesLanguage = "notesLanguage"
+
+ /// 对方说 on iOS: one language the user picks (detecting it comes later); the Mac's "auto" reads as English.
+ static var sourceLang: Lang {
+ let v = UserDefaults.standard.string(forKey: source) ?? "en-US"
+ return sourceLanguages.first { $0.locale == v } ?? sourceLanguages[0]
+ }
+
+ /// 对方说 in the UI's language ("英语", "English"), as the Mac's menu shows it.
+ static func name(of lang: Lang) -> String {
+ Locale.current.localizedString(forLanguageCode: lang.code) ?? lang.name
+ }
+ static var sourceName: String { name(of: sourceLang) }
+
+ /// "英 → 中" for two translation codes, as a meeting row says it.
+ static func pairText(_ source: String, _ target: String) -> String {
+ let line = TranscriptLine(id: "", t: 0, speaker: "them", src: "", dst: nil, srcLang: source, dstLang: target)
+ let s = Session(id: "", title: "", startedAt: Date(), endedAt: nil, lines: [line], hasAudio: false)
+ return RecordList.pair(s, short: true) ?? ""
+ }
+
+ static var targetCode: String {
+ let t = UserDefaults.standard.string(forKey: target) ?? "system"
+ return t == "system" ? myLanguage(systemLanguages: Locale.preferredLanguages) : t
+ }
+}
+
+/// Wires the shared engines to the screens, like the Mac's AppModel. M1: the records, the key and
+/// their notes.
+@MainActor
+final class AppModel: ObservableObject {
+ @Published var store = SessionStore()
+ let ling = LingClient()
+ lazy var notes = NotesEngine(ling: ling, store: store)
+ lazy var translator = TranslationService(ling: ling)
+ lazy var room: RoomListen = {
+ let r = RoomListen(store: store, translator: translator, notes: notes)
+ r.onStateChange = { [weak self] in self?.listeningChanged() }
+ r.onLine = { [weak self] line in self?.liveActivity.update(line: line) }
+ return r
+ }()
+ let liveActivity = LiveActivityController()
+ /// 正在听's 字幕 / 纪要 switch, so a debug command can flip it.
+ @Published var livePage: LivePage = .subtitles
+ /// The record page's picked speaker (scheme A: only they are drawn in ink).
+ @Published var focusSpeaker: Int?
+ @Published var tab: AppTab = .records
+ @Published var selection: String?
+ /// A meeting opened from 搜索 (iPhone).
+ @Published var searchPath: [String] = []
+ /// The record page's 文字记录 / 纪要 switch, kept here so a debug command can flip it.
+ @Published var recordPage: RecordPage = .transcript
+ @Published var query = ""
+ /// iPad: settings is a sheet over the records.
+ @Published var showSettings = false
+ /// What the 听会议室 card and the import button would start; they come with M2 and M3.
+ @Published var comingSoon: String?
+ /// "说话人 6 已改成 David · 撤销", for a few seconds after a speaker edit, as on the Mac.
+ @Published var speakerUndo: SpeakerUndo?
+ /// The speaker number whose 是谁 prompt is open on the record page.
+ @Published var namingSpeaker: Int?
+ /// Dev only: the iPad window size `window:` lays the app out at (DevWindow in Debug.swift).
+ @Published var devWindow: CGSize?
+
+ init() {
+ UserDefaults.standard.register(defaults: [Pref.source: "en-US", Pref.voices: true, Pref.model: LingClient.models[0], Pref.notesLanguage: "mine"])
+ TranscriptExport.voices = UserDefaults.standard.bool(forKey: Pref.voices)
+ // Ling only for now: the Mac's other services (AIProvider) come to iOS with their settings.
+ ling.config = {
+ AIConfig(provider: .ling, base: AIProvider.ling.base,
+ textModel: UserDefaults.standard.string(forKey: Pref.model) ?? LingClient.models[0])
+ }
+ wireNotes()
+ #if targetEnvironment(simulator)
+ HostRecognizer.install()
+ #endif
+ DebugChannel.listen(self)
+ debugLog("ios launch \(DevBuild.label ?? "release") sessions=\(store.sessions.count) key=\(ling.hasKey)")
+ if ling.hasKey { Task { await ling.check() } }
+ }
+
+ // MARK: 听会议室
+
+ func startListening() {
+ guard !room.isRunning else { return }
+ selection = nil
+ searchPath = []
+ tab = .records
+ room.start(source: Pref.sourceLang.locale, target: Pref.targetCode, voices: UserDefaults.standard.bool(forKey: Pref.voices))
+ }
+
+ func stopListening() { room.stop() }
+
+ private func listeningChanged() {
+ objectWillChange.send()
+ if room.isRunning, let start = room.startedAt {
+ liveActivity.start(startedAt: start, pair: Pref.pairText(room.languagePair.source, room.languagePair.target))
+ } else if !room.isRunning {
+ liveActivity.end()
+ }
+ }
+
+ /// Full notes for a stored meeting, as the Mac's 生成纪要.
+ func generateNotes(_ id: String) {
+ guard ling.hasKey else { return }
+ recordPage = .notes
+ notes.generate(for: id)
+ }
+
+ func wireNotes() {
+ notes.language = { [weak self] id in TranslationService.englishName(self?.notesLanguageCode(id) ?? Pref.targetCode) }
+ }
+
+ // MARK: Notes language (the Mac's AppModel.notesLanguageCode)
+
+ /// The language the other side spoke most in a meeting.
+ func meetingLanguage(_ id: String) -> String? {
+ let heard = store.session(id)?.lines.filter { $0.speaker != "me" }.map(\.srcLang) ?? []
+ return Dictionary(heard.map { ($0, 1) }, uniquingKeysWith: +).max { $0.value < $1.value }?.key
+ }
+
+ func notesLanguageCode(_ id: String) -> String {
+ UserDefaults.standard.string(forKey: Pref.notesLanguage) == "source" ? (meetingLanguage(id) ?? Pref.targetCode) : Pref.targetCode
+ }
+
+ // MARK: Editing a record (the Mac's rules live in SessionStore)
+
+ /// An unchanged title isn't a rename; an empty one goes back to the automatic title.
+ func rename(_ id: String, to title: String) {
+ store.rename(id, to: title)
+ debugLog("rename \(id) renamed=\(store.session(id)?.renamed ?? false)")
+ }
+
+ func deleteSession(_ id: String) {
+ if selection == id { selection = nil }
+ searchPath.removeAll { $0 == id }
+ if speakerUndo?.session == id { speakerUndo = nil }
+ store.delete(id)
+ debugLog("delete \(id) sessions=\(store.sessions.count)")
+ }
+
+ // MARK: Speakers (the Mac's AppModel.renameSpeaker / mergeSpeaker / undoSpeakerEdit)
+
+ /// Name a voice ("" keeps 说话人 N, nil goes back to Ling's guess).
+ func renameSpeaker(session id: String, voice: Int, _ name: String?) {
+ guard let s = store.session(id) else { return }
+ let n = SpeakerLabels.voiceNumbers(s.lines)[voice] ?? 0
+ let before = SpeakerLabels.label(n, SpeakerLabels.names(s))
+ speakerEdit(id) { store.setVoiceName(id, voice: voice, name) }
+ let after = store.session(id).map { SpeakerLabels.label(n, SpeakerLabels.names($0)) } ?? before
+ if after != before { speakerUndo?.text = L("\(before) 已改成 \(after)") } else { speakerUndo = nil }
+ }
+
+ /// Two voices are one person.
+ func mergeSpeaker(session id: String, _ from: Int, into: Int) {
+ guard let s = store.session(id) else { return }
+ let numbers = SpeakerLabels.voiceNumbers(s.lines), names = SpeakerLabels.names(s)
+ let a = SpeakerLabels.label(numbers[from] ?? 0, names), b = SpeakerLabels.label(numbers[into] ?? 0, names)
+ speakerEdit(id) { store.mergeVoice(id, from, into: into) }
+ speakerUndo?.text = L("\(a) 已并入 \(b)")
+ }
+
+ func undoSpeakerEdit() {
+ guard let u = speakerUndo else { return }
+ speakerUndo = nil
+ store.restore(u.session, u.snapshot)
+ debugLog("speakers: undo \(u.session)")
+ }
+
+ private func speakerEdit(_ id: String, _ change: () -> Void) {
+ guard let snap = store.voiceSnapshot(id) else { return }
+ change()
+ let undo = SpeakerUndo(session: id, snapshot: snap, text: "")
+ speakerUndo = undo
+ debugLog("speakers: edit \(id)")
+ DispatchQueue.main.asyncAfter(deadline: .now() + 6) { [weak self] in
+ if self?.speakerUndo?.id == undo.id { self?.speakerUndo = nil }
+ }
+ }
+
+ /// cicada-dev://debug?cmd=… (dev builds only).
+ func open(_ url: URL) {
+ guard DevBuild.isDev, url.scheme == "cicada-dev", url.host == "debug",
+ let cmd = URLComponents(url: url, resolvingAgainstBaseURL: false)?
+ .queryItems?.first(where: { $0.name == "cmd" })?.value else { return }
+ debugCommand(cmd)
+ }
+}
diff --git a/ios/Sources/Cicada/Components.swift b/ios/Sources/Cicada/Components.swift
new file mode 100644
index 0000000..cd9e939
--- /dev/null
+++ b/ios/Sources/Cicada/Components.swift
@@ -0,0 +1,135 @@
+import SwiftUI
+
+// The pieces the design canvas (知了 iOS 设计) is built from: white cards on the grey ground,
+// grey section labels, a grey pill switch, hairlines, and Liquid Glass for what floats.
+
+/// A white card, the design's 22 pt corners.
+struct Card<Content: View>: View {
+ var radius: CGFloat = 22
+ @ViewBuilder var content: Content
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) { content }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Color.white, in: RoundedRectangle(cornerRadius: radius, style: .continuous))
+ }
+}
+
+/// The grey label above a card ("今天", "AI 服务").
+struct SectionLabel: View {
+ let text: String
+
+ var body: some View {
+ Text(text)
+ .font(.footnote)
+ .foregroundStyle(Ink.secondary)
+ .padding(.horizontal, 16)
+ .padding(.top, 22)
+ .padding(.bottom, 8)
+ }
+}
+
+/// The 0.5 pt line between rows in a card, inset like the design's.
+struct Hairline: View {
+ var inset: CGFloat = 16
+
+ var body: some View {
+ Rectangle().fill(Ink.line).frame(height: 0.5).padding(.leading, inset)
+ }
+}
+
+/// The design's two-way switch: a grey track, the picked side a white pill with a soft shadow.
+struct PillSwitch<Value: Hashable>: View {
+ @Binding var selection: Value
+ let options: [(Value, LocalizedStringKey)]
+
+ var body: some View {
+ HStack(spacing: 0) {
+ ForEach(options, id: \.0) { value, title in
+ let on = selection == value
+ Button {
+ withAnimation(.snappy(duration: 0.2)) { selection = value }
+ } label: {
+ Text(title)
+ .font(.subheadline.weight(.semibold))
+ .foregroundStyle(on ? Ink.ink : Ink.secondary)
+ .frame(maxWidth: .infinity, minHeight: 30)
+ .background {
+ if on {
+ Capsule().fill(Color.white).shadow(color: Ink.ink.opacity(0.12), radius: 1.5, y: 1)
+ }
+ }
+ .contentShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(on ? .isSelected : [])
+ }
+ }
+ .padding(3)
+ .background(Ink.ground, in: Capsule())
+ }
+}
+
+/// A row's trailing chevron.
+struct Chevron: View {
+ var body: some View {
+ Image(systemName: "chevron.right")
+ .font(.footnote.weight(.semibold))
+ .foregroundStyle(Ink.tertiary)
+ .accessibilityHidden(true)
+ }
+}
+
+/// The design's round glass buttons (back, import, the trailing pair on a record): 44 pt, ink icon.
+struct GlassIcon: View {
+ let systemName: String
+ var size: CGFloat = 44
+
+ var body: some View {
+ Image(systemName: systemName)
+ .font(.system(size: 17, weight: .semibold))
+ .foregroundStyle(Ink.ink)
+ .frame(width: size, height: size)
+ .glassEffect(.regular.interactive(), in: Circle())
+ }
+}
+
+/// Lays out chips left to right and wraps, so every voice shows without scrolling sideways.
+struct FlowLayout: Layout {
+ var spacing: CGFloat = 8
+
+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
+ let rows = arrange(width: proposal.width ?? .infinity, subviews)
+ return CGSize(width: rows.map(\.width).max() ?? 0, height: rows.last.map { $0.y + $0.height } ?? 0)
+ }
+
+ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
+ for row in arrange(width: bounds.width, subviews) {
+ var x = bounds.minX
+ for i in row.items {
+ let s = subviews[i].sizeThatFits(.unspecified)
+ subviews[i].place(at: CGPoint(x: x, y: bounds.minY + row.y), proposal: ProposedViewSize(s))
+ x += s.width + spacing
+ }
+ }
+ }
+
+ private struct Row { var items: [Int] = []; var width: CGFloat = 0; var height: CGFloat = 0; var y: CGFloat = 0 }
+
+ private func arrange(width: CGFloat, _ subviews: Subviews) -> [Row] {
+ var rows: [Row] = [Row()]
+ for i in subviews.indices {
+ let s = subviews[i].sizeThatFits(.unspecified)
+ if !rows[rows.count - 1].items.isEmpty, rows[rows.count - 1].width + spacing + s.width > width {
+ let last = rows[rows.count - 1]
+ rows.append(Row(y: last.y + last.height + spacing))
+ }
+ var r = rows[rows.count - 1]
+ r.width += (r.items.isEmpty ? 0 : spacing) + s.width
+ r.height = max(r.height, s.height)
+ r.items.append(i)
+ rows[rows.count - 1] = r
+ }
+ return rows
+ }
+}
diff --git a/ios/Sources/Cicada/Debug.swift b/ios/Sources/Cicada/Debug.swift
new file mode 100644
index 0000000..ae31a1a
--- /dev/null
+++ b/ios/Sources/Cicada/Debug.swift
@@ -0,0 +1,162 @@
+import SwiftUI
+import UIKit
+
+/// The iOS side of the Mac's `AppModel.debugCommand`. `ios/scripts/ctl.sh <cmd>` writes the command
+/// into the container's Caches/debug-command and posts a Darwin notification, which wakes us here;
+/// `simctl openurl` with cicada-dev://debug?cmd=… works too but asks for confirmation every time.
+/// Same names as on the Mac where the command means the same thing.
+enum DebugChannel {
+ static let name = "com.wquguru.cicada.debug" as CFString
+ static var file: URL {
+ FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("debug-command")
+ }
+
+ @MainActor static func listen(_ model: AppModel) {
+ guard DevBuild.isDev else { return }
+ let center = CFNotificationCenterGetDarwinNotifyCenter()
+ CFNotificationCenterAddObserver(center, Unmanaged.passUnretained(model).toOpaque(), { _, observer, _, _, _ in
+ guard let observer else { return }
+ let model = Unmanaged<AppModel>.fromOpaque(observer).takeUnretainedValue()
+ DispatchQueue.main.async { MainActor.assumeIsolated { DebugChannel.drain(model) } }
+ }, name, nil, .deliverImmediately)
+ }
+
+ /// One command per line, run in order.
+ @MainActor static func drain(_ model: AppModel) {
+ guard let text = try? String(contentsOf: file, encoding: .utf8) else { return }
+ try? FileManager.default.removeItem(at: file)
+ for line in text.split(separator: "\n") where !line.isEmpty { model.debugCommand(String(line)) }
+ }
+}
+
+extension AppModel {
+ func debugCommand(_ cmd: String) {
+ debugLog("debug command: \(cmd)")
+ let (name, arg) = cmd.split(separator: ":", maxSplits: 1).map(String.init).splitPair
+ switch name {
+ case "open":
+ tab = .records
+ selection = nil
+ case "settings":
+ // iPhone: the tab; iPad: the sheet (the app can't tell which from here, so both).
+ tab = .settings
+ showSettings = true
+ case "closeSettings":
+ showSettings = false
+ tab = .records
+ case "listen", "start":
+ startListening()
+ case "window":
+ // window:half|landscape|landscapeHalf|full: the iPad window drawn at that size (DevWindow).
+ let s = UIApplication.shared.connectedScenes.compactMap { ($0 as? UIWindowScene)?.screen.bounds.size }.first ?? .zero
+ let (short, long) = (min(s.width, s.height), max(s.width, s.height))
+ switch arg {
+ case "half": devWindow = CGSize(width: (short - 10) / 2, height: long)
+ case "landscape": devWindow = CGSize(width: long, height: short)
+ case "landscapeHalf": devWindow = CGSize(width: (long - 10) / 2, height: short)
+ default: devWindow = nil
+ }
+ debugLog("window: \(arg) \(devWindow.map { "\($0)" } ?? "screen")")
+ case "stop":
+ stopListening()
+ case "import":
+ // What the import button shows until M3.
+ comingSoon = L("导入录音或视频")
+ case "livePage":
+ livePage = arg == "notes" ? .notes : .subtitles
+ case "source":
+ // source:<locale>, 对方说 (en-US, ja-JP…)
+ UserDefaults.standard.set(arg, forKey: Pref.source)
+ case "target":
+ // target:<code|system>, 翻译成
+ UserDefaults.standard.set(arg, forKey: Pref.target)
+ case "focusSpeaker":
+ // focusSpeaker:<speaker number>, as tapping a chip; empty clears it
+ focusSpeaker = Int(arg)
+ case "play":
+ NotificationCenter.default.post(name: .debugPlay, object: Double(arg) ?? 0)
+ case "search":
+ tab = .search
+ searchPath = []
+ query = arg
+ case "mainShow":
+ // mainShow:<id>[,transcript|notes]
+ let parts = arg.split(separator: ",").map(String.init)
+ tab = .records
+ selection = parts.first.flatMap { id in store.sessions.contains(where: { $0.id == id }) ? id : nil }
+ ?? store.sessions.first?.id
+ if parts.count > 1 { recordPage = parts[1] == "notes" ? .notes : .transcript }
+ case "back":
+ selection = nil
+ searchPath = []
+ comingSoon = nil
+ case "reload":
+ store = SessionStore()
+ notes = NotesEngine(ling: ling, store: store)
+ wireNotes()
+ case "generateNotes":
+ // generateNotes:<id>, as the record page's 生成纪要 (needs a key).
+ generateNotes(arg.isEmpty ? (selection ?? store.sessions.first?.id ?? "") : arg)
+ case "rename":
+ // rename:<id>,<title> (an empty title goes back to the automatic one)
+ let parts = arg.split(separator: ",", maxSplits: 1, omittingEmptySubsequences: false).map(String.init)
+ rename(parts[0], to: parts.count > 1 ? parts[1] : "")
+ case "delete":
+ deleteSession(arg)
+ case "speakers":
+ UserDefaults.standard.set(arg == "on", forKey: Pref.voices)
+ TranscriptExport.voices = arg == "on"
+ objectWillChange.send()
+ case "notesLang":
+ UserDefaults.standard.set(arg, forKey: Pref.notesLanguage)
+ case "nameSpeaker":
+ // nameSpeaker:<id>,<voice>,<name>
+ let p = arg.split(separator: ",", maxSplits: 2, omittingEmptySubsequences: false).map(String.init)
+ if p.count == 3, let v = Int(p[1]) { renameSpeaker(session: p[0], voice: v, p[2]) }
+ case "mergeSpeaker":
+ // mergeSpeaker:<id>,<from voice>,<into voice>
+ let p = arg.split(separator: ",").map(String.init)
+ if p.count == 3, let a = Int(p[1]), let b = Int(p[2]) { mergeSpeaker(session: p[0], a, into: b) }
+ case "speakerPrompt":
+ // speakerPrompt:<speaker number>: the 是谁 prompt a chip's 改名字 opens
+ namingSpeaker = Int(arg)
+ case "undoSpeaker":
+ undoSpeakerEdit()
+ case "state":
+ debugLog("room running=\(room.isRunning) lines=\(room.lines.count) draft=\(room.draft.count) level=\(room.level) status=\(room.status) session=\(room.sessionID ?? "-")")
+ debugLog("state tab=\(tab.rawValue) selection=\(selection ?? "-") page=\(recordPage) sessions=\(store.sessions.count) query=\(query) notesLang=\(notesLanguageCode(selection ?? store.sessions.first?.id ?? "")) undo=\(speakerUndo?.text ?? "-")")
+ default:
+ debugLog("debug command unknown: \(cmd)")
+ }
+ }
+}
+
+/// Dev only: the iPad windows the simulator can't be put into from a script. There is no
+/// Simulator.app to rotate it, iPadOS refuses a programmatic rotation in windowed mode, and no API
+/// sizes a window. So the app is laid out at that window's size and size class, scaled to fit.
+struct DevWindow: ViewModifier {
+ @ObservedObject var model: AppModel
+
+ func body(content: Content) -> some View {
+ if let size = model.devWindow {
+ GeometryReader { geo in
+ let scale = min(1, geo.size.width / size.width, geo.size.height / size.height)
+ content
+ // iPadOS gives a window regular width from about 678 points.
+ .environment(\.horizontalSizeClass, size.width >= 678 ? .regular : .compact)
+ .frame(width: size.width, height: size.height)
+ .clipShape(RoundedRectangle(cornerRadius: 22, style: .continuous))
+ .scaleEffect(scale, anchor: .topLeading)
+ .frame(width: size.width * scale, height: size.height * scale, alignment: .topLeading)
+ .frame(width: geo.size.width, height: geo.size.height, alignment: .topLeading)
+ }
+ .background(Color(white: 0.3).ignoresSafeArea())
+ } else {
+ content
+ }
+ }
+}
+
+private extension Array where Element == String {
+ var splitPair: (String, String) { (first ?? "", count > 1 ? self[1] : "") }
+}
diff --git a/ios/Sources/Cicada/DevBuild.swift b/ios/Sources/Cicada/DevBuild.swift
new file mode 100644
index 0000000..3b9ae0f
--- /dev/null
+++ b/ios/Sources/Cicada/DevBuild.swift
@@ -0,0 +1,36 @@
+import Foundation
+
+/// The iOS counterpart of the Mac's `DevBuild` and `debugLog` (`Sources/LiveSubs/DevBuild.swift`,
+/// `Settings.swift`): the shared sources call them by the same names. No /tmp on iOS, so the log
+/// lives in the app container, where `xcrun simctl get_app_container booted <id> data` finds it.
+enum DevBuild {
+ /// Where it came from ("main @ 1b3d7f7"), or nil for a release build.
+ static let label: String? = Bundle.main.object(forInfoDictionaryKey: "LiveSubsDev") as? String
+
+ static var isDev: Bool { label != nil }
+
+ /// Folder name under Application Support, kept the same as on the Mac.
+ static var supportFolder: String { isDev ? "LiveSubs Dev" : "LiveSubs" }
+
+ static var logPath: String {
+ FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent(isDev ? "livesubs-dev-debug.log" : "livesubs-debug.log").path
+ }
+}
+
+func debugLog(_ message: String) {
+ let line = "\(Date()) \(message)\n"
+ let path = DevBuild.logPath
+ if let handle = FileHandle(forWritingAtPath: path) {
+ handle.seekToEndOfFile()
+ handle.write(line.data(using: .utf8) ?? Data())
+ handle.closeFile()
+ } else {
+ try? line.write(toFile: path, atomically: true, encoding: .utf8)
+ }
+}
+
+/// Transcript content is only logged when the `debug` default is on, as on the Mac.
+func contentLog(_ message: @autoclosure () -> String) {
+ if UserDefaults.standard.bool(forKey: "debug") { debugLog(message()) }
+}
diff --git a/ios/Sources/Cicada/HostRecognizer.swift b/ios/Sources/Cicada/HostRecognizer.swift
new file mode 100644
index 0000000..f41537f
--- /dev/null
+++ b/ios/Sources/Cicada/HostRecognizer.swift
@@ -0,0 +1,118 @@
+import AVFoundation
+import Foundation
+
+#if targetEnvironment(simulator)
+/// The simulator's speech models are empty placeholders (every recognizer answers "model not
+/// available"), so a dev build there sends its audio to the Mac it runs on: `ios/tools/host-recognizer`
+/// reads it from the app's container and recognizes it on device with the Mac's own `Recognition`,
+/// writing the pieces back. Same clock as any `RecognitionStream`: seconds of audio appended.
+/// Only for testing in the simulator; an iPhone recognizes on itself.
+enum HostRecognizer {
+ static var root: URL {
+ FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("host-recognizer", isDirectory: true)
+ }
+
+ static func install() {
+ guard DevBuild.isDev else { return }
+ Recognition.host = { locale, drafts in try HostStream(locale: locale, drafts: drafts) }
+ debugLog("recognizer: the Mac's (ios/tools/host-recognizer)")
+ }
+}
+
+final class HostStream: RecognitionStream, @unchecked Sendable {
+ let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16_000, channels: 1, interleaved: false)!
+ let results: AsyncThrowingStream<Recognition.Piece, Error>
+ private let out: AsyncThrowingStream<Recognition.Piece, Error>.Continuation
+ private let dir: URL
+ private let audio: FileHandle
+ private let queue = DispatchQueue(label: "com.wquguru.cicada.host-recognizer")
+ private var reader: Task<Void, Never>?
+ private var done = false
+
+ private struct Line: Decodable {
+ var text: String?
+ var isFinal: Bool?
+ var start: Double?
+ var end: Double?
+ var confidence: Double?
+ var done: Bool?
+ var error: String?
+ }
+
+ init(locale: String, drafts: Bool) throws {
+ dir = HostRecognizer.root.appendingPathComponent(UUID().uuidString, isDirectory: true)
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let audioURL = dir.appendingPathComponent("audio.f32")
+ FileManager.default.createFile(atPath: audioURL.path, contents: nil)
+ FileManager.default.createFile(atPath: dir.appendingPathComponent("results.jsonl").path, contents: nil)
+ audio = try FileHandle(forWritingTo: audioURL)
+ (results, out) = AsyncThrowingStream.makeStream(of: Recognition.Piece.self)
+ // Written last: the host starts on a folder once its request is there.
+ let request = try JSONSerialization.data(withJSONObject: ["locale": locale, "drafts": drafts])
+ try request.write(to: dir.appendingPathComponent("request.json"))
+ let resultsURL = dir.appendingPathComponent("results.jsonl")
+ let out = self.out
+ reader = Task.detached { [weak self] in
+ var offset: UInt64 = 0, pending = Data()
+ let started = Date()
+ var heard = false
+ while !Task.isCancelled {
+ if let h = try? FileHandle(forReadingFrom: resultsURL) {
+ try? h.seek(toOffset: offset)
+ let data = h.readDataToEndOfFile()
+ try? h.close()
+ offset += UInt64(data.count)
+ pending.append(data)
+ while let nl = pending.firstIndex(of: 0x0A) {
+ let lineData = pending[pending.startIndex..<nl]
+ pending.removeSubrange(pending.startIndex...nl)
+ heard = true
+ guard let line = try? JSONDecoder().decode(Line.self, from: lineData) else { continue }
+ if line.done == true { out.finish(); return }
+ if let e = line.error { out.finish(throwing: NSError(domain: "HostRecognizer", code: 1, userInfo: [NSLocalizedDescriptionKey: e])); return }
+ if let text = line.text {
+ out.yield(.init(text: text, isFinal: line.isFinal ?? false, start: line.start ?? 0, end: line.end ?? 0, confidence: line.confidence))
+ }
+ }
+ }
+ if !heard, Date().timeIntervalSince(started) > 8, self?.claimed == false {
+ out.finish(throwing: NSError(domain: "HostRecognizer", code: 2, userInfo: [NSLocalizedDescriptionKey: "host-recognizer isn't running on the Mac"]))
+ return
+ }
+ try? await Task.sleep(nanoseconds: 100_000_000)
+ }
+ }
+ }
+
+ private var claimed: Bool { FileManager.default.fileExists(atPath: dir.appendingPathComponent("claimed").path) }
+
+ func append(_ buffer: AVAudioPCMBuffer) {
+ guard let p = buffer.floatChannelData?[0] else { return }
+ let data = Data(bytes: p, count: Int(buffer.frameLength) * MemoryLayout<Float>.size)
+ queue.async { [audio] in try? audio.write(contentsOf: data) }
+ }
+
+ func finalize(through seconds: Double) async throws {}
+
+ func finish() async {
+ queue.sync { try? audio.close() }
+ FileManager.default.createFile(atPath: dir.appendingPathComponent("end").path, contents: nil)
+ // The host finishes the last line and says done; don't wait forever on it.
+ for _ in 0..<100 where reader?.isCancelled == false {
+ if (try? String(contentsOf: dir.appendingPathComponent("results.jsonl"), encoding: .utf8))?.contains("\"done\"") == true { break }
+ try? await Task.sleep(nanoseconds: 100_000_000)
+ }
+ try? await Task.sleep(nanoseconds: 300_000_000)
+ reader?.cancel()
+ out.finish()
+ try? FileManager.default.removeItem(at: dir)
+ }
+
+ func cancel() async {
+ queue.sync { try? audio.close() }
+ FileManager.default.createFile(atPath: dir.appendingPathComponent("end").path, contents: nil)
+ reader?.cancel()
+ out.finish()
+ }
+}
+#endif
diff --git a/ios/Sources/Cicada/ListenActivity.swift b/ios/Sources/Cicada/ListenActivity.swift
new file mode 100644
index 0000000..182bb66
--- /dev/null
+++ b/ios/Sources/Cicada/ListenActivity.swift
@@ -0,0 +1,18 @@
+import ActivityKit
+import Foundation
+
+/// 正在听 on the lock screen and in the Dynamic Island. Compiled into the app and into the
+/// CicadaLive extension (ios/LiveActivity), which draws it; the app only starts, feeds and ends it.
+struct ListenActivity: ActivityAttributes {
+ struct ContentState: Codable, Hashable {
+ /// The newest translated line and what was said.
+ var line: String
+ var source: String
+ /// Distinct voices so far.
+ var people: Int
+ }
+
+ var startedAt: Date
+ /// "英 → 中".
+ var pair: String
+}
diff --git a/ios/Sources/Cicada/LiveActivityController.swift b/ios/Sources/Cicada/LiveActivityController.swift
new file mode 100644
index 0000000..e7846b7
--- /dev/null
+++ b/ios/Sources/Cicada/LiveActivityController.swift
@@ -0,0 +1,63 @@
+import ActivityKit
+import Foundation
+
+/// Starts the Live Activity when listening starts, sends it each translated line (at most every
+/// 1.5 s: the system throttles more anyway) and ends it with the meeting.
+@MainActor
+final class LiveActivityController {
+ private var activity: Activity<ListenActivity>?
+ private var lastSent = Date.distantPast
+ private var pending: ListenActivity.ContentState?
+ private var people = 0
+
+ func start(startedAt: Date, pair: String) {
+ guard activity == nil else { return }
+ guard ActivityAuthorizationInfo().areActivitiesEnabled else {
+ debugLog("live activity: not enabled")
+ return
+ }
+ people = 0
+ let state = ListenActivity.ContentState(line: "", source: "", people: 0)
+ do {
+ activity = try Activity.request(attributes: ListenActivity(startedAt: startedAt, pair: pair),
+ content: .init(state: state, staleDate: nil))
+ debugLog("live activity: started \(activity?.id ?? "-")")
+ } catch {
+ debugLog("live activity: request failed: \(error)")
+ }
+ }
+
+ func update(line: RoomListen.Line, people: Int? = nil) {
+ guard let activity else { return }
+ if let people { self.people = people }
+ let state = ListenActivity.ContentState(line: line.dst ?? "", source: line.src, people: self.people)
+ let wait = 1.5 - Date().timeIntervalSince(lastSent)
+ if wait > 0 {
+ let first = pending == nil
+ pending = state
+ if first {
+ DispatchQueue.main.asyncAfter(deadline: .now() + wait) { [weak self] in
+ MainActor.assumeIsolated { self?.flush() }
+ }
+ }
+ return
+ }
+ lastSent = Date()
+ Task { await activity.update(.init(state: state, staleDate: nil)) }
+ }
+
+ private func flush() {
+ guard let activity, let state = pending else { return }
+ pending = nil
+ lastSent = Date()
+ Task { await activity.update(.init(state: state, staleDate: nil)) }
+ }
+
+ func end() {
+ guard let activity else { return }
+ self.activity = nil
+ pending = nil
+ Task { await activity.end(nil, dismissalPolicy: .immediate) }
+ debugLog("live activity: ended")
+ }
+}
diff --git a/ios/Sources/Cicada/LiveViews.swift b/ios/Sources/Cicada/LiveViews.swift
new file mode 100644
index 0000000..6467ba2
--- /dev/null
+++ b/ios/Sources/Cicada/LiveViews.swift
@@ -0,0 +1,288 @@
+import SwiftUI
+
+// The design's scheme 3 (知了当标题): the logo, the date and 会议记录 make the home's title, 开始听 is
+// one glass bar under it, and while listening the same two places turn into 正在听 · 12:48 and the
+// wave, who is talking and 结束. iPhone and the iPad's sidebar share them.
+
+/// "11月4日 星期三 / 会议记录", or "● 正在听 · 12:48 / 会议室 · 英 → 中" while listening.
+struct HomeTitle: View {
+ @EnvironmentObject var model: AppModel
+ @EnvironmentObject var room: RoomListen
+ var logo: CGFloat = 52
+ var titleSize: CGFloat = 28
+ var trailing: AnyView? = nil
+
+ var body: some View {
+ HStack(spacing: 12) {
+ Logo(size: logo)
+ VStack(alignment: .leading, spacing: 1) {
+ if room.isRunning {
+ TimelineView(.periodic(from: .now, by: 1)) { _ in
+ HStack(spacing: 6) {
+ LiveDot()
+ Text(L("正在听 · \(TranscriptExport.clock(room.elapsed))"))
+ }
+ .font(.footnote.weight(.semibold).monospacedDigit())
+ .foregroundStyle(Ink.accentText)
+ }
+ Text(L("会议室 · \(Pref.pairText(room.languagePair.source, room.languagePair.target))"))
+ .font(.system(size: titleSize - 4, weight: .bold)).foregroundStyle(Ink.ink)
+ .lineLimit(1).minimumScaleFactor(0.7)
+ } else {
+ Text(dateText(Date(), "MMMdEEEE")).font(.footnote).foregroundStyle(Ink.secondary)
+ Text("会议记录").font(.system(size: titleSize, weight: .bold)).foregroundStyle(Ink.ink)
+ }
+ }
+ Spacer(minLength: 0)
+ if let trailing, !room.isRunning { trailing }
+ }
+ .padding(.horizontal, 4)
+ }
+}
+
+/// The orange dot that breathes while listening.
+struct LiveDot: View {
+ @State private var on = false
+
+ var body: some View {
+ Circle().fill(Ink.accent).frame(width: 8, height: 8)
+ .shadow(color: Ink.accent.opacity(on ? 0 : 0.45), radius: on ? 6 : 0)
+ .onAppear { withAnimation(.easeInOut(duration: 1.6).repeatForever(autoreverses: false)) { on = true } }
+ .accessibilityHidden(true)
+ }
+}
+
+/// 开始听 · 英语 → 简体中文 · the orange round button; while listening: the wave, who is talking, 结束.
+struct ListenBar: View {
+ @EnvironmentObject var model: AppModel
+ @EnvironmentObject var room: RoomListen
+ @AppStorage(Pref.source) private var source = "en-US"
+ @AppStorage(Pref.target) private var target = "system"
+ /// Glass on the ground (iPhone); white on the iPad's glass sidebar.
+ var onGlass = false
+
+ var body: some View {
+ HStack(spacing: 10) {
+ if room.isRunning { live } else { idle }
+ }
+ .frame(height: 58)
+ .background {
+ if onGlass {
+ Capsule().fill(Color.white).shadow(color: Ink.ink.opacity(0.08), radius: 2, y: 1)
+ }
+ }
+ .modifier(GlassCapsule(on: !onGlass))
+ .animation(.snappy(duration: 0.25), value: room.isRunning)
+ }
+
+ private var idle: some View {
+ Group {
+ Text("开始听").font(.headline).foregroundStyle(Ink.ink).padding(.leading, 18)
+ Rectangle().fill(Ink.line).frame(width: 1, height: 20)
+ Menu {
+ Picker(selection: $source) {
+ ForEach(sourceLanguages, id: \.locale) { Text(Pref.name(of: $0)).tag($0.locale) }
+ } label: { Text("对方说") }
+ Picker(selection: $target) {
+ Text("跟随系统").tag("system")
+ ForEach(targetLanguages, id: \.code) { Text($0.name).tag($0.code) }
+ } label: { Text("翻译成") }
+ } label: {
+ Text(verbatim: "\(Pref.sourceName) → \(targetName(Pref.targetCode))")
+ .font(.subheadline).foregroundStyle(Ink.secondary).lineLimit(1).minimumScaleFactor(0.75)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .frame(minHeight: 44)
+ .contentShape(Rectangle())
+ }
+ .accessibilityLabel(Text("对方说和翻译成"))
+ Button { model.startListening() } label: {
+ Image(systemName: "mic.fill")
+ .font(.system(size: 19, weight: .semibold))
+ .foregroundStyle(.white)
+ .frame(width: 46, height: 46)
+ .background(Ink.accent, in: Circle())
+ }
+ .buttonStyle(.plain)
+ .padding(.trailing, 6)
+ .keyboardShortcut("r", modifiers: .command)
+ .accessibilityLabel(Text("开始听"))
+ }
+ }
+
+ private var live: some View {
+ Group {
+ Wave(level: room.level).padding(.leading, 16)
+ let people = room.speakerCount
+ Text(people >= 2 ? L("\(people) 人在说") : (room.status.isEmpty ? L("正在听") : room.status))
+ .font(.subheadline).foregroundStyle(Ink.secondary).lineLimit(1)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ Button { model.stopListening() } label: {
+ Text("结束").font(.headline).foregroundStyle(.white)
+ .padding(.horizontal, 20).frame(height: 46)
+ .background(Ink.ink, in: Capsule())
+ }
+ .buttonStyle(.plain)
+ .padding(.trailing, 6)
+ .keyboardShortcut("r", modifiers: .command)
+ }
+ }
+}
+
+private struct GlassCapsule: ViewModifier {
+ let on: Bool
+ func body(content: Content) -> some View {
+ if on { content.glassEffect(.regular, in: Capsule()) } else { content }
+ }
+}
+
+/// Five bars that follow the microphone's level.
+struct Wave: View {
+ let level: Float
+
+ var body: some View {
+ TimelineView(.animation(minimumInterval: 0.08)) { t in
+ HStack(spacing: 3) {
+ ForEach(0..<5, id: \.self) { i in
+ let phase = sin(t.date.timeIntervalSinceReferenceDate * 7 + Double(i) * 1.3)
+ let h = 5 + CGFloat(level) * 16 * CGFloat(0.55 + 0.45 * phase)
+ Capsule().fill(Ink.accent).frame(width: 3, height: max(5, h))
+ }
+ }
+ .frame(height: 22)
+ }
+ .accessibilityHidden(true)
+ }
+}
+
+/// 正在听 on the iPhone: the title and bar as on the home, 字幕 / 纪要, and the lines as cards.
+struct LivePhone: View {
+ @EnvironmentObject var model: AppModel
+ @EnvironmentObject var room: RoomListen
+ @EnvironmentObject var notes: NotesEngine
+ @State private var page: LivePage = .subtitles
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ VStack(alignment: .leading, spacing: 16) {
+ HomeTitle()
+ ListenBar()
+ PillSwitch(selection: $page, options: [(.subtitles, "字幕"), (.notes, notesTitle)])
+ }
+ .padding(.horizontal, 16)
+ .padding(.top, 6)
+ switch page {
+ case .subtitles: LiveLines().padding(.top, 12)
+ case .notes:
+ ScrollView { NotesPage(notes: notes.notes).padding(20) }
+ }
+ }
+ .background(Ink.ground)
+ .onChange(of: model.livePage) { page = model.livePage }
+ }
+
+ private var notesTitle: LocalizedStringKey {
+ notes.fresh.isEmpty ? "纪要" : "纪要 · \(notes.fresh.count) 条新"
+ }
+}
+
+enum LivePage: String { case subtitles, notes }
+
+/// The lines so far as white cards, the one being said outlined in the accent; follows the newest.
+struct LiveLines: View {
+ @EnvironmentObject var model: AppModel
+ @EnvironmentObject var room: RoomListen
+ @ScaledMetric(relativeTo: .subheadline) private var srcSize: CGFloat = 14
+ @ScaledMetric(relativeTo: .body) private var dstSize: CGFloat = 17
+
+ var body: some View {
+ let session = model.store.session(room.sessionID)
+ let numbers = session.map(TranscriptExport.speakerNumbers) ?? [:]
+ let names = session.map(SpeakerLabels.names) ?? [:]
+ ScrollViewReader { proxy in
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 12) {
+ if room.lines.isEmpty && room.draft.isEmpty {
+ Text(room.status.isEmpty ? L("开始说话后,字幕会出现在这里") : room.status)
+ .font(.subheadline).foregroundStyle(Ink.secondary)
+ .frame(maxWidth: .infinity).padding(.top, 40)
+ }
+ ForEach(room.lines) { l in
+ card(who: numbers[l.id].map { SpeakerLabels.label($0, names) }, time: l.t, src: l.src, dst: l.dst, live: false)
+ .id(l.id)
+ }
+ if !room.draft.isEmpty {
+ card(who: nil, time: nil, src: room.draft, dst: room.draftTranslation.isEmpty ? nil : room.draftTranslation, live: true)
+ .id("draft")
+ }
+ Color.clear.frame(height: 40).id("end")
+ }
+ .padding(.horizontal, 16)
+ }
+ .onChange(of: room.lines.count) { withAnimation { proxy.scrollTo("end", anchor: .bottom) } }
+ .onChange(of: room.draft) { proxy.scrollTo("end", anchor: .bottom) }
+ }
+ }
+
+ private func card(who: String?, time: Double?, src: String, dst: String?, live: Bool) -> some View {
+ VStack(alignment: .leading, spacing: 6) {
+ Text(live ? L("正在说") : [who, time.map(TranscriptExport.clock)].compactMap { $0 }.joined(separator: " · "))
+ .font(.caption.weight(.semibold)).foregroundStyle(live ? Ink.accentText : Ink.ink)
+ Text(src).font(.system(size: srcSize)).foregroundStyle(Ink.secondary).lineSpacing(2)
+ if let dst { Text(dst).font(.system(size: dstSize)).foregroundStyle(live ? Ink.secondary : Ink.ink).lineSpacing(4) }
+ }
+ .padding(.horizontal, 16).padding(.vertical, 14)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Color.white, in: RoundedRectangle(cornerRadius: 20, style: .continuous))
+ .overlay {
+ if live { RoundedRectangle(cornerRadius: 20, style: .continuous).strokeBorder(Ink.accent.opacity(0.35), lineWidth: 1.5) }
+ }
+ }
+}
+
+/// 正在听 on the iPad, beside the sidebar: 字幕 and 纪要 side by side when wide, switched when not.
+struct LivePad: View {
+ @EnvironmentObject var model: AppModel
+ @EnvironmentObject var room: RoomListen
+ @EnvironmentObject var notes: NotesEngine
+ @State private var page: LivePage = .subtitles
+
+ var body: some View {
+ GeometryReader { g in
+ if g.size.width >= 820 {
+ HStack(alignment: .top, spacing: 22) {
+ column("字幕") { LiveLines().padding(.horizontal, -16) }
+ column(notesTitle) {
+ ScrollView {
+ NotesPage(notes: notes.notes).padding(20)
+ .background(Color.white, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
+ }
+ }
+ .frame(width: g.size.width * 0.42)
+ }
+ .padding(.horizontal, 20).padding(.top, 18)
+ } else {
+ VStack(alignment: .leading, spacing: 12) {
+ PillSwitch(selection: $page, options: [(.subtitles, "字幕"), (.notes, notesTitle)]).frame(maxWidth: 320)
+ if page == .subtitles { LiveLines().padding(.horizontal, -16) } else {
+ ScrollView { NotesPage(notes: notes.notes).padding(20).background(Color.white, in: RoundedRectangle(cornerRadius: 22)) }
+ }
+ }
+ .padding(.horizontal, 20).padding(.top, 18)
+ }
+ }
+ .background(Ink.ground)
+ .onChange(of: model.livePage) { page = model.livePage }
+ }
+
+ private var notesTitle: LocalizedStringKey {
+ notes.fresh.isEmpty ? "纪要" : "纪要 · \(notes.fresh.count) 条新"
+ }
+
+ private func column<C: View>(_ title: LocalizedStringKey, @ViewBuilder _ content: () -> C) -> some View {
+ VStack(alignment: .leading, spacing: 10) {
+ Text(title).font(.footnote.weight(.semibold)).foregroundStyle(Ink.secondary).padding(.leading, 4)
+ content()
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+}
diff --git a/ios/Sources/Cicada/RecordView.swift b/ios/Sources/Cicada/RecordView.swift
new file mode 100644
index 0000000..6b802d8
--- /dev/null
+++ b/ios/Sources/Cicada/RecordView.swift
@@ -0,0 +1,537 @@
+import AVFoundation
+import SwiftUI
+
+enum RecordPage: String { case transcript, notes }
+
+/// One meeting, as the design's 会议记录 screen: one white sheet with the title, the voices as
+/// chips, the 文字记录 / 纪要 switch, and the recording on a glass bar at the bottom.
+struct RecordView: View {
+ @EnvironmentObject var model: AppModel
+ @EnvironmentObject var ling: LingClient
+ @EnvironmentObject var notes: NotesEngine
+ let session: Session
+ @StateObject private var player = RecordPlayer()
+ @State private var needsKey = false
+ /// What's typed into the title; nil until it is touched, so opening it changes nothing.
+ @State private var titleDraft: String?
+ @FocusState private var titleFocused: Bool
+ /// The speaker picked on a chip (scheme A: only they are drawn in ink); nil follows the recording.
+ private var picked: Int? { model.focusSpeaker }
+ @AppStorage(Pref.voices) private var voicesOn = true
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 0) {
+ // The design's 28 pt title; the day is in the line below, so a notes title's
+ // leading "11月3日" goes.
+ // Editable in place, as on the Mac: an unchanged title isn't a rename, an emptied
+ // one goes back to the automatic title.
+ TextField(text: Binding(get: { titleDraft ?? shownTitle }, set: setTitle), axis: .vertical) {
+ Text("未命名会议")
+ }
+ .font(.title.bold())
+ .foregroundStyle(Ink.ink)
+ .focused($titleFocused)
+ .submitLabel(.done)
+ .onChange(of: titleFocused) { if !titleFocused { commitTitle() } }
+ .accessibilityLabel(Text("标题"))
+ Text(Self.meta(session))
+ .font(.footnote).foregroundStyle(Ink.secondary)
+ .padding(.top, 4)
+ let numbers = voicesOn ? TranscriptExport.speakerNumbers(session) : [:]
+ let runs = SpeakerRail.runs(session, numbers: numbers)
+ let focus = picked ?? playingNumber(numbers)
+ if !runs.isEmpty {
+ MeetingRail(runs: runs, focus: focus,
+ playhead: player.available && (player.playing || player.now > 0) && player.duration > 0 ? player.now / player.duration : nil)
+ .padding(.top, 16)
+ }
+ SpeakerChips(session: session, shares: SpeakerRail.shares(runs), focus: focus, picked: $model.focusSpeaker).padding(.top, 12)
+ if let n = picked {
+ Text(L("只看 \(SpeakerLabels.label(n, SpeakerLabels.names(session))) · \(runs.filter { $0.number == n }.count) 段 · 再点一下取消"))
+ .font(.footnote).foregroundStyle(Ink.secondary).padding(.top, 6)
+ }
+ PillSwitch(selection: $model.recordPage,
+ options: [(.transcript, "文字记录"), (.notes, "纪要")])
+ .padding(.top, 16)
+
+ switch model.recordPage {
+ case .transcript: TranscriptList(session: session, playing: player.lineID(in: session), focus: picked ?? playingNumber(voicesOn ? TranscriptExport.speakerNumbers(session) : [:]), dimOthers: picked != nil) { player.seek($0) }
+ case .notes:
+ if notes.generatingID == session.id {
+ HStack(spacing: 10) {
+ ProgressView()
+ Text("正在整理纪要…").foregroundStyle(Ink.secondary)
+ }
+ .frame(maxWidth: .infinity).padding(.top, 40)
+ } else {
+ // Ling wrote "说话人 6" before anyone was named; show the names since given.
+ NotesPage(notes: session.notes.map { SpeakerLabels.named($0, SpeakerLabels.names(session)) })
+ .padding(.top, 18)
+ }
+ }
+ }
+ .padding(.horizontal, 20)
+ .padding(.top, 8)
+ .padding(.bottom, player.available ? 110 : 40)
+ .frame(maxWidth: 720, alignment: .leading)
+ .frame(maxWidth: .infinity)
+ }
+ .background(Color.white)
+ .navigationBarTitleDisplayMode(.inline)
+ // The design's trailing glass pair: 生成纪要 and 导出, in ink like the back button.
+ .toolbar {
+ ToolbarItemGroup(placement: .topBarTrailing) {
+ Button {
+ if ling.hasKey { model.generateNotes(session.id) } else { needsKey = true }
+ } label: {
+ if notes.generatingID == session.id { ProgressView() } else { Image(systemName: "arrow.triangle.2.circlepath") }
+ }
+ .disabled(notes.generatingID != nil || session.lines.isEmpty)
+ .accessibilityLabel(Text("生成纪要"))
+ ShareLink(item: TranscriptExport.markdown(session), subject: Text(session.displayTitle)) {
+ Image(systemName: "square.and.arrow.up")
+ }
+ .accessibilityLabel(Text("导出"))
+ }
+ }
+ .tint(Ink.ink)
+ .alert(Text("生成纪要"), isPresented: $needsKey) {
+ Button("去填 key") { model.selection = nil; model.searchPath = []; model.tab = .settings; model.showSettings = true }
+ Button("取消", role: .cancel) {}
+ } message: {
+ Text("前往 设置 › AI 服务 填入 Ling 的 API key 后即可生成。")
+ }
+ .safeAreaInset(edge: .bottom) {
+ if let u = model.speakerUndo, u.session == session.id, !u.text.isEmpty, !player.available {
+ SpeakerUndoBar(text: u.text) { model.undoSpeakerEdit() }.padding(.horizontal, 16).padding(.bottom, 8)
+ }
+ if player.available {
+ VStack(spacing: 8) {
+ if let u = model.speakerUndo, u.session == session.id, !u.text.isEmpty {
+ SpeakerUndoBar(text: u.text) { model.undoSpeakerEdit() }
+ }
+ PlayerBar(player: player)
+ }
+ .padding(.horizontal, 16)
+ .padding(.bottom, 8)
+ // The page fades out under the bar, as in the design, so text doesn't show through the glass.
+ .background(alignment: .bottom) {
+ LinearGradient(colors: [.white.opacity(0), .white], startPoint: .top, endPoint: .center)
+ .padding(.top, -24)
+ .ignoresSafeArea(edges: .bottom)
+ }
+ }
+ }
+ .animation(.snappy(duration: 0.2), value: model.speakerUndo?.id)
+ .onAppear { player.load(store: model.store, session: session) }
+ .onChange(of: session.id) { titleDraft = nil; model.focusSpeaker = nil; player.load(store: model.store, session: session) }
+ .onDisappear { player.stop() }
+ .onReceive(NotificationCenter.default.publisher(for: .debugPlay)) { n in
+ if let t = n.object as? Double { player.seek(t) }
+ }
+ }
+
+ /// The speaker the recording is at, while it plays.
+ private func playingNumber(_ numbers: [String: Int]) -> Int? {
+ guard player.playing, let id = player.lineID(in: session) else { return nil }
+ return numbers[id]
+ }
+
+ private var shownTitle: String { RecordList.untitled(session) ? "" : RecordList.listTitle(session) }
+
+ /// Return ends the edit (the field wraps long titles, so it would otherwise add a line).
+ private func setTitle(_ v: String) {
+ if v.contains("\n") {
+ titleDraft = v.replacingOccurrences(of: "\n", with: "")
+ titleFocused = false
+ } else {
+ titleDraft = v
+ }
+ }
+
+ private func commitTitle() {
+ defer { titleDraft = nil }
+ guard let draft = titleDraft?.trimmingCharacters(in: .whitespacesAndNewlines), draft != shownTitle else { return }
+ model.rename(session.id, to: draft)
+ }
+
+ /// "今天 10:02 · 48 分钟 · 英 → 中".
+ static func meta(_ s: Session) -> String {
+ var parts = [dateText(s.startedAt, "MMMdHHmm"), RecordList.length(s)]
+ if let pair = RecordList.pair(s, short: true) { parts.append(pair) }
+ return parts.joined(separator: " · ")
+ }
+}
+
+/// The voices told apart in this meeting, as chips in their colours ("Sarah", "说话人 3"); only
+/// with 说话人识别 on, as the transcript. A chip renames the voice or merges it into another.
+struct SpeakerChips: View {
+ @EnvironmentObject var model: AppModel
+ let session: Session
+ /// Each speaker number's share of the meeting, shown on the chip ("Sarah · 58%").
+ var shares: [Int: Double] = [:]
+ /// Drawn in ink: the picked speaker, or the one playing.
+ var focus: Int? = nil
+ @Binding var picked: Int?
+ @AppStorage(Pref.voices) private var voicesOn = true
+ @State private var draft = ""
+ /// The speaker number being named; on the model so a debug command can open it too.
+ private var naming: Int? { model.namingSpeaker }
+
+ var body: some View {
+ let names = SpeakerLabels.names(session)
+ let voices = voicesOn ? SpeakerLabels.voiceNumbers(session.lines) : [:]
+ // Voice id by its speaker number.
+ let byNumber = Dictionary(uniqueKeysWithValues: voices.map { ($1, $0) })
+ let numbers = byNumber.keys.sorted()
+ if !numbers.isEmpty {
+ FlowLayout(spacing: 8) {
+ ForEach(numbers, id: \.self) { n in
+ // Tap picks the speaker (only they stay in ink); a long press renames or merges.
+ Menu {
+ Button { draft = names[n] ?? ""; model.namingSpeaker = n } label: { Label("改名字", systemImage: "pencil") }
+ Section("其实是同一个人") {
+ ForEach(numbers.filter { $0 != n }, id: \.self) { other in
+ Button(L("并入 \(SpeakerLabels.label(other, names))")) {
+ if let a = byNumber[n], let b = byNumber[other] { model.mergeSpeaker(session: session.id, a, into: b) }
+ }
+ }
+ }
+ } label: {
+ let on = focus == n
+ Text(shares[n].map { "\(SpeakerLabels.label(n, names)) · \(Int(($0 * 100).rounded()))%" } ?? SpeakerLabels.label(n, names))
+ .font(.footnote.weight(.semibold))
+ .foregroundStyle(on ? .white : Ink.ink)
+ .padding(.horizontal, 12)
+ .frame(minHeight: 30)
+ .background(on ? Ink.ink : .white, in: Capsule())
+ .overlay(Capsule().strokeBorder(on ? Ink.ink : Ink.line, lineWidth: 1))
+ .contentShape(Capsule())
+ } primaryAction: {
+ picked = picked == n ? nil : n
+ }
+ .frame(minHeight: 44)
+ .accessibilityAddTraits(picked == n ? .isSelected : [])
+ .accessibilityHint(Text("只看这个人;按住可改名字,或和别人合并"))
+ }
+ }
+ .onChange(of: model.namingSpeaker) { if let n = model.namingSpeaker, draft.isEmpty { draft = names[n] ?? "" } }
+ .alert(Text("是谁"), isPresented: Binding(get: { naming != nil }, set: { if !$0 { model.namingSpeaker = nil } })) {
+ TextField(L("输入名字"), text: $draft)
+ Button("保存") { save(byNumber) }
+ Button("取消", role: .cancel) { model.namingSpeaker = nil }
+ }
+ }
+ }
+
+ /// The Mac's rule: keeping Ling's guess stores nothing, so a later, better guess can still replace it.
+ private func save(_ byNumber: [Int: Int]) {
+ guard let n = naming, let voice = byNumber[n] else { return }
+ model.namingSpeaker = nil
+ let name = draft.trimmingCharacters(in: .whitespacesAndNewlines)
+ let guess = session.voiceGuesses?[String(voice)]
+ if let guess, name == guess.name { model.renameSpeaker(session: session.id, voice: voice, nil) }
+ else if session.voiceNames?[String(voice)] != nil || !name.isEmpty { model.renameSpeaker(session: session.id, voice: voice, name) }
+ }
+}
+
+/// "说话人 6 已改成 David · 撤销", dark above the player, the Mac toast's pale accent on 撤销, for a few seconds.
+struct SpeakerUndoBar: View {
+ let text: String
+ let undo: () -> Void
+
+ var body: some View {
+ HStack(spacing: 14) {
+ Text(text).font(.subheadline).foregroundStyle(.white).lineLimit(2)
+ Spacer(minLength: 0)
+ Button("撤销", action: undo).font(.subheadline.weight(.semibold)).foregroundStyle(Color(red: 0.99, green: 0.93, blue: 0.906))
+ .frame(minHeight: 44)
+ }
+ .padding(.horizontal, 18)
+ .frame(minHeight: 52)
+ .background(Ink.ink, in: Capsule())
+ .shadow(color: Ink.ink.opacity(0.18), radius: 10, y: 4)
+ .transition(.move(edge: .bottom).combined(with: .opacity))
+ }
+}
+
+struct TranscriptList: View {
+ let session: Session
+ /// The line the recording is at, highlighted like the design's.
+ let playing: String?
+ /// Scheme A: this speaker's lines carry an ink bar, the rest a light grey one.
+ var focus: Int? = nil
+ /// A speaker was picked on purpose: the others' lines step back.
+ var dimOthers = false
+ let seek: (Double) -> Void
+ @Environment(\.dynamicTypeSize) private var typeSize
+ /// The design's 14 pt grey original over a 16 pt translation, scaling with the text size.
+ @ScaledMetric(relativeTo: .subheadline) private var srcSize: CGFloat = 14
+ @ScaledMetric(relativeTo: .callout) private var dstSize: CGFloat = 16
+
+ var body: some View {
+ let numbers = TranscriptExport.speakerNumbers(session), names = SpeakerLabels.names(session)
+ // At the largest text sizes the time column would squeeze the text: the time goes on the
+ // speaker's line instead.
+ let inline = typeSize.isAccessibilitySize
+ LazyVStack(alignment: .leading, spacing: 0) {
+ ForEach(Array(session.lines.enumerated()), id: \.element.id) { i, l in
+ let on = l.id == playing
+ let mine = focus != nil && numbers[l.id] == focus
+ HStack(alignment: .firstTextBaseline, spacing: 12) {
+ if !inline { time(l, on).frame(width: 40, alignment: .leading) }
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 8) {
+ if inline { time(l, on) }
+ if session.sourceFile == nil {
+ Text(TranscriptExport.speakerName(l, numbers, names))
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(l.speaker == "me" ? Ink.accentText : (focus == nil || mine ? Ink.ink : Ink.tertiary))
+ }
+ }
+ Text(l.src).font(.system(size: srcSize)).foregroundStyle(Ink.secondary).lineSpacing(2)
+ if let d = l.dst, d != l.src {
+ Text(d).font(.system(size: dstSize)).foregroundStyle(Ink.ink).lineSpacing(4)
+ }
+ }
+ }
+ .textSelection(.enabled)
+ .opacity(dimOthers && !mine ? 0.4 : 1)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.vertical, 14)
+ .padding(.horizontal, 20)
+ .background(on ? Ink.accent.opacity(0.06) : .clear)
+ // The upright strip beside the text: each line in its speaker's run.
+ .overlay(alignment: .leading) {
+ if !numbers.isEmpty {
+ RoundedRectangle(cornerRadius: 2).fill(mine ? SpeakerRail.focus : SpeakerRail.rest)
+ .frame(width: 4).padding(.vertical, 1).padding(.leading, 8)
+ }
+ }
+ .padding(.horizontal, -20)
+ .overlay(alignment: .bottom) { if i < session.lines.count - 1 { Rectangle().fill(Ink.line).frame(height: 0.5) } }
+ }
+ }
+ .padding(.top, 6)
+ .overlay {
+ if session.lines.isEmpty { Text("还没有句子").foregroundStyle(Ink.secondary).padding(.top, 40) }
+ }
+ }
+
+ /// The time; with a recording it plays from that line.
+ private func time(_ l: TranscriptLine, _ on: Bool) -> some View {
+ Button { seek(l.t) } label: {
+ Text(TranscriptExport.clock(l.t))
+ .font(.caption.monospacedDigit().weight(on ? .semibold : .regular))
+ .foregroundStyle(on ? Ink.accentText : Ink.tertiary)
+ }
+ .buttonStyle(.plain)
+ }
+}
+
+struct NotesPage: View {
+ let notes: MeetingNotes?
+ /// The design's 16 pt notes text, as the transcript's translation.
+ @ScaledMetric(relativeTo: .callout) private var size: CGFloat = 16
+
+ var body: some View {
+ if let n = notes, !n.summary.isEmpty || !n.topics.isEmpty {
+ VStack(alignment: .leading, spacing: 22) {
+ if !n.summary.isEmpty {
+ block("总结") { Text(n.summary).font(.system(size: size)).lineSpacing(5) }
+ }
+ if !n.topics.isEmpty {
+ block("议题") {
+ ForEach(n.topics) { t in
+ VStack(alignment: .leading, spacing: 6) {
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ Text(TranscriptExport.clock(t.start)).font(.caption.monospacedDigit()).foregroundStyle(Ink.link)
+ Text(t.title).font(.system(size: size, weight: .semibold))
+ }
+ if !t.summary.isEmpty {
+ Text(t.summary).font(.subheadline).foregroundStyle(Ink.secondary).lineSpacing(3)
+ }
+ ForEach(t.points, id: \.self) { p in
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ Circle().fill(Ink.tertiary).frame(width: 4, height: 4).alignmentGuide(.firstTextBaseline) { $0[.bottom] + 5 }
+ Text(p).font(.subheadline).foregroundStyle(Ink.ink).lineSpacing(3)
+ }
+ }
+ if let f = t.fishbone, !f.branches.isEmpty { FishboneList(fishbone: f) }
+ }
+ .padding(.bottom, 6)
+ }
+ }
+ }
+ if !n.conclusions.isEmpty {
+ block("结论") {
+ ForEach(Array(n.conclusions.enumerated()), id: \.element.id) { i, c in
+ HStack(alignment: .firstTextBaseline, spacing: 10) {
+ Text("\(i + 1)").font(.system(size: size, weight: .bold)).foregroundStyle(Ink.link)
+ Text(c.text).font(.system(size: size)).lineSpacing(3)
+ }
+ }
+ }
+ }
+ if !n.todos.isEmpty {
+ block("待办") {
+ ForEach(n.todos) { t in
+ HStack(alignment: .firstTextBaseline, spacing: 10) {
+ Image(systemName: "square").font(.system(size: size)).foregroundStyle(Ink.tertiary)
+ Text((t.owner.map { "\($0):" } ?? "") + t.text).font(.system(size: size)).lineSpacing(3)
+ }
+ }
+ }
+ }
+ if !n.terms.isEmpty {
+ block("人名和术语") {
+ ForEach(n.terms) { t in
+ VStack(alignment: .leading, spacing: 2) {
+ Text(t.name).font(.subheadline.weight(.semibold))
+ if !t.note.isEmpty { Text(t.note).font(.footnote).foregroundStyle(Ink.secondary) }
+ }
+ }
+ }
+ }
+ }
+ .foregroundStyle(Ink.ink)
+ .textSelection(.enabled)
+ } else {
+ Text("这场会议还没有纪要").foregroundStyle(Ink.secondary).frame(maxWidth: .infinity).padding(.top, 40)
+ }
+ }
+
+ private func block<C: View>(_ title: LocalizedStringKey, @ViewBuilder _ content: () -> C) -> some View {
+ VStack(alignment: .leading, spacing: 10) {
+ Text(title).font(.footnote.weight(.semibold)).foregroundStyle(Ink.secondary)
+ content()
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+}
+
+/// A topic's fishbone as the narrow Mac window draws it upright: the question, then each cause.
+struct FishboneList: View {
+ let fishbone: Fishbone
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ Text(fishbone.question.isEmpty ? L("为什么") : fishbone.question).font(.subheadline.weight(.semibold))
+ ForEach(fishbone.branches) { b in
+ (Text(b.label).fontWeight(.semibold) + Text(verbatim: ":") + Text(b.detail))
+ .font(.subheadline).foregroundStyle(b.support == 0 ? Ink.secondary : Ink.ink).lineSpacing(3)
+ }
+ }
+ .padding(12)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Ink.ground, in: RoundedRectangle(cornerRadius: 14, style: .continuous))
+ .padding(.top, 4)
+ }
+}
+
+// MARK: - The recording
+
+/// Plays the meeting's system.m4a; the transcript follows it and its times seek.
+@MainActor
+final class RecordPlayer: ObservableObject {
+ @Published private(set) var now: Double = 0
+ @Published private(set) var playing = false
+ private(set) var duration: Double = 0
+ private var audio: AVAudioPlayer?
+ private var timer: Timer?
+
+ var available: Bool { audio != nil }
+
+ private var loaded: String?
+
+ /// The meeting's recording; another meeting's replaces it (the page is reused when one is picked).
+ func load(store: SessionStore, session: Session) {
+ guard loaded != session.id else { return }
+ stop()
+ loaded = session.id
+ audio = nil
+ now = 0
+ duration = 0
+ objectWillChange.send()
+ guard session.hasAudio else { return }
+ let url = store.systemAudioURL(session.id)
+ guard let a = try? AVAudioPlayer(contentsOf: url) else { return }
+ audio = a
+ duration = a.duration
+ objectWillChange.send()
+ }
+
+ func toggle() {
+ guard let audio else { return }
+ if audio.isPlaying { audio.pause(); playing = false; timer?.invalidate(); return }
+ try? AVAudioSession.sharedInstance().setCategory(.playback)
+ audio.play(); playing = true
+ timer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { [weak self] _ in
+ MainActor.assumeIsolated {
+ guard let self, let a = self.audio else { return }
+ self.now = a.currentTime
+ if !a.isPlaying { self.playing = false; self.timer?.invalidate() }
+ }
+ }
+ }
+
+ func seek(_ t: Double) {
+ guard let audio else { return }
+ audio.currentTime = min(max(0, t), duration)
+ now = audio.currentTime
+ if !audio.isPlaying { toggle() }
+ }
+
+ func stop() { audio?.stop(); playing = false; timer?.invalidate() }
+
+ /// The last line that started at or before the playhead, once playing has begun.
+ func lineID(in s: Session) -> String? {
+ guard playing || now > 0 else { return nil }
+ return s.lines.last(where: { $0.t <= now + 0.2 })?.id
+ }
+}
+
+/// The design's glass bar: play / pause, a progress line, the time and the length.
+struct PlayerBar: View {
+ @ObservedObject var player: RecordPlayer
+
+ var body: some View {
+ HStack(spacing: 12) {
+ Button(action: player.toggle) {
+ Image(systemName: player.playing ? "pause.fill" : "play.fill")
+ .font(.system(size: 16, weight: .bold))
+ .foregroundStyle(.white)
+ .frame(width: 46, height: 46)
+ .background(Ink.ink, in: Circle())
+ }
+ .accessibilityLabel(player.playing ? Text("暂停") : Text("播放"))
+ VStack(spacing: 6) {
+ GeometryReader { g in
+ ZStack(alignment: .leading) {
+ Capsule().fill(Ink.line)
+ Capsule().fill(Ink.accent)
+ .frame(width: g.size.width * (player.duration > 0 ? min(1, player.now / player.duration) : 0))
+ }
+ }
+ .frame(height: 4)
+ HStack {
+ Text(TranscriptExport.clock(player.now))
+ Spacer()
+ Text(TranscriptExport.clock(player.duration))
+ }
+ .font(.caption2.monospacedDigit())
+ .foregroundStyle(Ink.secondary)
+ }
+ }
+ .padding(.leading, 8)
+ .padding(.trailing, 18)
+ .frame(height: 62)
+ .glassEffect(.regular, in: Capsule())
+ }
+}
+
+extension Notification.Name {
+ /// Debug `play:<seconds>`: the open record plays from there.
+ static let debugPlay = Notification.Name("cicada.debugPlay")
+}
diff --git a/ios/Sources/Cicada/RecordsView.swift b/ios/Sources/Cicada/RecordsView.swift
new file mode 100644
index 0000000..7860795
--- /dev/null
+++ b/ios/Sources/Cicada/RecordsView.swift
@@ -0,0 +1,315 @@
+import SwiftUI
+
+/// 会议记录 (iPhone), as the design's home: the title with the import button, the 听会议室 card,
+/// then the meetings as grouped white cards on the grey ground. Grouping and titles are the Mac's
+/// (RecordList).
+struct RecordsSplit: View {
+ @EnvironmentObject var model: AppModel
+ @EnvironmentObject var room: RoomListen
+ @ObservedObject var store: SessionStore
+
+ var body: some View {
+ if room.isRunning {
+ LivePhone()
+ } else {
+ records
+ }
+ }
+
+ private var records: some View {
+ NavigationStack(path: Binding(get: { model.selection.map { [$0] } ?? [] },
+ set: { model.selection = $0.last })) {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 0) {
+ HomeTitle(trailing: AnyView(
+ Button { model.comingSoon = L("导入录音或视频") } label: { GlassIcon(systemName: "arrow.down.to.line") }
+ .buttonStyle(.plain)
+ .accessibilityLabel(Text("导入录音或视频"))))
+ .padding(.top, 6)
+ ListenBar().padding(.top, 16)
+ if store.sessions.isEmpty {
+ EmptyRecords().frame(maxWidth: .infinity).padding(.top, 40)
+ } else {
+ RecordGroups(sessions: store.sessions, style: .cards, picked: nil) { model.selection = $0 }
+ .padding(.top, 4)
+ }
+ }
+ .padding(.horizontal, 16)
+ .padding(.bottom, 120)
+ }
+ .background(Ink.ground)
+ .toolbar(.hidden, for: .navigationBar)
+ .navigationDestination(for: String.self) { id in
+ if let s = store.sessions.first(where: { $0.id == id }) { RecordView(session: s) }
+ }
+ }
+ }
+}
+
+/// The app icon, drawn by the Mac's renderer at build time (ios/scripts/build.sh); its macOS margin
+/// is cropped so the tile fills the frame.
+struct Logo: View {
+ let size: CGFloat
+ private static let image = Bundle.main.path(forResource: "logo", ofType: "png").flatMap(UIImage.init(contentsOfFile:))
+
+ var body: some View {
+ Group {
+ if let image = Self.image {
+ Image(uiImage: image).resizable().scaledToFill().scaleEffect(1.24)
+ } else {
+ Ink.accent
+ }
+ }
+ .frame(width: size, height: size)
+ .clipShape(RoundedRectangle(cornerRadius: size / 4, style: .continuous))
+ .accessibilityHidden(true)
+ }
+}
+
+/// iPad: the design's glass sidebar (title, import, settings, a search field, the meetings) beside
+/// the open meeting, which is the newest until one is picked, as on the Mac.
+struct PadRoot: View {
+ @EnvironmentObject var model: AppModel
+ @EnvironmentObject var room: RoomListen
+ @ObservedObject var store: SessionStore
+
+ var body: some View {
+ HStack(spacing: 0) {
+ sidebar
+ .frame(width: 320)
+ .padding(12)
+ Group {
+ if room.isRunning {
+ LivePad()
+ } else if let s = shown {
+ NavigationStack { RecordView(session: s) }.id(s.id)
+ } else {
+ Color.white
+ }
+ }
+ .frame(maxWidth: .infinity)
+ }
+ .background(Ink.ground)
+ .sheet(isPresented: $model.showSettings) {
+ SettingsView(sheet: true)
+ }
+ }
+
+ private var sidebar: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ HomeTitle(logo: 48, titleSize: 26, trailing: AnyView(HStack(spacing: 0) {
+ Button { model.comingSoon = L("导入录音或视频") } label: { PadIcon(systemName: "arrow.down.to.line") }
+ .buttonStyle(.plain).accessibilityLabel(Text("导入录音或视频"))
+ Button { model.showSettings = true } label: { PadIcon(systemName: "gearshape") }
+ .buttonStyle(.plain).accessibilityLabel(Text("设置"))
+ }))
+ .padding(.horizontal, 4)
+ ListenBar(onGlass: true).padding(.top, 14).padding(.bottom, 12)
+ HStack(spacing: 8) {
+ Image(systemName: "magnifyingglass").foregroundStyle(Ink.secondary)
+ TextField(text: $model.query) { Text("搜索文字记录") }
+ .textFieldStyle(.plain)
+ .submitLabel(.search)
+ if !model.query.isEmpty {
+ Button { model.query = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(Ink.tertiary) }
+ .buttonStyle(.plain).accessibilityLabel(Text("清除"))
+ }
+ }
+ .font(.subheadline)
+ .padding(.horizontal, 12)
+ .frame(height: 38)
+ .background(Ink.ink.opacity(0.06), in: RoundedRectangle(cornerRadius: 12, style: .continuous))
+ ScrollView {
+ let found = SearchView.matches(store.sessions, model.query)
+ if store.sessions.isEmpty {
+ EmptyRecords().frame(maxWidth: .infinity).padding(.top, 40)
+ } else if found.isEmpty {
+ Text(L("没有找到“\(model.query)”")).font(.subheadline).foregroundStyle(Ink.secondary)
+ .frame(maxWidth: .infinity).padding(.top, 40)
+ } else {
+ RecordGroups(sessions: found, style: .sidebar, picked: shown?.id) { model.selection = $0 }
+ }
+ }
+ .scrollIndicators(.hidden)
+ }
+ .padding(.horizontal, 14)
+ .padding(.top, 22)
+ .frame(maxHeight: .infinity, alignment: .top)
+ .glassEffect(.regular, in: RoundedRectangle(cornerRadius: 26, style: .continuous))
+ }
+
+ private var shown: Session? {
+ if let id = model.selection, let s = store.sessions.first(where: { $0.id == id }) { return s }
+ return store.sessions.first
+ }
+}
+
+/// The sidebar's small white round buttons.
+struct PadIcon: View {
+ let systemName: String
+
+ var body: some View {
+ Image(systemName: systemName)
+ .font(.system(size: 15, weight: .semibold))
+ .foregroundStyle(Ink.ink)
+ .frame(width: 36, height: 36)
+ .background(Color.white, in: Circle())
+ .frame(width: 44, height: 44)
+ .contentShape(Circle())
+ }
+}
+
+struct EmptyRecords: View {
+ var body: some View {
+ Text("还没有会议").font(.title3.weight(.semibold)).foregroundStyle(Ink.ink).padding(32)
+ }
+}
+
+/// 今天 / 昨天 / 本周 / months, each a card of rows (iPhone) or plain rows with the picked one on a
+/// white card (iPad's sidebar, as in the design's iPad screen).
+struct RecordGroups: View {
+ @EnvironmentObject var model: AppModel
+ enum Style { case cards, sidebar }
+ let sessions: [Session]
+ let style: Style
+ let picked: String?
+ let pick: (String) -> Void
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ ForEach(RecordList.groups(sessions), id: \.title) { group in
+ SectionLabel(text: group.title)
+ switch style {
+ case .cards:
+ Card {
+ ForEach(Array(group.sessions.enumerated()), id: \.element.id) { i, s in
+ if i > 0 { Hairline() }
+ Button { pick(s.id) } label: { RecordRow(session: s, chevron: true) }
+ .buttonStyle(RowPress())
+ .contextMenu { menu(s) }
+ }
+ }
+ case .sidebar:
+ VStack(spacing: 2) {
+ ForEach(group.sessions) { s in
+ Button { pick(s.id) } label: {
+ RecordRow(session: s, chevron: false)
+ // White on the light glass needs a soft edge to read as picked.
+ .background(RoundedRectangle(cornerRadius: 14, style: .continuous)
+ .fill(s.id == picked ? Color.white : .clear)
+ .shadow(color: Ink.ink.opacity(s.id == picked ? 0.10 : 0), radius: 6, y: 2))
+ }
+ .buttonStyle(RowPress())
+ .contextMenu { menu(s) }
+ .accessibilityAddTraits(s.id == picked ? .isSelected : [])
+ }
+ }
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ /// The Mac's row menu, less what iOS can't do (Finder, the original file).
+ @ViewBuilder private func menu(_ s: Session) -> some View {
+ if s.renamed ?? !s.title.hasPrefix("会议 "), s.notes?.title != nil {
+ Button { model.rename(s.id, to: "") } label: { Label("恢复自动标题", systemImage: "arrow.uturn.backward") }
+ }
+ Button(role: .destructive) { model.deleteSession(s.id) } label: { Label("删除", systemImage: "trash") }
+ .disabled(s.id == model.store.liveID)
+ }
+}
+
+/// A pressed row darkens slightly, like a system list cell.
+struct RowPress: ButtonStyle {
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label.background(configuration.isPressed ? Ink.ink.opacity(0.05) : .clear)
+ }
+}
+
+struct RecordRow: View {
+ let session: Session
+ let chevron: Bool
+ /// Watched here so "3 人" comes and goes with 说话人识别 (a row's session doesn't change).
+ @AppStorage(Pref.voices) private var voices = true
+
+ private var runs: [SpeakerRail.Run] {
+ SpeakerRail.runs(session, numbers: voices ? TranscriptExport.speakerNumbers(session) : [:])
+ }
+
+ var body: some View {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 3) {
+ Text(RecordList.untitled(session) ? L("未命名会议") : RecordList.listTitle(session))
+ .font(.body.weight(.semibold))
+ .foregroundStyle(Ink.ink)
+ .lineLimit(2)
+ .multilineTextAlignment(.leading)
+ Text(Self.meta(session, voices: voices))
+ .font(.footnote)
+ .foregroundStyle(Ink.secondary)
+ .lineLimit(1)
+ }
+ .padding(.leading, runs.isEmpty ? 0 : 14)
+ // Scheme A's upright strip: each person's turns in grey, a bookmark of the meeting.
+ .overlay(alignment: .leading) {
+ if !runs.isEmpty { RailView(runs: runs, axis: .upright, thickness: 4).padding(.vertical, 2) }
+ }
+ Spacer(minLength: 0)
+ if chevron { Chevron() }
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 14)
+ .frame(minHeight: 44)
+ .contentShape(Rectangle())
+ }
+
+ /// "10:02 · 48 分钟 · 3 人 · 英 → 中 · 会议室", as in the design's rows.
+ static func meta(_ s: Session, voices on: Bool) -> String {
+ var parts = [RecordList.when(s), RecordList.length(s)]
+ let voices = on ? SpeakerLabels.voiceNumbers(s.lines).count : 0
+ if voices >= 2 { parts.append(L("\(voices) 人")) }
+ if let pair = RecordList.pair(s, short: true) { parts.append(pair) }
+ if s.sourceFile != nil { parts.append(L("导入")) } else if s.room == true { parts.append(L("会议室")) }
+ return parts.joined(separator: " · ")
+ }
+}
+
+/// Search on its own tab: titles and every line, original and translation.
+struct SearchView: View {
+ @EnvironmentObject var model: AppModel
+ @ObservedObject var store: SessionStore
+
+ static func matches(_ sessions: [Session], _ query: String) -> [Session] {
+ let q = query.trimmingCharacters(in: .whitespaces)
+ guard !q.isEmpty else { return sessions }
+ return sessions.filter { s in
+ s.displayTitle.localizedCaseInsensitiveContains(q)
+ || s.lines.contains { $0.src.localizedCaseInsensitiveContains(q) || ($0.dst?.localizedCaseInsensitiveContains(q) ?? false) }
+ }
+ }
+
+ var body: some View {
+ let found = Self.matches(store.sessions, model.query)
+ NavigationStack(path: $model.searchPath) {
+ ScrollView {
+ if found.isEmpty && !model.query.isEmpty {
+ Text(L("没有找到“\(model.query)”"))
+ .font(.body).foregroundStyle(Ink.secondary)
+ .frame(maxWidth: .infinity).padding(.top, 80)
+ } else {
+ RecordGroups(sessions: found, style: .cards, picked: nil) { model.searchPath = [$0] }
+ .padding(.horizontal, 16)
+ .padding(.bottom, 120)
+ }
+ }
+ .background(Ink.ground)
+ .navigationTitle("搜索")
+ .navigationDestination(for: String.self) { id in
+ if let s = store.sessions.first(where: { $0.id == id }) { RecordView(session: s) }
+ }
+ // At the top, under the title: the bottom is the tab bar's.
+ .searchable(text: $model.query, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("搜索文字记录"))
+ }
+ }
+}
diff --git a/ios/Sources/Cicada/RoomListen.swift b/ios/Sources/Cicada/RoomListen.swift
new file mode 100644
index 0000000..6938d6d
--- /dev/null
+++ b/ios/Sources/Cicada/RoomListen.swift
@@ -0,0 +1,339 @@
+import AVFoundation
+import Foundation
+
+/// 听会议室 on iPhone and iPad: the microphone → the shared recognizer (`Recognition`) → the shared
+/// translation chain → the meeting record, with live notes from the shared `NotesEngine`. The Mac's
+/// `ListenEngine` is bound to Core Audio and AppKit; this is the same pipeline cut down to one source
+/// and one language the user picked (对方说; detecting it comes later).
+@MainActor
+final class RoomListen: ObservableObject {
+ /// One sentence on the 字幕 page.
+ struct Line: Identifiable, Equatable {
+ let id: String
+ var src: String
+ var dst: String?
+ var voice: Int?
+ var t: Double
+ }
+
+ @Published private(set) var isRunning = false
+ @Published private(set) var startedAt: Date?
+ @Published private(set) var lines: [Line] = []
+ /// The sentence in progress and its draft translation.
+ @Published private(set) var draft = ""
+ @Published private(set) var draftTranslation = ""
+ /// 0–1, for the wave.
+ @Published private(set) var level: Float = 0
+ @Published private(set) var status = ""
+ @Published private(set) var sessionID: String?
+
+ /// Every finished line, for the Live Activity.
+ var onLine: ((Line) -> Void)?
+ var onStateChange: (() -> Void)?
+
+ private let store: SessionStore
+ private let translator: TranslationService
+ private let notes: NotesEngine
+ private let speakers = SpeakerTagger()
+ private let audio = RoomAudio()
+ private var stream: RecognitionStream?
+ private var reader: Task<Void, Never>?
+ /// The last meeting still closing: its recognizer flushes the last sentence before its session ends.
+ private var stopping: Task<Void, Never>?
+ private var lang = sourceLanguages[0]
+ private var target = "zh-Hans"
+ private var counter = 0
+ /// The last line written, with where it sits on the recognizer's clock, for joining a sentence a pause cut.
+ private var last: (id: String, src: String, end: Double)?
+ private var draftAsked = Date.distantPast
+ private var draftEpoch = 0
+ /// The microphone heard something loud enough to be a voice, for keeping a meeting with no lines.
+ private var heardVoice = false
+
+ init(store: SessionStore, translator: TranslationService, notes: NotesEngine) {
+ self.store = store
+ self.translator = translator
+ self.notes = notes
+ speakers.onVoice = { [weak self] lineID, voice in
+ guard let self else { return }
+ self.store.setVoice(lineID: lineID, voice)
+ if let i = self.lines.firstIndex(where: { $0.id == lineID }) { self.lines[i].voice = voice }
+ }
+ }
+
+ /// Distinct voices heard so far.
+ var speakerCount: Int { Set(lines.compactMap(\.voice)).count }
+
+ var elapsed: TimeInterval { startedAt.map { Date().timeIntervalSince($0) } ?? 0 }
+ var languagePair: (source: String, target: String) { (lang.code, target) }
+
+ func start(source: String, target: String, voices: Bool) {
+ guard !isRunning else { return }
+ lang = sourceLanguages.first { $0.locale == source } ?? sourceLanguages[0]
+ self.target = target
+ status = L("正在准备…")
+ isRunning = true
+ onStateChange?()
+ Task { await begin(voices: voices) }
+ }
+
+ private func begin(voices: Bool) async {
+ // Started again right after 结束: the last meeting's closing would otherwise cancel this one's
+ // reader and end this one's session, leaving the microphone on with nothing coming in.
+ await stopping?.value
+ guard isRunning else { return }
+ lines = []
+ draft = ""
+ draftTranslation = ""
+ last = nil
+ counter = 0
+ speakers.reset()
+ guard await AVAudioApplication.requestRecordPermission() else {
+ fail(L("请在设置里允许知了使用麦克风"))
+ return
+ }
+ do {
+ if await Recognition.status(lang.locale) != .installed {
+ status = L("正在下载 \(lang.name) 语音模型…")
+ try await Recognition.install(lang.locale)
+ }
+ let stream = try await Recognition.start(lang.locale, drafts: true, confidence: true)
+ guard isRunning else { await stream.cancel(); return }
+ self.stream = stream
+ let s = store.begin()
+ store.markLiveInRoom()
+ sessionID = s.id
+ startedAt = s.startedAt
+ notes.begin(s.id)
+ audio.voices = voices
+ try audio.start(recognizer: stream, recording: AudioFileWriter.partial(store.systemAudioURL(s.id)))
+ heardVoice = false
+ audio.onLevel = { [weak self] v in
+ self?.level = v
+ if v > 0.55 { self?.heardVoice = true }
+ }
+ reader = Task { [weak self] in
+ do {
+ for try await piece in stream.results { self?.handle(piece) }
+ } catch {
+ debugLog("room: recognizer ended: \(error)")
+ // The meeting so far is kept; listening stops with a reason rather than hearing nothing.
+ guard let self, self.isRunning else { return }
+ self.stop()
+ self.status = L("识别中断了,请重新开始听")
+ }
+ }
+ status = ""
+ debugLog("room: listening locale=\(lang.locale) target=\(target) format=\(stream.format) session=\(s.id)")
+ onStateChange?()
+ } catch {
+ debugLog("room: start failed: \(error)")
+ fail(Recognition.needsUser(error) ? error.localizedDescription : L("没能下载 \(lang.name) 语音模型"))
+ }
+ }
+
+ private func fail(_ message: String) {
+ status = message
+ isRunning = false
+ onStateChange?()
+ }
+
+ func stop() {
+ guard isRunning else { return }
+ isRunning = false
+ audio.stop()
+ let stream = self.stream, reader = self.reader
+ self.stream = nil
+ self.reader = nil
+ stopping = Task {
+ await stream?.finish()
+ reader?.cancel()
+ notes.finish()
+ // A meeting with no line is kept only when the microphone heard voices (its recording holds them).
+ store.end(heardSpeech: heardVoice)
+ debugLog("room: stopped lines=\(lines.count)")
+ sessionID = nil
+ startedAt = nil
+ level = 0
+ onStateChange?()
+ }
+ onStateChange?()
+ }
+
+ private func handle(_ piece: Recognition.Piece) {
+ let text = piece.text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard piece.isFinal else {
+ if text != draft {
+ draft = text
+ translateDraft()
+ }
+ return
+ }
+ let final = HeardText.fuller(final: HeardText.clean(text), draft: draft)
+ draft = ""
+ draftTranslation = ""
+ draftEpoch += 1
+ guard final.contains(where: \.isLetter), let start = startedAt else { return }
+ contentLog("FINAL [\(lang.locale)] \(final)")
+ // One sentence a pause cut in two: the earlier line takes the rest.
+ if let prev = last, lines.last?.id == prev.id,
+ HeardText.continues(prev.src, final, gap: piece.start - prev.end, cut: false) {
+ let joined = HeardText.join(prev.src, final)
+ last = (prev.id, joined, piece.end)
+ store.setSource(lineID: prev.id, joined)
+ if let i = lines.firstIndex(where: { $0.id == prev.id }) { lines[i].src = joined }
+ translate(prev.id, joined)
+ return
+ }
+ counter += 1
+ let id = "r\(counter)"
+ // Where the sentence started, in meeting time: the recognizer's clock runs on the audio fed.
+ let t = max(0, Date().timeIntervalSince(start) - max(0, audio.fedSeconds - piece.start))
+ store.append(TranscriptLine(id: id, t: t, speaker: "them", src: final, dst: nil,
+ srcLang: lang.code, dstLang: target))
+ lines.append(Line(id: id, src: final, dst: nil, voice: nil, t: t))
+ if lines.count > 60 { lines.removeFirst(lines.count - 60) }
+ last = (id, final, piece.end)
+ if let samples = audio.voiceSamples(from: piece.start, to: piece.end) {
+ speakers.tag(lineID: id, samples: samples)
+ }
+ translate(id, final)
+ }
+
+ /// `retry`: every provider failed before (Ling busy while Google answers 429): asked again a
+ /// little later, twice at most, as the Mac does.
+ private func translate(_ id: String, _ text: String, retry: Int = 0) {
+ let source = lang.code, target = self.target
+ Task {
+ guard let out = await translator.translate(text, source: source, target: target, kind: .sentence) else {
+ debugLog("room: translation failed, try \(retry + 1)")
+ guard retry < 2 else { return }
+ try? await Task.sleep(nanoseconds: UInt64(retry == 0 ? 10 : 20) * 1_000_000_000)
+ guard isRunning, lines.first(where: { $0.id == id })?.src == text else { return }
+ translate(id, text, retry: retry + 1)
+ return
+ }
+ // Joined meanwhile: only the whole sentence's translation counts.
+ guard let i = lines.firstIndex(where: { $0.id == id }), lines[i].src == text else { return }
+ lines[i].dst = out
+ store.setTranslation(lineID: id, out)
+ contentLog("TRANSLATE [\(source)→\(target)] \(text) => \(out)")
+ onLine?(lines[i])
+ }
+ }
+
+ /// The line in progress, at most every second (Google, never Ling: AGENTS.md).
+ private func translateDraft() {
+ guard Date().timeIntervalSince(draftAsked) > 1, draft.count >= 6 else { return }
+ draftAsked = Date()
+ let epoch = draftEpoch, text = draft, source = lang.code, target = self.target
+ Task {
+ let out = await translator.translate(text, source: source, target: target, kind: .draft)
+ guard epoch == draftEpoch, let out else { return }
+ draftTranslation = out
+ }
+ }
+}
+
+/// The microphone side, off the main actor: `AVAudioEngine`'s input tap → the recognizer's format,
+/// the meeting's recording, a level and the last minute of 16 kHz audio for voiceprints.
+final class RoomAudio: @unchecked Sendable {
+ var voices = true
+ var onLevel: (@MainActor (Float) -> Void)?
+
+ /// A new engine for each meeting: one restarted after `stop` hears only silence in the simulator.
+ private var engine = AVAudioEngine()
+ private let queue = DispatchQueue(label: "com.wquguru.cicada.room", qos: .userInitiated)
+ private let toRecognizer = PCMConverter()
+ private let toVoice = PCMConverter()
+ private let voiceFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16_000, channels: 1, interleaved: false)!
+ private var stream: RecognitionStream?
+ private var recorder: AVAudioFile?
+ private var recordingURL: URL?
+ /// Recognizer-clock seconds of audio appended, and the voice ring (its first sample's time).
+ private var fed = 0.0
+ private var ring: [Float] = []
+ private var ringStart = 0.0
+ private var lastLevel = Date.distantPast
+
+ var fedSeconds: Double { queue.sync { fed } }
+
+ func start(recognizer: RecognitionStream, recording: URL) throws {
+ let session = AVAudioSession.sharedInstance()
+ // .measurement: no voice processing, which would duck what the room says as "echo".
+ try session.setCategory(.playAndRecord, mode: .measurement, options: [.defaultToSpeaker])
+ try session.setActive(true)
+ engine = AVAudioEngine()
+ queue.sync {
+ stream = recognizer
+ recordingURL = recording
+ fed = 0
+ ring = []
+ ringStart = 0
+ }
+ let input = engine.inputNode
+ let format = input.outputFormat(forBus: 0)
+ debugLog("room: input \(format) route=\(session.currentRoute.inputs.map(\.portName))")
+ input.installTap(onBus: 0, bufferSize: 4096, format: format) { [weak self] buffer, _ in
+ guard let self, let copy = buffer.copy() as? AVAudioPCMBuffer else { return }
+ self.queue.async { self.feed(copy) }
+ }
+ engine.prepare()
+ try engine.start()
+ }
+
+ func stop() {
+ engine.inputNode.removeTap(onBus: 0)
+ engine.stop()
+ queue.sync {
+ stream = nil
+ recorder = nil
+ }
+ try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
+ }
+
+ private func feed(_ buffer: AVAudioPCMBuffer) {
+ guard let stream else { return }
+ if let c = toRecognizer.convert(buffer, to: stream.format) {
+ stream.append(c)
+ fed += Double(c.frameLength) / c.format.sampleRate
+ }
+ guard let v = toVoice.convert(buffer, to: voiceFormat), let p = v.floatChannelData?[0] else { return }
+ let n = Int(v.frameLength)
+ if recorder == nil, let url = recordingURL { recorder = AudioFileWriter.open(url, format: voiceFormat) }
+ try? recorder?.write(from: v)
+ if voices {
+ ring.append(contentsOf: UnsafeBufferPointer(start: p, count: n))
+ let keep = 60 * 16_000
+ if ring.count > keep + 16_000 {
+ let drop = ring.count - keep
+ ring.removeFirst(drop)
+ ringStart += Double(drop) / 16_000
+ }
+ // The ring runs on the voice clock; it tracks the recognizer's since both see every buffer.
+ } else {
+ ringStart = fed
+ }
+ if Date().timeIntervalSince(lastLevel) > 0.08 {
+ lastLevel = Date()
+ var sum: Float = 0
+ for i in 0..<n { sum += p[i] * p[i] }
+ let rms = n > 0 ? (sum / Float(n)).squareRoot() : 0
+ // -50…-10 dBFS onto 0…1.
+ let db = 20 * log10(max(rms, 1e-6))
+ let v = max(0, min(1, (db + 50) / 40))
+ let cb = onLevel
+ DispatchQueue.main.async { MainActor.assumeIsolated { cb?(v) } }
+ }
+ }
+
+ /// 16 kHz mono audio between two recognizer-clock times, if still in the ring and long enough.
+ func voiceSamples(from: Double, to: Double) -> [Float]? {
+ queue.sync {
+ guard voices else { return nil }
+ let a = max(0, Int((from - ringStart) * 16_000)), b = min(ring.count, Int((to - ringStart) * 16_000))
+ guard b - a >= Int(Voiceprints.minSeconds * 16_000) else { return nil }
+ return Array(ring[a..<min(b, a + Int(Voiceprints.maxSeconds * 16_000))])
+ }
+ }
+}
diff --git a/ios/Sources/Cicada/RootView.swift b/ios/Sources/Cicada/RootView.swift
new file mode 100644
index 0000000..b9d30f5
--- /dev/null
+++ b/ios/Sources/Cicada/RootView.swift
@@ -0,0 +1,116 @@
+import SwiftUI
+
+/// The design's shell. iPhone: 会议记录 and 设置 on a glass bar, search a glass circle beside it, and
+/// the bar only on those top screens (a meeting has the page to itself). iPad: a glass sidebar of
+/// meetings beside the open one, settings as a sheet. The system TabView can't draw either: it
+/// merges search into the bar and puts a tab pill over the iPad's detail.
+struct RootView: View {
+ @EnvironmentObject var model: AppModel
+ @Environment(\.horizontalSizeClass) private var sizeClass
+
+ var body: some View {
+ Group {
+ if sizeClass == .regular {
+ PadRoot(store: model.store)
+ } else {
+ PhoneRoot()
+ }
+ }
+ .tint(Ink.accent)
+ // The Mac's palette is light only (Palette in Views.swift); a dark one comes later, for both.
+ .preferredColorScheme(.light)
+ .alert(Text(model.comingSoon ?? ""), isPresented: Binding(get: { model.comingSoon != nil },
+ set: { if !$0 { model.comingSoon = nil } })) {
+ Button("好") { model.comingSoon = nil }
+ } message: {
+ Text("下一版就能用")
+ }
+ }
+}
+
+struct PhoneRoot: View {
+ @EnvironmentObject var model: AppModel
+
+ var body: some View {
+ ZStack {
+ // Each tab keeps its place while another is shown, like a tab bar's.
+ RecordsSplit(store: model.store).opacity(model.tab == .records ? 1 : 0)
+ .allowsHitTesting(model.tab == .records)
+ SettingsView().opacity(model.tab == .settings ? 1 : 0)
+ .allowsHitTesting(model.tab == .settings)
+ if model.tab == .search { SearchView(store: model.store) }
+ }
+ .overlay(alignment: .bottom) {
+ if barShown { TabBar().transition(.move(edge: .bottom).combined(with: .opacity)) }
+ }
+ .animation(.snappy(duration: 0.25), value: barShown)
+ .ignoresSafeArea(.keyboard, edges: .bottom)
+ }
+
+ private var barShown: Bool {
+ switch model.tab {
+ case .records: model.selection == nil && !model.room.isRunning
+ case .settings: true
+ case .search: model.searchPath.isEmpty
+ }
+ }
+}
+
+/// Two tabs in a glass capsule, the picked one on a faint accent pill, and search on its own.
+struct TabBar: View {
+ @EnvironmentObject var model: AppModel
+
+ var body: some View {
+ GlassEffectContainer(spacing: 12) {
+ HStack(spacing: 12) {
+ HStack(spacing: 4) {
+ item(.records, "会议记录", "list.bullet")
+ item(.settings, "设置", "gearshape")
+ }
+ .padding(.horizontal, 5)
+ .frame(height: 62)
+ .glassEffect(.regular, in: Capsule())
+
+ Button { pick(.search) } label: {
+ Image(systemName: "magnifyingglass")
+ .font(.system(size: 20, weight: .semibold))
+ .foregroundStyle(model.tab == .search ? Ink.accentText : Ink.ink)
+ .frame(width: 62, height: 62)
+ .background(model.tab == .search ? Ink.accentWash : .clear, in: Circle())
+ .contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .glassEffect(.regular.interactive(), in: Circle())
+ .accessibilityLabel(Text("搜索"))
+ .accessibilityAddTraits(model.tab == .search ? .isSelected : [])
+ }
+ }
+ .padding(.horizontal, 16)
+ .padding(.bottom, 4)
+ }
+
+ private func item(_ tab: AppTab, _ title: LocalizedStringKey, _ icon: String) -> some View {
+ let on = model.tab == tab
+ return Button { pick(tab) } label: {
+ VStack(spacing: 2) {
+ Image(systemName: icon).font(.system(size: 19, weight: .medium)).frame(height: 24)
+ Text(title).font(.system(size: 11, weight: on ? .semibold : .regular))
+ }
+ .foregroundStyle(on ? Ink.accentText : Ink.secondary)
+ .frame(maxWidth: .infinity, minHeight: 52)
+ .background(on ? Ink.accentWash : .clear, in: Capsule())
+ .contentShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(on ? .isSelected : [])
+ }
+
+ private func pick(_ tab: AppTab) {
+ // Tapping the open tab again goes back to its top, as a tab bar does.
+ if model.tab == tab {
+ if tab == .records { model.selection = nil }
+ if tab == .search { model.searchPath = [] }
+ }
+ model.tab = tab
+ }
+}
diff --git a/ios/Sources/Cicada/SettingsView.swift b/ios/Sources/Cicada/SettingsView.swift
new file mode 100644
index 0000000..e3cbae7
--- /dev/null
+++ b/ios/Sources/Cicada/SettingsView.swift
@@ -0,0 +1,232 @@
+import SwiftUI
+
+/// 设置, as the design's: grey section labels over white cards. Only what the app does today:
+/// the Ling key and model (纪要), the language meetings are translated into, and 说话人识别.
+/// 同声传译 and 快速开始 come with M3 and M4.
+struct SettingsView: View {
+ /// iPad shows it as a sheet, with 完成.
+ var sheet = false
+ @EnvironmentObject var model: AppModel
+ @EnvironmentObject var ling: LingClient
+ @Environment(\.dismiss) private var dismiss
+ @AppStorage(Pref.model) private var aiModel = LingClient.models[0]
+ @AppStorage(Pref.target) private var target = "system"
+ @AppStorage(Pref.voices) private var voices = true
+ @AppStorage(Pref.notesLanguage) private var notesLanguage = "mine"
+
+ var body: some View {
+ NavigationStack {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 0) {
+ if !sheet {
+ Text("设置").font(.largeTitle.bold()).foregroundStyle(Ink.ink)
+ .padding(.horizontal, 4).padding(.top, 6)
+ }
+ SectionLabel(text: L("AI 服务"))
+ Card {
+ NavigationLink { KeyPage() } label: {
+ row(Text(verbatim: "Ling key")) {
+ KeyStatus(state: ling.keyState)
+ Chevron()
+ }
+ }
+ .buttonStyle(RowPress())
+ Hairline()
+ row(Text("模型")) {
+ Picker(selection: $aiModel) {
+ ForEach(LingClient.models, id: \.self) { Text(verbatim: $0).tag($0) }
+ } label: { Text("模型") }
+ .pickerStyle(.menu)
+ .tint(Ink.secondary)
+ }
+ }
+ SectionLabel(text: L("听对方"))
+ Card {
+ row(Text("翻译成")) {
+ Picker(selection: $target) {
+ Text("跟随系统").tag("system")
+ ForEach(targetLanguages, id: \.code) { Text(verbatim: $0.name).tag($0.code) }
+ } label: { Text("翻译成") }
+ .pickerStyle(.menu)
+ .tint(Ink.secondary)
+ }
+ Hairline()
+ row(Text("说话人识别")) {
+ Toggle(isOn: $voices) { Text("说话人识别") }
+ .labelsHidden()
+ .tint(Ink.ok)
+ }
+ }
+ SectionLabel(text: L("纪要"))
+ Card {
+ row(Text("纪要语言")) {
+ Picker(selection: $notesLanguage) {
+ Text(L("我的语言 · \(targetName(Pref.targetCode))")).tag("mine")
+ Text("会议原文").tag("source")
+ } label: { Text("纪要语言") }
+ .pickerStyle(.menu)
+ .tint(Ink.secondary)
+ }
+ }
+ Text(L("版本 \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "")"))
+ .font(.footnote).foregroundStyle(Ink.tertiary)
+ .frame(maxWidth: .infinity)
+ .padding(.top, 28)
+ }
+ .padding(.horizontal, 16)
+ .padding(.bottom, 120)
+ // On iPad a readable column, not the whole width.
+ .frame(maxWidth: 640)
+ .frame(maxWidth: .infinity)
+ }
+ .background(Ink.ground)
+ .toolbar(sheet ? .visible : .hidden, for: .navigationBar)
+ .navigationTitle(sheet ? Text("设置") : Text(""))
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ if sheet {
+ ToolbarItem(placement: .confirmationAction) { Button("完成") { dismiss() } }
+ }
+ }
+ }
+ .onChange(of: voices) { TranscriptExport.voices = voices; model.objectWillChange.send() }
+ .tint(Ink.ink)
+ }
+
+ private func row<V: View>(_ title: Text, @ViewBuilder value: () -> V) -> some View {
+ HStack(spacing: 8) {
+ title.foregroundStyle(Ink.ink)
+ Spacer()
+ value()
+ }
+ .font(.body)
+ .padding(.horizontal, 16)
+ .frame(minHeight: 50)
+ .contentShape(Rectangle())
+ }
+}
+
+/// "● 已连接" and the other key states, as on the Mac's AI 服务 page.
+struct KeyStatus: View {
+ let state: LingClient.KeyState
+
+ var body: some View {
+ HStack(spacing: 6) {
+ Circle().fill(color).frame(width: 7, height: 7)
+ Text(title).foregroundStyle(Ink.secondary)
+ }
+ }
+
+ private var color: Color {
+ switch state {
+ case .ok: Ink.ok
+ case .invalid, .unreachable: Color(red: 0.80, green: 0.20, blue: 0.16)
+ case .checking, .unchecked: Ink.accent
+ case .none: Color(white: 0.75)
+ }
+ }
+
+ var title: String {
+ switch state {
+ case .none: L("还没填 API key")
+ case .unchecked, .checking: L("正在检查…")
+ case .ok: L("已连接")
+ case .invalid: L("这个 key 用不了")
+ case .unreachable: L("暂时连不上")
+ }
+ }
+}
+
+/// Paste or type the key; it is checked with one tiny request and kept only in the app's file.
+struct KeyPage: View {
+ @EnvironmentObject var ling: LingClient
+ @AppStorage(Pref.model) private var aiModel = LingClient.models[0]
+ @State private var draft = ""
+ @State private var editing = false
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 0) {
+ Card {
+ VStack(alignment: .leading, spacing: 6) {
+ KeyStatus(state: ling.keyState).font(.body.weight(.semibold))
+ if let detail { Text(detail).font(.footnote).foregroundStyle(Ink.secondary) }
+ }
+ .padding(16)
+ Hairline()
+ if let key = ling.key, !editing {
+ HStack {
+ Text(verbatim: AIKey.masked(key)).font(.body.monospaced()).foregroundStyle(Ink.ink)
+ Spacer()
+ Button("更换") { draft = ""; editing = true }
+ }
+ .padding(.horizontal, 16).frame(minHeight: 50)
+ } else {
+ SecureField(text: $draft) { Text(verbatim: "sk-…") }
+ .font(.body.monospaced())
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ .submitLabel(.done)
+ .onSubmit(save)
+ .padding(.horizontal, 16).frame(minHeight: 50)
+ }
+ }
+ .padding(.top, 12)
+
+ if ling.key == nil || editing {
+ HStack(spacing: 10) {
+ Button { draft = UIPasteboard.general.string ?? ""; save() } label: {
+ Text("粘贴并检查").font(.headline).foregroundStyle(.white)
+ .frame(maxWidth: .infinity, minHeight: 50)
+ .background(Ink.ink, in: Capsule())
+ }
+ .buttonStyle(.plain)
+ if !draft.isEmpty {
+ Button("保存并检查", action: save).font(.headline)
+ }
+ }
+ .padding(.top, 16)
+ Text("在 Ling 开放平台点“创建令牌”,复制以 sk- 开头的那串。")
+ .font(.footnote).foregroundStyle(Ink.secondary)
+ .padding(.horizontal, 4).padding(.top, 12)
+ Link("打开 Ling 开放平台 ↗", destination: URL(string: "https://chat.ant-ling.com/platform/api")!)
+ .font(.footnote.weight(.semibold))
+ .padding(.horizontal, 4).padding(.top, 8)
+ }
+ if ling.key != nil && !editing {
+ HStack {
+ if case .unreachable = ling.keyState { Button("重试") { Task { await ling.check() } } }
+ Spacer()
+ Button("移除", role: .destructive) { ling.removeKey() }
+ }
+ .font(.subheadline)
+ .padding(.horizontal, 4).padding(.top, 14)
+ }
+ }
+ .padding(.horizontal, 16)
+ .frame(maxWidth: 640)
+ .frame(maxWidth: .infinity)
+ }
+ .background(Ink.ground)
+ .navigationTitle(Text(verbatim: "Ling key"))
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ private var detail: String? {
+ switch ling.keyState {
+ case .ok(let s): L("\(aiModel) · 响应约 \(String(format: "%.1f", s)) 秒")
+ case .invalid: L("Ling 提示此令牌无效,请检查是否复制完整,或重新创建一个")
+ case .unreachable(let why): why
+ case .none: L("不填 key 时,字幕和翻译仍可正常使用")
+ default: nil
+ }
+ }
+
+ private func save() {
+ let k = draft.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !k.isEmpty else { return }
+ draft = ""
+ editing = false
+ Task { await ling.setKey(k) }
+ }
+}
diff --git a/ios/Sources/Cicada/SpeakerRail.swift b/ios/Sources/Cicada/SpeakerRail.swift
new file mode 100644
index 0000000..aad35cb
--- /dev/null
+++ b/ios/Sources/Cicada/SpeakerRail.swift
@@ -0,0 +1,129 @@
+import SwiftUI
+
+/// Scheme A of the speaker colours (the design page 说话人配色): everyone's stretch of the meeting
+/// is the same light grey, so a strip shows how many turns and how long; only the person you are
+/// looking for, picked on a chip or the one the recording is at, is drawn in ink. Names stay ink
+/// or grey text. The accent keeps meaning "live" and the playhead.
+enum SpeakerRail {
+ static let rest = Color(hex: 0xD5D8DE)
+ static let focus = Ink.ink
+
+ /// One person's unbroken stretch: consecutive lines of the same voice are one run.
+ struct Run: Equatable {
+ var number: Int?
+ var start: Double
+ var length: Double
+ }
+
+ /// The meeting as runs, by its lines' times (a line lasts until the next one starts).
+ static func runs(_ s: Session, numbers: [String: Int]) -> [Run] {
+ let lines = s.lines
+ guard !lines.isEmpty else { return [] }
+ let end = max(s.duration, (lines.last?.t ?? 0) + 3)
+ var out: [Run] = []
+ for (i, l) in lines.enumerated() {
+ let next = i + 1 < lines.count ? lines[i + 1].t : end
+ let n = numbers[l.id]
+ let len = max(0.5, next - l.t)
+ if var lastRun = out.last, lastRun.number == n {
+ lastRun.length = next - lastRun.start
+ out[out.count - 1] = lastRun
+ } else {
+ out.append(Run(number: n, start: l.t, length: len))
+ }
+ }
+ return out
+ }
+
+ /// What a strip can draw: a turn under `minShare` of the meeting joins the one before it (a
+ /// strip beside a row is a few dozen points tall), and neighbours of the same person merge.
+ static func compact(_ runs: [Run], minShare: Double) -> [Run] {
+ let total = runs.reduce(0) { $0 + $1.length }
+ guard total > 0 else { return runs }
+ var out: [Run] = []
+ for r in runs {
+ if var prev = out.last, prev.number == r.number || r.length < total * minShare {
+ prev.length += r.length
+ out[out.count - 1] = prev
+ } else if out.isEmpty || r.length >= total * minShare {
+ out.append(r)
+ }
+ }
+ // A short first turn swallowed nothing before it: fold it into the next.
+ if out.count > 1, out[0].length < total * minShare {
+ out[1].start = out[0].start
+ out[1].length += out[0].length
+ out.removeFirst()
+ }
+ var merged: [Run] = []
+ for r in out {
+ if var prev = merged.last, prev.number == r.number { prev.length += r.length; merged[merged.count - 1] = prev } else { merged.append(r) }
+ }
+ return merged
+ }
+
+ /// Each speaker number's share of the time (0–1).
+ static func shares(_ runs: [Run]) -> [Int: Double] {
+ let total = runs.reduce(0) { $0 + $1.length }
+ guard total > 0 else { return [:] }
+ var out: [Int: Double] = [:]
+ for r in runs { if let n = r.number { out[n, default: 0] += r.length / total } }
+ return out
+ }
+}
+
+/// The strip: across under a meeting's title, or upright beside a row.
+struct RailView: View {
+ enum Axis { case across, upright }
+ let runs: [SpeakerRail.Run]
+ var focus: Int? = nil
+ var axis: Axis = .across
+ var thickness: CGFloat = 8
+
+ var body: some View {
+ GeometryReader { g in
+ let length = axis == .across ? g.size.width : g.size.height
+ let runs = SpeakerRail.compact(self.runs, minShare: axis == .across ? 0.01 : 0.08)
+ let total = max(0.001, runs.reduce(0) { $0 + $1.length })
+ // Too many turns for the room: no gaps, rather than a dotted line.
+ let gap: CGFloat = CGFloat(runs.count) > length / 5 ? 0 : 2
+ let room = length - gap * CGFloat(max(0, runs.count - 1))
+ let layout = axis == .across ? AnyLayout(HStackLayout(spacing: gap)) : AnyLayout(VStackLayout(spacing: gap))
+ layout {
+ ForEach(Array(runs.enumerated()), id: \.offset) { _, r in
+ let size = max(1, room * r.length / total)
+ RoundedRectangle(cornerRadius: min(3, thickness / 2), style: .continuous)
+ .fill(focus != nil && r.number == focus ? SpeakerRail.focus : SpeakerRail.rest)
+ .frame(width: axis == .across ? size : thickness, height: axis == .across ? thickness : size)
+ }
+ }
+ }
+ .frame(width: axis == .upright ? thickness : nil, height: axis == .across ? thickness : nil)
+ .clipShape(RoundedRectangle(cornerRadius: min(3, thickness / 2), style: .continuous))
+ .animation(.easeOut(duration: 0.18), value: focus)
+ .accessibilityHidden(true)
+ }
+}
+
+/// The record page's strip with the playhead: an accent mark where the recording is.
+struct MeetingRail: View {
+ let runs: [SpeakerRail.Run]
+ let focus: Int?
+ /// 0–1, nil before playing.
+ let playhead: Double?
+
+ var body: some View {
+ RailView(runs: runs, focus: focus, thickness: 10)
+ .overlay(alignment: .leading) {
+ if let p = playhead {
+ GeometryReader { g in
+ Capsule().fill(Ink.accent)
+ .frame(width: 3, height: 18)
+ .overlay(Capsule().stroke(.white, lineWidth: 2))
+ .offset(x: g.size.width * min(1, max(0, p)) - 1.5, y: -4)
+ }
+ }
+ }
+ .frame(height: 10)
+ }
+}
diff --git a/ios/Sources/Cicada/Theme.swift b/ios/Sources/Cicada/Theme.swift
new file mode 100644
index 0000000..1f75d7a
--- /dev/null
+++ b/ios/Sources/Cicada/Theme.swift
@@ -0,0 +1,38 @@
+import SwiftUI
+
+/// The Mac's colours (AGENTS.md › Design): grey ground, white cards, one accent for "live".
+enum Ink {
+ static let ground = Color(red: 0xF3 / 255, green: 0xF4 / 255, blue: 0xF6 / 255)
+ static let ink = Color(red: 0x15 / 255, green: 0x17 / 255, blue: 0x1C / 255)
+ static let accent = Color(red: 0xE8 / 255, green: 0x55 / 255, blue: 0x2B / 255)
+ /// The accent as text on white: ≥ 4.5:1, the plain accent is not.
+ static let accentText = Color(red: 0xC8 / 255, green: 0x43 / 255, blue: 0x1D / 255)
+ static let secondary = Color(red: 0x5A / 255, green: 0x5F / 255, blue: 0x6B / 255)
+ static let tertiary = Color(red: 0x6B / 255, green: 0x70 / 255, blue: 0x80 / 255)
+ /// Hairlines between rows.
+ static let line = Color(red: 0xE2 / 255, green: 0xE4 / 255, blue: 0xE9 / 255)
+ /// The selected tab's pill: the accent, faint.
+ static let accentWash = Color(red: 0xE8 / 255, green: 0x55 / 255, blue: 0x2B / 255).opacity(0.12)
+ /// 已连接.
+ static let ok = Color(red: 0x2F / 255, green: 0x9E / 255, blue: 0x5B / 255)
+ /// Numbers that order the notes: the Mac's `Palette.link`, the logo's orange as ink.
+ static let link = Color(red: 0.70, green: 0.23, blue: 0.08)
+}
+
+/// 说话人 1, 2, 3…: the design canvas's chips (blue, orange…), each a pale fill with a dark ink of the
+/// same hue that passes 4.5:1 on it and on white. The Mac's `SpeakerColor` uses other hues.
+enum SpeakerInk {
+ private static let pairs: [(ink: UInt32, tint: UInt32)] = [
+ (0x1F4E8C, 0xDCE7F7), (0x8A3A16, 0xF6E2D6), (0x1E6B45, 0xDDEFE4), (0x5B3A8C, 0xE9E1F5), (0x3F434C, 0xE7E9EE),
+ ]
+ private static func pair(_ number: Int) -> (ink: UInt32, tint: UInt32) { pairs[(max(1, number) - 1) % pairs.count] }
+ static func ink(_ number: Int) -> Color { Color(hex: pair(number).ink) }
+ /// The chip behind a speaker's name.
+ static func tint(_ number: Int) -> Color { Color(hex: pair(number).tint) }
+}
+
+extension Color {
+ init(hex: UInt32) {
+ self.init(red: Double(hex >> 16 & 0xFF) / 255, green: Double(hex >> 8 & 0xFF) / 255, blue: Double(hex & 0xFF) / 255)
+ }
+}
diff --git a/ios/scripts/build.sh b/ios/scripts/build.sh
new file mode 100755
index 0000000..c98dc9c
--- /dev/null
+++ b/ios/scripts/build.sh
@@ -0,0 +1,73 @@
+#!/usr/bin/env bash
+# Builds ios/build/Cicada.app for the iOS simulator: the shared Mac sources (ios/shared-sources.txt)
+# and ios/Sources in one module, bundled by hand like the Mac's scripts/build.sh (no .xcodeproj).
+# Without RELEASE=1 it is a dev build: "Cicada Dev", bundle id com.wquguru.cicada.dev, cicada-dev:// commands.
+set -euo pipefail
+cd "$(dirname "$0")/../.."
+
+SDK=iphonesimulator
+TARGET=arm64-apple-ios26.0-simulator
+APP=ios/build/Cicada.app
+rm -rf "$APP"
+mkdir -p "$APP"
+
+files=()
+while IFS= read -r line; do [[ -z $line || $line == \#* ]] || files+=("$line"); done < ios/shared-sources.txt
+while IFS= read -r f; do files+=("$f"); done < <(find ios/Sources -name '*.swift' | sort)
+
+# STRINGS_OUT=<dir>: also write the UI text keys there (scripts/strings.py).
+extra=()
+[[ -n "${STRINGS_OUT:-}" ]] && extra=(-emit-localized-strings -emit-localized-strings-path "$STRINGS_OUT")
+xcrun --sdk "$SDK" swiftc -O -swift-version 5 -parse-as-library -module-name Cicada \
+ -target "$TARGET" -sdk "$(xcrun --show-sdk-path --sdk "$SDK")" -D CICADA_IOS \
+ "${extra[@]+"${extra[@]}"}" "${files[@]}" -o "$APP/Cicada"
+
+cp ios/Resources/Info.plist "$APP/Info.plist"
+# UI text is the Mac's: the Chinese source is the key, the other languages translate it.
+for d in Resources/*.lproj; do
+ mkdir -p "$APP/$(basename "$d")"
+ cp "$d/Localizable.strings" "$APP/$(basename "$d")/" 2>/dev/null || true
+done
+cp -R "$APP/zh-Hans.lproj" "$APP/zh-Hant.lproj"
+cp Resources/sample/sample.m4a "$APP/"
+# 说话人识别's voiceprint model, compiled on first use as on the Mac (SpeakerID.swift).
+cp -R Resources/models/SpeakerEmbedding.mlpackage "$APP/"
+# The logo on the 听会议室 card: the Mac's own icon renderer (Sources/LiveSubsIcon), not a fourth
+# copy of the geometry. It is a host tool, built once.
+ICON_TOOL=.build/release/LiveSubsIcon
+[[ -x $ICON_TOOL ]] || swift build -c release --product LiveSubsIcon >/dev/null
+ICONS=$(mktemp -d)
+"$ICON_TOOL" "$ICONS/logo.iconset" >/dev/null
+cp "$ICONS/logo.iconset/[email protected]" "$APP/logo.png"
+rm -rf "$ICONS"
+
+# The Live Activity (lock screen, Dynamic Island): a WidgetKit extension in PlugIns. The attributes
+# type is compiled into both, so the app and the extension agree on it. Linked like Xcode links an
+# app extension: entered through _NSExtensionMain, which runs the @main WidgetBundle on the main
+# queue (the plain Swift entry point dies in libdispatch before the bundle loads).
+APPEX="$APP/PlugIns/CicadaLive.appex"
+mkdir -p "$APPEX"
+xcrun --sdk "$SDK" swiftc -O -swift-version 5 -parse-as-library -application-extension -module-name CicadaLive \
+ -target "$TARGET" -sdk "$(xcrun --show-sdk-path --sdk "$SDK")" \
+ -Xlinker -e -Xlinker _NSExtensionMain \
+ ios/LiveActivity/*.swift ios/Sources/Cicada/ListenActivity.swift -o "$APPEX/CicadaLive"
+cp ios/LiveActivity/Info.plist "$APPEX/Info.plist"
+cp "$APP/logo.png" "$APPEX/"
+for d in "$APP"/*.lproj; do cp -R "$d" "$APPEX/"; done
+
+PLIST="$APP/Info.plist"
+/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $(tr -d '[:space:]' < VERSION)" "$PLIST"
+if [[ "${RELEASE:-}" != 1 ]]; then
+ STAMP="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo local) @ $(git rev-parse --short HEAD 2>/dev/null || echo none)"
+ /usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier com.wquguru.cicada.dev" \
+ -c "Set :CFBundleName Cicada Dev" -c "Set :CFBundleDisplayName Cicada Dev" \
+ -c "Add :LiveSubsDev string $STAMP" \
+ -c "Add :CFBundleURLTypes array" -c "Add :CFBundleURLTypes:0 dict" \
+ -c "Add :CFBundleURLTypes:0:CFBundleURLSchemes array" -c "Add :CFBundleURLTypes:0:CFBundleURLSchemes:0 string cicada-dev" \
+ "$PLIST"
+ /usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier com.wquguru.cicada.dev.live" "$APPEX/Info.plist"
+fi
+/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $(tr -d '[:space:]' < VERSION)" "$APPEX/Info.plist"
+codesign --force --sign - "$APPEX" 2>/dev/null
+codesign --force --sign - "$APP" 2>/dev/null
+echo "Built $APP ($(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$PLIST"))"
diff --git a/ios/scripts/ctl.sh b/ios/scripts/ctl.sh
new file mode 100755
index 0000000..46c14d0
--- /dev/null
+++ b/ios/scripts/ctl.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Sends debug commands to the dev build in a simulator (ios/Sources/Cicada/Debug.swift), the iOS
+# counterpart of tools/lsctl: ios/scripts/ctl.sh [-d "<device>"] <cmd> [<cmd>...]
+set -euo pipefail
+DEVICE=booted
+if [[ ${1:-} == -d ]]; then DEVICE=$2; shift 2; fi
+DATA=$(xcrun simctl get_app_container "$DEVICE" com.wquguru.cicada.dev data)
+printf '%s\n' "$@" >> "$DATA/Library/Caches/debug-command"
+xcrun simctl spawn "$DEVICE" notifyutil -p com.wquguru.cicada.debug
diff --git a/ios/scripts/run.sh b/ios/scripts/run.sh
new file mode 100755
index 0000000..ebfb9b0
--- /dev/null
+++ b/ios/scripts/run.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+# Installs ios/build/Cicada.app into a simulator and launches it.
+# ios/scripts/run.sh [device name] [--seed <session folder>...]
+# --seed copies Mac meeting folders (…/LiveSubs Dev/Sessions/<id>) into the app first.
+# Then drive it: xcrun simctl openurl "<device>" 'cicada-dev://debug?cmd=…' (commands: ios/Sources/Cicada/Debug.swift).
+set -euo pipefail
+cd "$(dirname "$0")/../.."
+DEVICE=${1:-"iPhone 18 Pro"}; shift || true
+ID=com.wquguru.cicada.dev
+
+xcrun simctl boot "$DEVICE" 2>/dev/null || true
+xcrun simctl bootstatus "$DEVICE" -b >/dev/null
+xcrun simctl terminate "$DEVICE" "$ID" 2>/dev/null || true
+xcrun simctl install "$DEVICE" ios/build/Cicada.app
+if [[ "${1:-}" == --seed ]]; then
+ shift
+ DATA=$(xcrun simctl get_app_container "$DEVICE" "$ID" data)
+ mkdir -p "$DATA/Library/Application Support/LiveSubs Dev/Sessions"
+ for s in "$@"; do cp -R "$s" "$DATA/Library/Application Support/LiveSubs Dev/Sessions/"; done
+fi
+xcrun simctl launch "$DEVICE" "$ID" >/dev/null
+echo "Running on $DEVICE; log: $(xcrun simctl get_app_container "$DEVICE" "$ID" data)/Library/Caches/livesubs-dev-debug.log"
diff --git a/ios/scripts/typecheck.sh b/ios/scripts/typecheck.sh
new file mode 100755
index 0000000..df23b55
--- /dev/null
+++ b/ios/scripts/typecheck.sh
@@ -0,0 +1,18 @@
+#!/usr/bin/env bash
+# Typechecks the Mac sources the iOS app shares (ios/shared-sources.txt) together with ios/Sources.
+# Without Xcode only the macOS SDK is there: SDK=macosx proves the shared set is self-contained and
+# AppKit-free, not that every API exists on iOS. With Xcode, the default checks against the simulator SDK.
+set -euo pipefail
+cd "$(dirname "$0")/../.."
+SDK=${SDK:-iphonesimulator}
+if [[ $SDK == iphonesimulator ]]; then TARGET=(-target arm64-apple-ios26.0-simulator); else TARGET=(-target arm64-apple-macos26.0); fi
+files=()
+while IFS= read -r line; do [[ -z $line || $line == \#* ]] || files+=("$line"); done < ios/shared-sources.txt
+shared=("${files[@]}")
+while IFS= read -r f; do files+=("$f"); done < <(find ios/Sources -name '*.swift' | sort)
+# Frameworks iOS doesn't have: the macOS SDK would accept them, so catch them here.
+bad=$(awk '/^#if (os\(macOS\)|canImport\(AppKit\)|!CICADA_IOS)/{g=1} /^#endif/{g=0} !g && /^import (AppKit|CoreAudio|Carbon|SwiftUI|ServiceManagement|IOKit)$/{print FILENAME": "$0}' "${shared[@]}")
+if [[ -n $bad ]]; then echo "Mac-only imports in shared sources:"; echo "$bad"; exit 1; fi
+xcrun swiftc -typecheck -swift-version 5 -module-name Cicada -sdk "$(xcrun --show-sdk-path --sdk "$SDK")" "${TARGET[@]}" \
+ -D CICADA_IOS "${files[@]}"
+echo "typecheck ok ($SDK, ${#files[@]} files)"
diff --git a/ios/shared-sources.txt b/ios/shared-sources.txt
new file mode 100644
index 0000000..c6eba11
--- /dev/null
+++ b/ios/shared-sources.txt
@@ -0,0 +1,18 @@
+# Mac sources compiled into the iOS app as they are (one module, so no `public`).
+# Keep these free of AppKit and of Mac-only APIs. Guard what needs AppKit with #if os(macOS), and what
+# needs the rest of the Mac app with #if !CICADA_IOS (the iOS build sets it). ios/scripts/typecheck.sh checks.
+Sources/LiveSubs/Ling.swift
+Sources/LiveSubs/AIProviders.swift
+Sources/LiveSubs/Notes.swift
+Sources/LiveSubs/HeardText.swift
+Sources/LiveSubs/MeetingEnd.swift
+Sources/LiveSubs/Localization.swift
+Sources/LiveSubs/Voices.swift
+Sources/LiveSubs/SessionStore.swift
+Sources/LiveSubs/SpeakerID.swift
+Sources/LiveSubs/AudioFiles.swift
+Sources/LiveSubs/Translator.swift
+Sources/LiveSubs/Diagnostics.swift
+Sources/LiveSubs/RecordList.swift
+Sources/LiveSubs/Languages.swift
+Sources/LiveSubs/Recognition.swift
diff --git a/scripts/strings.py b/scripts/strings.py
index 7758468..8276444 100755
--- a/scripts/strings.py
+++ b/scripts/strings.py
@@ -30,8 +30,15 @@ def code_keys():
subprocess.run(["swift", "build", "--product", "LiveSubs", "-Xswiftc", "-emit-localized-strings",
"-Xswiftc", "-emit-localized-strings-path", "-Xswiftc", out],
cwd=ROOT, check=True, stdout=subprocess.DEVNULL)
+ # The iOS app's text shares the same tables (ios/AGENTS.md); it needs Xcode's iOS SDK.
+ if subprocess.run(["xcrun", "--sdk", "iphonesimulator", "--show-sdk-path"], capture_output=True).returncode == 0:
+ subprocess.run([os.path.join(ROOT, "ios/scripts/build.sh")], cwd=ROOT, check=True, stdout=subprocess.DEVNULL,
+ env={**os.environ, "STRINGS_OUT": os.path.join(out, "ios")})
+ else:
+ print("ios: no iOS SDK (needs Xcode), its strings are not checked")
keys = {}
- for f in sorted(glob.glob(os.path.join(out, "*.stringsdata"))):
+ # The shared files are in both builds: iOS writes into its own folder, not over the Mac's.
+ for f in sorted(glob.glob(os.path.join(out, "*.stringsdata")) + glob.glob(os.path.join(out, "ios", "*.stringsdata"))):
for entries in json.load(open(f))["tables"].values():
for e in entries:
if CJK.search(e["key"]): # "%@ · %@" and the like need no translation