diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 7ff828f..431e489 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -216,6 +216,1326 @@ pub fn trf(key: &'static str, args: &[(&str, &dyn Display)]) -> String { // [English, Русский, Français, Deutsch, Español, Italiano, Português (BR), O‘zbekcha, Қазақша] // Uzbek o‘ and g‘ are written with ‘ (U+2018): the interface font has no U+02BB. const ROWS: &[[&str; 9]] = &[ + [ + "Learned", + "Выучено", + "Appris", + "Gelernt", + "Aprendidas", + "Imparate", + "Aprendidas", + "O‘rganildi", + "Үйренілді", + ], + [ + "You play White", + "Вы играете белыми", + "Vous jouez les Blancs", + "Sie spielen Weiß", + "Juegas con blancas", + "Giochi con il Bianco", + "Você joga de brancas", + "Siz oq bilan o‘ynaysiz", + "Сіз ақпен ойнайсыз", + ], + [ + "You play Black", + "Вы играете чёрными", + "Vous jouez les Noirs", + "Sie spielen Schwarz", + "Juegas con negras", + "Giochi con il Nero", + "Você joga de pretas", + "Siz qora bilan o‘ynaysiz", + "Сіз қарамен ойнайсыз", + ], + [ + "Correct!", + "Верно", + "Exact !", + "Richtig!", + "¡Correcto!", + "Esatto!", + "Correto!", + "To‘g‘ri!", + "Дұрыс!", + ], + [ + "tomorrow", + "завтра", + "demain", + "morgen", + "mañana", + "domani", + "amanhã", + "ertaga", + "ертең", + ], + [ + "today at {time}", + "сегодня в {time}", + "aujourd’hui à {time}", + "heute um {time}", + "hoy a las {time}", + "oggi alle {time}", + "hoje às {time}", + "bugun soat {time} da", + "бүгін {time}", + ], + [ + "in {days} days", + "через {days} дн.", + "dans {days} jours", + "in {days} Tagen", + "en {days} días", + "tra {days} giorni", + "em {days} dias", + "{days} kundan keyin", + "{days} күннен кейін", + ], + [ + "Not trained", + "Не тренируется", + "Pas entraînée", + "Wird nicht trainiert", + "No se entrena", + "Non allenata", + "Não treinada", + "Mashq qilinmaydi", + "Жаттықтырылмайды", + ], + [ + "Counting moves…", + "Считаем ходы…", + "Comptage des coups…", + "Züge werden gezählt…", + "Contando jugadas…", + "Conteggio delle mosse…", + "Contando lances…", + "Yurishlar sanalmoqda…", + "Жүрістер саналуда…", + ], + [ + "Review all lines", + "Повторить всё подряд", + "Réviser toutes les lignes", + "Alle Varianten wiederholen", + "Repasar todas las líneas", + "Ripassa tutte le linee", + "Revisar todas as linhas", + "Barcha variantlarni takrorlash", + "Барлық нұсқаны қайталау", + ], + [ + "Train this branch", + "Тренировать эту ветку", + "Entraîner cette branche", + "Diesen Zweig trainieren", + "Entrenar esta rama", + "Allena questo ramo", + "Treinar este ramo", + "Shu shoxni mashq qilish", + "Осы тармақты жаттықтыру", + ], + [ + "Train again", + "Снова тренировать", + "Entraîner à nouveau", + "Wieder trainieren", + "Volver a entrenar", + "Allena di nuovo", + "Treinar de novo", + "Yana mashq qilish", + "Қайта жаттықтыру", + ], + [ + "Don't train", + "Не тренировать", + "Ne pas entraîner", + "Nicht trainieren", + "No entrenar", + "Non allenare", + "Não treinar", + "Mashq qilmaslik", + "Жаттықтырмау", + ], + [ + "⬅ Repertoires", + "⬅ Репертуары", + "⬅ Répertoires", + "⬅ Repertoires", + "⬅ Repertorios", + "⬅ Repertori", + "⬅ Repertórios", + "⬅ Repertuarlar", + "⬅ Репертуарлар", + ], + [ + "⬅ Lines", + "⬅ Варианты", + "⬅ Lignes", + "⬅ Varianten", + "⬅ Líneas", + "⬅ Linee", + "⬅ Linhas", + "⬅ Variantlar", + "⬅ Нұсқалар", + ], + [ + "⬅ To game", + "⬅ К партии", + "⬅ À la partie", + "⬅ Zur Partie", + "⬅ A la partida", + "⬅ Alla partita", + "⬅ Para a partida", + "⬅ Partiyaga", + "⬅ Партияға", + ], + [ + "Below: {n} lines · {y} your moves · learned {x}", + "Дальше: вариантов {n} · ваших ходов {y} · выучено {x}", + "En dessous : {n} lignes · {y} de vos coups · {x} appris", + "Darunter: {n} Varianten · {y} eigene Züge · {x} gelernt", + "Debajo: {n} líneas · {y} jugadas tuyas · {x} aprendidas", + "Sotto: {n} linee · {y} tue mosse · {x} imparate", + "Abaixo: {n} linhas · {y} lances seus · {x} aprendidos", + "Keyin: {n} ta variant · sizning {y} ta yurishingiz · {x} tasi o‘rganilgan", + "Әрі қарай: {n} нұсқа · сіздің {y} жүрісіңіз · {x} үйренілді", + ], + [ + "Lines · {n} lines · {y} your moves", + "Варианты · вариантов: {n} · ваших ходов: {y}", + "Lignes · {n} lignes · {y} de vos coups", + "Varianten · {n} Varianten · {y} eigene Züge", + "Líneas · {n} líneas · {y} jugadas tuyas", + "Linee · {n} linee · {y} tue mosse", + "Linhas · {n} linhas · {y} lances seus", + "Variantlar · {n} ta variant · sizning {y} ta yurishingiz", + "Нұсқалар · {n} нұсқа · сіздің {y} жүрісіңіз", + ], + [ + "Training · you play White", + "Тренировка · вы играете белыми", + "Entraînement · vous jouez les Blancs", + "Training · Sie spielen Weiß", + "Entrenamiento · juegas con blancas", + "Allenamento · giochi con il Bianco", + "Treino · você joga de brancas", + "Mashq · siz oq bilan o‘ynaysiz", + "Жаттығу · сіз ақпен ойнайсыз", + ], + [ + "Training · you play Black", + "Тренировка · вы играете чёрными", + "Entraînement · vous jouez les Noirs", + "Training · Sie spielen Schwarz", + "Entrenamiento · juegas con negras", + "Allenamento · giochi con il Nero", + "Treino · você joga de pretas", + "Mashq · siz qora bilan o‘ynaysiz", + "Жаттығу · сіз қарамен ойнайсыз", + ], + [ + "Review all lines · you play White", + "Повторение подряд · вы играете белыми", + "Révision de toutes les lignes · vous jouez les Blancs", + "Alle Varianten · Sie spielen Weiß", + "Repaso de todas las líneas · juegas con blancas", + "Ripasso di tutte le linee · giochi con il Bianco", + "Revisão de todas as linhas · você joga de brancas", + "Barchasini takrorlash · siz oq bilan o‘ynaysiz", + "Бәрін қайталау · сіз ақпен ойнайсыз", + ], + [ + "Review all lines · you play Black", + "Повторение подряд · вы играете чёрными", + "Révision de toutes les lignes · vous jouez les Noirs", + "Alle Varianten · Sie spielen Schwarz", + "Repaso de todas las líneas · juegas con negras", + "Ripasso di tutte le linee · giochi con il Nero", + "Revisão de todas as linhas · você joga de pretas", + "Barchasini takrorlash · siz qora bilan o‘ynaysiz", + "Бәрін қайталау · сіз қарамен ойнайсыз", + ], + [ + "Watch", + "Смотрите", + "Regardez", + "Zuschauen", + "Observa", + "Guarda", + "Observe", + "Kuzating", + "Қараңыз", + ], + [ + "Moves up to your next question", + "Ходы до вашего следующего вопроса", + "Les coups jusqu’à votre prochaine question", + "Die Züge bis zu Ihrer nächsten Frage", + "Las jugadas hasta tu próxima pregunta", + "Le mosse fino alla prossima domanda", + "Os lances até a sua próxima pergunta", + "Keyingi savolingizgacha bo‘lgan yurishlar", + "Келесі сұрағыңызға дейінгі жүрістер", + ], + [ + "Next line", + "Следующий вариант", + "Ligne suivante", + "Nächste Variante", + "Siguiente línea", + "Linea successiva", + "Próxima linha", + "Keyingi variant", + "Келесі нұсқа", + ], + [ + "New move", + "Новый ход", + "Nouveau coup", + "Neuer Zug", + "Jugada nueva", + "Mossa nuova", + "Lance novo", + "Yangi yurish", + "Жаңа жүріс", + ], + [ + "Your move", + "Ваш ход", + "À vous", + "Ihr Zug", + "Tu jugada", + "Tocca a te", + "Sua vez", + "Sizning yurishingiz", + "Сіздің жүрісіңіз", + ], + [ + "Play the move from your repertoire", + "Сыграйте ход из репертуара", + "Jouez le coup de votre répertoire", + "Spielen Sie den Zug Ihres Repertoires", + "Juega la jugada de tu repertorio", + "Gioca la mossa del tuo repertorio", + "Jogue o lance do seu repertório", + "Repertuaringizdagi yurishni qiling", + "Репертуарыңыздағы жүрісті жасаңыз", + ], + [ + "Not this move", + "Не тот ход", + "Pas ce coup", + "Nicht dieser Zug", + "No es esta jugada", + "Non è questa mossa", + "Não é este lance", + "Bu yurish emas", + "Бұл жүріс емес", + ], + [ + "This one is in your repertoire too", + "Этот ход тоже есть в репертуаре", + "Ce coup est aussi dans votre répertoire", + "Auch dieser Zug ist in Ihrem Repertoire", + "Esta jugada también está en tu repertorio", + "Anche questa mossa è nel tuo repertorio", + "Este lance também está no seu repertório", + "Bu yurish ham repertuaringizda bor", + "Бұл жүріс те репертуарыңызда бар", + ], + [ + "Got it", + "Запомним", + "Noté", + "Gemerkt", + "Anotado", + "Ricevuto", + "Anotado", + "Eslab qolamiz", + "Есте сақтаймыз", + ], + [ + "Could not save your answer", + "Не удалось сохранить ответ", + "Impossible d’enregistrer votre réponse", + "Ihre Antwort konnte nicht gespeichert werden", + "No se pudo guardar tu respuesta", + "Impossibile salvare la risposta", + "Não foi possível salvar sua resposta", + "Javobingizni saqlab bo‘lmadi", + "Жауабыңызды сақтау мүмкін болмады", + ], + [ + "Could not continue the session", + "Не удалось продолжить занятие", + "Impossible de poursuivre la séance", + "Die Übung konnte nicht fortgesetzt werden", + "No se pudo continuar la sesión", + "Impossibile continuare la sessione", + "Não foi possível continuar a sessão", + "Mashg‘ulotni davom ettirib bo‘lmadi", + "Сабақты жалғастыру мүмкін болмады", + ], + [ + "Session stopped", + "Занятие прервано", + "Séance interrompue", + "Übung abgebrochen", + "Sesión interrumpida", + "Sessione interrotta", + "Sessão interrompida", + "Mashg‘ulot to‘xtatildi", + "Сабақ үзілді", + ], + [ + "Session complete", + "Занятие окончено", + "Séance terminée", + "Übung beendet", + "Sesión terminada", + "Sessione completata", + "Sessão concluída", + "Mashg‘ulot tugadi", + "Сабақ аяқталды", + ], + [ + "Everything is saved", + "Всё сохранено", + "Tout est enregistré", + "Alles ist gespeichert", + "Todo está guardado", + "Tutto è salvato", + "Tudo está salvo", + "Hammasi saqlandi", + "Бәрі сақталды", + ], + [ + "left", + "осталось", + "restants", + "übrig", + "quedan", + "rimaste", + "restantes", + "qoldi", + "қалды", + ], + [ + "line", + "вариант", + "ligne", + "Variante", + "línea", + "linea", + "linha", + "variant", + "нұсқа", + ], + [ + "Lines reviewed", + "Пройдено вариантов", + "Lignes révisées", + "Wiederholte Varianten", + "Líneas repasadas", + "Linee ripassate", + "Linhas revisadas", + "Takrorlangan variantlar", + "Қайталанған нұсқалар", + ], + [ + "Correct first time", + "Верно с первого раза", + "Justes du premier coup", + "Beim ersten Mal richtig", + "Correctas a la primera", + "Giuste al primo colpo", + "Certos de primeira", + "Birinchi urinishda to‘g‘ri", + "Бірінші реттен дұрыс", + ], + [ + "New moves learned", + "Новых ходов", + "Nouveaux coups appris", + "Neue Züge gelernt", + "Jugadas nuevas aprendidas", + "Mosse nuove imparate", + "Lances novos aprendidos", + "Yangi yurishlar", + "Жаңа жүрістер", + ], + [ + "Moves to remember", + "Что запомнить", + "Coups à retenir", + "Züge zum Merken", + "Jugadas que recordar", + "Mosse da ricordare", + "Lances para lembrar", + "Eslab qolinadigan yurishlar", + "Есте сақтайтын жүрістер", + ], + [ + "10 more new (N)", + "Ещё 10 новых (N)", + "10 nouveaux de plus (N)", + "10 weitere neue (N)", + "10 nuevas más (N)", + "Altre 10 nuove (N)", + "Mais 10 novos (N)", + "Yana 10 ta yangi (N)", + "Тағы 10 жаңа (N)", + ], + [ + "{n} more new (N)", + "Ещё {n} новых (N)", + "{n} nouveaux de plus (N)", + "{n} weitere neue (N)", + "{n} nuevas más (N)", + "Altre {n} nuove (N)", + "Mais {n} novos (N)", + "Yana {n} ta yangi (N)", + "Тағы {n} жаңа (N)", + ], + [ + "To lines (Enter)", + "К вариантам (Enter)", + "Aux lignes (Entrée)", + "Zu den Varianten (Enter)", + "A las líneas (Intro)", + "Alle linee (Invio)", + "Para as linhas (Enter)", + "Variantlarga (Enter)", + "Нұсқаларға (Enter)", + ], + [ + "To repertoires (Enter)", + "К репертуарам (Enter)", + "Aux répertoires (Entrée)", + "Zu den Repertoires (Enter)", + "A los repertorios (Intro)", + "Ai repertori (Invio)", + "Para os repertórios (Enter)", + "Repertuarlarga (Enter)", + "Репертуарларға (Enter)", + ], + [ + "Finish", + "Закончить", + "Terminer", + "Beenden", + "Terminar", + "Termina", + "Encerrar", + "Tugatish", + "Аяқтау", + ], + [ + "× Finish", + "× Закончить", + "× Terminer", + "× Beenden", + "× Terminar", + "× Termina", + "× Encerrar", + "× Tugatish", + "× Аяқтау", + ], + [ + "Finish the session (Esc)", + "Закончить занятие (Esc)", + "Terminer la séance (Échap)", + "Übung beenden (Esc)", + "Terminar la sesión (Esc)", + "Termina la sessione (Esc)", + "Encerrar a sessão (Esc)", + "Mashg‘ulotni tugatish (Esc)", + "Сабақты аяқтау (Esc)", + ], + [ + "Hint (H)", + "Подсказка (H)", + "Indice (H)", + "Hinweis (H)", + "Pista (H)", + "Suggerimento (H)", + "Dica (H)", + "Maslahat (H)", + "Кеңес (H)", + ], + [ + "Skip (Enter)", + "Пропустить (Enter)", + "Passer (Entrée)", + "Überspringen (Enter)", + "Saltar (Intro)", + "Salta (Invio)", + "Pular (Enter)", + "O‘tkazib yuborish (Enter)", + "Өткізу (Enter)", + ], + [ + "Preparing…", + "Готовим занятие…", + "Préparation…", + "Wird vorbereitet…", + "Preparando…", + "Preparazione…", + "Preparando…", + "Tayyorlanmoqda…", + "Дайындалуда…", + ], + [ + "Branch: {path}", + "Ветка: {path}", + "Branche : {path}", + "Zweig: {path}", + "Rama: {path}", + "Ramo: {path}", + "Ramo: {path}", + "Shox: {path}", + "Тармақ: {path}", + ], + [ + "today, {n} more", + "сегодня, ещё {n}", + "aujourd’hui, encore {n}", + "heute, noch {n}", + "hoy, {n} más", + "oggi, altre {n}", + "hoje, mais {n}", + "bugun, yana {n} ta", + "бүгін, тағы {n}", + ], + [ + "{k} of {n}", + "{k} из {n}", + "{k} sur {n}", + "{k} von {n}", + "{k} de {n}", + "{k} di {n}", + "{k} de {n}", + "{n} tadan {k}", + "{n} ішінен {k}", + ], + [ + "Play {san} — it is shown by the arrow", + "Сыграйте {san} — он показан стрелкой", + "Jouez {san} — la flèche le montre", + "Spielen Sie {san} — der Pfeil zeigt ihn", + "Juega {san}: la flecha lo muestra", + "Gioca {san}: lo mostra la freccia", + "Jogue {san} — a seta o mostra", + "{san} yurishini qiling — u strelka bilan ko‘rsatilgan", + "{san} жүрісін жасаңыз — ол көрсеткімен көрсетілген", + ], + [ + "One more move of yours here, not {san}", + "Здесь есть ещё один ваш ход, не {san}", + "Vous avez un autre coup ici, pas {san}", + "Hier gibt es noch einen eigenen Zug, nicht {san}", + "Aquí tienes otra jugada, no {san}", + "Qui hai un’altra mossa, non {san}", + "Há mais um lance seu aqui, não {san}", + "Bu yerda yana bir yurishingiz bor, {san} emas", + "Мұнда тағы бір жүрісіңіз бар, {san} емес", + ], + [ + "Correct: {san}. Play it", + "Правильно: {san}. Сыграйте его", + "Le bon coup : {san}. Jouez-le", + "Richtig ist {san}. Spielen Sie ihn", + "La correcta: {san}. Juégala", + "Quella giusta: {san}. Giocala", + "O correto: {san}. Jogue-o", + "To‘g‘risi: {san}. Uni qiling", + "Дұрысы: {san}. Соны жасаңыз", + ], + [ + "Now the other one: play {san}", + "Сейчас нужен другой: сыграйте {san}", + "Maintenant l’autre : jouez {san}", + "Jetzt der andere: Spielen Sie {san}", + "Ahora la otra: juega {san}", + "Ora l’altra: gioca {san}", + "Agora o outro: jogue {san}", + "Endi boshqasi: {san} yurishini qiling", + "Енді басқасы: {san} жүрісін жасаңыз", + ], + [ + "{move} will come back in this session", + "{move} вернётся в этом занятии", + "{move} reviendra dans cette séance", + "{move} kommt in dieser Übung wieder", + "{move} volverá en esta sesión", + "{move} tornerà in questa sessione", + "{move} voltará nesta sessão", + "{move} shu mashg‘ulotda yana so‘raladi", + "{move} осы сабақта қайта сұралады", + ], + [ + "Play {san}", + "Сыграйте {san}", + "Jouez {san}", + "Spielen Sie {san}", + "Juega {san}", + "Gioca {san}", + "Jogue {san}", + "{san} yurishini qiling", + "{san} жүрісін жасаңыз", + ], + [ + "Play {san}. It will come back in this session", + "Сыграйте {san}. Ход вернётся в этом занятии", + "Jouez {san}. Il reviendra dans cette séance", + "Spielen Sie {san}. Er kommt in dieser Übung wieder", + "Juega {san}. Volverá en esta sesión", + "Gioca {san}. Tornerà in questa sessione", + "Jogue {san}. Ele voltará nesta sessão", + "{san} yurishini qiling. U shu mashg‘ulotda yana so‘raladi", + "{san} жүрісін жасаңыз. Ол осы сабақта қайта сұралады", + ], + [ + "after {path}", + "после {path}", + "après {path}", + "nach {path}", + "después de {path}", + "dopo {path}", + "depois de {path}", + "{path} dan keyin", + "{path} кейін", + ], + [ + "and {k} more", + "и ещё {k}", + "et {k} de plus", + "und {k} weitere", + "y {k} más", + "e altre {k}", + "e mais {k}", + "va yana {k} ta", + "және тағы {k}", + ], + [ + "Nothing to train here right now", + "Сейчас здесь нечего тренировать", + "Rien à entraîner ici pour l’instant", + "Hier gibt es gerade nichts zu trainieren", + "Ahora no hay nada que entrenar aquí", + "Al momento qui non c’è niente da allenare", + "Nada para treinar aqui agora", + "Hozir bu yerda mashq qiladigan narsa yo‘q", + "Қазір мұнда жаттығатын ештеңе жоқ", + ], + [ + "A repertoire is your opening moves as a PGN with variations. Import a file, or open any game, pick a move and choose “Add to repertoire…”.", + "Репертуар — это ваши дебютные ходы в PGN с вариантами. Импортируйте файл или откройте любую партию, выберите ход и нажмите «Добавить в репертуар…».", + "Un répertoire, ce sont vos coups d’ouverture dans un PGN avec variantes. Importez un fichier, ou ouvrez une partie, choisissez un coup et « Ajouter au répertoire… ».", + "Ein Repertoire sind Ihre Eröffnungszüge als PGN mit Varianten. Importieren Sie eine Datei oder öffnen Sie eine Partie, wählen Sie einen Zug und „Zum Repertoire hinzufügen…“.", + "Un repertorio son tus jugadas de apertura en un PGN con variantes. Importa un archivo, o abre una partida, elige una jugada y pulsa «Añadir al repertorio…».", + "Un repertorio sono le tue mosse d’apertura in un PGN con varianti. Importa un file, oppure apri una partita, scegli una mossa e «Aggiungi al repertorio…».", + "Um repertório são seus lances de abertura em um PGN com variantes. Importe um arquivo, ou abra uma partida, escolha um lance e clique em “Adicionar ao repertório…”.", + "Repertuar — bu variantlari bor PGN dagi debyut yurishlaringiz. Faylni import qiling yoki istalgan partiyani ochib, yurishni tanlang va «Repertuarga qo‘shish…» ni bosing.", + "Репертуар — нұсқалары бар PGN-дегі дебют жүрістеріңіз. Файлды импорттаңыз немесе кез келген партияны ашып, жүрісті таңдап, «Репертуарға қосу…» басыңыз.", + ], + [ + "Moves are added from a PGN file or with “Add to repertoire…” in any game.", + "Ходы добавляются из PGN-файла или кнопкой «Добавить в репертуар…» в любой партии.", + "Les coups s’ajoutent depuis un fichier PGN ou avec « Ajouter au répertoire… » dans une partie.", + "Züge kommen aus einer PGN-Datei oder über „Zum Repertoire hinzufügen…“ in einer Partie.", + "Las jugadas se añaden desde un archivo PGN o con «Añadir al repertorio…» en cualquier partida.", + "Le mosse si aggiungono da un file PGN o con «Aggiungi al repertorio…» in una partita.", + "Os lances são adicionados de um arquivo PGN ou com “Adicionar ao repertório…” em qualquer partida.", + "Yurishlar PGN fayldan yoki istalgan partiyadagi «Repertuarga qo‘shish…» tugmasi bilan qo‘shiladi.", + "Жүрістер PGN файлынан немесе кез келген партиядағы «Репертуарға қосу…» батырмасымен қосылады.", + ], + [ + "Rename repertoire", + "Переименовать репертуар", + "Renommer le répertoire", + "Repertoire umbenennen", + "Renombrar el repertorio", + "Rinomina il repertorio", + "Renomear o repertório", + "Repertuar nomini o‘zgartirish", + "Репертуар атын өзгерту", + ], + [ + "Switch", + "Переключить", + "Changer", + "Wechseln", + "Cambiar", + "Cambia", + "Trocar", + "Almashtirish", + "Ауыстыру", + ], + [ + "The moves themselves and PGN files do not change.", + "Сами ходы и PGN-файлы не меняются.", + "Les coups eux-mêmes et les fichiers PGN ne changent pas.", + "Die Züge selbst und die PGN-Dateien ändern sich nicht.", + "Las jugadas y los archivos PGN no cambian.", + "Le mosse e i file PGN non cambiano.", + "Os lances e os arquivos PGN não mudam.", + "Yurishlarning o‘zi va PGN fayllar o‘zgarmaydi.", + "Жүрістердің өзі мен PGN файлдары өзгермейді.", + ], + [ + "The repertoire leaves this list. PGN files on disk do not change.", + "Репертуар исчезнет из списка. PGN-файлы на диске не меняются.", + "Le répertoire quitte cette liste. Les fichiers PGN sur le disque ne changent pas.", + "Das Repertoire verschwindet aus der Liste. PGN-Dateien auf dem Datenträger ändern sich nicht.", + "El repertorio desaparece de la lista. Los archivos PGN del disco no cambian.", + "Il repertorio esce dall’elenco. I file PGN sul disco non cambiano.", + "O repertório sai da lista. Os arquivos PGN no disco não mudam.", + "Repertuar ro‘yxatdan yo‘qoladi. Diskdagi PGN fayllar o‘zgarmaydi.", + "Репертуар тізімнен жоғалады. Дискідегі PGN файлдары өзгермейді.", + ], + [ + "Your answers are kept: import the same PGN again and the progress returns.", + "Ответы сохранятся: если импортировать тот же PGN снова, прогресс вернётся.", + "Vos réponses sont conservées : réimportez le même PGN et la progression revient.", + "Ihre Antworten bleiben: Importieren Sie dieselbe PGN erneut, ist der Fortschritt wieder da.", + "Tus respuestas se conservan: importa el mismo PGN de nuevo y el progreso vuelve.", + "Le risposte restano: reimporta lo stesso PGN e i progressi tornano.", + "Suas respostas ficam guardadas: importe o mesmo PGN de novo e o progresso volta.", + "Javoblaringiz saqlanadi: o‘sha PGN ni qayta import qilsangiz, natija qaytadi.", + "Жауаптарыңыз сақталады: сол PGN-ді қайта импорттасаңыз, нәтиже қайтады.", + ], + [ + "Nothing to review today", + "Повторять сегодня нечего", + "Rien à réviser aujourd’hui", + "Heute nichts zu wiederholen", + "Hoy no hay nada que repasar", + "Oggi niente da ripassare", + "Nada para revisar hoje", + "Bugun takrorlash kerak emas", + "Бүгін қайталайтын ештеңе жоқ", + ], + [ + "Done for today", + "На сегодня всё", + "C’est fini pour aujourd’hui", + "Für heute fertig", + "Por hoy, terminado", + "Per oggi è tutto", + "Por hoje é só", + "Bugunga yetarli", + "Бүгінге осы", + ], + [ + "No moves yet", + "Ходов пока нет", + "Pas encore de coups", + "Noch keine Züge", + "Aún no hay jugadas", + "Ancora nessuna mossa", + "Ainda sem lances", + "Hali yurishlar yo‘q", + "Әзірге жүріс жоқ", + ], + [ + "Add a PGN, or use “Add to repertoire…” in any game", + "Добавьте PGN или нажмите «Добавить в репертуар…» в любой партии", + "Ajoutez un PGN, ou « Ajouter au répertoire… » dans une partie", + "Fügen Sie eine PGN hinzu oder „Zum Repertoire hinzufügen…“ in einer Partie", + "Añade un PGN o usa «Añadir al repertorio…» en una partida", + "Aggiungi un PGN o usa «Aggiungi al repertorio…» in una partita", + "Adicione um PGN ou use “Adicionar ao repertório…” em uma partida", + "PGN qo‘shing yoki istalgan partiyada «Repertuarga qo‘shish…» ni bosing", + "PGN қосыңыз немесе кез келген партияда «Репертуарға қосу…» басыңыз", + ], + [ + "No moves for White here", + "Здесь нет ходов за белых", + "Pas de coups des Blancs ici", + "Hier gibt es keine Züge für Weiß", + "Aquí no hay jugadas de las blancas", + "Qui non ci sono mosse del Bianco", + "Não há lances das brancas aqui", + "Bu yerda oq uchun yurishlar yo‘q", + "Мұнда ақтың жүрістері жоқ", + ], + [ + "No moves for Black here", + "Здесь нет ходов за чёрных", + "Pas de coups des Noirs ici", + "Hier gibt es keine Züge für Schwarz", + "Aquí no hay jugadas de las negras", + "Qui non ci sono mosse del Nero", + "Não há lances das pretas aqui", + "Bu yerda qora uchun yurishlar yo‘q", + "Мұнда қараның жүрістері жоқ", + ], + [ + "This PGN may be a repertoire for the other colour", + "Возможно, это репертуар за другой цвет", + "Ce PGN est peut-être un répertoire pour l’autre couleur", + "Diese PGN ist vielleicht ein Repertoire für die andere Farbe", + "Quizá este PGN sea un repertorio del otro color", + "Forse questo PGN è un repertorio per l’altro colore", + "Talvez este PGN seja um repertório da outra cor", + "Ehtimol, bu boshqa rang uchun repertuar", + "Мүмкін, бұл басқа түстің репертуары", + ], + [ + "Cannot read this repertoire", + "Не удалось прочитать репертуар", + "Impossible de lire ce répertoire", + "Dieses Repertoire kann nicht gelesen werden", + "No se puede leer este repertorio", + "Impossibile leggere questo repertorio", + "Não foi possível ler este repertório", + "Bu repertuarni o‘qib bo‘lmadi", + "Бұл репертуарды оқу мүмкін болмады", + ], + [ + "Play as Black", + "Играть чёрными", + "Jouer les Noirs", + "Mit Schwarz spielen", + "Jugar con negras", + "Gioca con il Nero", + "Jogar de pretas", + "Qora bilan o‘ynash", + "Қарамен ойнау", + ], + [ + "Play as White", + "Играть белыми", + "Jouer les Blancs", + "Mit Weiß spielen", + "Jugar con blancas", + "Gioca con il Bianco", + "Jogar de brancas", + "Oq bilan o‘ynash", + "Ақпен ойнау", + ], + [ + "Lines…", + "Варианты…", + "Lignes…", + "Varianten…", + "Líneas…", + "Linee…", + "Linhas…", + "Variantlar…", + "Нұсқалар…", + ], + [ + "Rename…", + "Переименовать…", + "Renommer…", + "Umbenennen…", + "Renombrar…", + "Rinomina…", + "Renomear…", + "Nomini o‘zgartirish…", + "Атын өзгерту…", + ], + [ + "Add PGN to this repertoire…", + "Добавить PGN в этот репертуар…", + "Ajouter un PGN à ce répertoire…", + "PGN zu diesem Repertoire hinzufügen…", + "Añadir un PGN a este repertorio…", + "Aggiungi un PGN a questo repertorio…", + "Adicionar PGN a este repertório…", + "Bu repertuarga PGN qo‘shish…", + "Бұл репертуарға PGN қосу…", + ], + [ + "Reset progress…", + "Сбросить прогресс…", + "Réinitialiser la progression…", + "Fortschritt zurücksetzen…", + "Restablecer el progreso…", + "Azzera i progressi…", + "Redefinir o progresso…", + "Natijani tiklash…", + "Нәтижені тастау…", + ], + [ + "You play", + "Вы играете", + "Vous jouez", + "Sie spielen", + "Juegas con", + "Giochi con", + "Você joga de", + "Siz o‘ynaysiz", + "Сіз ойнайсыз", + ], + [ + "Import PGN", + "Импорт PGN", + "Importer un PGN", + "PGN importieren", + "Importar PGN", + "Importa PGN", + "Importar PGN", + "PGN import qilish", + "PGN импорттау", + ], + [ + "Chosen from the PGN — check it", + "Выбрано по PGN — проверьте", + "Choisi d’après le PGN — vérifiez", + "Aus der PGN gewählt — bitte prüfen", + "Elegido según el PGN: compruébalo", + "Scelto in base al PGN: controlla", + "Escolhido pelo PGN — confira", + "PGN bo‘yicha tanlandi — tekshiring", + "PGN бойынша таңдалды — тексеріңіз", + ], + [ + "Reading the file…", + "Читаем файл…", + "Lecture du fichier…", + "Datei wird gelesen…", + "Leyendo el archivo…", + "Lettura del file…", + "Lendo o arquivo…", + "Fayl o‘qilmoqda…", + "Файл оқылуда…", + ], + [ + "Nothing new in this file", + "В файле нет новых ходов", + "Rien de nouveau dans ce fichier", + "Nichts Neues in dieser Datei", + "No hay nada nuevo en este archivo", + "Niente di nuovo in questo file", + "Nada de novo neste arquivo", + "Bu faylda yangi yurishlar yo‘q", + "Бұл файлда жаңа жүріс жоқ", + ], + [ + "No moves for this colour", + "Нет ходов за этот цвет", + "Aucun coup pour cette couleur", + "Keine Züge für diese Farbe", + "No hay jugadas de este color", + "Nessuna mossa per questo colore", + "Sem lances para esta cor", + "Bu rang uchun yurishlar yo‘q", + "Бұл түс үшін жүріс жоқ", + ], + [ + "Import", + "Импортировать", + "Importer", + "Importieren", + "Importar", + "Importa", + "Importar", + "Import qilish", + "Импорттау", + ], + [ + "No games with moves in this file", + "В файле нет партий с ходами", + "Aucune partie avec des coups dans ce fichier", + "Keine Partie mit Zügen in dieser Datei", + "No hay partidas con jugadas en este archivo", + "Nessuna partita con mosse in questo file", + "Nenhuma partida com lances neste arquivo", + "Bu faylda yurishli partiyalar yo‘q", + "Бұл файлда жүрісі бар партия жоқ", + ], + [ + "Saved to {path}", + "Сохранено: {path}", + "Enregistré : {path}", + "Gespeichert: {path}", + "Guardado en {path}", + "Salvato in {path}", + "Salvo em {path}", + "Saqlandi: {path}", + "Сақталды: {path}", + ], + [ + "{n} repertoires", + "Репертуаров: {n}", + "{n} répertoires", + "{n} Repertoires", + "{n} repertorios", + "{n} repertori", + "{n} repertórios", + "Repertuarlar: {n}", + "Репертуарлар: {n}", + ], + [ + "Could not read the repertoires: {e}", + "Не удалось прочитать репертуары: {e}", + "Impossible de lire les répertoires : {e}", + "Die Repertoires konnten nicht gelesen werden: {e}", + "No se pudieron leer los repertorios: {e}", + "Impossibile leggere i repertori: {e}", + "Não foi possível ler os repertórios: {e}", + "Repertuarlarni o‘qib bo‘lmadi: {e}", + "Репертуарларды оқу мүмкін болмады: {e}", + ], + [ + "{n} to review, {m} new", + "Повторить: {n}, новых: {m}", + "{n} à réviser, {m} nouveaux", + "{n} zu wiederholen, {m} neu", + "{n} para repasar, {m} nuevas", + "{n} da ripassare, {m} nuove", + "{n} para revisar, {m} novos", + "Takrorlash: {n}, yangi: {m}", + "Қайталау: {n}, жаңа: {m}", + ], + [ + "Play “{name}” as Black?", + "Играть «{name}» чёрными?", + "Jouer « {name} » avec les Noirs ?", + "„{name}“ mit Schwarz spielen?", + "¿Jugar «{name}» con negras?", + "Giocare «{name}» con il Nero?", + "Jogar “{name}” de pretas?", + "«{name}» ni qora bilan o‘ynaysizmi?", + "«{name}» қарамен ойнайсыз ба?", + ], + [ + "Play “{name}” as White?", + "Играть «{name}» белыми?", + "Jouer « {name} » avec les Blancs ?", + "„{name}“ mit Weiß spielen?", + "¿Jugar «{name}» con blancas?", + "Giocare «{name}» con il Bianco?", + "Jogar “{name}” de brancas?", + "«{name}» ni oq bilan o‘ynaysizmi?", + "«{name}» ақпен ойнайсыз ба?", + ], + [ + "You will be asked Black's moves: {y}. Progress for White is kept and comes back if you switch again.", + "Спрашиваться будут ходы чёрных: {y}. Прогресс за белых сохранится и вернётся, если переключить обратно.", + "On vous demandera les coups des Noirs : {y}. La progression des Blancs est conservée et revient si vous changez à nouveau.", + "Gefragt werden die Züge von Schwarz: {y}. Der Fortschritt für Weiß bleibt erhalten und kehrt beim Zurückwechseln zurück.", + "Se te preguntarán las jugadas de las negras: {y}. El progreso de las blancas se guarda y vuelve si cambias de nuevo.", + "Ti verranno chieste le mosse del Nero: {y}. I progressi del Bianco restano e tornano se cambi di nuovo.", + "Serão perguntados os lances das pretas: {y}. O progresso das brancas fica guardado e volta se você trocar de novo.", + "Qoraning yurishlari so‘raladi: {y}. Oq bo‘yicha natija saqlanadi va qayta almashtirsangiz qaytadi.", + "Қараның жүрістері сұралады: {y}. Ақтағы нәтиже сақталады және қайта ауыстырсаңыз қайтады.", + ], + [ + "You will be asked White's moves: {y}. Progress for Black is kept and comes back if you switch again.", + "Спрашиваться будут ходы белых: {y}. Прогресс за чёрных сохранится и вернётся, если переключить обратно.", + "On vous demandera les coups des Blancs : {y}. La progression des Noirs est conservée et revient si vous changez à nouveau.", + "Gefragt werden die Züge von Weiß: {y}. Der Fortschritt für Schwarz bleibt erhalten und kehrt beim Zurückwechseln zurück.", + "Se te preguntarán las jugadas de las blancas: {y}. El progreso de las negras se guarda y vuelve si cambias de nuevo.", + "Ti verranno chieste le mosse del Bianco: {y}. I progressi del Nero restano e tornano se cambi di nuovo.", + "Serão perguntados os lances das brancas: {y}. O progresso das pretas fica guardado e volta se você trocar de novo.", + "Oqning yurishlari so‘raladi: {y}. Qora bo‘yicha natija saqlanadi va qayta almashtirsangiz qaytadi.", + "Ақтың жүрістері сұралады: {y}. Қарадағы нәтиже сақталады және қайта ауыстырсаңыз қайтады.", + ], + [ + "Reset progress of “{name}”?", + "Сбросить прогресс «{name}»?", + "Réinitialiser la progression de « {name} » ?", + "Fortschritt von „{name}“ zurücksetzen?", + "¿Restablecer el progreso de «{name}»?", + "Azzerare i progressi di «{name}»?", + "Redefinir o progresso de “{name}”?", + "«{name}» natijasini tiklaysizmi?", + "«{name}» нәтижесін тастау керек пе?", + ], + [ + "All {y} moves of this repertoire become new again: answers and review dates are erased.", + "Все ходы этого репертуара ({y}) снова станут новыми: ответы и сроки повторений будут стёрты.", + "Les {y} coups de ce répertoire redeviennent nouveaux : réponses et dates de révision sont effacées.", + "Alle {y} Züge dieses Repertoires werden wieder neu: Antworten und Wiederholungstermine werden gelöscht.", + "Las {y} jugadas de este repertorio vuelven a ser nuevas: se borran las respuestas y las fechas de repaso.", + "Tutte le {y} mosse di questo repertorio tornano nuove: risposte e date di ripasso vengono cancellate.", + "Todos os {y} lances deste repertório voltam a ser novos: respostas e datas de revisão são apagadas.", + "Bu repertuarning barcha yurishlari ({y}) yana yangi bo‘ladi: javoblar va takrorlash muddatlari o‘chiriladi.", + "Бұл репертуардың барлық жүрісі ({y}) қайта жаңа болады: жауаптар мен қайталау мерзімдері өшіріледі.", + ], + [ + "{s} of these moves are also in: {names}. They become new there too.", + "Из них {s} встречаются также в: {names}. Там они тоже станут новыми.", + "{s} de ces coups sont aussi dans : {names}. Ils y redeviennent nouveaux aussi.", + "{s} dieser Züge stehen auch in: {names}. Dort werden sie ebenfalls neu.", + "{s} de estas jugadas también están en: {names}. Allí también vuelven a ser nuevas.", + "{s} di queste mosse sono anche in: {names}. Anche lì tornano nuove.", + "{s} desses lances também estão em: {names}. Lá eles também voltam a ser novos.", + "Ulardan {s} tasi bularda ham bor: {names}. U yerda ham yangi bo‘ladi.", + "Олардың {s} жүрісі мұнда да бар: {names}. Онда да жаңа болады.", + ], + [ + "Delete “{name}”?", + "Удалить «{name}»?", + "Supprimer « {name} » ?", + "„{name}“ löschen?", + "¿Eliminar «{name}»?", + "Eliminare «{name}»?", + "Excluir “{name}”?", + "«{name}» ni o‘chirasizmi?", + "«{name}» жою керек пе?", + ], + [ + "Today: {n} to review · {m} new", + "Сегодня: {n} повторить · {m} новых", + "Aujourd’hui : {n} à réviser · {m} nouveaux", + "Heute: {n} wiederholen · {m} neu", + "Hoy: {n} para repasar · {m} nuevas", + "Oggi: {n} da ripassare · {m} nuove", + "Hoje: {n} para revisar · {m} novos", + "Bugun: {n} ta takrorlash · {m} ta yangi", + "Бүгін: {n} қайталау · {m} жаңа", + ], + [ + "Today: {n} to review", + "Сегодня: {n} повторить", + "Aujourd’hui : {n} à réviser", + "Heute: {n} wiederholen", + "Hoy: {n} para repasar", + "Oggi: {n} da ripassare", + "Hoje: {n} para revisar", + "Bugun: {n} ta takrorlash", + "Бүгін: {n} қайталау", + ], + [ + "About {t} min", + "Примерно {t} мин", + "Environ {t} min", + "Etwa {t} Min.", + "Unos {t} min", + "Circa {t} min", + "Cerca de {t} min", + "Taxminan {t} daqiqa", + "Шамамен {t} мин", + ], + [ + "Today: {m} new moves", + "Сегодня: {m} новых ходов", + "Aujourd’hui : {m} nouveaux coups", + "Heute: {m} neue Züge", + "Hoy: {m} jugadas nuevas", + "Oggi: {m} mosse nuove", + "Hoje: {m} lances novos", + "Bugun: {m} ta yangi yurish", + "Бүгін: {m} жаңа жүріс", + ], + [ + "Next review: {when} · {n} moves", + "Следующее повторение: {when} · ходов: {n}", + "Prochaine révision : {when} · {n} coups", + "Nächste Wiederholung: {when} · {n} Züge", + "Próximo repaso: {when} · {n} jugadas", + "Prossimo ripasso: {when} · {n} mosse", + "Próxima revisão: {when} · {n} lances", + "Keyingi takrorlash: {when} · {n} ta yurish", + "Келесі қайталау: {when} · {n} жүріс", + ], + [ + "Learn {m} new", + "Учить {m} новых", + "Apprendre {m} nouveaux", + "{m} neue lernen", + "Aprender {m} nuevas", + "Impara {m} nuove", + "Aprender {m} novos", + "{m} ta yangisini o‘rganish", + "{m} жаңасын үйрену", + ], + [ + "Learned {x} of {y} moves", + "Выучено {x} из {y} ходов", + "{x} coups appris sur {y}", + "{x} von {y} Zügen gelernt", + "{x} de {y} jugadas aprendidas", + "{x} mosse imparate su {y}", + "{x} de {y} lances aprendidos", + "{y} ta yurishdan {x} tasi o‘rganildi", + "{y} жүрістің {x} үйренілді", + ], + [ + "{k} in progress", + "учится: {k}", + "{k} en cours", + "{k} in Arbeit", + "{k} en curso", + "{k} in corso", + "{k} em andamento", + "o‘rganilmoqda: {k}", + "үйренілуде: {k}", + ], + [ + "Add PGN to “{name}”", + "Добавить PGN в «{name}»", + "Ajouter un PGN à « {name} »", + "PGN zu „{name}“ hinzufügen", + "Añadir un PGN a «{name}»", + "Aggiungi un PGN a «{name}»", + "Adicionar PGN a “{name}”", + "«{name}» ga PGN qo‘shish", + "«{name}» ішіне PGN қосу", + ], + [ + "{m} new moves · {v} new lines", + "Новых ходов: {m} · новых вариантов: {v}", + "{m} nouveaux coups · {v} nouvelles lignes", + "{m} neue Züge · {v} neue Varianten", + "{m} jugadas nuevas · {v} líneas nuevas", + "{m} mosse nuove · {v} linee nuove", + "{m} lances novos · {v} linhas novas", + "Yangi yurishlar: {m} · yangi variantlar: {v}", + "Жаңа жүрістер: {m} · жаңа нұсқалар: {v}", + ], + [ + "{g} games · {v} lines · {y} your moves", + "Партий: {g} · вариантов: {v} · ваших ходов: {y}", + "{g} parties · {v} lignes · {y} de vos coups", + "{g} Partien · {v} Varianten · {y} eigene Züge", + "{g} partidas · {v} líneas · {y} jugadas tuyas", + "{g} partite · {v} linee · {y} tue mosse", + "{g} partidas · {v} linhas · {y} lances seus", + "Partiyalar: {g} · variantlar: {v} · yurishlaringiz: {y}", + "Партиялар: {g} · нұсқалар: {v} · сіздің жүрістеріңіз: {y}", + ], + [ + "Game {n}: could not be read", + "Партия {n}: не удалось прочитать", + "Partie {n} : illisible", + "Partie {n}: nicht lesbar", + "Partida {n}: no se pudo leer", + "Partita {n}: illeggibile", + "Partida {n}: não foi possível ler", + "{n}-partiya: o‘qib bo‘lmadi", + "{n}-партия: оқу мүмкін болмады", + ], + [ + "Game {n}: {message}", + "Партия {n}: {message}", + "Partie {n} : {message}", + "Partie {n}: {message}", + "Partida {n}: {message}", + "Partita {n}: {message}", + "Partida {n}: {message}", + "{n}-partiya: {message}", + "{n}-партия: {message}", + ], + [ + "Game {n} has no moves", + "В партии {n} нет ходов", + "La partie {n} n’a pas de coups", + "Partie {n} hat keine Züge", + "La partida {n} no tiene jugadas", + "La partita {n} non ha mosse", + "A partida {n} não tem lances", + "{n}-partiyada yurishlar yo‘q", + "{n}-партияда жүріс жоқ", + ], [ "Your turn: play a repertoire move.", "Ваш ход: сыграйте ход из репертуара.", @@ -20437,12 +21757,10 @@ mod tests { include_str!("chatgpt.rs"), include_str!("san.rs"), include_str!("prep_ui.rs"), - include_str!("learning_training.rs"), - include_str!("learning_context_controls.rs"), - include_str!("learning_branches.rs"), - include_str!("learning_charts.rs"), - include_str!("learning_dashboard.rs"), - include_str!("repertoire_editor.rs"), + include_str!("opening_layout.rs"), + include_str!("opening_lines.rs"), + include_str!("opening_session.rs"), + include_str!("repertoire_ui.rs"), ]; let mut chars = std::collections::BTreeSet::new(); for row in ROWS.iter() { @@ -20515,14 +21833,10 @@ mod tests { include_str!("chatgpt.rs"), include_str!("san.rs"), include_str!("prep_ui.rs"), - include_str!("learning_training.rs"), - include_str!("learning_context_controls.rs"), - include_str!("learning_branches.rs"), - include_str!("learning_charts.rs"), - include_str!("learning_dashboard.rs"), - include_str!("repertoire_editor.rs"), + include_str!("opening_layout.rs"), + include_str!("opening_lines.rs"), + include_str!("opening_session.rs"), include_str!("repertoire_ui.rs"), - include_str!("repertoire_training.rs"), ]; let mut missing = Vec::new(); let mut found = 0; diff --git a/apps/desktop/src/learning_branches.rs b/apps/desktop/src/learning_branches.rs deleted file mode 100644 index 1886709..0000000 --- a/apps/desktop/src/learning_branches.rs +++ /dev/null @@ -1,763 +0,0 @@ -use std::collections::HashMap; - -use egui::{Align, Layout, RichText, Sense, Ui}; -use egui_extras::{Column, TableBuilder}; -use trainer::repertoire::{BranchLearningAnalytics, RepertoireId}; - -use crate::i18n::tr; - -const HEADER_HEIGHT: f32 = 40.0; -const ROW_HEIGHT: f32 = 32.0; -const BODY_TEXT_SIZE: f32 = 14.0; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct BranchSelection { - pub repertoire_id: RepertoireId, - pub branch_root: Vec, -} - -pub fn show( - ui: &mut egui::Ui, - rows: &[BranchLearningAnalytics], - names: &HashMap, - labels: &HashMap<(RepertoireId, Vec), Vec>, - selected: &mut Option, -) { - ui.style_mut().interaction.selectable_labels = false; - if rows.is_empty() { - *selected = None; - ui.label(tr("No branches in this scope")); - return; - } - if selected - .as_ref() - .is_none_or(|selection| !rows.iter().any(|row| selection == &selection_for(row))) - { - *selected = Some(selection_for(&rows[0])); - } - - ui.add( - egui::Label::new(tr( - "Continuations to review. Shared moves may appear in several variations.", - )) - .wrap(), - ); - ui.add_space(6.0); - let include_repertoire = include_repertoire_names(rows); - let mut clicked = None; - show_table( - ui, - rows, - names, - labels, - include_repertoire, - selected.as_ref(), - &mut clicked, - ); - if let Some(selection) = clicked { - *selected = Some(selection); - } - - if let Some(selection) = selected.as_ref() - && let Some(row) = rows.iter().find(|row| selection == &selection_for(row)) - { - ui.separator(); - show_details(ui, row, names, labels, include_repertoire); - } -} - -fn selection_for(row: &BranchLearningAnalytics) -> BranchSelection { - BranchSelection { - repertoire_id: row.repertoire_id.clone(), - branch_root: row.branch_root.clone(), - } -} - -fn include_repertoire_names(rows: &[BranchLearningAnalytics]) -> bool { - rows.first().is_some_and(|first| { - rows.iter() - .any(|row| row.repertoire_id != first.repertoire_id) - }) -} - -fn san_path( - row: &BranchLearningAnalytics, - labels: &HashMap<(RepertoireId, Vec), Vec>, -) -> String { - let labels = labels.get(&(row.repertoire_id.clone(), row.branch_root.clone())); - row.branch_root - .iter() - .enumerate() - .map(|(index, uci)| { - let label = labels.and_then(|labels| labels.get(index)).unwrap_or(uci); - crate::san::show(label).into_owned() - }) - .collect::>() - .join(" ") -} - -fn branch_text( - row: &BranchLearningAnalytics, - names: &HashMap, - labels: &HashMap<(RepertoireId, Vec), Vec>, - include_repertoire: bool, -) -> String { - let path = san_path(row, labels); - if !include_repertoire { - return if path.is_empty() { - "—".to_owned() - } else { - path - }; - } - let name = names - .get(&row.repertoire_id) - .map_or_else(|| row.repertoire_id.as_str(), String::as_str); - if path.is_empty() { - name.to_owned() - } else { - format!("{name} · {path}") - } -} - -#[allow(clippy::too_many_arguments)] -fn show_table( - ui: &mut Ui, - rows: &[BranchLearningAnalytics], - names: &HashMap, - labels: &HashMap<(RepertoireId, Vec), Vec>, - include_repertoire: bool, - selected: Option<&BranchSelection>, - clicked: &mut Option, -) { - let numeric_width = (ui.available_width() - 3.0 * ui.spacing().item_spacing.x) * 0.4 / 3.0; - TableBuilder::new(ui) - .id_salt("learning_branches") - .striped(true) - .sense(Sense::click()) - .max_scroll_height(192.0) - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::remainder().clip(true)) - .column(Column::exact(numeric_width).clip(true)) - .column(Column::exact(numeric_width).clip(true)) - .column(Column::exact(numeric_width).clip(true)) - .header(HEADER_HEIGHT, |mut header| { - for (index, key) in ["Variation start", "Learnt", "Due now", "Accuracy"] - .into_iter() - .enumerate() - { - header.col(|ui| { - header_cell(ui, tr(key), index > 0); - }); - } - }) - .body(|body| { - body.rows(ROW_HEIGHT, rows.len(), |mut table_row| { - let row = &rows[table_row.index()]; - let selection = selection_for(row); - table_row.set_selected(selected == Some(&selection)); - table_row.col(|ui| { - let text = branch_text(row, names, labels, include_repertoire); - text_cell(ui, &text, false).on_hover_text(text); - }); - for value in [ - format!("{} / {}", row.summary.learnt, row.summary.total), - row.summary.due.to_string(), - format_percent(row.summary.accuracy_percent), - ] { - table_row.col(|ui| { - text_cell(ui, &value, true); - }); - } - if table_row.response().clicked() { - *clicked = Some(selection); - } - }); - }); -} - -fn show_details( - ui: &mut Ui, - row: &BranchLearningAnalytics, - names: &HashMap, - labels: &HashMap<(RepertoireId, Vec), Vec>, - include_repertoire: bool, -) { - let branch = branch_text(row, names, labels, include_repertoire); - ui.add(egui::Label::new(RichText::new(&branch).strong().size(BODY_TEXT_SIZE)).wrap()) - .on_hover_text(branch); - ui.add_space(4.0); - let details = [ - ( - "Learnt moves", - format!("{} / {}", row.summary.learnt, row.summary.total), - ), - ("Due now", row.summary.due.to_string()), - ("Not practised yet", row.summary.unseen.to_string()), - ("Accuracy", format_percent(row.summary.accuracy_percent)), - ]; - show_details_rows(ui, &details); -} - -fn show_details_rows(ui: &mut Ui, details: &[(&'static str, String)]) { - let label_width = (ui.available_width() * 0.36).clamp(110.0, 160.0); - TableBuilder::new(ui) - .id_salt("learning_branches_details") - .vscroll(false) - .cell_layout(Layout::left_to_right(Align::Min)) - .column(Column::exact(label_width).clip(true)) - .column(Column::remainder().at_least(80.0).clip(true)) - .body(|body| { - body.rows(36.0, details.len(), |mut row| { - let (label, value) = &details[row.index()]; - row.col(|ui| { - ui.add( - egui::Label::new(RichText::new(tr(label)).weak().size(BODY_TEXT_SIZE)) - .wrap(), - ); - }); - row.col(|ui| { - ui.add(egui::Label::new(RichText::new(value).size(BODY_TEXT_SIZE)).wrap()); - }); - }); - }); -} - -fn header_cell(ui: &mut Ui, text: &str, _numeric: bool) -> egui::Response { - ui.add(egui::Label::new(RichText::new(text).strong().size(BODY_TEXT_SIZE)).wrap()) -} - -fn text_cell(ui: &mut Ui, text: &str, _numeric: bool) -> egui::Response { - ui.add(egui::Label::new(RichText::new(text).size(BODY_TEXT_SIZE)).truncate()) -} - -fn format_percent(value: Option) -> String { - value.map_or_else(|| "—".to_owned(), |value| format!("{value:.0} %")) -} - -#[cfg(test)] -mod tests { - use trainer::repertoire::{LearningAggregate, Repertoire}; - - use super::*; - - const BASE: i64 = 1_800_000_000; - - struct Fixture { - rows: Vec, - names: HashMap, - labels: HashMap<(RepertoireId, Vec), Vec>, - } - - fn fixture() -> Fixture { - let first = Repertoire::default().id; - let second = Repertoire::default().id; - let branch_root = vec!["e2e4".to_owned(), "e7e5".to_owned()]; - let summary = LearningAggregate { - total: 8, - unseen: 2, - learning: 2, - learnt: 4, - uncertain: 1, - learnt_confident: 3, - due: 3, - learnt_percent: Some(50.0), - accuracy_correct: 6, - accuracy_wrong: 2, - accuracy_attempts: 8, - accuracy_percent: Some(75.0), - ..LearningAggregate::default() - }; - let rows = vec![ - BranchLearningAnalytics { - repertoire_id: first.clone(), - branch_root: branch_root.clone(), - summary: summary.clone(), - last_independent_at: Some(BASE), - }, - BranchLearningAnalytics { - repertoire_id: second.clone(), - branch_root: branch_root.clone(), - summary, - last_independent_at: Some(BASE), - }, - ]; - let names = HashMap::from([ - (first.clone(), "First".to_owned()), - (second.clone(), "Second".to_owned()), - ]); - let labels = HashMap::from([ - ( - (first, branch_root.clone()), - vec!["1.e4".to_owned(), "1...e5".to_owned()], - ), - ((second, branch_root), vec!["1.e4".to_owned()]), - ]); - Fixture { - rows, - names, - labels, - } - } - - #[allow(clippy::too_many_arguments)] - fn render( - ctx: &egui::Context, - width: f32, - height: f32, - time: f64, - events: Vec, - rows: &[BranchLearningAnalytics], - names: &HashMap, - labels: &HashMap<(RepertoireId, Vec), Vec>, - selected: &mut Option, - ) -> Vec { - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - time: Some(time), - events, - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - show(ui, rows, names, labels, selected); - }); - }, - ); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - shapes - } - - fn has_text(shapes: &[egui::epaint::ClippedShape], expected: &str) -> bool { - shapes.iter().any(|clipped| match &clipped.shape { - egui::Shape::Text(text) => text.galley.text().replace('\n', " ") == expected, - _ => false, - }) - } - - fn has_translated_text(shapes: &[egui::epaint::ClippedShape], key: &'static str) -> bool { - crate::i18n::all_languages(key) - .into_iter() - .any(|translation| has_text(shapes, translation)) - } - - fn text_position(shapes: &[egui::epaint::ClippedShape], expected: &str) -> Option { - shapes.iter().find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) if text.galley.text().replace('\n', " ") == expected => { - Some(text.pos + egui::vec2(8.0, 6.0)) - } - _ => None, - }) - } - - fn text_occurrences(shapes: &[egui::epaint::ClippedShape], expected: &str) -> usize { - shapes - .iter() - .filter(|clipped| match &clipped.shape { - egui::Shape::Text(text) => text.galley.text().replace('\n', " ") == expected, - _ => false, - }) - .count() - } - - fn click(position: egui::Pos2) -> Vec { - vec![ - egui::Event::PointerMoved(position), - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }, - ] - } - - fn assert_bounds(shapes: &[egui::epaint::ClippedShape], width: f32, height: f32) { - for clipped in shapes { - let bounds = clipped.shape.visual_bounding_rect(); - if bounds.is_finite() && bounds.is_positive() { - assert!( - bounds.min.x >= -0.5 - && bounds.min.y >= -0.5 - && bounds.max.x <= width + 0.5 - && bounds.max.y <= height + 0.5, - "shape outside {width}x{height}: {bounds:?}" - ); - } - } - } - - #[test] - fn summarized_shared_rows_are_not_deduplicated_and_labels_fall_back_to_uci() { - let fixture = fixture(); - let ctx = egui::Context::default(); - let mut selected = None; - let shapes = render( - &ctx, - 1200.0, - 800.0, - 0.0, - Vec::new(), - &fixture.rows, - &fixture.names, - &fixture.labels, - &mut selected, - ); - assert_eq!(selected, Some(selection_for(&fixture.rows[0]))); - assert!(has_text(&shapes, "First · 1.e4 1...e5")); - assert!(has_text(&shapes, "Second · 1.e4 e7e5")); - - let names = fixture.names.clone(); - let shapes = render( - &ctx, - 1200.0, - 800.0, - 1.0, - Vec::new(), - &fixture.rows[..1], - &names, - &fixture.labels, - &mut selected, - ); - assert!(has_text(&shapes, "1.e4 1...e5")); - assert!(!has_text(&shapes, "First · 1.e4 1...e5")); - } - - #[test] - fn unified_layout_stays_in_bounds_in_light_and_dark() { - let fixture = fixture(); - for visuals in [egui::Visuals::light(), egui::Visuals::dark()] { - for (width, height) in [(1400.0, 900.0), (960.0, 600.0), (640.0, 480.0)] { - let ctx = egui::Context::default(); - ctx.set_visuals(visuals.clone()); - let mut selected = None; - for pass in 0..2 { - let shapes = render( - &ctx, - width, - height, - pass as f64, - Vec::new(), - &fixture.rows, - &fixture.names, - &fixture.labels, - &mut selected, - ); - assert!(!shapes.is_empty()); - assert_bounds(&shapes, width, height); - for key in [ - "Variation start", - "Learnt", - "Due now", - "Accuracy", - "Learnt moves", - "Not practised yet", - ] { - assert!( - has_translated_text(&shapes, key), - "missing header/detail {key}" - ); - } - } - } - } - } - - #[test] - fn headers_fit_accepted_matrix_in_russian_and_german() { - let cases = [ - ["Начало варианта", "Изучено", "Повторить", "Точность"], - ["Variantenanfang", "Gelernt", "Wiederholen", "Genauigkeit"], - ]; - for visuals in [egui::Visuals::light(), egui::Visuals::dark()] { - for (width, height) in [(960.0, 600.0), (1400.0, 900.0)] { - for headers in &cases { - let ctx = egui::Context::default(); - ctx.set_visuals(visuals.clone()); - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - ..Default::default() - }, - |ui| { - let numeric_width = - (ui.available_width() - 3.0 * ui.spacing().item_spacing.x) * 0.4 - / 3.0; - let mut table = TableBuilder::new(ui) - .id_salt("learning_branches_wide_header_test") - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::remainder().at_least(120.0).clip(true)); - for _ in 0..3 { - table = table.column(Column::exact(numeric_width).clip(true)); - } - table.header(HEADER_HEIGHT, |mut header| { - for (index, key) in headers.iter().enumerate() { - header.col(|ui| { - header_cell(ui, tr(key), index > 0); - }); - } - }); - }, - ); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - assert_bounds(&shapes, width, height); - for expected in headers { - let (rect, clip, lines) = shapes - .iter() - .find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) - if text.galley.text().replace('\n', " ") == *expected => - { - Some(( - egui::Rect::from_min_size(text.pos, text.galley.size()), - clipped.clip_rect, - text.galley.text().lines().count(), - )) - } - _ => None, - }) - .unwrap_or_else(|| { - panic!("missing full header {expected} at {width}x{height}") - }); - assert!(lines <= 2, "header wraps too much: {expected}"); - assert!( - rect.min.x >= clip.min.x - 0.1 - && rect.min.y >= clip.min.y - 0.1 - && rect.max.x <= clip.max.x + 0.1 - && rect.max.y <= clip.max.y + 0.1, - "clipped header {expected} at {width}x{height}: {rect:?} {clip:?}" - ); - } - } - } - } - } - - #[test] - fn details_are_visible_and_click_selects_the_branch() { - let fixture = fixture(); - let ctx = egui::Context::default(); - let mut selected = None; - let shapes = render( - &ctx, - 640.0, - 480.0, - 0.0, - Vec::new(), - &fixture.rows, - &fixture.names, - &fixture.labels, - &mut selected, - ); - assert_eq!(selected, Some(selection_for(&fixture.rows[0]))); - let second = text_position(&shapes, "Second · 1.e4 e7e5") - .expect("second branch row should be visible"); - let shapes = render( - &ctx, - 640.0, - 480.0, - 1.0, - click(second), - &fixture.rows, - &fixture.names, - &fixture.labels, - &mut selected, - ); - assert_eq!(selected, Some(selection_for(&fixture.rows[1]))); - assert!(text_occurrences(&shapes, "Second · 1.e4 e7e5") >= 2); - for key in ["Learnt moves", "Due now", "Not practised yet", "Accuracy"] { - assert!(has_translated_text(&shapes, key), "missing detail {key}"); - } - } - - #[test] - fn details_keep_long_labels_readable_at_all_widths() { - let cases: Vec> = vec![ - vec![ - ("Новый", "2".to_owned()), - ("Изучается", "1".to_owned()), - ("Изучено", "4".to_owned()), - ("Не подтверждено", "1".to_owned()), - ("К повторению", "3".to_owned()), - ("Точность", "75 %".to_owned()), - ("Последняя тренировка", "2026-11-04 08:26".to_owned()), - ], - vec![ - ("Neu", "2".to_owned()), - ("Wird gelernt", "1".to_owned()), - ("Gelernt", "4".to_owned()), - ("Nicht bestätigt", "1".to_owned()), - ("Fällig", "3".to_owned()), - ("Genauigkeit", "75 %".to_owned()), - ("Zuletzt trainiert", "2026-11-04 08:26".to_owned()), - ], - ]; - for visuals in [egui::Visuals::light(), egui::Visuals::dark()] { - for width in [320.0, 360.0, 420.0, 640.0] { - for details in &cases { - let ctx = egui::Context::default(); - ctx.set_visuals(visuals.clone()); - let mut expected_label_width = 0.0; - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, 700.0), - )), - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - expected_label_width = - (ui.available_width() * 0.36).clamp(110.0, 160.0); - show_details_rows(ui, details); - }); - }, - ); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - assert_bounds(&shapes, width, 700.0); - for (label, _) in details { - let (clip, lines) = shapes - .iter() - .find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) - if text.galley.text().replace('\n', " ") == *label => - { - Some((clipped.clip_rect, text.galley.text().lines().count())) - } - _ => None, - }) - .unwrap_or_else(|| panic!("missing full label {label} at {width}")); - assert!( - (clip.width() - expected_label_width).abs() < 0.1, - "label column at {width}: {clip:?}, expected {expected_label_width}: {label}" - ); - assert!(lines <= 2, "label wraps too much at {width}: {label}"); - } - assert!(has_text(&shapes, "2026-11-04 08:26")); - assert!(has_text(&shapes, "75 %")); - } - } - } - } - - #[test] - fn null_accuracy_renders_as_dashes_in_table_and_details() { - let fixture = fixture(); - let mut row = fixture.rows[0].clone(); - row.summary.accuracy_percent = None; - row.summary.learnt_percent = None; - row.last_independent_at = None; - let names = HashMap::from([(row.repertoire_id.clone(), "Only".to_owned())]); - let labels = HashMap::new(); - let ctx = egui::Context::default(); - let mut selected = None; - let shapes = render( - &ctx, - 640.0, - 480.0, - 0.0, - Vec::new(), - std::slice::from_ref(&row), - &names, - &labels, - &mut selected, - ); - let dashes = text_occurrences(&shapes, "—"); - assert!( - dashes >= 2, - "expected null accuracy in table and details: {dashes}" - ); - assert_eq!(format_percent(None), "—"); - assert_eq!(format_percent(Some(75.0)), "75 %"); - } - - #[test] - fn long_selected_notation_wraps_in_details_and_row_retains_wide_column() { - let mut fixture = fixture(); - fixture.rows.truncate(1); - fixture.rows[0].branch_root = (0..40).map(|i| format!("move{i}")).collect(); - let notation: Vec<_> = (1..=40).map(|i| format!("{i}.Nf3")).collect(); - fixture.labels.insert( - ( - fixture.rows[0].repertoire_id.clone(), - fixture.rows[0].branch_root.clone(), - ), - notation, - ); - let expected = san_path(&fixture.rows[0], &fixture.labels); - for width in [960.0, 1400.0] { - let ctx = egui::Context::default(); - let mut selected = None; - let shapes = render( - &ctx, - width, - 900.0, - 0.0, - Vec::new(), - &fixture.rows, - &fixture.names, - &fixture.labels, - &mut selected, - ); - assert_bounds(&shapes, width, 900.0); - let texts: Vec<_> = shapes - .iter() - .filter_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) if text.galley.text() == expected => { - Some((clipped, text)) - } - _ => None, - }) - .collect(); - assert_eq!(texts.len(), 2, "table row and full selected notation"); - assert!(texts[0].0.clip_rect.width() >= width * 0.5); - assert_eq!( - texts[0].1.galley.rows.len(), - 1, - "table notation stays on one line" - ); - assert!( - texts[1].1.galley.rows.len() > 1, - "full selected notation wraps" - ); - assert!(has_text(&shapes, "4 / 8")); - } - } - - #[test] - fn empty_scope_clears_selection() { - let fixture = fixture(); - let ctx = egui::Context::default(); - let mut selected = Some(selection_for(&fixture.rows[0])); - let shapes = render( - &ctx, - 640.0, - 480.0, - 0.0, - Vec::new(), - &[], - &fixture.names, - &fixture.labels, - &mut selected, - ); - assert_eq!(selected, None); - assert!(has_translated_text(&shapes, "No branches in this scope")); - } -} diff --git a/apps/desktop/src/learning_charts.rs b/apps/desktop/src/learning_charts.rs deleted file mode 100644 index 7712335..0000000 --- a/apps/desktop/src/learning_charts.rs +++ /dev/null @@ -1,507 +0,0 @@ -use std::{collections::BTreeMap, fmt}; - -use egui::{ - Align2, Color32, FontId, Painter, Pos2, Rect, RichText, Sense, Shape, Stroke, Ui, Visuals, - pos2, vec2, -}; -use trainer::repertoire::{LearningSnapshot, ScheduledBuckets, SequenceHistograms}; - -use crate::i18n::tr; - -const CHART_HEIGHT: f32 = 180.0; -const HISTORY_DATE_HEIGHT: f32 = 18.0; -const SCHEDULED_LABEL_HEIGHT: f32 = 40.0; -const HISTOGRAM_LABEL_HEIGHT: f32 = 28.0; -const MAX_HISTOGRAM_BARS: usize = 12; -const WIDE_SEQUENCE_WIDTH: f32 = 900.0; - -#[derive(Clone, Copy)] -enum Marker { - Circle, - Square, - Diamond, -} - -type HistorySeries = (Color32, Marker, fn(&LearningSnapshot) -> usize); - -impl Marker { - fn paint(self, painter: &Painter, center: Pos2, color: Color32) { - match self { - Self::Circle => { - painter.circle_filled(center, 2.8, color); - } - Self::Square => { - painter.rect_filled(Rect::from_center_size(center, vec2(5.2, 5.2)), 0.0, color); - } - Self::Diamond => { - painter.add(Shape::convex_polygon( - vec![ - pos2(center.x, center.y - 3.4), - pos2(center.x + 3.4, center.y), - pos2(center.x, center.y + 3.4), - pos2(center.x - 3.4, center.y), - ], - color, - Stroke::NONE, - )); - } - } - } -} - -pub fn history(ui: &mut Ui, snapshots: &[LearningSnapshot]) { - if snapshots.is_empty() { - return; - } - let palette = series_palette(ui.visuals()); - history_legend(ui, &palette); - ui.add_space(4.0); - - let mut ordered = snapshots.iter().collect::>(); - ordered.sort_by_key(|snapshot| snapshot.as_of); - let (Some(first), Some(last)) = (ordered.first(), ordered.last()) else { - return; - }; - let start = first.as_of; - let end = last.as_of; - let max_value = snapshots.iter().fold(0_usize, |max, snapshot| { - max.max(snapshot.learning) - .max(snapshot.learnt) - .max(snapshot.uncertain) - }); - - let (rect, painter) = chart_area(ui); - let plot = plot_rect(&painter, rect, max_value, HISTORY_DATE_HEIGHT); - draw_axes(&painter, plot, max_value, ui.visuals()); - - let series: [HistorySeries; 3] = [ - (palette[0], Marker::Circle, |snapshot| snapshot.learning), - (palette[1], Marker::Square, |snapshot| snapshot.learnt), - (palette[2], Marker::Diamond, |snapshot| snapshot.uncertain), - ]; - for (color, marker, value) in series { - let points = ordered - .iter() - .map(|snapshot| { - pos2( - time_x(snapshot.as_of, start, end, plot.left(), plot.right()), - value_y(value(snapshot), max_value, plot.top(), plot.bottom()), - ) - }) - .collect::>(); - if points.len() >= 2 { - painter.add(Shape::line(points.clone(), Stroke::new(1.6, color))); - } - for point in points { - marker.paint(&painter, point, color); - } - } - - let text_color = ui.visuals().weak_text_color(); - if ordered.len() == 1 { - painter.text( - pos2(plot.center().x, rect.bottom()), - Align2::CENTER_BOTTOM, - &first.date, - label_font(), - text_color, - ); - } else { - painter.text( - pos2(plot.left(), rect.bottom()), - Align2::LEFT_BOTTOM, - &first.date, - label_font(), - text_color, - ); - painter.text( - pos2(plot.right(), rect.bottom()), - Align2::RIGHT_BOTTOM, - &last.date, - label_font(), - text_color, - ); - } -} - -pub fn scheduled(ui: &mut Ui, buckets: ScheduledBuckets) { - let rows = [ - (tr("Overdue").to_owned(), buckets.overdue), - (tr("Today").to_owned(), buckets.today), - (tr("Next 7 days").to_owned(), buckets.week), - (tr("Next 30 days").to_owned(), buckets.month), - (tr("Next 365 days").to_owned(), buckets.year), - (tr("Later").to_owned(), buckets.later), - ]; - let color = series_palette(ui.visuals())[0]; - bar_chart(ui, &rows, color, SCHEDULED_LABEL_HEIGHT, 56.0); -} - -pub fn sequences(ui: &mut Ui, histograms: &SequenceHistograms) { - let correct = histogram_rows(&histograms.correct_streak); - let wrong = histogram_rows(&histograms.wrong_streak); - let attempts = histogram_rows(&histograms.attempts); - let palette = series_palette(ui.visuals()); - - if ui.available_width() >= WIDE_SEQUENCE_WIDTH { - ui.columns(3, |columns| { - sequence_chart(&mut columns[0], "Correct streak", &correct, palette[1]); - sequence_chart(&mut columns[1], "Wrong streak", &wrong, palette[2]); - sequence_chart(&mut columns[2], "Attempts", &attempts, palette[0]); - }); - } else { - sequence_chart(ui, "Correct streak", &correct, palette[1]); - sequence_chart(ui, "Wrong streak", &wrong, palette[2]); - sequence_chart(ui, "Attempts", &attempts, palette[0]); - } -} - -fn history_legend(ui: &mut Ui, palette: &[Color32; 3]) { - ui.horizontal_wrapped(|ui| { - for (key, color, marker) in [ - ("Still learning", palette[0], Marker::Circle), - ("Learnt moves", palette[1], Marker::Square), - ("Long overdue learnt moves", palette[2], Marker::Diamond), - ] { - ui.horizontal(|ui| { - let (rect, _) = ui.allocate_exact_size(vec2(18.0, 12.0), Sense::hover()); - let painter = ui.painter().with_clip_rect(rect); - let y = rect.center().y; - painter.line_segment( - [pos2(rect.left(), y), pos2(rect.right(), y)], - Stroke::new(1.6, color), - ); - marker.paint(&painter, rect.center(), color); - ui.label(tr(key)); - }); - } - }); -} - -fn sequence_chart(ui: &mut Ui, title: &'static str, rows: &[(String, usize)], color: Color32) { - ui.add(egui::Label::new(RichText::new(tr(title)).strong()).truncate()); - ui.add_space(4.0); - bar_chart(ui, rows, color, HISTOGRAM_LABEL_HEIGHT, 38.0); - ui.add_space(10.0); -} - -fn chart_area(ui: &mut Ui) -> (Rect, Painter) { - let width = ui.available_width().max(1.0); - let (rect, _) = ui.allocate_exact_size(vec2(width, CHART_HEIGHT), Sense::hover()); - let painter = ui.painter().with_clip_rect(rect); - (rect, painter) -} - -fn plot_rect(painter: &Painter, rect: Rect, max_value: usize, label_height: f32) -> Rect { - let text_color = Color32::TRANSPARENT; - let y_label_width = [max_value.to_string(), "0".to_owned()] - .into_iter() - .map(|label| { - painter - .layout_no_wrap(label, label_font(), text_color) - .size() - .x - }) - .fold(0.0_f32, f32::max); - let reserved = (y_label_width + 8.0).min((rect.width() - 32.0).max(0.0)); - let right = (rect.right() - 4.0).max(rect.left()); - let left = (rect.left() + reserved).min(right); - let top = (rect.top() + 6.0).min(rect.bottom()); - let bottom = (rect.bottom() - label_height).max(top).min(rect.bottom()); - Rect::from_min_max(pos2(left, top), pos2(right, bottom)) -} - -fn draw_axes(painter: &Painter, plot: Rect, max_value: usize, visuals: &Visuals) { - let grid_color = visuals.weak_text_color().gamma_multiply(0.18); - for y in [plot.top(), plot.center().y, plot.bottom()] { - painter.line_segment( - [pos2(plot.left(), y), pos2(plot.right(), y)], - Stroke::new(1.0, grid_color), - ); - } - let axis_color = visuals.weak_text_color().gamma_multiply(0.55); - painter.line_segment( - [plot.left_top(), plot.left_bottom()], - Stroke::new(1.0, axis_color), - ); - painter.line_segment( - [plot.left_bottom(), plot.right_bottom()], - Stroke::new(1.0, axis_color), - ); - let text_color = visuals.weak_text_color(); - painter.text( - pos2(plot.left() - 6.0, plot.top()), - Align2::RIGHT_TOP, - max_value, - label_font(), - text_color, - ); - painter.text( - pos2(plot.left() - 6.0, plot.bottom()), - Align2::RIGHT_BOTTOM, - 0, - label_font(), - text_color, - ); -} - -fn bar_chart( - ui: &mut Ui, - rows: &[(String, usize)], - color: Color32, - label_height: f32, - max_bar_width: f32, -) { - let max_value = rows.iter().map(|(_, count)| *count).max().unwrap_or(0); - let (rect, painter) = chart_area(ui); - let plot = plot_rect(&painter, rect, max_value, label_height); - draw_axes(&painter, plot, max_value, ui.visuals()); - if rows.is_empty() { - return; - } - - let slot_width = (plot.width() / rows.len() as f32).max(0.0); - let text_color = ui.visuals().weak_text_color(); - for (index, (label, count)) in rows.iter().enumerate() { - let center = plot.left() + (index as f32 + 0.5) * slot_width; - if *count > 0 && max_value > 0 { - let width = (slot_width - 6.0).max(0.0).min(max_bar_width); - if width > 0.0 { - let top = value_y(*count, max_value, plot.top(), plot.bottom()); - painter.rect_filled( - Rect::from_min_max( - pos2(center - width / 2.0, top), - pos2(center + width / 2.0, plot.bottom()), - ), - 0.0, - color, - ); - } - } - let galley = painter.layout(label.clone(), label_font(), text_color, slot_width.max(1.0)); - painter.galley( - pos2( - center - galley.size().x / 2.0, - rect.bottom() - galley.size().y, - ), - galley, - text_color, - ); - } -} - -fn value_y(value: usize, max_value: usize, top: f32, bottom: f32) -> f32 { - if max_value == 0 { - return bottom; - } - let fraction = (value as f64 / max_value as f64).clamp(0.0, 1.0) as f32; - bottom - (bottom - top) * fraction -} - -fn time_x(at: i64, start: i64, end: i64, left: f32, right: f32) -> f32 { - if start == end { - return (left + right) / 2.0; - } - let numerator = i128::from(at) - i128::from(start); - let denominator = i128::from(end) - i128::from(start); - let fraction = (numerator as f64 / denominator as f64).clamp(0.0, 1.0) as f32; - left + (right - left) * fraction -} - -fn histogram_rows(histogram: &BTreeMap) -> Vec<(String, usize)> { - if histogram.len() <= MAX_HISTOGRAM_BARS { - return histogram - .iter() - .map(|(value, count)| (value.to_string(), *count)) - .collect(); - } - - let mut rows = histogram - .iter() - .take(MAX_HISTOGRAM_BARS - 1) - .map(|(value, count)| (value.to_string(), *count)) - .collect::>(); - if let Some((value, _)) = histogram.iter().nth(MAX_HISTOGRAM_BARS - 1) { - let count = histogram - .iter() - .skip(MAX_HISTOGRAM_BARS - 1) - .fold(0_usize, |sum, (_, count)| sum.saturating_add(*count)); - rows.push((format!("{value}+"), count)); - } - rows -} - -fn series_palette(visuals: &Visuals) -> [Color32; 3] { - if visuals.dark_mode { - [ - Color32::from_rgb(112, 184, 232), - Color32::from_rgb(126, 200, 150), - Color32::from_rgb(232, 174, 100), - ] - } else { - [ - Color32::from_rgb(35, 105, 155), - Color32::from_rgb(45, 125, 80), - Color32::from_rgb(170, 95, 35), - ] - } -} - -fn label_font() -> FontId { - FontId::proportional(12.0) -} - -#[cfg(test)] -mod tests { - use trainer::repertoire::{LearningSide, LocalDatePolicy, StatsScope}; - - use super::*; - - fn snapshot( - at: i64, - date: &str, - learning: usize, - learnt: usize, - uncertain: usize, - ) -> LearningSnapshot { - LearningSnapshot { - date: date.to_owned(), - scope: StatsScope::new(Vec::new(), LearningSide::White, at), - as_of: at, - timezone: LocalDatePolicy::UTC, - total: learning + learnt, - unseen: 0, - learning, - learnt, - uncertain, - due: 0, - } - } - - fn input(width: f32, height: f32) -> egui::RawInput { - egui::RawInput { - screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(width, height))), - time: Some(0.0), - ..Default::default() - } - } - - #[test] - fn value_scaling_has_stable_endpoints() { - assert_eq!(value_y(0, 20, 10.0, 150.0), 150.0); - assert_eq!(value_y(20, 20, 10.0, 150.0), 10.0); - assert_eq!(value_y(10, 20, 10.0, 150.0), 80.0); - } - - #[test] - fn zero_scaling_stays_on_the_baseline() { - assert_eq!(value_y(0, 0, 10.0, 150.0), 150.0); - } - - #[test] - fn one_time_point_is_centered() { - assert_eq!(time_x(42, 42, 42, 20.0, 220.0), 120.0); - } - - #[test] - fn time_scaling_handles_the_full_timestamp_range() { - assert_eq!(time_x(i64::MIN, i64::MIN, i64::MAX, 20.0, 220.0), 20.0); - assert_eq!(time_x(i64::MAX, i64::MIN, i64::MAX, 20.0, 220.0), 220.0); - let middle = time_x(0, i64::MIN, i64::MAX, 20.0, 220.0); - assert!((middle - 120.0).abs() < 0.001); - } - - #[test] - fn histogram_tail_preserves_zero_and_total() { - let histogram = (0_u64..25).map(|value| (value, 1_usize)).collect(); - let rows = histogram_rows(&histogram); - assert_eq!(rows.len(), MAX_HISTOGRAM_BARS); - assert_eq!(rows[0], ("0".to_owned(), 1)); - assert_eq!(rows.last(), Some(&("11+".to_owned(), 14))); - assert_eq!(rows.iter().map(|(_, count)| count).sum::(), 25); - } - - #[test] - fn one_snapshot_paints_a_visible_marker() { - let snapshots = [snapshot(42, "2026-11-04", 2, 3, 1)]; - let ctx = egui::Context::default(); - let output = ctx.run_ui(input(640.0, 480.0), |ui| history(ui, &snapshots)); - assert!( - output - .shapes - .iter() - .any(|clipped| matches!(&clipped.shape, Shape::Circle(_))) - ); - output.drop_without_applying_deltas(); - } - - #[test] - fn charts_render_wide_narrow_light_and_dark_without_horizontal_overflow() { - let snapshots = vec![ - snapshot(100, "2026-11-02", 8, 2, 0), - snapshot(200, "2026-11-03", 5, 5, 1), - snapshot(300, "2026-11-04", 3, 9, 2), - ]; - let scheduled_buckets = ScheduledBuckets { - overdue: 4, - today: 2, - week: 7, - month: 3, - year: 5, - later: 1, - }; - let histograms = SequenceHistograms { - correct_streak: (0_u32..18).map(|key| (key, 2)).collect(), - wrong_streak: BTreeMap::from([(0, 8), (1, 3), (2, 1)]), - attempts: (0_u64..16).map(|key| (key, 1)).collect(), - }; - - for visuals in [Visuals::light(), Visuals::dark()] { - for (width, height) in [(1400.0, 900.0), (640.0, 480.0)] { - let ctx = egui::Context::default(); - ctx.set_visuals(visuals.clone()); - for _ in 0..2 { - let output = ctx.run_ui(input(width, height), |ui| { - history(ui, &snapshots); - ui.separator(); - scheduled(ui, scheduled_buckets); - ui.separator(); - sequences(ui, &histograms); - }); - assert!(!output.shapes.is_empty()); - for clipped in &output.shapes { - let bounds = clipped - .shape - .visual_bounding_rect() - .intersect(clipped.clip_rect); - if bounds.is_finite() && bounds.is_positive() { - assert!( - bounds.min.x >= -0.5 && bounds.max.x <= width + 0.5, - "horizontal overflow at {width}x{height}: {bounds:?}" - ); - } - } - output.drop_without_applying_deltas(); - } - } - } - } - - #[test] - fn empty_and_all_zero_inputs_render() { - let zero_histograms = SequenceHistograms { - correct_streak: BTreeMap::from([(0, 0)]), - wrong_streak: BTreeMap::from([(0, 0)]), - attempts: BTreeMap::from([(0_u64, 0)]), - }; - let ctx = egui::Context::default(); - let output = ctx.run_ui(input(640.0, 480.0), |ui| { - history(ui, &[]); - scheduled(ui, ScheduledBuckets::default()); - sequences(ui, &SequenceHistograms::default()); - sequences(ui, &zero_histograms); - }); - assert!(!output.shapes.is_empty()); - output.drop_without_applying_deltas(); - } -} diff --git a/apps/desktop/src/learning_context_controls.rs b/apps/desktop/src/learning_context_controls.rs deleted file mode 100644 index fca2448..0000000 --- a/apps/desktop/src/learning_context_controls.rs +++ /dev/null @@ -1,204 +0,0 @@ -use trainer::repertoire::LearningContextPolicy; - -use crate::i18n::tr; - -fn hint(ui: &mut egui::Ui, text: &'static str) { - ui.add(egui::Label::new(egui::RichText::new(tr(text)).weak()).wrap()); -} - -pub fn show(ui: &mut egui::Ui, policy: &mut LearningContextPolicy) -> bool { - let before = *policy; - ui.strong(tr("Moves before the task")); - hint(ui, "The app shows the moves leading to the task position."); - ui.add_space(6.0); - ui.checkbox( - &mut policy.consider_leadup_moves, - tr("Ask me to play preceding moves"), - ); - ui.add_enabled_ui( - policy.consider_leadup_moves || !policy.use_fixed_piece_speed, - |ui| { - ui.horizontal_wrapped(|ui| { - ui.label(tr("Correct answers in a row")); - ui.add( - egui::DragValue::new(&mut policy.reinforce_minimum_correct).range(0..=u32::MAX), - ); - }); - }, - ); - hint( - ui, - "Ask until this streak is reached. This also sets the maximum acceleration point for adaptive playback.", - ); - ui.add_space(6.0); - ui.add_enabled_ui(policy.consider_leadup_moves, |ui| { - let mut enabled = policy.reinforce_minimum_days.is_some(); - if ui - .checkbox(&mut enabled, tr("Review ahead of schedule")) - .changed() - { - policy.reinforce_minimum_days = enabled.then_some(7); - } - ui.add_enabled_ui(enabled, |ui| { - ui.horizontal_wrapped(|ui| { - ui.label(tr("Days before the due date")); - let mut days = policy.reinforce_minimum_days.unwrap_or(7); - if ui - .add(egui::DragValue::new(&mut days).range(0..=u32::MAX)) - .changed() - { - policy.reinforce_minimum_days = Some(days); - } - }); - }); - }); - hint(ui, "Also ask moves that are already due."); - ui.add_space(10.0); - ui.separator(); - ui.strong(tr("Skip a familiar opening")); - ui.horizontal_wrapped(|ui| { - ui.label(tr("Skip after this many correct answers in a row")); - ui.add( - egui::DragValue::new(&mut policy.dont_show_start_moves_threshold).range(0..=u32::MAX), - ); - }); - hint( - ui, - "Each of your opening moves must reach this streak. 0 means always show the opening.", - ); - ui.add_space(10.0); - ui.separator(); - ui.strong(tr("Playback speed")); - let mut adaptive = !policy.use_fixed_piece_speed; - if ui - .checkbox(&mut adaptive, tr("Speed up familiar moves")) - .changed() - { - policy.use_fixed_piece_speed = !adaptive; - } - hint( - ui, - "Base animation speed comes from board settings. Familiar moves play up to twice as fast.", - ); - if adaptive { - ui.horizontal_wrapped(|ui| { - ui.label(tr("Base speed multiplier")); - ui.add(egui::DragValue::new(&mut policy.move_speed_adjustment) - .range(-2.0..=2.0).speed(0.05).fixed_decimals(2).suffix(" ×")) - .on_hover_text(tr("Range −2…2. Adaptive speed = adjustment × (1 + learned fraction), limited to 0.25×–4×: 1.5 gives 3× for a fully learned move; 0 or less gives 0.25×.")); - }); - hint(ui, "0 or less uses the minimum speed (0.25×)."); - } - ui.add_space(6.0); - hint(ui, "Learning counters do not use these playback settings."); - *policy != before -} - -#[cfg(test)] -mod tests { - use super::*; - - fn render( - ctx: &egui::Context, - width: f32, - height: f32, - container_width: f32, - time: f64, - events: Vec, - policy: &mut LearningContextPolicy, - ) -> (Vec, bool, egui::Rect) { - let mut changed = false; - let mut container = - egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(container_width, height)); - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - time: Some(time), - events, - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - let available = ui.available_rect_before_wrap(); - container = egui::Rect::from_min_size( - available.min, - egui::vec2(container_width, available.height()), - ); - ui.scope_builder(egui::UiBuilder::new().max_rect(container), |ui| { - ui.set_clip_rect(container); - changed = show(ui, policy); - }); - }); - }, - ); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - (shapes, changed, container) - } - - fn text_rect(shapes: &[egui::epaint::ClippedShape], key: &'static str) -> Option { - let translations = crate::i18n::all_languages(key); - shapes.iter().find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) - if translations - .iter() - .any(|candidate| *candidate == text.galley.text()) => - { - Some(egui::Rect::from_min_size(text.pos, text.galley.size())) - } - _ => None, - }) - } - - fn text_position( - shapes: &[egui::epaint::ClippedShape], - key: &'static str, - ) -> Option { - text_rect(shapes, key).map(|rect| rect.min + egui::vec2(8.0, 6.0)) - } - - fn click(position: egui::Pos2) -> Vec { - vec![ - egui::Event::PointerMoved(position), - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }, - ] - } - - #[test] - fn context_options_preserve_values_until_changed_and_enable_dependencies() { - let ctx = egui::Context::default(); - let mut policy = LearningContextPolicy::default(); - let (shapes, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 0.0, Vec::new(), &mut policy); - assert!(!changed); - assert_eq!(policy, LearningContextPolicy::default()); - let leadup = text_position(&shapes, "Ask me to play preceding moves").unwrap(); - let (_, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 1.0, click(leadup), &mut policy); - assert!(changed); - assert!(policy.consider_leadup_moves); - let (shapes, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 2.0, Vec::new(), &mut policy); - assert!(!changed); - let days = text_position(&shapes, "Review ahead of schedule").unwrap(); - let (_, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 3.0, click(days), &mut policy); - assert!(changed); - assert_eq!(policy.reinforce_minimum_days, Some(7)); - let speed = text_position(&shapes, "Speed up familiar moves").unwrap(); - let (_, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 4.0, click(speed), &mut policy); - assert!(changed); - assert!(!policy.use_fixed_piece_speed); - assert_eq!(policy.move_speed_adjustment, 1.0); - } -} diff --git a/apps/desktop/src/learning_dashboard.rs b/apps/desktop/src/learning_dashboard.rs deleted file mode 100644 index 55cad56..0000000 --- a/apps/desktop/src/learning_dashboard.rs +++ /dev/null @@ -1,1968 +0,0 @@ -use std::{ - collections::HashMap, - sync::mpsc::{self, Receiver, Sender}, - time::Duration, -}; - -use chess_core::shakmaty::{CastlingMode, Chess, fen::Fen, san::San, uci::UciMove}; -use egui::{Align, Key, Layout, Modifiers, RichText, Ui}; -use egui_extras::{Column, TableBuilder}; -use trainer::repertoire::{ - BranchLearningAnalytics, LearningAggregate, LearningItemKey, LearningSide, LearningSnapshot, - LearningStore, LearningStoreData, Library, LocalDatePolicy, MoveLearningStatus, - PersistedLearningSnapshot, RepertoireId, RepertoireTree, ScheduledBuckets, SequenceHistograms, - SrsSettings, StatsScope, aggregate_scope, branch_learning_analytics, - log_global_total_invariant, scheduled_buckets, scoped_move_learning_analytics, - sequence_histograms, -}; - -use crate::i18n::{tr, trf}; -use crate::learning_branches::BranchSelection; -use crate::settings::Settings; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum LearningDashboardAction { - Close, - OpenSettings, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -enum ScopeSelection { - Global, - Repertoire(RepertoireId), -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -enum DashboardTab { - #[default] - Summary, - Branches, - History, - Scheduled, - Sequences, - Moves, -} - -struct SummaryRow { - id: Option, - name: String, - summary: LearningAggregate, -} - -struct DashboardView { - selection: ScopeSelection, - scope: StatsScope, - summary: LearningAggregate, - branches: Vec, - history: Vec, - scheduled: ScheduledBuckets, - sequences: SequenceHistograms, - moves: Vec, -} - -struct DashboardData { - as_of: i64, - timezone: LocalDatePolicy, - summary: Vec, - views: Vec, - names: HashMap, - labels: HashMap<(RepertoireId, Vec), Vec>, -} - -#[cfg(test)] -std::thread_local! { - static GLOBAL_TOTAL_INVARIANT_CALLS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -fn log_dashboard_global_total_invariant(global_total: usize, summary: &[SummaryRow]) { - log_global_total_invariant( - global_total, - summary - .iter() - .filter(|row| row.id.is_some()) - .map(|row| row.summary.total), - ); - #[cfg(test)] - GLOBAL_TOTAL_INVARIANT_CALLS.with(|calls| calls.set(calls.get() + 1)); -} - -struct MoveRow { - key: LearningItemKey, - san: String, - status: MoveLearningStatus, - resistant: bool, - accuracy_percent: Option, - independent_attempts: u64, - correct_count: u64, - wrong_count: u64, - correct_streak: u32, - wrong_streak: u32, - next_review_at: Option, - review_in_seconds: Option, - overdue_seconds: Option, - uncertain_grace_seconds: Option, - response_time_median_ms: Option, - wrong_moves: Vec, - memberships: Vec, -} - -struct WrongMoveRow { - san: String, - count: u64, - last_at: i64, -} - -struct MembershipRow { - repertoire: String, - branch: Vec, -} - -enum Event { - Loaded(u64, Box>), - Snapshot(u64, Box>), -} - -pub struct LearningDashboardUi { - library: Library, - learning_store: LearningStore, - selection: ScopeSelection, - side: LearningSide, - tab: DashboardTab, - data: Option, - loading: bool, - error: Option, - snapshot_pending: bool, - snapshot_message: Option, - snapshot_error: Option, - automatic_snapshot_scope: Option, - selected_move: Option, - selected_branch: Option, - generation: u64, - tx: Sender, - rx: Receiver, -} - -impl LearningDashboardUi { - pub fn new(library: Library, learning_store: LearningStore) -> Self { - Self::with_selection( - library, - learning_store, - ScopeSelection::Global, - LearningSide::White, - ) - } - - pub fn new_for_repertoire( - library: Library, - learning_store: LearningStore, - repertoire: RepertoireId, - side: LearningSide, - ) -> Self { - let selection = if library.repertoire(&repertoire).is_some() { - ScopeSelection::Repertoire(repertoire) - } else { - ScopeSelection::Global - }; - Self::with_selection(library, learning_store, selection, side) - } - - fn with_selection( - library: Library, - learning_store: LearningStore, - selection: ScopeSelection, - side: LearningSide, - ) -> Self { - let (tx, rx) = mpsc::channel(); - let mut this = Self { - library, - learning_store, - selection, - side, - tab: match std::env::var("CP_LEARNING_DASHBOARD_TAB").as_deref() { - Ok("branches") => DashboardTab::Branches, - Ok("history") => DashboardTab::History, - Ok("scheduled") => DashboardTab::Scheduled, - Ok("sequences") => DashboardTab::Sequences, - Ok("moves") => DashboardTab::Moves, - _ => DashboardTab::Summary, - }, - data: None, - loading: false, - error: None, - snapshot_pending: false, - snapshot_message: None, - snapshot_error: None, - automatic_snapshot_scope: None, - selected_move: None, - selected_branch: None, - generation: 0, - tx, - rx, - }; - this.reload(); - this - } - - #[cfg(test)] - pub fn selected_repertoire(&self) -> Option<&RepertoireId> { - match &self.selection { - ScopeSelection::Global => None, - ScopeSelection::Repertoire(id) => Some(id), - } - } - - #[cfg(test)] - pub fn selected_side(&self) -> LearningSide { - self.side - } - - #[cfg(test)] - pub fn wait_until_idle_for_test(&mut self) { - while self.loading || self.snapshot_pending { - let event = self - .rx - .recv_timeout(Duration::from_secs(5)) - .expect("learning dashboard background work timed out"); - self.tx.send(event).unwrap(); - self.poll(); - } - } - - pub fn show(&mut self, ui: &mut Ui, settings: &Settings) -> Vec { - crate::san::set(settings.move_notation); - self.poll(); - let mut actions = Vec::new(); - if !ui.ctx().egui_wants_keyboard_input() - && !crate::app::overlay_open(ui.ctx()) - && ui.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)) - { - actions.push(LearningDashboardAction::Close); - } - if self.loading || self.snapshot_pending { - ui.ctx().request_repaint_after(Duration::from_millis(100)); - } - - egui::Panel::top("learning_dashboard_header").show(ui, |ui| { - let back = if ui.available_width() < 600.0 { - tr("Back") - } else { - tr("Back to repertoire") - }; - let (back, settings) = - crate::widgets::section_header(ui, &format!("← {back}"), tr("Training statistics")); - if back { - actions.push(LearningDashboardAction::Close); - } - if settings { - actions.push(LearningDashboardAction::OpenSettings); - } - }); - egui::CentralPanel::default().show(ui, |ui| { - ui.add_space(4.0); - self.scope_controls(ui); - - self.tabs(ui); - ui.separator(); - if self.tab == DashboardTab::History { - self.capture_line(ui); - } - - egui::ScrollArea::vertical() - .id_salt("learning_dashboard_scroll") - .auto_shrink([false, false]) - .show(ui, |ui| { - ui.set_width(ui.available_width()); - if self.loading && self.data.is_none() { - loading_body(ui); - return; - } - if let Some(error) = self.error.clone() { - error_body(ui, &error); - if ui.button(tr("Retry")).clicked() { - self.reload(); - } - return; - } - let Some(data) = self.data.as_ref() else { - loading_body(ui); - return; - }; - let Some(view) = data - .views - .iter() - .find(|view| view.selection == self.selection) - else { - self.error = - Some(tr("The selected scope is no longer available").to_owned()); - return; - }; - match self.tab { - DashboardTab::Summary => show_summary(ui, data, view), - DashboardTab::Branches => crate::learning_branches::show( - ui, - &view.branches, - &data.names, - &data.labels, - &mut self.selected_branch, - ), - DashboardTab::History => show_history(ui, view), - DashboardTab::Scheduled => show_scheduled(ui, view), - DashboardTab::Sequences => show_sequences(ui, view), - DashboardTab::Moves => show_moves(ui, view, &mut self.selected_move), - } - }); - }); - actions - } - - fn reload(&mut self) { - self.load(false); - } - - fn refresh(&mut self) { - self.load(true); - } - - fn load(&mut self, preserve_data: bool) { - self.generation = self.generation.wrapping_add(1); - let generation = self.generation; - self.loading = true; - self.error = None; - if !preserve_data { - self.data = None; - } - let library = self.library.clone(); - let store = self.learning_store.clone(); - let side = self.side; - let tx = self.tx.clone(); - if let Err(error) = crate::platform::spawn("learning-dashboard", move || { - let result = store - .load() - .map_err(|error| error.to_string()) - .and_then(|data| { - let as_of = now(); - DashboardData::build(&library, &data, side, as_of, local_date_policy(as_of)) - }); - let _ = tx.send(Event::Loaded(generation, Box::new(result))); - }) { - self.loading = false; - self.error = Some(error.to_string()); - } - } - - fn poll(&mut self) { - while let Ok(event) = self.rx.try_recv() { - match event { - Event::Loaded(generation, result) if generation == self.generation => { - self.loading = false; - match *result { - Ok(data) => { - self.data = Some(data); - self.error = None; - self.ensure_snapshot_after_load(); - } - Err(error) => { - self.data = None; - self.error = Some(error); - } - } - } - Event::Snapshot(generation, result) if generation == self.generation => { - self.snapshot_pending = false; - match *result { - Ok(saved) => { - self.snapshot_error = None; - self.snapshot_message = Some(if saved.recorded { - trf( - "Snapshot captured: {date}", - &[("date", &saved.snapshot.date)], - ) - } else { - trf( - "Snapshot already exists for this date and scope: {date}", - &[("date", &saved.snapshot.date)], - ) - }); - if saved.recorded { - self.refresh(); - } - } - Err(error) => { - self.snapshot_message = None; - self.snapshot_error = Some(error); - } - } - } - _ => {} - } - } - } - - fn ensure_snapshot_after_load(&mut self) { - if self.snapshot_pending { - return; - } - let Some((scope, timezone)) = self.selected_capture() else { - return; - }; - if self - .automatic_snapshot_scope - .as_ref() - .is_some_and(|attempted| same_scope(attempted, &scope)) - { - return; - } - self.automatic_snapshot_scope = Some(scope.clone()); - self.capture_snapshot(scope, timezone); - } - - fn scope_controls(&mut self, ui: &mut Ui) { - let previous_side = self.side; - let previous_selection = self.selection.clone(); - let enabled = !self.loading && !self.snapshot_pending; - ui.add_enabled_ui(enabled, |ui| { - ui.horizontal_wrapped(|ui| { - ui.label(RichText::new(tr("Repertoire")).weak()) - .on_hover_text(format!( - "{}: {}", - tr("Calculated at"), - self.data - .as_ref() - .map_or_else(|| "…".to_owned(), |data| format_time(Some(data.as_of))) - )); - let selected_text = self.selection_label(&self.selection); - egui::ComboBox::from_id_salt("learning_dashboard_scope") - .selected_text(selected_text) - .width(260.0) - .truncate() - .show_ui(ui, |ui| { - ui.selectable_value( - &mut self.selection, - ScopeSelection::Global, - tr("All repertoires"), - ); - for repertoire in &self.library.repertoires { - ui.selectable_value( - &mut self.selection, - ScopeSelection::Repertoire(repertoire.id.clone()), - &repertoire.name, - ); - } - }); - ui.label(RichText::new(tr("Side")).weak()); - egui::ComboBox::from_id_salt("learning_dashboard_side") - .selected_text(side_label(self.side)) - .show_ui(ui, |ui| { - ui.selectable_value(&mut self.side, LearningSide::White, tr("White")); - ui.selectable_value(&mut self.side, LearningSide::Black, tr("Black")); - }); - }); - }); - if previous_selection != self.selection { - self.selected_branch = None; - self.snapshot_message = None; - self.snapshot_error = None; - } - if previous_side != self.side { - self.selected_move = None; - self.selected_branch = None; - self.snapshot_message = None; - self.snapshot_error = None; - self.reload(); - } else if previous_selection != self.selection { - self.ensure_snapshot_after_load(); - } - } - - fn selected_capture(&self) -> Option<(StatsScope, LocalDatePolicy)> { - let data = self.data.as_ref()?; - let view = data - .views - .iter() - .find(|view| view.selection == self.selection)?; - Some((view.scope.clone(), data.timezone)) - } - - fn capture_line(&mut self, ui: &mut Ui) { - ui.label( - egui::RichText::new(tr("History is saved automatically once a day when viewed.")) - .weak(), - ); - if let Some(error) = self.snapshot_error.clone() { - ui.horizontal_wrapped(|ui| { - ui.colored_label(ui.visuals().error_fg_color, error); - if ui - .add_enabled(!self.snapshot_pending, egui::Button::new(tr("Retry"))) - .clicked() - && let Some((scope, timezone)) = self.selected_capture() - { - self.capture_snapshot(scope, timezone); - } - }); - } - } - - fn capture_snapshot(&mut self, scope: StatsScope, timezone: LocalDatePolicy) { - self.snapshot_pending = true; - self.snapshot_message = None; - self.snapshot_error = None; - let generation = self.generation; - let library = self.library.clone(); - let store = self.learning_store.clone(); - let tx = self.tx.clone(); - if let Err(error) = crate::platform::spawn("learning-dashboard-snapshot", move || { - let result = capture_snapshot(&store, &library, &scope, timezone); - let _ = tx.send(Event::Snapshot(generation, Box::new(result))); - }) { - self.snapshot_pending = false; - self.snapshot_error = Some(error.to_string()); - } - } - - fn tabs(&mut self, ui: &mut Ui) { - ui.horizontal_wrapped(|ui| { - for (tab, label) in [ - (DashboardTab::Summary, tr("Overview")), - (DashboardTab::History, tr("Progress over time")), - (DashboardTab::Scheduled, tr("Scheduled")), - (DashboardTab::Moves, tr("Moves")), - ] { - if ui.selectable_label(self.tab == tab, label).clicked() { - self.tab = tab; - } - } - let extra = match self.tab { - DashboardTab::Branches => tr("Variants"), - DashboardTab::Sequences => tr("Sequences"), - _ => tr("More statistics"), - }; - ui.menu_button(extra, |ui| { - for (tab, label) in [ - (DashboardTab::Branches, tr("Variants")), - (DashboardTab::Sequences, tr("Sequences")), - ] { - if ui.selectable_label(self.tab == tab, label).clicked() { - self.tab = tab; - ui.close(); - } - } - }); - }); - } - - fn selection_label(&self, selection: &ScopeSelection) -> String { - match selection { - ScopeSelection::Global => tr("All repertoires").to_owned(), - ScopeSelection::Repertoire(id) => self - .library - .repertoire(id) - .map(|repertoire| repertoire.name.clone()) - .unwrap_or_else(|| tr("The selected scope is no longer available").to_owned()), - } - } -} - -impl DashboardData { - fn build( - library: &Library, - data: &LearningStoreData, - side: LearningSide, - as_of: i64, - timezone: LocalDatePolicy, - ) -> Result { - let ids = library - .repertoires - .iter() - .map(|repertoire| repertoire.id.clone()) - .collect::>(); - let labels = membership_labels(library); - let names = library - .repertoires - .iter() - .map(|repertoire| (repertoire.id.clone(), repertoire.name.clone())) - .collect(); - let global_scope = StatsScope::new(ids, side, as_of); - let global = DashboardView::build( - library, - data, - ScopeSelection::Global, - global_scope, - timezone, - &labels, - )?; - let global_summary = global.summary.clone(); - let mut views = vec![global]; - let mut summary = Vec::with_capacity(library.repertoires.len() + 1); - for repertoire in &library.repertoires { - let scope = StatsScope::for_repertoire(repertoire.id.clone(), side, as_of); - let view = DashboardView::build( - library, - data, - ScopeSelection::Repertoire(repertoire.id.clone()), - scope, - timezone, - &labels, - )?; - summary.push(SummaryRow { - id: Some(repertoire.id.clone()), - name: repertoire.name.clone(), - summary: view.summary.clone(), - }); - views.push(view); - } - let global_total = global_summary.total; - summary.push(SummaryRow { - id: None, - name: String::new(), - summary: global_summary, - }); - log_dashboard_global_total_invariant(global_total, &summary); - Ok(Self { - as_of, - timezone, - summary, - views, - names, - labels, - }) - } -} - -impl DashboardView { - fn build( - library: &Library, - data: &LearningStoreData, - selection: ScopeSelection, - scope: StatsScope, - timezone: LocalDatePolicy, - labels: &HashMap<(RepertoireId, Vec), Vec>, - ) -> Result { - let settings = SrsSettings::default(); - let scoped = aggregate_scope(library, &data.learning, &scope, &settings) - .map_err(|error| error.to_string())?; - let scheduled = scheduled_buckets(scoped.items.iter(), scope.as_of, timezone); - let sequences = sequence_histograms(scoped.items.iter()); - let branches = branch_learning_analytics(library, &data.learning, &scope, &settings) - .map_err(|error| error.to_string())?; - let analytics = scoped_move_learning_analytics(library, &data.learning, &scope, &settings) - .map_err(|error| error.to_string())?; - let names = library - .repertoires - .iter() - .map(|repertoire| (repertoire.id.clone(), repertoire.name.clone())) - .collect::>(); - let moves = analytics - .into_iter() - .map(|analytics| { - let mut wrong_moves = analytics - .wrong_move_histogram - .iter() - .map(|(uci, stats)| WrongMoveRow { - san: san_from_fen4(&analytics.key.position_fen4, uci) - .unwrap_or_else(|| "—".to_owned()), - count: stats.count, - last_at: stats.last_at, - }) - .collect::>(); - wrong_moves.sort_by(|left, right| { - right - .count - .cmp(&left.count) - .then_with(|| right.last_at.cmp(&left.last_at)) - .then_with(|| left.san.cmp(&right.san)) - }); - let memberships = analytics - .memberships - .iter() - .map(|membership| MembershipRow { - repertoire: names - .get(&membership.repertoire_id) - .cloned() - .unwrap_or_else(|| "—".to_owned()), - branch: labels - .get(&(membership.repertoire_id.clone(), membership.path.clone())) - .cloned() - .unwrap_or_default(), - }) - .collect(); - MoveRow { - san: san_from_fen4(&analytics.key.position_fen4, &analytics.key.expected_uci) - .unwrap_or_else(|| "—".to_owned()), - key: analytics.key, - status: analytics.status, - resistant: analytics.resistant, - accuracy_percent: analytics.accuracy_percent, - independent_attempts: analytics.independent_attempts, - correct_count: analytics.correct_count, - wrong_count: analytics.wrong_count, - correct_streak: analytics.correct_streak, - wrong_streak: analytics.wrong_streak, - next_review_at: analytics.next_review_at, - review_in_seconds: analytics.review_in_seconds, - overdue_seconds: analytics.overdue_seconds, - uncertain_grace_seconds: analytics.uncertain_grace_seconds, - response_time_median_ms: analytics.response_time_median_ms, - wrong_moves, - memberships, - } - }) - .collect(); - let history = data - .snapshots - .iter() - .filter(|snapshot| same_scope(&snapshot.scope, &scope)) - .cloned() - .collect(); - Ok(Self { - selection, - scope, - summary: scoped.summary, - branches, - history, - scheduled, - sequences, - moves, - }) - } -} - -fn capture_snapshot( - store: &LearningStore, - library: &Library, - scope: &StatsScope, - timezone: LocalDatePolicy, -) -> Result { - store - .record_snapshot(library, scope, &SrsSettings::default(), timezone) - .map_err(|error| error.to_string()) -} - -fn same_scope(left: &StatsScope, right: &StatsScope) -> bool { - let mut left = left.clone(); - let mut right = right.clone(); - left.as_of = 0; - right.as_of = 0; - left == right -} - -fn membership_labels(library: &Library) -> HashMap<(RepertoireId, Vec), Vec> { - let mut result = HashMap::new(); - for repertoire in &library.repertoires { - let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); - let game = tree.game(); - for node in game.attached_nodes() { - let Some(path) = tree.path(node) else { - continue; - }; - let labels = game - .path(node) - .into_iter() - .skip(1) - .filter_map(|id| game.move_label(id)) - .collect::>(); - result.insert((repertoire.id.clone(), path.to_vec()), labels); - } - } - result -} - -fn san_from_fen4(position_fen4: &str, uci: &str) -> Option { - let fen = format!("{position_fen4} 0 1").parse::().ok()?; - let position = fen.into_position::(CastlingMode::Standard).ok()?; - let mv = uci.parse::().ok()?.to_move(&position).ok()?; - Some(San::from_move(&position, mv).to_string()) -} - -fn loading_body(ui: &mut Ui) { - ui.allocate_ui_with_layout( - egui::vec2(ui.available_width(), 160.0), - Layout::top_down(Align::Min), - |ui| { - ui.add_space(24.0); - ui.horizontal(|ui| { - ui.spinner(); - ui.label(tr("Loading learning statistics…")); - }); - }, - ); -} - -fn error_body(ui: &mut Ui, error: &str) { - ui.allocate_ui_with_layout( - egui::vec2(ui.available_width(), 120.0), - Layout::top_down(Align::Min), - |ui| { - ui.add_space(12.0); - ui.colored_label(ui.visuals().error_fg_color, error); - }, - ); -} - -fn show_summary(ui: &mut Ui, data: &DashboardData, view: &DashboardView) { - let summary = &view.summary; - ui.add_space(8.0); - ui.heading(trf( - "Learnt {learnt} of {total} moves", - &[("learnt", &summary.learnt), ("total", &summary.total)], - )) - .on_hover_text(tr("A move is learnt after 3 correct answers in a row without hints. Only main replies for the selected colour count; shared positions count once. A wrong answer resets the streak.")); - ui.add_space(8.0); - ui.add( - egui::ProgressBar::new(summary.learnt_percent.unwrap_or(0.0) as f32 / 100.0) - .desired_width(ui.available_width().min(600.0)) - .text(format_percent(summary.learnt_percent)), - ); - ui.add_space(12.0); - egui::Grid::new("learning_overview_counts") - .spacing([24.0, 10.0]) - .show(ui, |ui| { - for (label, value) in [ - ("Due now", summary.due), - ("Not practised yet", summary.unseen), - ("Still learning", summary.learning), - ("Long overdue learnt moves", summary.uncertain), - ] { - let response = ui.label(tr(label)); - if label == "Long overdue learnt moves" { - response.on_hover_text(tr("Of the moves already learnt")); - } - ui.strong(value.to_string()); - ui.end_row(); - } - }); - ui.add_space(8.0); - ui.label(tr( - "Progress counts your repertoire moves, with shared positions counted once.", - )); - ui.add_space(12.0); - egui::CollapsingHeader::new(tr("Learning details")).show(ui, |ui| { - egui::Grid::new("learning_overview_details") - .spacing([24.0, 8.0]) - .show(ui, |ui| { - for (label, value) in [ - ("Accuracy", format_percent(summary.accuracy_percent)), - ("Confident %", format_percent(summary.confident_percent)), - ("Next review", format_time(summary.next_due_at)), - ] { - ui.label(tr(label)); - ui.label(value); - ui.end_row(); - } - }); - ui.label(tr( - "Learnt = Confident + Uncertain · percentages use Total.", - )); - }); - if view.selection != ScopeSelection::Global { - return; - } - ui.add_space(16.0); - ui.strong(tr("All repertoires")); - let number_width = (ui.available_width() * 0.14).clamp(80.0, 140.0); - TableBuilder::new(ui) - .id_salt("learning_dashboard_summary") - .striped(true) - .vscroll(false) - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::remainder().at_least(160.0).clip(true)) - .column(Column::exact(number_width)) - .column(Column::exact(number_width)) - .column(Column::exact(number_width)) - .column(Column::exact(number_width)) - .header(40.0, |mut header| { - for (index, label) in ["Repertoire", "Learnt moves", "Learnt %", "Due now", "Not practised yet"].into_iter().enumerate() { - header.col(|ui| { header_cell(ui, tr(label), index > 0); }); - } - }) - .body(|body| { - body.rows(32.0, data.summary.len(), |mut row| { - let item = &data.summary[row.index()]; - let global = item.id.is_none(); - row.col(|ui| { - text_cell(ui, if global { tr("Total without duplicates") } else { &item.name }, global, false) - .on_hover_text(tr("Global total counts each shared learning item once; repertoire rows can add up to more.")); - }); - for text in [format!("{} / {}", item.summary.learnt, item.summary.total), format_percent(item.summary.learnt_percent), item.summary.due.to_string(), item.summary.unseen.to_string()] { - row.col(|ui| { text_cell(ui, &text, global, true); }); - } - }); - }); -} - -fn show_history(ui: &mut Ui, view: &DashboardView) { - if view.history.is_empty() { - ui.label(tr( - "Progress history will appear after your first daily snapshot.", - )); - return; - } - crate::learning_charts::history(ui, &view.history); - ui.add_space(8.0); - let number_width = (ui.available_width() * 0.18).clamp(100.0, 160.0); - let headers = ["Date", "Learnt moves", "Not practised yet", "Due now"]; - let mut table = TableBuilder::new(ui) - .id_salt("learning_dashboard_history") - .striped(true) - .max_scroll_height(360.0) - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::remainder().at_least(90.0).clip(true)); - for _ in 1..headers.len() { - table = table.column(Column::exact(number_width)); - } - table - .header(40.0, |mut header| { - for (index, key) in headers.into_iter().enumerate() { - header.col(|ui| { - header_cell(ui, tr(key), index > 0); - }); - } - }) - .body(|body| { - body.rows(24.0, view.history.len(), |mut row| { - let snapshot = &view.history[row.index()]; - row.col(|ui| { - text_cell(ui, &snapshot.date, false, false).on_hover_text(format!( - "{}: {}", - tr("Calculated at"), - format_time(Some(snapshot.as_of)) - )); - }); - let values = [snapshot.learnt, snapshot.unseen, snapshot.due]; - for value in values { - row.col(|ui| { - text_cell(ui, &value.to_string(), false, true); - }); - } - }); - }); -} - -fn show_scheduled(ui: &mut Ui, view: &DashboardView) { - let buckets = view.scheduled; - crate::learning_charts::scheduled(ui, buckets); - ui.add_space(8.0); - let rows = [ - (tr("Overdue").to_owned(), buckets.overdue), - (tr("Today").to_owned(), buckets.today), - (tr("Next 7 days").to_owned(), buckets.week), - (tr("Next 30 days").to_owned(), buckets.month), - (tr("Next 365 days").to_owned(), buckets.year), - (tr("Later").to_owned(), buckets.later), - ]; - distribution_table( - ui, - "learning_dashboard_scheduled", - "Scheduled", - "Scheduled", - &rows, - buckets.introduced(), - ) - .on_hover_text(tr( - "Today ends at local midnight; the other buckets use fixed 7, 30 and 365-day ranges.", - )); - ui.label(format!("{}: {}", tr("Introduced"), buckets.introduced())); -} - -fn show_sequences(ui: &mut Ui, view: &DashboardView) { - if view.moves.is_empty() { - ui.label(tr("No moves in this scope")); - return; - } - crate::learning_charts::sequences(ui, &view.sequences); - let correct = histogram_rows(&view.sequences.correct_streak); - let wrong = histogram_rows(&view.sequences.wrong_streak); - let attempts = histogram_rows(&view.sequences.attempts); - let total = view.moves.len(); - if ui.available_width() >= 900.0 { - ui.columns(3, |columns| { - distribution_table( - &mut columns[0], - "learning_dashboard_correct_sequences", - "Correct streak", - "Length / attempts", - &correct, - total, - ); - distribution_table( - &mut columns[1], - "learning_dashboard_wrong_sequences", - "Wrong streak", - "Length / attempts", - &wrong, - total, - ); - distribution_table( - &mut columns[2], - "learning_dashboard_attempt_sequences", - "Attempts", - "Length / attempts", - &attempts, - total, - ); - }); - } else { - distribution_table( - ui, - "learning_dashboard_correct_sequences", - "Correct streak", - "Length / attempts", - &correct, - total, - ); - distribution_table( - ui, - "learning_dashboard_wrong_sequences", - "Wrong streak", - "Length / attempts", - &wrong, - total, - ); - distribution_table( - ui, - "learning_dashboard_attempt_sequences", - "Attempts", - "Length / attempts", - &attempts, - total, - ); - } -} - -fn histogram_rows( - histogram: &std::collections::BTreeMap, -) -> Vec<(String, usize)> { - histogram - .iter() - .map(|(value, count)| (value.to_string(), *count)) - .collect() -} - -fn distribution_table( - ui: &mut Ui, - id: &'static str, - title: &'static str, - first_header: &'static str, - rows: &[(String, usize)], - total: usize, -) -> egui::Response { - let response = ui.strong(tr(title)); - TableBuilder::new(ui) - .id_salt(id) - .striped(true) - .vscroll(false) - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::remainder().at_least(100.0).clip(true)) - .column(Column::exact(70.0)) - .header(28.0, |mut header| { - header.col(|ui| { - header_cell(ui, tr(first_header), false); - }); - header.col(|ui| { - header_cell(ui, tr("Items"), true); - }); - }) - .body(|body| { - body.rows(24.0, rows.len() + 1, |mut row| { - if row.index() == rows.len() { - row.col(|ui| { - text_cell(ui, tr("Total"), true, false); - }); - row.col(|ui| { - text_cell(ui, &total.to_string(), true, true); - }); - return; - } - let (value, count) = &rows[row.index()]; - row.col(|ui| { - text_cell(ui, value, false, false); - }); - row.col(|ui| { - text_cell(ui, &count.to_string(), false, true); - }); - }); - }); - ui.add_space(10.0); - response -} - -fn show_moves(ui: &mut Ui, view: &DashboardView, selected: &mut Option) { - if view.moves.is_empty() { - ui.label(tr("No moves in this scope")); - *selected = None; - return; - } - if selected - .as_ref() - .is_none_or(|key| !view.moves.iter().any(|row| &row.key == key)) - { - *selected = Some(view.moves[0].key.clone()); - } - let mut clicked = None; - let compact = ui.available_width() < 700.0; - TableBuilder::new(ui) - .id_salt("learning_dashboard_moves") - .striped(true) - .sense(egui::Sense::click()) - .max_scroll_height(if compact { 180.0 } else { 300.0 }) - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::remainder().at_least(72.0).clip(true)) - .column(Column::exact(if compact { 68.0 } else { 100.0 })) - .column(Column::exact(if compact { 58.0 } else { 76.0 })) - .column(Column::exact(if compact { 58.0 } else { 76.0 })) - .column(Column::exact(if compact { 108.0 } else { 142.0 })) - .header(30.0, |mut header| { - for (index, key) in ["Move", "Status", "Accuracy", "Streak", "Next review"] - .into_iter() - .enumerate() - { - header.col(|ui| { - header_cell(ui, tr(key), index > 0).on_hover_text(if key == "Streak" { - format!("{} / {}", tr("Correct streak"), tr("Wrong streak")) - } else { - tr(key).to_owned() - }); - }); - } - }) - .body(|body| { - body.rows(24.0, view.moves.len(), |mut row| { - let move_row = &view.moves[row.index()]; - row.set_selected(selected.as_ref() == Some(&move_row.key)); - row.col(|ui| { - text_cell(ui, &crate::san::show(&move_row.san), false, false); - }); - row.col(|ui| { - text_cell( - ui, - &move_status_label(move_row.status, move_row.resistant), - false, - false, - ); - }); - row.col(|ui| { - text_cell(ui, &format_percent(move_row.accuracy_percent), false, true); - }); - row.col(|ui| { - text_cell( - ui, - &format!("{} / {}", move_row.correct_streak, move_row.wrong_streak), - false, - true, - ) - .on_hover_text(format!( - "{} / {}", - tr("Correct streak"), - tr("Wrong streak") - )); - }); - row.col(|ui| { - text_cell(ui, &format_time(move_row.next_review_at), false, true); - }); - if row.response().clicked() { - clicked = Some(move_row.key.clone()); - } - }); - }); - if let Some(key) = clicked { - *selected = Some(key); - } - let Some(selected) = selected.as_ref() else { - return; - }; - let Some(move_row) = view.moves.iter().find(|row| &row.key == selected) else { - return; - }; - ui.separator(); - show_move_details(ui, move_row); -} - -fn show_move_details(ui: &mut Ui, move_row: &MoveRow) { - ui.strong(crate::san::show(&move_row.san)); - let narrow = ui.available_width() < 700.0; - let details = [ - ( - "Status", - move_status_label(move_row.status, move_row.resistant), - "The current learning status of this move.", - ), - ( - "Accuracy", - format_percent(move_row.accuracy_percent), - "Independent correct answers divided by all independent attempts.", - ), - ( - "Attempts", - format!( - "{} · {} {} · {} {}", - move_row.independent_attempts, - move_row.correct_count, - tr("Correct"), - move_row.wrong_count, - tr("Wrong") - ), - "Only independent attempts count; previews, automatic context and replays are excluded.", - ), - ( - "Correct streak", - move_row.correct_streak.to_string(), - "Consecutive independent correct answers.", - ), - ( - "Wrong streak", - move_row.wrong_streak.to_string(), - "Consecutive independent wrong answers.", - ), - ( - "Next review", - format_time(move_row.next_review_at), - "The scheduled review time, or a dash for an unseen move.", - ), - ( - "Review in", - format_duration(move_row.review_in_seconds), - "Time remaining until the scheduled review.", - ), - ( - "Overdue by", - format_duration(move_row.overdue_seconds), - "Elapsed time since the scheduled review.", - ), - ( - "Median response", - format_median(move_row.response_time_median_ms), - "Median response time over independent attempts.", - ), - ( - "Uncertain grace", - format_duration(move_row.uncertain_grace_seconds), - "The overdue grace period before a learnt move becomes uncertain.", - ), - ]; - egui::Grid::new("learning_dashboard_move_details") - .num_columns(if narrow { 2 } else { 4 }) - .spacing([12.0, 5.0]) - .show(ui, |ui| { - for (index, (label, value, tooltip)) in details.into_iter().enumerate() { - ui.label(RichText::new(tr(label)).weak()) - .on_hover_text(tr(tooltip)); - ui.label(value).on_hover_text(tr(tooltip)); - if narrow || index % 2 == 1 { - ui.end_row(); - } - } - }); - ui.add_space(8.0); - ui.strong(tr("Wrong answers")); - if move_row.wrong_moves.is_empty() { - ui.label(tr("No wrong answers")); - } else { - TableBuilder::new(ui) - .id_salt("learning_dashboard_wrong_moves") - .striped(true) - .vscroll(false) - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::remainder().at_least(90.0).clip(true)) - .column(Column::exact(70.0)) - .column(Column::exact(150.0)) - .header(28.0, |mut header| { - header.col(|ui| { - header_cell(ui, tr("Move"), false); - }); - header.col(|ui| { - header_cell(ui, tr("Count"), true); - }); - header.col(|ui| { - header_cell(ui, tr("Last at"), true); - }); - }) - .body(|body| { - body.rows(24.0, move_row.wrong_moves.len(), |mut row| { - let wrong = &move_row.wrong_moves[row.index()]; - row.col(|ui| { - text_cell(ui, &crate::san::show(&wrong.san), false, false); - }); - row.col(|ui| { - text_cell(ui, &wrong.count.to_string(), false, true); - }); - row.col(|ui| { - text_cell(ui, &format_time(Some(wrong.last_at)), false, true); - }); - }); - }); - } - ui.add_space(8.0); - ui.strong(tr("Found in")); - for membership in &move_row.memberships { - let branch = membership - .branch - .iter() - .map(|label| crate::san::show(label)) - .collect::>() - .join(" "); - let text = if branch.is_empty() { - membership.repertoire.clone() - } else { - format!("{} · {branch}", membership.repertoire) - }; - ui.add(egui::Label::new(&text).truncate()) - .on_hover_text(tr( - "Repertoires and branches that contain this learning item.", - )) - .on_hover_text(text); - } -} - -fn move_status_label(status: MoveLearningStatus, resistant: bool) -> String { - let status = match status { - MoveLearningStatus::Unseen => tr("Unseen"), - MoveLearningStatus::Learning => tr("Learning"), - MoveLearningStatus::LearntFresh => tr("Learnt fresh"), - MoveLearningStatus::Uncertain => tr("Uncertain"), - }; - if resistant { - format!("{status} · {}", tr("Resistant")) - } else { - status.to_owned() - } -} - -fn header_cell(ui: &mut Ui, text: &str, numeric: bool) -> egui::Response { - if numeric { - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add(egui::Label::new(RichText::new(text).strong()).truncate()) - }) - .inner - } else { - ui.add(egui::Label::new(RichText::new(text).strong()).truncate()) - } -} - -fn text_cell(ui: &mut Ui, text: &str, strong: bool, numeric: bool) -> egui::Response { - let text = if strong { - RichText::new(text).strong() - } else { - RichText::new(text) - }; - if numeric { - let size = egui::vec2(ui.available_width(), ui.available_height()); - ui.allocate_ui_with_layout(size, Layout::right_to_left(Align::Center), |ui| { - ui.add(egui::Label::new(text).truncate()) - }) - .inner - } else { - ui.add(egui::Label::new(text).truncate()) - } -} - -fn side_label(side: LearningSide) -> &'static str { - tr(match side { - LearningSide::White => "White", - LearningSide::Black => "Black", - }) -} - -fn format_percent(value: Option) -> String { - value.map_or_else(|| "—".to_owned(), |value| format!("{value:.0} %")) -} - -fn format_median(value: Option) -> String { - value.map_or_else(|| "—".to_owned(), |value| format!("{value:.0} ms")) -} - -fn format_duration(value: Option) -> String { - let Some(seconds) = value else { - return "—".to_owned(); - }; - let seconds = seconds.max(0); - let days = seconds / 86_400; - let hours = seconds % 86_400 / 3_600; - let minutes = seconds % 3_600 / 60; - let seconds = seconds % 60; - if days > 0 { - format!("{days} d {hours} h") - } else if hours > 0 { - format!("{hours} h {minutes} min") - } else if minutes > 0 { - format!("{minutes} min {seconds} s") - } else { - format!("{seconds} s") - } -} - -fn format_time(at: Option) -> String { - at.and_then(|at| chrono::DateTime::from_timestamp(at, 0)) - .map(|at| { - at.with_timezone(&chrono::Local) - .format("%Y-%m-%d %H:%M") - .to_string() - }) - .unwrap_or_else(|| "—".to_owned()) -} - -fn local_date_policy(as_of: i64) -> LocalDatePolicy { - let offset = chrono::DateTime::from_timestamp(as_of, 0) - .map(|date| { - date.with_timezone(&chrono::Local) - .offset() - .local_minus_utc() - }) - .unwrap_or(0); - LocalDatePolicy::fixed(offset) -} - -fn now() -> i64 { - web_time::SystemTime::now() - .duration_since(web_time::UNIX_EPOCH) - .map_or(0, |duration| duration.as_secs() as i64) -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeMap; - use std::path::PathBuf; - use std::sync::atomic::{AtomicU64, Ordering}; - - use trainer::repertoire::{LearningData, LearningItem, WrongMoveStats, active_learning_keys}; - - use super::*; - - const BASE: i64 = 1_800_000_000; - const DAY: i64 = 86_400; - static NEXT_DIR: AtomicU64 = AtomicU64::new(1); - - struct TestDir(PathBuf); - - impl TestDir { - fn new(name: &str) -> Self { - let sequence = NEXT_DIR.fetch_add(1, Ordering::Relaxed); - let path = std::env::temp_dir().join(format!( - "cp-learning-dashboard-{}-{sequence}-{name}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - Self(path) - } - - fn store(&self) -> LearningStore { - LearningStore::new(self.0.join("learning.json")) - } - } - - impl Drop for TestDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } - } - - fn add_repertoire(library: &mut Library, name: &str, pgn: &str) -> RepertoireId { - let game = chess_core::parse_str(pgn).game; - library.create(name, &game).unwrap() - } - - fn key(library: &Library, id: &RepertoireId, expected: &str) -> LearningItemKey { - active_learning_keys( - library, - &StatsScope::for_repertoire(id.clone(), LearningSide::White, BASE), - ) - .unwrap() - .into_iter() - .find(|key| key.expected_uci == expected) - .unwrap() - } - - fn introduced(key: LearningItemKey, streak: u32, next: i64) -> LearningItem { - let mut item = LearningItem::new(key); - item.introduced = true; - item.correct_streak = streak; - item.correct_count = u64::from(streak); - item.next_review_at = Some(next); - item.previous_interval_seconds = Some(DAY); - item - } - - fn build(library: &Library, data: &LearningStoreData) -> Result { - DashboardData::build( - library, - data, - LearningSide::White, - BASE, - LocalDatePolicy::UTC, - ) - } - - fn loaded_dashboard( - library: Library, - learning_store: LearningStore, - selection: ScopeSelection, - data: DashboardData, - ) -> LearningDashboardUi { - let automatic_snapshot_scope = data - .views - .iter() - .find(|view| view.selection == selection) - .map(|view| view.scope.clone()); - let (tx, rx) = mpsc::channel(); - LearningDashboardUi { - library, - learning_store, - selection, - side: data.views[0].scope.side, - tab: DashboardTab::Summary, - data: Some(data), - loading: false, - error: None, - snapshot_pending: false, - snapshot_message: None, - snapshot_error: None, - automatic_snapshot_scope, - selected_move: None, - selected_branch: None, - generation: 0, - tx, - rx, - } - } - - fn render_dashboard( - dashboard: &mut LearningDashboardUi, - ctx: &egui::Context, - settings: &Settings, - width: f32, - height: f32, - ) -> (egui::Rect, egui::FullOutput) { - let mut content = None; - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - ..Default::default() - }, - |ui| { - let available = ui.available_rect_before_wrap(); - assert!(dashboard.show(ui, settings).is_empty()); - let rect = ui.min_rect(); - assert!(rect.min.x >= available.min.x, "{rect:?} {available:?}"); - assert!(rect.min.y >= available.min.y, "{rect:?} {available:?}"); - assert!( - rect.max.x <= available.max.x + 0.1, - "{rect:?} {available:?}" - ); - assert!( - rect.max.y <= available.max.y + 0.1, - "{rect:?} {available:?}" - ); - content = Some(rect); - }, - ); - (content.unwrap(), output) - } - - fn assert_narrow_summary(shapes: &[egui::epaint::ClippedShape]) { - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0)); - for expected in [ - "Learnt 1 of 2 moves", - "Not practised yet", - "Still learning", - "Due now", - ] { - assert!(shapes.iter().any(|clipped| matches!(&clipped.shape, egui::Shape::Text(text) if text.galley.text() == expected)), "missing overview text {expected}"); - } - for excluded in [ - "Save statistics to History", - "Total", - "Unseen", - "Global total", - ] { - assert!(!shapes.iter().any(|clipped| matches!(&clipped.shape, egui::Shape::Text(text) if text.galley.text() == excluded)), "unexpected technical or unrelated text {excluded}"); - } - for clipped in shapes { - if let egui::Shape::Text(text) = &clipped.shape { - let rect = egui::Rect::from_min_size(text.pos, text.galley.size()); - assert!( - rect.min.x >= screen.min.x - && rect.min.y >= screen.min.y - && rect.max.x <= screen.max.x + 0.1 - && rect.max.y <= screen.max.y + 0.1, - "text outside 640x480: {rect:?} {}", - text.galley.text() - ); - } - } - } - - #[test] - fn mixed_summary_and_global_union_are_deduplicated() { - let mut library = Library::default(); - let first = add_repertoire(&mut library, "Open", "1. e4 e5 2. Nf3 Nc6 *"); - let second = add_repertoire(&mut library, "Vienna", "1. e4 e5 2. Nc3 Nf6 *"); - let shared = key(&library, &first, "e2e4"); - assert_eq!(shared, key(&library, &second, "e2e4")); - let mut learning = LearningData::default(); - let mut shared_item = introduced(shared, 3, BASE - 10 * DAY); - shared_item.wrong_move_histogram = BTreeMap::from([( - "d2d4".to_owned(), - WrongMoveStats { - count: 2, - last_at: BASE - DAY, - }, - )]); - shared_item.independent_response_times_ms = vec![100, 300, 200]; - learning.items.push(shared_item); - learning - .items - .push(introduced(key(&library, &first, "g1f3"), 1, BASE + DAY)); - learning - .items - .push(LearningItem::new(key(&library, &second, "b1c3"))); - let data = LearningStoreData { - learning, - ..LearningStoreData::default() - }; - let dashboard = build(&library, &data).unwrap(); - let first_summary = &dashboard.summary[0].summary; - let second_summary = &dashboard.summary[1].summary; - let global = &dashboard.summary[2].summary; - assert_eq!((first_summary.total, first_summary.unseen), (2, 0)); - assert_eq!((first_summary.learning, first_summary.learnt), (1, 1)); - assert_eq!((first_summary.uncertain, first_summary.due), (1, 1)); - assert_eq!((second_summary.total, second_summary.unseen), (2, 1)); - assert_eq!((global.total, global.unseen), (3, 1)); - assert_eq!((global.learning, global.learnt), (1, 1)); - assert_eq!( - global.total, - global.unseen + global.learning + global.learnt - ); - assert!(global.uncertain <= global.learnt); - assert!(global.total <= first_summary.total + second_summary.total); - assert!(global.total < first_summary.total + second_summary.total); - - let global_view = &dashboard.views[0]; - assert_eq!(global_view.moves.len(), 3); - assert!(global_view.moves.iter().all(|row| row.san != "—")); - assert!(global_view.moves.iter().any(|row| row.san == "e4")); - assert!(global_view.sequences.attempts.contains_key(&0)); - for total in [ - global_view.sequences.correct_streak.values().sum::(), - global_view.sequences.wrong_streak.values().sum::(), - global_view.sequences.attempts.values().sum::(), - ] { - assert_eq!(total, global.total); - } - let e4 = global_view - .moves - .iter() - .find(|row| row.san == "e4") - .unwrap(); - assert_eq!(e4.wrong_moves[0].san, "d4"); - assert_eq!(e4.response_time_median_ms, Some(200.0)); - assert_eq!(e4.memberships.len(), 2); - assert!( - e4.memberships - .iter() - .all(|membership| membership.branch.iter().any(|label| label.contains("e4"))) - ); - } - - #[test] - fn global_total_invariant_runs_on_empty_build_without_changing_data() { - GLOBAL_TOTAL_INVARIANT_CALLS.with(|calls| calls.set(0)); - - let dashboard = build(&Library::default(), &LearningStoreData::default()).unwrap(); - - assert_eq!(GLOBAL_TOTAL_INVARIANT_CALLS.with(|calls| calls.get()), 1); - assert_eq!(dashboard.views[0].scope.side, LearningSide::White); - assert_eq!(dashboard.as_of, BASE); - assert_eq!(dashboard.timezone, LocalDatePolicy::UTC); - assert_eq!(dashboard.summary.len(), 1); - assert!(dashboard.summary[0].id.is_none()); - assert_eq!(dashboard.summary[0].summary, LearningAggregate::default()); - assert_eq!(dashboard.views.len(), 1); - assert_eq!(dashboard.views[0].summary, LearningAggregate::default()); - assert!(dashboard.names.is_empty()); - assert!(dashboard.labels.is_empty()); - } - - #[test] - fn empty_scope_has_no_false_percentages_or_buckets() { - let dashboard = build(&Library::default(), &LearningStoreData::default()).unwrap(); - assert_eq!(dashboard.summary.len(), 1); - let global = &dashboard.summary[0].summary; - assert_eq!(global.total, 0); - assert_eq!(global.learnt_percent, None); - assert_eq!(global.confident_percent, None); - assert_eq!(format_percent(global.learnt_percent), "—"); - let view = &dashboard.views[0]; - assert!(view.moves.is_empty()); - assert!(view.history.is_empty()); - assert_eq!(view.scheduled.introduced(), 0); - assert!(view.sequences.correct_streak.is_empty()); - assert!(view.sequences.wrong_streak.is_empty()); - assert!(view.sequences.attempts.is_empty()); - } - - #[test] - fn scheduled_buckets_partition_introduced_items() { - let mut library = Library::default(); - let id = add_repertoire( - &mut library, - "Spanish", - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 *", - ); - let schedules = [ - ("e2e4", Some(BASE - 1)), - ("g1f3", Some(BASE + 60)), - ("f1b5", Some(BASE + 2 * DAY)), - ("b5a4", Some(BASE + 10 * DAY)), - ("e1g1", Some(BASE + 60 * DAY)), - ("f1e1", Some(BASE + 400 * DAY)), - ]; - let mut learning = LearningData::default(); - for (expected, next) in schedules { - let mut item = LearningItem::new(key(&library, &id, expected)); - item.introduced = true; - item.next_review_at = next; - learning.items.push(item); - } - learning - .items - .push(LearningItem::new(key(&library, &id, "a4b3"))); - let dashboard = build( - &library, - &LearningStoreData { - learning, - ..LearningStoreData::default() - }, - ) - .unwrap(); - let view = &dashboard.views[1]; - assert_eq!(view.summary.total, 7); - assert_eq!(view.summary.unseen, 1); - assert_eq!( - view.scheduled, - ScheduledBuckets { - overdue: 1, - today: 1, - week: 1, - month: 1, - year: 1, - later: 1, - } - ); - assert_eq!( - view.scheduled.introduced(), - view.summary.total - view.summary.unseen - ); - } - - #[test] - fn snapshot_capture_deduplicates_same_date_and_scope() { - let dir = TestDir::new("duplicate"); - let store = dir.store(); - let mut library = Library::default(); - let id = add_repertoire(&mut library, "Open", "1. e4 e5 *"); - let scope = StatsScope::for_repertoire(id, LearningSide::White, BASE); - let first = capture_snapshot(&store, &library, &scope, LocalDatePolicy::UTC).unwrap(); - assert!(first.recorded); - let mut repeated_scope = scope.clone(); - repeated_scope.as_of += 60; - let second = - capture_snapshot(&store, &library, &repeated_scope, LocalDatePolicy::UTC).unwrap(); - assert!(!second.recorded); - assert_eq!(first.snapshot.date, second.snapshot.date); - assert_eq!(store.load().unwrap().snapshots.len(), 1); - } - - #[test] - fn history_preserves_old_snapshots_after_new_capture() { - let dir = TestDir::new("history"); - let store = dir.store(); - let mut library = Library::default(); - let id = add_repertoire(&mut library, "Open", "1. e4 e5 *"); - let scope = StatsScope::for_repertoire(id, LearningSide::White, BASE); - let old = capture_snapshot(&store, &library, &scope, LocalDatePolicy::UTC).unwrap(); - let mut next_scope = scope.clone(); - next_scope.as_of += DAY; - let new = capture_snapshot(&store, &library, &next_scope, LocalDatePolicy::UTC).unwrap(); - assert!(new.recorded); - let stored = store.load().unwrap(); - assert_eq!(stored.snapshots.len(), 2); - let dashboard = build(&library, &stored).unwrap(); - let history = &dashboard.views[1].history; - assert_eq!(history.len(), 2); - assert_eq!(history[0].date, old.snapshot.date); - assert_eq!(history[0].as_of, old.snapshot.as_of); - assert_eq!(history[1].date, new.snapshot.date); - assert!(history[0].as_of < history[1].as_of); - } - - #[test] - fn automatic_snapshot_runs_once_per_scope_and_reopening_does_not_write() { - let dir = TestDir::new("automatic"); - let store = dir.store(); - let mut library = Library::default(); - let id = add_repertoire(&mut library, "Open", "1. e4 e5 *"); - add_repertoire(&mut library, "Queen's pawn", "1. d4 d5 *"); - let mut dashboard = LearningDashboardUi::new_for_repertoire( - library.clone(), - store.clone(), - id.clone(), - LearningSide::Black, - ); - dashboard.wait_until_idle_for_test(); - - let stored = store.load().unwrap(); - assert_eq!(stored.snapshots.len(), 1); - assert_eq!(stored.snapshots[0].scope.side, LearningSide::Black); - assert_eq!(stored.snapshots[0].scope.repertoire_ids.len(), 1); - assert!(stored.snapshots[0].scope.repertoire_ids.contains(&id)); - let before_reopen = std::fs::read(store.path()).unwrap(); - let mut reopened = LearningDashboardUi::new_for_repertoire( - library, - store.clone(), - id.clone(), - LearningSide::Black, - ); - reopened.wait_until_idle_for_test(); - assert_eq!(std::fs::read(store.path()).unwrap(), before_reopen); - - reopened.selection = ScopeSelection::Global; - reopened.ensure_snapshot_after_load(); - reopened.wait_until_idle_for_test(); - let stored = store.load().unwrap(); - assert_eq!(stored.snapshots.len(), 2); - assert!( - stored - .snapshots - .iter() - .any(|snapshot| snapshot.scope.repertoire_ids.len() == 2) - ); - let before_existing = std::fs::read(store.path()).unwrap(); - reopened.selection = ScopeSelection::Repertoire(id); - reopened.ensure_snapshot_after_load(); - reopened.wait_until_idle_for_test(); - assert_eq!(std::fs::read(store.path()).unwrap(), before_existing); - } - - #[test] - fn snapshot_refresh_preserves_the_visible_summary_and_its_height() { - let dir = TestDir::new("refresh"); - let store = dir.store(); - let mut library = Library::default(); - let id = add_repertoire(&mut library, "Open", "1. e4 e5 2. Nf3 Nc6 *"); - let data = build(&library, &LearningStoreData::default()).unwrap(); - let scope = data.views[1].scope.clone(); - let mut dashboard = loaded_dashboard( - library.clone(), - store.clone(), - ScopeSelection::Repertoire(id), - data, - ); - let settings = Settings::default(); - let ctx = egui::Context::default(); - let (before, output) = render_dashboard(&mut dashboard, &ctx, &settings, 1000.0, 700.0); - output.drop_without_applying_deltas(); - let saved = capture_snapshot(&store, &library, &scope, LocalDatePolicy::UTC).unwrap(); - assert!(saved.recorded); - - dashboard - .tx - .send(Event::Snapshot(dashboard.generation, Box::new(Ok(saved)))) - .unwrap(); - dashboard.poll(); - assert!(dashboard.loading); - assert!(dashboard.data.is_some()); - let (after, output) = render_dashboard(&mut dashboard, &ctx, &settings, 1000.0, 700.0); - - assert_eq!(after, before); - assert!(output.shapes.iter().any(|clipped| { - matches!(&clipped.shape, egui::Shape::Text(text) if text.galley.text() == "Learnt 0 of 2 moves") - })); - assert!(!output.shapes.iter().any(|clipped| { - matches!(&clipped.shape, egui::Shape::Text(text) if text.galley.text() == "Loading learning statistics…") - })); - output.drop_without_applying_deltas(); - dashboard.wait_until_idle_for_test(); - assert_eq!(store.load().unwrap().snapshots.len(), 1); - } - - #[test] - fn every_tab_renders_at_both_window_sizes() { - let dir = TestDir::new("layout"); - let mut library = Library::default(); - let id = add_repertoire(&mut library, "Open", "1. e4 e5 2. Nf3 Nc6 *"); - let mut learning = LearningData::default(); - let mut item = introduced(key(&library, &id, "e2e4"), 3, BASE + DAY); - item.wrong_move_histogram = BTreeMap::from([( - "d2d4".to_owned(), - WrongMoveStats { - count: 1, - last_at: BASE - DAY, - }, - )]); - learning.items.push(item); - let scope = StatsScope::for_repertoire(id.clone(), LearningSide::White, BASE); - let snapshot = LearningSnapshot::capture( - &library, - &learning, - &scope, - &SrsSettings::default(), - LocalDatePolicy::UTC, - ) - .unwrap(); - let stored = LearningStoreData { - learning, - snapshots: vec![snapshot], - ..LearningStoreData::default() - }; - let data = build(&library, &stored).unwrap(); - let mut dashboard = - loaded_dashboard(library, dir.store(), ScopeSelection::Repertoire(id), data); - let settings = Settings::default(); - let ctx = egui::Context::default(); - for (width, height) in [(1400.0, 900.0), (960.0, 600.0), (640.0, 480.0)] { - for tab in [ - DashboardTab::Summary, - DashboardTab::Branches, - DashboardTab::History, - DashboardTab::Scheduled, - DashboardTab::Sequences, - DashboardTab::Moves, - ] { - dashboard.tab = tab; - let (_, output) = render_dashboard(&mut dashboard, &ctx, &settings, width, height); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - if width == 640.0 && tab == DashboardTab::Summary { - assert_narrow_summary(&shapes); - } - } - } - } - - #[test] - fn dashboard_stays_full_when_training_depth_is_limited() { - let mut library = Library::default(); - let id = add_repertoire(&mut library, "Open", "1. e4 e5 2. Nf3 Nc6 *"); - library.repertoire_mut(&id).unwrap().set_max_plies(2); - let dashboard = build(&library, &LearningStoreData::default()).unwrap(); - let view = &dashboard.views[1]; - assert_eq!(view.scope.max_depth, None); - assert_eq!(view.summary.total, 2); - assert!(!view.branches.is_empty()); - - let training_scope = - StatsScope::for_repertoire(id, LearningSide::White, BASE).with_max_depth(Some(2)); - let training = aggregate_scope( - &library, - &LearningData::default(), - &training_scope, - &SrsSettings::default(), - ) - .unwrap(); - assert_eq!(training.summary.total, 1); - } -} diff --git a/apps/desktop/src/learning_training.rs b/apps/desktop/src/learning_training.rs deleted file mode 100644 index bc13807..0000000 --- a/apps/desktop/src/learning_training.rs +++ /dev/null @@ -1,4139 +0,0 @@ -use std::{ - collections::{BTreeMap, BTreeSet, VecDeque}, - sync::{ - atomic::{AtomicU64, Ordering}, - mpsc, - }, - time::Duration, -}; - -use chess_core::shakmaty::{ - CastlingMode, Chess, Color, Move, Position, Square, fen::Fen, uci::UciMove, -}; -use chess_core::{Game, NodeId}; -use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2}; -use trainer::repertoire::{ - AttemptApplication, LearningContextPolicy, LearningContextStep, LearningData, LearningItemKey, - LearningPresentation, LearningSessionError, LearningSessionPhase, LearningSessionSnapshot, - LearningSide, LearningStore, Library, PersistedSessionAttempt, QueueMode, RepertoireId, - SrsSettings, StatsScope, TrainingAttempt, TrainingEventType, TrainingMode, - active_learning_keys, fen4, -}; -use web_time::{Instant, SystemTime, UNIX_EPOCH}; - -use crate::assets::Sound; -use crate::board::{Arrow, BoardState, BoardView}; -use crate::i18n::{tr, trf}; -use crate::repertoire_training::{BoardAnnotations, pgn_annotations_at}; -use crate::settings::Settings; - -const WRONG_SHOWN: Duration = Duration::from_millis(400); -const DEFAULT_ANIMATION: Duration = Duration::from_millis(250); -static NEXT_ID: AtomicU64 = AtomicU64::new(1); - -pub enum LearningTrainingAction { - Back, - OpenSettings, - Sound(Sound), - Toast(String), -} - -#[derive(Clone)] -struct VisualMove { - #[allow(dead_code)] - uci: String, - before: Chess, - after: Chess, - from: Square, - to: Square, -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum PlayOutcome { - CorrectIndependent, - WrongIndependent, - WrongReplay, - ReplayAfterError, - PreviewedReplay, -} - -#[derive(Clone)] -enum CommitKind { - Context, - ReusedContext, - Play { - visual: Box, - outcome: PlayOutcome, - shown_prefix: ShownPrefix, - }, - Preview, -} - -#[derive(Clone)] -struct ShownPrefix { - repertoire_id: RepertoireId, - path: Vec, -} - -#[derive(Clone)] -struct PendingCommit { - attempts: Vec, - kind: CommitKind, -} - -enum Playback { - Automatic { - current: Box, - remaining: VecDeque, - started_at: Instant, - duration: Duration, - completed: usize, - total: usize, - }, - Paused { - remaining: VecDeque, - completed: usize, - }, - Wrong { - visual: Box, - until: Instant, - }, - Alternative { - visual: Box, - until: Instant, - }, - Accepted { - started_at: Instant, - duration: Duration, - independent_success: bool, - }, -} - -pub struct LearningTrainingUi { - library: Library, - store: LearningStore, - session: LearningSessionSnapshot, - learning: LearningData, - presentation: Option, - completed_attempt_ids: BTreeSet, - pending_commit: Option, - commit_in_flight: Option>>, - #[cfg(test)] - synchronous_commits: bool, - save_error: Option, - error: Option, - board: BoardState, - board_position: Chess, - // Parsed once in the training-start worker, never in a frame or save callback. - annotation_games: BTreeMap, - repertoire_answers: BTreeSet, - // The visible node is independent of the session's already-advanced target. - displayed_node: Option<(RepertoireId, NodeId)>, - board_shown: bool, - pending_automatic: Option>, - shown_prefix: Option, - playback: Option, - pause_requested: bool, - stopped: bool, - needs_prepare: bool, - animation: Duration, - ready_since: Option, - last_move: Option<(Square, Square)>, - flipped: bool, - message: Option, - confirm_discard: bool, - discard_requested: bool, - pending_sounds: Vec, - #[cfg(test)] - visual_log: Vec, -} - -impl LearningTrainingUi { - #[allow(dead_code)] - pub fn new( - library: Library, - store: LearningStore, - scope: StatsScope, - settings: SrsSettings, - introduce_new: bool, - flipped: bool, - ) -> Result { - Self::new_with_policy( - library, - store, - scope, - settings, - introduce_new, - flipped, - QueueMode::SpacedRepetition, - LearningContextPolicy::default(), - ) - } - - #[allow(dead_code)] - pub fn new_with_mode( - library: Library, - store: LearningStore, - scope: StatsScope, - settings: SrsSettings, - introduce_new: bool, - flipped: bool, - mode: QueueMode, - ) -> Result { - Self::new_with_policy( - library, - store, - scope, - settings, - introduce_new, - flipped, - mode, - LearningContextPolicy::default(), - ) - } - - #[allow(clippy::too_many_arguments)] - pub fn new_with_policy( - library: Library, - store: LearningStore, - scope: StatsScope, - settings: SrsSettings, - introduce_new: bool, - flipped: bool, - mode: QueueMode, - context_policy: LearningContextPolicy, - ) -> Result { - if introduce_new && mode != QueueMode::SpacedRepetition { - return Err(format!("new learning items require SRS, not {mode:?}")); - } - let data = store.load().map_err(|error| error.to_string())?; - let existing = if introduce_new { - None - } else { - data.session_snapshots - .iter() - .filter(|session| { - (mode != QueueMode::SpacedRepetition - || session.phase != LearningSessionPhase::Finished) - && compatible(session, &scope, mode) - }) - .max_by_key(|session| session.revision) - .cloned() - }; - let mut session = match existing { - Some(session) => { - let mut session = session - .resume(&library) - .map_err(|error| error.to_string())?; - if session.phase == LearningSessionPhase::Finished - && matches!(mode, QueueMode::ReviewInOrder | QueueMode::LeastRecent) - { - session - .start_next_pass(&library, &data.learning) - .map_err(|error| error.to_string())?; - } - session - } - None => { - let mut session = LearningSessionSnapshot::new_with_mode( - unique_id("learning-session"), - &library, - &data.learning, - scope, - settings, - mode, - ) - .map_err(|error| error.to_string())?; - session.context_policy = context_policy; - if introduce_new { - session - .introduce_new(&library, &data.learning) - .map_err(|error| error.to_string())?; - } - session - } - }; - store - .save_session(&mut session) - .map_err(|error| error.to_string())?; - let completed_attempt_ids = data - .learning - .attempts - .iter() - .filter(|attempt| attempt.session_id == session.id()) - .map(|attempt| attempt.client_attempt_id.clone()) - .collect(); - let flipped = match session.stats_scope.side { - LearningSide::White => flipped, - LearningSide::Black => !flipped, - }; - let repertoire_answers = active_learning_keys(&library, &session.stats_scope) - .map_err(|error| error.to_string())?; - let annotation_games = session - .queue - .iter() - .map(|target| target.repertoire_id.clone()) - .collect::>() - .into_iter() - .filter_map(|id| { - library - .repertoire(&id) - .map(|repertoire| (id, repertoire.game())) - }) - .collect(); - Ok(Self { - library, - store, - session, - learning: data.learning, - presentation: None, - completed_attempt_ids, - pending_commit: None, - commit_in_flight: None, - #[cfg(test)] - synchronous_commits: false, - save_error: None, - error: None, - board: BoardState::default(), - board_position: Chess::default(), - annotation_games, - repertoire_answers, - displayed_node: None, - board_shown: false, - pending_automatic: None, - shown_prefix: None, - playback: None, - pause_requested: false, - stopped: false, - needs_prepare: true, - animation: DEFAULT_ANIMATION, - ready_since: None, - last_move: None, - flipped, - message: None, - confirm_discard: false, - discard_requested: false, - pending_sounds: Vec::new(), - #[cfg(test)] - visual_log: Vec::new(), - }) - } - - #[allow(dead_code)] - pub fn learning_data(&self) -> &LearningData { - &self.learning - } - - pub fn has_unsaved(&self) -> bool { - self.pending_commit.is_some() || self.save_error.is_some() - } - - pub fn target_available(&self) -> bool { - self.session.current_target().is_some() - } - - pub fn is_finished(&self) -> bool { - self.session.phase == LearningSessionPhase::Finished - && self.playback.is_none() - && !self.has_unsaved() - } - - #[allow(dead_code)] - pub fn session_id(&self) -> &str { - self.session.id() - } - - fn can_input(&self) -> bool { - !self.has_unsaved() - && !self.stopped - && self.error.is_none() - && !self.needs_prepare - && self.playback.is_none() - && self.session.current_target().is_some() - && matches!( - self.session.phase, - LearningSessionPhase::AwaitingIndependent - | LearningSessionPhase::AwaitingContextIndependent - | LearningSessionPhase::AwaitingReplayAfterError - | LearningSessionPhase::PreviewedReplay - ) - } - - fn can_hint(&self) -> bool { - self.can_input() && self.session.phase == LearningSessionPhase::AwaitingIndependent - } - - fn tick_at(&mut self, now: Instant, animation: Duration, happened_at: i64) { - self.animation = animation; - self.poll_commit(now); - if self.stopped || self.has_unsaved() { - return; - } - if self.board_shown - && let Some(steps) = self.pending_automatic.take() - { - self.start_next_automatic(steps, now, 0); - } - if self.needs_prepare { - self.prepare_presentation(now); - } - loop { - if self.stopped || self.has_unsaved() || self.error.is_some() { - return; - } - if self.needs_prepare { - self.prepare_presentation(now); - continue; - } - let Some(deadline) = self.playback_deadline() else { - return; - }; - if now < deadline { - return; - } - match self.playback { - Some(Playback::Wrong { .. } | Playback::Alternative { .. }) => { - self.finish_temporary_move(now); - } - Some(Playback::Accepted { .. }) => self.finish_accepted(now), - Some(Playback::Automatic { .. }) => { - let id = unique_id(self.session.id()); - self.advance_context_with_id_at(id, now, happened_at); - } - Some(Playback::Paused { .. }) | None => return, - } - if !animation.is_zero() { - return; - } - } - } - - fn playback_deadline(&self) -> Option { - match &self.playback { - Some(Playback::Automatic { - started_at, - duration, - .. - }) - | Some(Playback::Accepted { - started_at, - duration, - .. - }) => Some(*started_at + *duration), - Some(Playback::Wrong { until, .. } | Playback::Alternative { until, .. }) => { - Some(*until) - } - Some(Playback::Paused { .. }) | None => None, - } - } - - fn prepare_presentation(&mut self, now: Instant) { - let presentation = match self - .session - .presentation_with_learning(&self.library, &self.learning) - { - Ok(presentation) => presentation, - Err(error) => { - self.error = Some(error.to_string()); - self.needs_prepare = false; - self.ready_since = None; - return; - } - }; - self.error = None; - self.needs_prepare = false; - self.presentation = Some(presentation.clone()); - let Some(ref current) = presentation.current_position else { - self.ready_since = None; - self.pending_automatic = None; - if self.session.queue.is_empty() && self.message.is_none() { - self.message = - Some(tr("No due moves. New items are introduced only on request.").to_owned()); - } - return; - }; - // A following task may extend the line that is already on the board. Keep - // its context journal, but do not rewind and animate those same moves again. - // The complete path and repertoire must match; a transposed FEN is not enough. - if self.reuse_shown_context(&presentation, now) { - return; - } - self.shown_prefix = None; - if !presentation.automatic_context.is_empty() { - let mut steps = VecDeque::new(); - for step in presentation.automatic_context { - match VisualMove::from_context(&step) { - Ok(_) => steps.push_back(step), - Err(error) => { - self.error = Some(error); - self.ready_since = None; - return; - } - } - } - self.ready_since = None; - let Some(first) = steps.front() else { - self.error = Some("automatic context has no visual step".to_owned()); - return; - }; - self.board_position = match parse_position(&first.from) { - Ok(position) => position, - Err(error) => { - self.error = Some(error); - return; - } - }; - self.set_displayed_context(self.session.context_index); - self.board_shown = false; - self.pending_automatic = Some(steps); - self.playback = None; - self.last_move = None; - return; - } - self.pending_automatic = None; - let position = match parse_position(current) { - Ok(position) => position, - Err(error) => { - self.error = Some(error); - self.ready_since = None; - return; - } - }; - if fen4(&self.board_position) != current.fen4 { - self.last_move = None; - } - self.board_position = position; - self.set_displayed_context(self.session.context_index); - self.playback = None; - match self.session.phase { - LearningSessionPhase::AwaitingIndependent => { - self.ready_since = Some(now); - self.message = Some(tr("Your turn: play a repertoire move.").to_owned()); - } - LearningSessionPhase::AwaitingContextIndependent => { - self.ready_since = Some(now); - self.message = Some(format!( - "{} · {}", - tr("Automatic move/context"), - tr("Your turn: play a repertoire move.") - )); - } - LearningSessionPhase::AwaitingReplayAfterError => { - self.ready_since = None; - self.message = Some(tr("Wrong move. Replay the revealed move; it will not count as an independent success.").to_owned()); - } - LearningSessionPhase::PreviewedReplay => { - self.ready_since = None; - self.message = Some( - tr("PREVIEWED · replay the shown move; this is not an independent success.") - .to_owned(), - ); - } - phase => { - self.ready_since = None; - self.error = Some(format!( - "learning session has no playable position in {phase:?}" - )); - } - } - } - - fn reuse_shown_context(&mut self, presentation: &LearningPresentation, at: Instant) -> bool { - let Some(prefix) = &self.shown_prefix else { - return false; - }; - let Some(target) = self.session.current_target() else { - return false; - }; - let Some(remaining) = prefix.path.len().checked_sub(self.session.context_index) else { - return false; - }; - if remaining == 0 - || target.repertoire_id != prefix.repertoire_id - || !presentation.target_path.starts_with(&prefix.path) - // An independent context question must still be asked. Only reuse a - // prefix that the core explicitly allows to be automatic in full. - || presentation.automatic_context.len() < remaining - || presentation.automatic_context[remaining - 1].to.fen4 != fen4(&self.board_position) - { - return false; - } - // These moves are already visible. Preserve each AUTO_CONTEXT event, - // but commit the whole prefix once instead of rereading/writing all - // history and rebuilding the presentation once per old move. - let mut next_session = self.session.clone(); - let mut attempts = Vec::with_capacity(remaining); - let happened_at = now(); - for _ in 0..remaining { - let id = unique_id(next_session.id()); - match next_session.advance_context_with_learning( - &self.library, - &self.learning, - id, - happened_at, - ) { - Ok(attempt) => attempts.push(attempt), - Err(error) => { - self.error = Some(error.to_string()); - return true; - } - } - } - self.session = next_session; - self.ready_since = None; - self.pending_commit = Some(PendingCommit { - attempts, - kind: CommitKind::ReusedContext, - }); - self.persist_pending(at); - true - } - - fn start_next_automatic( - &mut self, - mut remaining: VecDeque, - now: Instant, - completed: usize, - ) { - let Some(step) = remaining.pop_front() else { - self.needs_prepare = true; - self.prepare_presentation(now); - return; - }; - let total = completed.saturating_add(remaining.len()).saturating_add(1); - let current = match VisualMove::from_context(&step) { - Ok(current) => current, - Err(error) => { - self.error = Some(error); - return; - } - }; - self.board_position = current.after.clone(); - self.set_displayed_context(self.session.context_index + 1); - self.last_move = Some((current.from, current.to)); - self.message = None; - self.playback = Some(Playback::Automatic { - current: Box::new(current.clone()), - remaining, - started_at: now, - duration: self.animation.div_f32(step.speed_factor.max(0.01) as f32), - completed, - total, - }); - #[cfg(test)] - self.visual_log.push(current.uci.clone()); - self.queue_sound(Sound::Move); - } - - fn advance_context_with_id_at( - &mut self, - client_attempt_id: String, - now: Instant, - happened_at: i64, - ) -> bool { - if self.has_unsaved() - || !matches!(self.playback, Some(Playback::Automatic { .. })) - || self.completed_attempt_ids.contains(&client_attempt_id) - { - return false; - } - let attempt = match self.session.advance_context_with_learning( - &self.library, - &self.learning, - client_attempt_id, - happened_at, - ) { - Ok(attempt) => attempt, - Err(error) => { - self.error = Some(error.to_string()); - return false; - } - }; - self.begin_commit(attempt, CommitKind::Context, now); - true - } - - fn finish_context(&mut self, now: Instant) { - let Some(Playback::Automatic { - remaining, - completed, - .. - }) = self.playback.take() - else { - self.error = Some("automatic context is missing its visual step".to_owned()); - return; - }; - let completed = completed + 1; - if self.pause_requested && !remaining.is_empty() { - self.pause_requested = false; - self.message = Some(tr("Paused").to_owned()); - self.playback = Some(Playback::Paused { - remaining, - completed, - }); - return; - } - self.pause_requested = false; - self.start_next_automatic(remaining, now, completed); - } - - fn is_autoplay(&self) -> bool { - matches!( - &self.playback, - Some(Playback::Automatic { .. } | Playback::Paused { .. }) - ) - } - - fn autoplay_paused(&self) -> bool { - matches!(&self.playback, Some(Playback::Paused { .. })) - } - - fn request_pause(&mut self) -> bool { - let active = matches!(&self.playback, Some(Playback::Automatic { .. })); - if active { - self.pause_requested = true; - } - active - } - - fn continue_autoplay(&mut self, now: Instant) -> bool { - if self.stopped || self.has_unsaved() { - return false; - } - let Some(Playback::Paused { - remaining, - completed, - }) = self.playback.take() - else { - return false; - }; - self.pause_requested = false; - self.start_next_automatic(remaining, now, completed); - true - } - - fn stop_autoplay(&mut self, actions: &mut Vec) -> bool { - if !self.is_autoplay() { - return false; - } - if self.has_unsaved() { - self.request_back(actions); - return true; - } - self.pause_requested = false; - let playback = self.playback.take(); - if let Some(Playback::Automatic { current, .. }) = playback { - self.board_position = current.before.clone(); - } - self.last_move = None; - self.ready_since = None; - self.stopped = true; - actions.push(LearningTrainingAction::Back); - true - } - - fn play_move_at(&mut self, mv: Move, now: Instant, happened_at: i64) -> bool { - let id = unique_id(self.session.id()); - self.play_move_with_id_at(mv, id, now, happened_at) - } - - fn play_move_with_id_at( - &mut self, - mv: Move, - client_attempt_id: String, - now: Instant, - happened_at: i64, - ) -> bool { - if !self.can_input() || self.completed_attempt_ids.contains(&client_attempt_id) { - return false; - } - let Some(expected_uci) = self.session.current_expected_uci().map(str::to_owned) else { - return false; - }; - let before = self.board_position.clone(); - let uci = mv.to_uci(CastlingMode::Standard).to_string(); - let visual = VisualMove::new(uci.clone(), before, mv); - let phase = self.session.phase; - let independent = matches!( - phase, - LearningSessionPhase::AwaitingIndependent - | LearningSessionPhase::AwaitingContextIndependent - ); - let Some(target) = self.session.current_target() else { - return false; - }; - let Some(prefix) = target.path.get(..self.session.context_index) else { - return false; - }; - let mut path = prefix.to_vec(); - path.push(uci.clone()); - let shown_prefix = ShownPrefix { - repertoire_id: target.repertoire_id.clone(), - path, - }; - if !independent && uci != expected_uci { - let key = LearningItemKey::new(target.key.user_id.clone(), fen4(&visual.before), &uci); - if self.repertoire_answers.contains(&key) { - let already_completed = self.session.completed_keys.contains(&key); - self.show_repertoire_alternative(visual, &shown_prefix, already_completed, now); - return true; - } - self.set_displayed_path(Some(&shown_prefix)); - self.start_playback(visual, PlayOutcome::WrongReplay, now); - return true; - } - let response_time_ms = independent.then(|| { - self.ready_since.map_or(0, |ready| { - u64::try_from(now.saturating_duration_since(ready).as_millis()).unwrap_or(u64::MAX) - }) - }); - let attempt = match self.session.play_uci_with_learning_answers( - &self.library, - &self.learning, - &self.repertoire_answers, - &uci, - client_attempt_id, - happened_at, - response_time_ms, - ) { - Ok(attempt) => attempt, - Err(LearningSessionError::RepertoireAlternative { already_completed }) => { - self.show_repertoire_alternative(visual, &shown_prefix, already_completed, now); - return true; - } - Err(error) => { - self.error = Some(error.to_string()); - return false; - } - }; - let outcome = match attempt.event_type { - TrainingEventType::CorrectIndependent => PlayOutcome::CorrectIndependent, - TrainingEventType::IncorrectIndependent => PlayOutcome::WrongIndependent, - TrainingEventType::ReplayAfterError => PlayOutcome::ReplayAfterError, - TrainingEventType::AutoContext => PlayOutcome::PreviewedReplay, - TrainingEventType::Previewed | TrainingEventType::IllegalMove => { - self.error = Some("legal board input produced a non-play event".to_owned()); - return false; - } - }; - // The legal move is visible immediately, including while its event is - // being saved. Input stays blocked until persistence acknowledges it. - // In particular a dropped piece must not jump back to its source square. - self.board_position = visual.after.clone(); - self.set_displayed_path(Some(&shown_prefix)); - self.last_move = Some((visual.from, visual.to)); - self.begin_commit( - attempt, - CommitKind::Play { - visual: Box::new(visual), - outcome, - shown_prefix, - }, - now, - ); - true - } - - fn play_uci_with_id_at( - &mut self, - uci: &str, - client_attempt_id: String, - now: Instant, - happened_at: i64, - ) -> bool { - if !self.can_input() || self.completed_attempt_ids.contains(&client_attempt_id) { - return false; - } - let mv = uci - .parse::() - .ok() - .and_then(|uci| uci.to_move(&self.board_position).ok()); - let Some(mv) = mv else { - self.message = Some(tr("Illegal move in the current position").to_owned()); - return false; - }; - self.play_move_with_id_at(mv, client_attempt_id, now, happened_at) - } - - fn start_playback(&mut self, visual: VisualMove, outcome: PlayOutcome, now: Instant) { - self.ready_since = None; - self.board_position = visual.after.clone(); - self.last_move = Some((visual.from, visual.to)); - match outcome { - PlayOutcome::WrongIndependent | PlayOutcome::WrongReplay => { - self.message = Some(tr("Wrong move. Replay the revealed move; it will not count as an independent success.").to_owned()); - self.playback = Some(Playback::Wrong { - visual: Box::new(visual), - until: now + WRONG_SHOWN, - }); - self.queue_sound(Sound::Wrong); - } - PlayOutcome::CorrectIndependent - | PlayOutcome::ReplayAfterError - | PlayOutcome::PreviewedReplay => { - self.message = Some( - tr(match outcome { - PlayOutcome::CorrectIndependent => "Correct independent answer.", - PlayOutcome::ReplayAfterError => { - "REPLAY_AFTER_ERROR · not an independent success." - } - PlayOutcome::PreviewedReplay => { - "PREVIEWED · shown move completed; no independent success recorded." - } - PlayOutcome::WrongIndependent | PlayOutcome::WrongReplay => { - "Wrong move. Replay the revealed move; it will not count as an independent success." - } - }) - .to_owned(), - ); - self.playback = Some(Playback::Accepted { - started_at: now, - duration: self.animation, - independent_success: outcome == PlayOutcome::CorrectIndependent, - }); - self.queue_sound(Sound::Move); - } - } - } - - fn show_repertoire_alternative( - &mut self, - visual: VisualMove, - shown_prefix: &ShownPrefix, - already_completed: bool, - now: Instant, - ) { - self.ready_since = None; - self.board_position = visual.after.clone(); - self.set_displayed_path(Some(shown_prefix)); - self.last_move = Some((visual.from, visual.to)); - self.message = Some( - tr(if already_completed { - "This repertoire move has already been reviewed in this session." - } else { - "This move is in your repertoire, but is not a task in this session." - }) - .to_owned(), - ); - self.playback = Some(Playback::Alternative { - visual: Box::new(visual), - until: now + WRONG_SHOWN.max(self.animation), - }); - } - - fn finish_temporary_move(&mut self, now: Instant) { - let (visual, explanation) = match self.playback.take() { - Some(Playback::Wrong { visual, .. }) => (visual, None), - Some(Playback::Alternative { visual, .. }) => (visual, self.message.clone()), - _ => return, - }; - self.board_position = visual.before; - self.last_move = None; - self.needs_prepare = true; - self.prepare_presentation(now); - if let Some(explanation) = explanation { - self.message = Some(format!( - "{explanation} {}", - self.message.as_deref().unwrap_or_default() - )); - } - } - - fn finish_accepted(&mut self, now: Instant) { - let Some(Playback::Accepted { - independent_success, - .. - }) = self.playback.take() - else { - return; - }; - if independent_success && self.session.phase == LearningSessionPhase::Finished { - self.queue_sound(Sound::Success); - } - self.needs_prepare = true; - self.prepare_presentation(now); - } - - fn request_hint_with_id_at( - &mut self, - client_attempt_id: String, - now: Instant, - happened_at: i64, - ) -> bool { - if !self.can_hint() || self.completed_attempt_ids.contains(&client_attempt_id) { - return false; - } - let attempt = match self.session.preview(client_attempt_id, happened_at) { - Ok(Some(attempt)) => attempt, - Ok(None) => return false, - Err(error) => { - self.error = Some(error.to_string()); - return false; - } - }; - self.board.clear(); - self.begin_commit(attempt, CommitKind::Preview, now); - true - } - - fn begin_commit(&mut self, attempt: TrainingAttempt, kind: CommitKind, now: Instant) { - if self.pending_commit.is_some() { - self.save_error = - Some("another learning event is still waiting to be saved".to_owned()); - return; - } - self.pending_commit = Some(PendingCommit { - attempts: vec![attempt], - kind, - }); - self.persist_pending(now); - } - - fn persist_pending(&mut self, _now: Instant) { - let Some(pending) = self.pending_commit.clone() else { - return; - }; - if self.commit_in_flight.is_some() { - return; - } - #[cfg(test)] - if self.synchronous_commits { - let result = self - .store - .apply_attempts_and_session(pending.attempts.clone(), &mut self.session) - .map_err(|error| error.to_string()); - self.finish_commit(result, _now); - return; - } - let store = self.store.clone(); - let mut session = self.session.clone(); - let (tx, rx) = mpsc::channel(); - self.commit_in_flight = Some(rx); - self.save_error = None; - if let Err(error) = crate::platform::spawn("learning-save-attempt", move || { - let result = store - .apply_attempts_and_session(pending.attempts, &mut session) - .map_err(|error| error.to_string()); - let _ = tx.send(result); - }) { - self.commit_in_flight = None; - self.save_error = Some(error.to_string()); - self.ready_since = None; - } - } - - fn poll_commit(&mut self, now: Instant) { - let Some(receiver) = &self.commit_in_flight else { - return; - }; - let result = match receiver.try_recv() { - Ok(result) => result, - Err(mpsc::TryRecvError::Empty) => return, - Err(mpsc::TryRecvError::Disconnected) => { - Err("learning save worker disconnected".to_owned()) - } - }; - self.commit_in_flight = None; - self.finish_commit(result, now); - } - - fn finish_commit(&mut self, result: Result, now: Instant) { - let Some(pending) = self.pending_commit.clone() else { - return; - }; - match result { - Ok(persisted) => { - let duplicate = persisted.application == AttemptApplication::Duplicate; - self.learning = persisted.learning; - self.session = persisted.session; - self.completed_attempt_ids.extend( - pending - .attempts - .iter() - .map(|attempt| attempt.client_attempt_id.clone()), - ); - self.pending_commit = None; - self.save_error = None; - self.confirm_discard = false; - if duplicate { - self.playback = None; - self.shown_prefix = None; - self.pause_requested = false; - self.ready_since = None; - self.needs_prepare = true; - self.prepare_presentation(now); - return; - } - match pending.kind { - CommitKind::Context => self.finish_context(now), - CommitKind::ReusedContext => self.needs_prepare = true, - CommitKind::Play { - visual, - outcome, - shown_prefix, - } => { - self.shown_prefix = (!matches!( - outcome, - PlayOutcome::WrongIndependent | PlayOutcome::WrongReplay - )) - .then_some(shown_prefix); - self.start_playback(*visual, outcome, now); - } - CommitKind::Preview => { - self.needs_prepare = true; - self.prepare_presentation(now); - } - } - } - Err(error) => { - self.save_error = Some(error.to_string()); - self.ready_since = None; - } - } - } - - fn retry_pending(&mut self, now: Instant) { - if self.pending_commit.is_some() { - self.persist_pending(now); - } - } - - fn queue_sound(&mut self, sound: Sound) { - if sound == Sound::Move && self.pending_sounds.last() == Some(&Sound::Move) { - return; - } - self.pending_sounds.push(sound); - } - - fn request_back(&mut self, actions: &mut Vec) { - if self.has_unsaved() { - self.confirm_discard = true; - } else { - actions.push(LearningTrainingAction::Back); - } - } - - fn keyboard(&mut self, ui: &Ui, actions: &mut Vec) { - if ui.ctx().egui_wants_keyboard_input() || crate::app::overlay_open(ui.ctx()) { - return; - } - let autoplay = self.is_autoplay(); - let mut command = None; - ui.input_mut(|input| { - if autoplay - && (input.consume_key(Modifiers::NONE, Key::Space) - || input.consume_key(Modifiers::NONE, Key::P)) - { - command = Some("toggle-pause"); - } else if autoplay && input.consume_key(Modifiers::NONE, Key::Escape) { - command = Some("stop"); - } else if input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W)) - || (!self.board.is_busy() && input.consume_key(Modifiers::NONE, Key::Escape)) - { - command = Some("back"); - } else if input.consume_key(Modifiers::NONE, Key::F) { - command = Some("flip"); - } else if input.consume_key(Modifiers::NONE, Key::H) { - command = Some("hint"); - } else if input.consume_key(Modifiers::NONE, Key::L) - || input.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) - { - command = Some("engine"); - } else if self.is_finished() && input.consume_key(Modifiers::NONE, Key::Enter) { - command = Some("back"); - } - }); - match command { - Some("toggle-pause") => { - if self.autoplay_paused() { - self.continue_autoplay(Instant::now()); - } else { - self.request_pause(); - } - } - Some("stop") => { - self.stop_autoplay(actions); - } - Some("back") => self.request_back(actions), - Some("flip") => self.flipped = !self.flipped, - Some("hint") => { - let id = unique_id(self.session.id()); - self.request_hint_with_id_at(id, Instant::now(), now()); - } - Some("engine") => actions.push(LearningTrainingAction::Toast( - tr("The engine is off while training").to_owned(), - )), - _ => {} - } - } - - fn board_animation_seconds(&self, settings: &Settings) -> f32 { - if self.pending_automatic.is_some() { - return 0.0; - } - match &self.playback { - Some(Playback::Automatic { duration, .. }) => duration.as_secs_f32(), - _ => settings.animation.seconds(), - } - } - - fn set_displayed_context(&mut self, played: usize) { - let prefix = self.session.current_target().and_then(|target| { - Some(ShownPrefix { - repertoire_id: target.repertoire_id.clone(), - path: target.path.get(..played)?.to_vec(), - }) - }); - self.set_displayed_path(prefix.as_ref()); - } - - fn set_displayed_path(&mut self, prefix: Option<&ShownPrefix>) { - self.displayed_node = prefix.and_then(|prefix| { - let game = self.annotation_games.get(&prefix.repertoire_id)?; - let mut at = NodeId::ROOT; - for uci in &prefix.path { - let mv = uci - .parse::() - .ok()? - .to_move(game.position(at)?) - .ok()?; - at = game.find_child(at, mv)?; - } - Some((prefix.repertoire_id.clone(), at)) - }); - } - - fn displayed_annotations(&self) -> BoardAnnotations { - let Some((id, at)) = &self.displayed_node else { - return BoardAnnotations::default(); - }; - let Some(game) = self.annotation_games.get(id) else { - return BoardAnnotations::default(); - }; - // A visual wrong move outside the source tree must never inherit the - // expected move's badge or arrows merely because the task advanced. - if game - .position(*at) - .is_none_or(|position| position != &self.board_position) - { - return BoardAnnotations::default(); - } - pgn_annotations_at(game, *at) - } - - fn board_ui(&mut self, ui: &mut Ui, settings: &Settings) { - let interactive = self.can_input(); - let annotations = self.displayed_annotations(); - let mut arrows = annotations.arrows; - if self.playback.is_none() - && let Some(uci) = self - .presentation - .as_ref() - .and_then(|presentation| presentation.revealed_move.as_deref()) - && let Some(mv) = uci - .parse::() - .ok() - .and_then(|uci| uci.to_move(&self.board_position).ok()) - { - arrows.push(Arrow { - from: mv.from().unwrap_or_else(|| mv.to()), - to: crate::board::ui_target(&mv), - color: Color32::from_rgba_unmultiplied(21, 120, 27, 190), - weight: 1.0, - }); - } - let alert = match &self.playback { - Some(Playback::Wrong { visual, .. }) => Some((visual.from, visual.to)), - _ => None, - }; - let area = ui.available_rect_before_wrap(); - let side = area.width().min(area.height()).max(1.0).floor(); - let left = area.left() + ((area.width() - side) / 2.0).max(0.0).floor(); - let top = area.top() + ((area.height() - side) / 2.0).max(0.0).floor(); - let rect = egui::Rect::from_min_size(egui::pos2(left, top), vec2(side, side)); - ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { - let played = BoardView { - pos: &self.board_position, - orientation: if self.flipped { - Color::Black - } else { - Color::White - }, - last_move: self.last_move, - arrows: &arrows, - circles: &annotations.circles, - badge: annotations.badge, - interactive, - show_coords: settings.show_coords, - theme: settings.board_theme.theme(), - pieces: settings.piece_set, - animation: self.board_animation_seconds(settings), - premove: None, - auto_queen: false, - alert, - } - .show(ui, &mut self.board); - if let Some(mv) = played { - self.play_move_at(mv, Instant::now(), now()); - } - }); - self.board_shown = true; - } - - fn status_card(&mut self, ui: &mut Ui) { - let alert = matches!(self.playback, Some(Playback::Wrong { .. })); - card(ui, alert).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.set_clip_rect(ui.max_rect()); - if self.is_finished() { - ui.label(RichText::new(tr("Training complete")).strong().size(17.0)); - } else if let Some(Playback::Automatic { - completed, total, .. - }) = &self.playback - { - ui.label( - RichText::new(trf( - "Automatic context · {current} of {total}", - &[("current", &(completed + 1)), ("total", total)], - )) - .strong(), - ); - } else if let Some(Playback::Paused { - remaining, - completed, - }) = &self.playback - { - let progress = trf( - "Automatic context · {current} of {total}", - &[ - ("current", completed), - ("total", &completed.saturating_add(remaining.len())), - ], - ); - ui.label(RichText::new(format!("{} · {progress}", tr("Paused"))).strong()); - } else if self.session.phase == LearningSessionPhase::PreviewedReplay { - ui.label(RichText::new(tr("Hint")).strong()); - } else if self.session.phase == LearningSessionPhase::AwaitingReplayAfterError { - ui.label(RichText::new(tr("Mistake")).strong()); - } - if self.can_input() { - let count = self - .session - .pending_answers_for_position(&fen4(&self.board_position)) - .len(); - if count > 1 { - ui.label(trf( - "Repertoire answers remaining here: {count}", - &[("count", &count)], - )); - } - } - if let Some(error) = self.error.clone().or_else(|| self.save_error.clone()) { - ui.colored_label( - ui.visuals().error_fg_color, - if self.save_error.is_some() { - tr("Could not save") - } else { - tr("Mistake") - }, - ); - egui::CollapsingHeader::new(tr("Details")).show(ui, |ui| { - egui::ScrollArea::vertical() - .max_height(120.0) - .show(ui, |ui| { - ui.add(egui::Label::new(error).wrap()); - }); - }); - } else if let Some(message) = &self.message - && !(self.autoplay_paused() && message == tr("Paused")) - { - ui.add(egui::Label::new(message).wrap()); - } - }); - } - - fn side(&mut self, ui: &mut Ui, actions: &mut Vec) { - let rect = ui.available_rect_before_wrap(); - let footer = egui::Rect::from_min_max( - egui::pos2(rect.left(), (rect.bottom() - 44.0).max(rect.top())), - rect.max, - ); - let body = egui::Rect::from_min_max(rect.min, egui::pos2(rect.right(), footer.top())); - ui.scope_builder(egui::UiBuilder::new().max_rect(body), |ui| { - ui.set_clip_rect(body); - self.side_body(ui, actions); - }); - ui.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| { - ui.separator(); - if ui - .add_sized( - [30.0, 30.0], - egui::Button::new(RichText::new("🔃").size(18.0)), - ) - .on_hover_text(tr("Flip board (F)")) - .clicked() - { - self.flipped = !self.flipped; - } - }); - } - - fn side_body(&mut self, ui: &mut Ui, actions: &mut Vec) { - ui.spacing_mut().item_spacing.y = 6.0; - fixed_block(ui, 44.0, |ui| { - let (done, total) = main_task_progress(&self.session); - ui.add( - egui::Label::new( - RichText::new(trf( - "Tasks: {done} of {total}", - &[("done", &done), ("total", &total)], - )) - .strong() - .size(15.0), - ) - .truncate(), - ); - let side = tr(match self.session.stats_scope.side { - LearningSide::White => "White", - LearningSide::Black => "Black", - }); - ui.add( - egui::Label::new(format!( - "{} · {side}", - queue_mode_label(self.session.session.mode) - )) - .truncate(), - ); - }); - let button_width = ((ui.available_width() - 8.0) / 2.0).clamp(80.0, 180.0); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 8.0; - let save_failed = self.pending_commit.is_some() && self.save_error.is_some(); - if save_failed { - if ui - .add_sized([button_width, 30.0], egui::Button::new(tr("Retry"))) - .clicked() - { - self.retry_pending(Instant::now()); - } - } else if self.is_autoplay() { - let paused = self.autoplay_paused(); - let label = if paused { tr("Continue") } else { tr("Pause") }; - if ui - .add_sized([button_width, 30.0], egui::Button::new(label)) - .on_hover_text("Space / P") - .clicked() - { - if paused { - self.continue_autoplay(Instant::now()); - } else { - self.request_pause(); - } - } - } else if self.is_finished() { - if crate::widgets::primary_wide(ui, tr("Back to repertoire"), button_width) - .on_hover_text("Enter") - .clicked() - { - self.request_back(actions); - } - } else if ui - .add_enabled( - self.can_hint(), - egui::Button::new(tr("Hint")).min_size(vec2(button_width, 30.0)), - ) - .clicked() - { - let id = unique_id(self.session.id()); - self.request_hint_with_id_at(id, Instant::now(), now()); - } - if save_failed { - let label = if self.confirm_discard { - tr("Exit") - } else { - tr("Back to repertoire") - }; - if ui - .add_sized([button_width, 30.0], egui::Button::new(label)) - .clicked() - { - if self.confirm_discard { - self.discard_requested = true; - } else { - self.confirm_discard = true; - } - } - } else if self.is_autoplay() { - if ui - .add_sized([button_width, 30.0], egui::Button::new(tr("Stop"))) - .on_hover_text("Escape") - .clicked() - { - self.stop_autoplay(actions); - } - } else { - ui.allocate_space(vec2(button_width, 30.0)); - } - }); - ui.add_space(2.0); - self.status_card(ui); - if self.confirm_discard && self.has_unsaved() { - ui.add( - egui::Label::new( - RichText::new(tr( - "Only the events that could not be saved will be discarded", - )) - .weak(), - ) - .wrap(), - ); - } - } - - pub fn show( - &mut self, - ui: &mut egui::Ui, - settings: &Settings, - name: &str, - ) -> Vec { - let animation = Duration::from_secs_f32(settings.animation.seconds()); - self.tick_at(Instant::now(), animation, now()); - if self.commit_in_flight.is_some() { - ui.ctx().request_repaint_after(Duration::from_millis(16)); - } else if let Some(deadline) = self.playback_deadline() { - ui.ctx() - .request_repaint_after(deadline.saturating_duration_since(Instant::now())); - } else if self.needs_prepare || self.pending_automatic.is_some() { - ui.ctx().request_repaint(); - } - let mut actions = Vec::new(); - self.keyboard(ui, &mut actions); - egui::Panel::top("learning_training_header").show(ui, |ui| { - let back = if ui.available_width() < 600.0 { - tr("Back") - } else { - tr("Back to repertoire") - }; - let (back, settings) = crate::widgets::section_header(ui, &format!("← {back}"), name); - if back { - self.request_back(&mut actions); - } - if settings { - actions.push(LearningTrainingAction::OpenSettings); - } - }); - let available = ui.available_rect_before_wrap(); - let background = ui.visuals().window_fill(); - ui.painter_at(available) - .rect_filled(available, 0.0, background); - let width = available.width(); - let height = available.height(); - let stacked = width < 900.0 && height > width; - if stacked { - let panel_height = (height * 0.52).clamp(340.0, 520.0); - let board_rect = egui::Rect::from_min_max( - available.min, - egui::pos2(available.right(), available.bottom() - panel_height), - ); - let side_rect = egui::Rect::from_min_max( - egui::pos2(available.left(), board_rect.bottom()), - available.max, - ); - ui.scope_builder(egui::UiBuilder::new().max_rect(board_rect), |ui| { - egui::CentralPanel::default().show(ui, |ui| self.board_ui(ui, settings)); - }); - ui.scope_builder(egui::UiBuilder::new().max_rect(side_rect), |ui| { - ui.set_clip_rect(side_rect); - egui::Frame::side_top_panel(ui.style()).show(ui, |ui| self.side(ui, &mut actions)); - }); - } else { - let side = egui::Panel::right("repertoire_workspace_side") - .resizable(true) - .default_size((width * 0.42).clamp(420.0, 560.0)) - .size_range(360.0..=(width - 220.0).max(360.0)) - .show(ui, |ui| self.side(ui, &mut actions)); - crate::widgets::check_panel("learning_training_side", &side.response); - egui::CentralPanel::default().show(ui, |ui| self.board_ui(ui, settings)); - } - actions.extend( - self.pending_sounds - .drain(..) - .map(LearningTrainingAction::Sound), - ); - if self.has_unsaved() && !self.discard_requested { - actions.retain(|action| !matches!(action, LearningTrainingAction::Back)); - } - if std::mem::take(&mut self.discard_requested) { - actions.push(LearningTrainingAction::Back); - } - actions - } - - pub fn debug_settle(&mut self) { - // Only this explicit QA hook waits. Normal frames poll workers without blocking. - let deadline = Instant::now() + Duration::from_secs(10); - loop { - if self.commit_in_flight.is_some() { - self.poll_commit(Instant::now()); - if Instant::now() >= deadline { - return; - } - if self.commit_in_flight.is_some() { - std::thread::sleep(Duration::from_millis(1)); - continue; - } - } - if self.has_unsaved() { - return; - } - if self.pending_automatic.is_some() { - self.board_shown = true; - } - let at = self - .playback_deadline() - .map_or_else(Instant::now, |at| at.max(Instant::now())); - self.tick_at(at, Duration::ZERO, now()); - if self.commit_in_flight.is_none() - && self.pending_automatic.is_none() - && !self.needs_prepare - && self.playback_deadline().is_none() - { - return; - } - if Instant::now() >= deadline { - return; - } - } - } - - pub fn debug_hint(&mut self) { - if self.needs_prepare { - self.debug_settle(); - } - let id = unique_id(self.session.id()); - self.request_hint_with_id_at(id, Instant::now(), now()); - } - - pub fn debug_moves(&mut self, moves: &str) { - if self.needs_prepare { - self.debug_settle(); - } - for text in moves.split_whitespace() { - match text { - "hint" => self.debug_hint(), - "settle" | "wait" => self.debug_settle(), - _ => { - let id = unique_id(self.session.id()); - self.play_uci_with_id_at(text, id, Instant::now(), now()); - } - } - } - } -} - -impl VisualMove { - fn from_context(step: &LearningContextStep) -> Result { - let before = parse_position(&step.from)?; - let mv = step - .uci - .parse::() - .ok() - .and_then(|uci| uci.to_move(&before).ok()) - .ok_or_else(|| format!("automatic context move {} is not legal", step.uci))?; - Ok(Self::new(step.uci.clone(), before, mv)) - } - - fn new(uci: String, before: Chess, mv: Move) -> Self { - let from = mv.from().unwrap_or_else(|| mv.to()); - let to = crate::board::ui_target(&mv); - let mut after = before.clone(); - after.play_unchecked(mv); - Self { - uci, - before, - after, - from, - to, - } - } -} - -fn parse_position(position: &trainer::repertoire::LearningPosition) -> Result { - position - .fen - .parse::() - .map_err(|error| error.to_string())? - .into_position(CastlingMode::Standard) - .map_err(|error| error.to_string()) -} - -fn main_task_progress(session: &LearningSessionSnapshot) -> (usize, usize) { - let total = session.queue.len(); - (total.saturating_sub(session.remaining()), total) -} - -pub fn queue_mode_label(mode: QueueMode) -> &'static str { - tr(match mode { - QueueMode::SpacedRepetition | QueueMode::Practice => "On schedule", - QueueMode::ReviewInOrder => "Review in order", - QueueMode::LeastRecent => "Least recent and unseen first", - }) -} - -fn compatible(session: &LearningSessionSnapshot, scope: &StatsScope, mode: QueueMode) -> bool { - let expected_side = match scope.side { - LearningSide::White => TrainingMode::White, - LearningSide::Black => TrainingMode::Black, - }; - session.session.mode == mode - && session.session.side == expected_side - && session.stats_scope.repertoire_ids == scope.repertoire_ids - && session.stats_scope.side == scope.side - && session.stats_scope.max_depth == scope.max_depth - && session.stats_scope.only_active == scope.only_active - && session.stats_scope.branch_root == scope.branch_root - && session.stats_scope.learning_priority == scope.learning_priority -} - -fn unique_id(prefix: &str) -> String { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |duration| duration.as_nanos()); - let sequence = NEXT_ID.fetch_add(1, Ordering::Relaxed); - format!("{prefix}-{nanos:x}-{}-{sequence:x}", std::process::id()) -} - -fn now() -> i64 { - chrono::Local::now().timestamp() -} - -fn fixed_block(ui: &mut Ui, height: f32, add: impl FnOnce(&mut Ui)) { - let width = ui.available_width().max(1.0); - let (rect, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover()); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect)); - child.set_clip_rect(rect); - add(&mut child); -} - -fn card(ui: &Ui, alert: bool) -> egui::Frame { - egui::Frame::new() - .inner_margin(egui::Margin::symmetric(10, 6)) - .corner_radius(4) - .stroke(egui::Stroke::new( - if alert { 1.5 } else { 1.0 }, - if alert { - ui.visuals().error_fg_color - } else { - ui.visuals().widgets.noninteractive.bg_stroke.color - }, - )) -} - -#[cfg(test)] -mod tests { - use std::path::PathBuf; - - use super::*; - use trainer::repertoire::{ - LearningItemKey, LearningPriority, LearningStoreData, active_learning_memberships, - }; - - #[test] - fn status_growth_does_not_move_training_controls() { - let mut positions = Vec::new(); - for message in [ - "Your turn", - "Hint\nReplay the shown move\nNo independent success", - ] { - let ctx = egui::Context::default(); - let output = ctx.run_ui(egui::RawInput::default(), |ui| { - egui::CentralPanel::default().show(ui, |ui| { - fixed_block(ui, 144.0, |ui| { - ui.label(message); - }); - positions.push(ui.button("Hint").rect.top()); - }); - }); - output.drop_without_applying_deltas(); - } - assert_eq!(positions[0], positions[1]); - assert!(positions[0] >= 144.0); - } - - const NOW: i64 = 1_800_000_000; - static NEXT_TEST: AtomicU64 = AtomicU64::new(1); - - struct TestDir(PathBuf); - - impl TestDir { - fn new(name: &str) -> Self { - let path = std::env::temp_dir().join(format!( - "cp-learning-training-{}-{}-{name}", - std::process::id(), - NEXT_TEST.fetch_add(1, Ordering::Relaxed) - )); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - Self(path) - } - - fn store(&self) -> LearningStore { - LearningStore::new(self.0.join("learning.json")) - } - } - - impl Drop for TestDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } - } - - struct Fixture { - _dir: TestDir, - library: Library, - scope: StatsScope, - store: LearningStore, - ui: LearningTrainingUi, - } - - impl Fixture { - fn new(pgn: &str, side: LearningSide, due: &[&str], name: &str) -> Self { - Self::with_introduction(pgn, side, due, name, false) - } - - fn with_introduction( - pgn: &str, - side: LearningSide, - due: &[&str], - name: &str, - introduce_new: bool, - ) -> Self { - let dir = TestDir::new(name); - let mut library = Library::default(); - let id = library - .create("Test", &chess_core::parse_str(pgn).game) - .unwrap(); - let scope = StatsScope::for_repertoire(id, side, NOW); - let mut learning = LearningData::default(); - for expected in due { - let key = key_for(&library, &scope, expected); - let item = learning.ensure_item(key); - item.introduced = true; - item.next_review_at = Some(NOW); - } - let bytes = serde_json::to_vec_pretty(&LearningStoreData { - learning, - ..LearningStoreData::default() - }) - .unwrap(); - std::fs::write(dir.0.join("learning.json"), bytes).unwrap(); - let store = dir.store(); - let mut ui = LearningTrainingUi::new( - library.clone(), - store.clone(), - scope.clone(), - SrsSettings::default(), - introduce_new, - false, - ) - .unwrap(); - ui.board_shown = true; - ui.synchronous_commits = true; - Self { - _dir: dir, - library, - scope, - store, - ui, - } - } - - fn with_mode( - pgn: &str, - side: LearningSide, - history: &[(&str, i64)], - name: &str, - mode: QueueMode, - priority: LearningPriority, - ) -> Self { - let dir = TestDir::new(name); - let mut library = Library::default(); - let id = library - .create("Test", &chess_core::parse_str(pgn).game) - .unwrap(); - let scope = StatsScope::for_repertoire(id, side, NOW).with_learning_priority(priority); - let mut learning = LearningData::default(); - for (expected, reviewed_at) in history { - let key = key_for(&library, &scope, expected); - let item = learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 1; - item.correct_count = 1; - item.last_review_at = Some(*reviewed_at); - item.last_correct_at = Some(*reviewed_at); - item.next_review_at = Some(NOW + 10 * 24 * 60 * 60); - item.previous_interval_seconds = Some(24 * 60 * 60); - } - let bytes = serde_json::to_vec_pretty(&LearningStoreData { - learning, - ..LearningStoreData::default() - }) - .unwrap(); - std::fs::write(dir.0.join("learning.json"), bytes).unwrap(); - let store = dir.store(); - let mut ui = LearningTrainingUi::new_with_mode( - library.clone(), - store.clone(), - scope.clone(), - SrsSettings::default(), - false, - false, - mode, - ) - .unwrap(); - ui.board_shown = true; - ui.synchronous_commits = true; - Self { - _dir: dir, - library, - scope, - store, - ui, - } - } - - fn attempts(&self) -> Vec { - self.store.load().unwrap().learning.attempts - } - } - - fn key_for(library: &Library, scope: &StatsScope, expected: &str) -> LearningItemKey { - active_learning_memberships(library, scope) - .unwrap() - .into_iter() - .find(|membership| membership.key.expected_uci == expected) - .unwrap() - .key - } - - fn normal() -> Duration { - Duration::from_millis(250) - } - - fn answer_current(f: &mut Fixture, at: Instant, happened_at: i64, id: &str) { - let expected = f.ui.session.current_expected_uci().unwrap().to_owned(); - assert!(f.ui.play_uci_with_id_at(&expected, id.to_owned(), at, happened_at,)); - tick_with_prime(&mut f.ui, at, Duration::ZERO, happened_at); - } - - #[test] - fn new_session_saves_custom_policy_and_resume_keeps_persisted_policy() { - let f = Fixture::new( - "1. e4 *", - LearningSide::White, - &[], - "context-policy-persistence", - ); - assert_eq!( - f.ui.session.context_policy, - LearningContextPolicy::default() - ); - let policy = LearningContextPolicy { - reinforce_minimum_correct: 6, - reinforce_minimum_days: Some(21), - dont_show_start_moves_threshold: 9, - use_fixed_piece_speed: false, - move_speed_adjustment: 1.5, - consider_leadup_moves: true, - }; - let started = LearningTrainingUi::new_with_policy( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - true, - false, - QueueMode::SpacedRepetition, - policy, - ) - .unwrap(); - assert_eq!(started.session.context_policy, policy); - let read_store = || { - let bytes = std::fs::read(f.store.path()).unwrap(); - serde_json::from_slice::(&bytes).unwrap() - }; - assert_eq!( - read_store() - .session_snapshot(started.session_id()) - .unwrap() - .context_policy, - policy - ); - - let resumed = LearningTrainingUi::new_with_policy( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - false, - false, - QueueMode::SpacedRepetition, - LearningContextPolicy { - reinforce_minimum_correct: 99, - ..LearningContextPolicy::default() - }, - ) - .unwrap(); - assert_eq!(resumed.session_id(), started.session_id()); - assert_eq!(resumed.session.context_policy, policy); - assert_eq!( - read_store() - .session_snapshot(started.session_id()) - .unwrap() - .context_policy, - policy - ); - } - - fn board_frame(f: &mut Fixture, ctx: &egui::Context, time: f64, settings: &Settings) { - ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(800.0, 800.0), - )), - time: Some(time), - ..Default::default() - }, - |ui| f.ui.board_ui(ui, settings), - ) - .drop_without_applying_deltas(); - } - - fn tick_with_prime( - ui: &mut LearningTrainingUi, - at: Instant, - animation: Duration, - happened_at: i64, - ) { - ui.tick_at(at, animation, happened_at); - if ui.pending_automatic.is_none() { - return; - } - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - let settings = Settings::default(); - ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(800.0, 800.0), - )), - time: Some(0.0), - ..Default::default() - }, - |root| ui.board_ui(root, &settings), - ) - .drop_without_applying_deltas(); - assert!(ui.board_shown); - assert!(ui.board.animation_at(0.0).is_none()); - ui.tick_at(at, animation, happened_at); - } - - fn automatic_duration(f: &Fixture) -> Duration { - match &f.ui.playback { - Some(Playback::Automatic { duration, .. }) => *duration, - _ => panic!("automatic playback expected"), - } - } - - fn assert_current_slide( - f: &Fixture, - time: f64, - expected_duration: Duration, - from: Square, - to: Square, - ) { - let (duration, slides, remaining) = - f.ui.board - .animation_at(time) - .expect("the current BoardView transition"); - assert_eq!(remaining, 1.0, "the first visual frame must be at from"); - assert!( - (duration - f64::from(expected_duration.as_secs_f32())).abs() < 1e-6, - "animation {duration} does not match scheduler {}", - expected_duration.as_secs_f32() - ); - assert!( - slides - .iter() - .any(|(_, slide_from, slide_to)| *slide_from == from && *slide_to == to), - "missing {from}{to} in {slides:?}" - ); - } - - fn assert_adaptive_board_slides(f: &mut Fixture, first_ms: u128, last_ms: u128) { - let ctx = egui::Context::default(); - let settings = Settings::default(); - let start = Instant::now(); - f.ui.board_shown = false; - f.ui.tick_at(start, normal(), NOW); - board_frame(f, &ctx, 0.0, &settings); - assert!(f.ui.board.animation_at(0.0).is_none()); - - f.ui.tick_at(start, normal(), NOW); - let first = automatic_duration(f); - assert_eq!(first.as_millis(), first_ms); - assert_eq!(f.ui.playback_deadline(), Some(start + first)); - assert_eq!(f.ui.session.context_index, 0); - board_frame(f, &ctx, 0.01, &settings); - assert_current_slide(f, 0.01, first, Square::E2, Square::E4); - assert!(f.ui.message.is_none()); - - tick_with_prime(&mut f.ui, start + first, normal(), NOW); - let last = automatic_duration(f); - assert_eq!(last.as_millis(), last_ms); - assert_eq!(f.ui.session.context_index, 1); - board_frame(f, &ctx, 0.02, &settings); - assert_current_slide(f, 0.02, last, Square::E7, Square::E5); - assert!(f.ui.message.is_none()); - - tick_with_prime(&mut f.ui, start + first + last, normal(), NOW); - assert_eq!(f.ui.session.context_index, 2); - assert!(f.ui.can_input()); - board_frame(f, &ctx, 10.0, &settings); - assert!( - f.ui.board.animation_at(10.0).is_none(), - "the final position must not start a settings-duration slide" - ); - assert_eq!(f.attempts().len(), 2); - } - - #[test] - fn adaptive_board_animation_matches_actual_slides_and_starts_at_from() { - let mut fast = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - &["g1f3"], - "adaptive-fast", - ); - let e4 = key_for(&fast.library, &fast.scope, "e2e4"); - fast.ui.learning.ensure_item(e4).correct_streak = 3; - fast.ui.session.context_policy.use_fixed_piece_speed = false; - fast.ui.session.context_policy.move_speed_adjustment = 1.5; - assert_adaptive_board_slides(&mut fast, 83, 166); - - let mut slow = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - &["g1f3"], - "adaptive-slow", - ); - slow.ui.session.context_policy.use_fixed_piece_speed = false; - slow.ui.session.context_policy.move_speed_adjustment = 0.0; - assert_adaptive_board_slides(&mut slow, 1000, 1000); - } - - #[test] - fn next_target_continues_the_shown_line_without_reverse_slide() { - fn settle_to_input(f: &mut Fixture, at: Instant) { - let mut at = at; - for _ in 0..32 { - if f.ui.can_input() { - return; - } - let next = f.ui.playback_deadline().unwrap_or(at); - tick_with_prime(&mut f.ui, next, normal(), NOW); - at = next; - } - panic!("training did not reach independent input"); - } - - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", - LearningSide::Black, - &["e7e5", "b8c6", "a7a6"], - "next-target-prime", - ); - f.ui.session.context_policy.use_fixed_piece_speed = false; - f.ui.session.context_policy.move_speed_adjustment = 0.0; - let start = Instant::now(); - settle_to_input(&mut f, start); - assert_eq!(f.ui.session.current_expected_uci(), Some("e7e5")); - answer_current( - &mut f, - start + Duration::from_secs(1), - NOW, - "first-target-e5", - ); - - settle_to_input(&mut f, start + Duration::from_secs(1) + normal()); - assert_eq!(f.ui.session.current_expected_uci(), Some("b8c6")); - answer_current( - &mut f, - start + Duration::from_secs(3), - NOW + 1, - "second-target-nc6", - ); - - let prime_at = start + Duration::from_secs(3) + normal(); - // Every old move keeps its event, but a long visible prefix requires - // only one store transaction before the next opponent move. - let before_reuse = f.store.load().unwrap(); - for _ in 0..8 { - f.ui.tick_at(prime_at, normal(), NOW); - if f.ui.pending_automatic.is_some() { - break; - } - } - assert!(f.ui.pending_automatic.is_some()); - let after_reuse = f.store.load().unwrap(); - assert_eq!(after_reuse.revision, before_reuse.revision + 1); - let added = &after_reuse.learning.attempts[before_reuse.learning.attempts.len()..]; - assert_eq!(added.len(), 4); - assert!( - added - .iter() - .all(|event| event.event_type == TrainingEventType::AutoContext) - ); - assert_eq!(f.ui.session.context_index, 4); - assert!(!f.ui.board_shown); - let ctx = egui::Context::default(); - let settings = Settings::default(); - board_frame(&mut f, &ctx, 10.0, &settings); - assert!( - f.ui.board.animation_at(10.0).is_none(), - "prime must not animate the previous target backwards" - ); - - f.ui.tick_at(prime_at, normal(), NOW); - let duration = automatic_duration(&f); - assert_eq!(duration, Duration::from_millis(1000)); - board_frame(&mut f, &ctx, 10.01, &settings); - assert_current_slide(&f, 10.01, duration, Square::F1, Square::B5); - let (_, slides, _) = f.ui.board.animation_at(10.01).unwrap(); - assert!( - slides - .iter() - .all(|(_, from, to)| !(*from == Square::F3 && *to == Square::G1)), - "next target started with a reverse slide: {slides:?}" - ); - assert!(matches!( - f.ui.playback, - Some(Playback::Automatic { total: 1, .. }) - )); - } - - fn emitted_sounds(f: &mut Fixture, ctx: &egui::Context, settings: &Settings) -> Vec { - let mut sounds = Vec::new(); - ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - vec2(960.0, 600.0), - )), - ..Default::default() - }, - |ui| { - sounds.extend( - f.ui.show(ui, settings, "Test") - .into_iter() - .filter_map(|action| { - if let LearningTrainingAction::Sound(sound) = action { - Some(sound) - } else { - None - } - }), - ); - }, - ) - .drop_without_applying_deltas(); - sounds - } - - #[test] - fn accepted_move_emits_once_and_next_task_only_animates_the_opponent_reply() { - for side in [LearningSide::White, LearningSide::Black] { - for animation in [ - crate::settings::Animation::Normal, - crate::settings::Animation::Off, - ] { - for replay in [false, true] { - let (due, reply, wrong) = match side { - LearningSide::White => (["e2e4", "g1f3"], "e7e5", "d2d4"), - LearningSide::Black => (["e7e5", "b8c6"], "g1f3", "d7d5"), - }; - let mut f = - Fixture::new("1. e4 e5 2. Nf3 Nc6 *", side, &due, "continuous-feedback"); - tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); - let ctx = egui::Context::default(); - let settings = Settings { - animation, - ..Settings::default() - }; - let at = Instant::now() + Duration::from_secs(60); - let duration = Duration::from_secs_f32(animation.seconds()); - f.ui.animation = duration; - f.ui.pending_sounds.clear(); - f.ui.visual_log.clear(); - if replay { - assert!(f.ui.play_uci_with_id_at( - wrong, - "wrong".into(), - at - WRONG_SHOWN, - NOW - )); - f.ui.tick_at(at, duration, NOW); - assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Wrong]); - } - assert!(f.ui.play_uci_with_id_at(due[0], "accepted".into(), at, NOW)); - let accepted_position = fen4(&f.ui.board_position); - assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Move]); - for _ in 0..8 { - f.ui.tick_at(at + duration, duration, NOW); - assert_eq!( - fen4(&f.ui.board_position), - accepted_position, - "accepted move must not rewind" - ); - if f.ui.pending_automatic.is_some() { - break; - } - } - assert!(f.ui.pending_automatic.is_some()); - // The prime frame is silent; a separate later frame emits the - // opponent move, so queue coalescing cannot conceal a duplicate. - assert!(emitted_sounds(&mut f, &ctx, &settings).is_empty()); - assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Move]); - assert_eq!(f.ui.visual_log, [reply]); - f.ui.debug_settle(); - assert_eq!(f.ui.session.current_expected_uci(), Some(due[1])); - let attempts = f.attempts(); - assert_eq!( - attempts - .iter() - .filter(|event| event.event_type.is_independent()) - .count(), - 1 - ); - assert!(attempts.iter().any(|event| event.expected_uci == due[0] - && event.event_type == TrainingEventType::AutoContext)); - assert_eq!( - attempts - .iter() - .filter(|event| event.event_type == TrainingEventType::ReplayAfterError) - .count(), - usize::from(replay) - ); - } - } - } - } - - #[test] - fn shown_context_requires_the_same_history_and_never_bypasses_a_question() { - let mut f = Fixture::new( - "1. Nf3 Nf6 2. g3 g6 3. Bg2 *", - LearningSide::White, - &["f1g2"], - "context-identity", - ); - let presentation = - f.ui.session - .presentation_with_learning(&f.library, &f.ui.learning) - .unwrap(); - f.ui.board_position = parse_position(&presentation.automatic_context[3].to).unwrap(); - let id = f.ui.session.current_target().unwrap().repertoire_id.clone(); - // Even with an identical final position, a different move order must not - // reuse context. A matching FEN alone cannot establish repetition history. - f.ui.shown_prefix = Some(ShownPrefix { - repertoire_id: id.clone(), - path: vec!["g2g3".into(), "g7g6".into(), "g1f3".into(), "g8f6".into()], - }); - assert!(!f.ui.reuse_shown_context(&presentation, Instant::now())); - assert!(f.attempts().is_empty()); - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - &["g1f3"], - "context-question", - ); - let presentation = - f.ui.session - .presentation_with_learning(&f.library, &f.ui.learning) - .unwrap(); - f.ui.board_position = parse_position(&presentation.automatic_context[1].to).unwrap(); - f.ui.shown_prefix = Some(ShownPrefix { - repertoire_id: f.ui.session.current_target().unwrap().repertoire_id.clone(), - path: vec!["e2e4".into(), "e7e5".into()], - }); - f.ui.session.context_policy.consider_leadup_moves = true; - let question = - f.ui.session - .presentation_with_learning(&f.library, &f.ui.learning) - .unwrap(); - assert_eq!( - question.phase, - LearningSessionPhase::AwaitingContextIndependent - ); - assert!(!f.ui.reuse_shown_context(&question, Instant::now())); - f.ui.prepare_presentation(Instant::now()); - assert!(f.ui.can_input()); - assert_eq!(f.ui.session.current_expected_uci(), Some("e2e4")); - assert!(f.attempts().is_empty()); - } - - fn assert_annotation_badge(ui: &LearningTrainingUi, text: &str, square: Square) { - let annotation = ui.displayed_annotations(); - let badge = annotation.badge.expect("PGN move badge"); - assert_eq!(badge.text, text); - assert_eq!(badge.square, square); - } - - #[test] - fn pgn_annotations_follow_visible_user_and_automatic_moves_not_the_next_task() { - let mut f = Fixture::new( - "1. e4!! {[%cal Re2e4,Ge7e5] [%csl Ye4,Re5]} e5?! {[%cal Bg1f3]} 2. Nf3! {[%csl Gf3]} Nc6 *", - LearningSide::White, - &["e2e4", "g1f3"], - "visible-pgn-annotations", - ); - let original = - f.ui.library - .repertoire(f.scope.repertoire_ids.iter().next().unwrap()) - .unwrap() - .pgn - .clone(); - let start = Instant::now(); - f.ui.tick_at(start, normal(), NOW); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert!(f.ui.displayed_annotations().arrows.is_empty()); - // A hint reveals the expected move, not that future node's annotations. - assert!(f.ui.request_hint_with_id_at("annotation-hint".into(), start, NOW)); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert!(f.ui.displayed_annotations().arrows.is_empty()); - assert!(f.ui.play_uci_with_id_at("e2e4", "annotation-e4".into(), start, NOW)); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "g1f3" - ); - assert_annotation_badge(&f.ui, "!!", Square::E4); - let annotation = f.ui.displayed_annotations(); - assert_eq!(annotation.arrows.len(), 2); - assert_eq!(annotation.circles.len(), 2); - assert!( - annotation - .arrows - .iter() - .any(|arrow| arrow.from == Square::E2 - && arrow.to == Square::E4 - && arrow.color == crate::game_view::shape_color(chess_core::ShapeColor::Red)) - ); - // Verify the helper's data actually reaches the rendered BoardView. - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - let output = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &Settings::default()); - assert!(output.shapes.iter().any( - |shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == "!!") - )); - output.drop_without_applying_deltas(); - f.ui.tick_at(start + normal(), normal(), NOW); - assert_annotation_badge(&f.ui, "!!", Square::E4); - assert!(f.ui.visual_log.is_empty(), "reused e4 must not play again"); - for _ in 0..8 { - tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); - if matches!(f.ui.playback, Some(Playback::Automatic { .. })) { - break; - } - } - assert_eq!(f.ui.visual_log, ["e7e5"]); - assert_annotation_badge(&f.ui, "?!", Square::E5); - assert_eq!(f.ui.displayed_annotations().arrows[0].from, Square::G1); - f.ui.tick_at(f.ui.playback_deadline().unwrap(), normal(), NOW); - assert!(f.ui.can_input()); - assert_annotation_badge(&f.ui, "?!", Square::E5); - assert!( - f.ui.displayed_annotations().circles.is_empty(), - "future Nf3 circle leaked before the answer" - ); - assert!(f.ui.play_uci_with_id_at( - "g1f3", - "annotation-nf3".into(), - start + Duration::from_secs(1), - NOW - )); - assert_annotation_badge(&f.ui, "!", Square::F3); - assert_eq!(f.ui.displayed_annotations().circles[0].0, Square::F3); - f.ui.debug_settle(); - assert_annotation_badge(&f.ui, "!", Square::F3); - assert_eq!( - f.ui.library - .repertoire(f.scope.repertoire_ids.iter().next().unwrap()) - .unwrap() - .pgn, - original - ); - } - - #[test] - fn pgn_annotations_clear_for_wrong_moves_and_survive_failed_async_save_and_retry() { - let mut f = Fixture::new( - "1. e4!! {[%csl Ge4]} *", - LearningSide::White, - &["e2e4"], - "annotations-retry", - ); - let start = Instant::now(); - f.ui.tick_at(start, normal(), NOW); - assert!(f.ui.play_uci_with_id_at("d2d4", "annotations-wrong".into(), start, NOW)); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert!(f.ui.displayed_annotations().circles.is_empty()); - f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); - assert!(f.ui.can_input()); - assert!(f.ui.displayed_annotations().badge.is_none()); - // Another wrong move during replay must not inherit the revealed e4 badge. - assert!(f.ui.play_uci_with_id_at( - "d2d4", - "annotations-wrong-replay".into(), - start + WRONG_SHOWN, - NOW - )); - assert!(f.ui.displayed_annotations().badge.is_none()); - f.ui.tick_at(start + WRONG_SHOWN * 2, normal(), NOW); - let store = f.ui.store.clone(); - f.ui.synchronous_commits = false; - f.ui.store = LearningStore::with_legacy(store.path(), store.path()); - assert!(f.ui.play_uci_with_id_at( - "e2e4", - "annotations-replay".into(), - start + WRONG_SHOWN * 2, - NOW - )); - assert!(f.ui.has_unsaved()); - assert_annotation_badge(&f.ui, "!!", Square::E4); - wait_for_commit(&mut f.ui); - assert!(f.ui.save_error.is_some()); - assert_annotation_badge(&f.ui, "!!", Square::E4); - f.ui.store = store; - f.ui.retry_pending(Instant::now()); - wait_for_commit(&mut f.ui); - assert_annotation_badge(&f.ui, "!!", Square::E4); - assert_eq!( - f.attempts() - .iter() - .filter(|attempt| attempt.event_type.is_independent()) - .count(), - 1 - ); - assert_eq!( - f.attempts().last().unwrap().event_type, - TrainingEventType::ReplayAfterError - ); - } - - #[test] - fn alternative_answer_credits_actual_move_and_completed_answer_is_silent_and_neutral() { - let mut f = Fixture::new( - "1. e4! (1. d4!! {[%csl Gd4]}) *", - LearningSide::White, - &["e2e4", "d2d4"], - "alternative-answers", - ); - let start = Instant::now(); - f.ui.tick_at(start, normal(), NOW); - let original = f.ui.session.current_expected_uci().unwrap().to_owned(); - let (played, badge, square) = if original == "e2e4" { - ("d2d4", "!!", Square::D4) - } else { - ("e2e4", "!", Square::E4) - }; - let initial_position = f.ui.board_position.clone(); - assert_eq!( - f.ui.session - .pending_answers_for_position(&fen4(&initial_position)) - .len(), - 2 - ); - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - let output = ctx.run_ui(egui::RawInput::default(), |ui| f.ui.status_card(ui)); - assert!(output.shapes.iter().any(|shape| matches!(&shape.shape, - egui::Shape::Text(text) if text.galley.text().contains("2")))); - output.drop_without_applying_deltas(); - assert!(f.ui.play_uci_with_id_at(played, "actual-alternative".into(), start, NOW)); - assert_annotation_badge(&f.ui, badge, square); - assert_eq!(f.attempts().len(), 1); - assert_eq!(f.attempts()[0].expected_uci, played); - assert_eq!( - f.attempts()[0].event_type, - TrainingEventType::CorrectIndependent - ); - assert_eq!(f.ui.session.current_expected_uci(), Some(original.as_str())); - assert_eq!(std::mem::take(&mut f.ui.pending_sounds), [Sound::Move]); - f.ui.tick_at(start + normal(), normal(), NOW); - assert_eq!(f.ui.board_position, initial_position); - assert!(f.ui.play_uci_with_id_at( - played, - "repeat-alternative".into(), - start + normal(), - NOW - )); - assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); - assert_annotation_badge(&f.ui, badge, square); - assert!(f.ui.message.as_deref().unwrap().contains(tr( - "This repertoire move has already been reviewed in this session." - ))); - assert!(f.ui.save_error.is_none() && f.ui.error.is_none()); - assert!(emitted_sounds(&mut f, &ctx, &Settings::default()).is_empty()); - f.ui.tick_at(start + normal() + WRONG_SHOWN, normal(), NOW); - assert_eq!(f.ui.board_position, initial_position); - assert!(f.ui.can_input()); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert_eq!(f.attempts().len(), 1); - assert_eq!(f.ui.session.remaining(), 1); - assert!(emitted_sounds(&mut f, &ctx, &Settings::default()).is_empty()); - } - - #[test] - fn move_input_uses_the_startup_answer_snapshot_in_independent_and_replay_phases() { - let mut f = Fixture::new( - "1. e4 (1. d4) *", - LearningSide::White, - &["e2e4"], - "cached-repertoire-answers", - ); - let start = Instant::now(); - f.ui.tick_at(start, normal(), NOW); - let key = key_for(&f.library, &f.scope, "d2d4"); - assert!(f.ui.repertoire_answers.contains(&key)); - // The production library is immutable for the UI's lifetime. Change it - // only here to detect any accidental rebuilding in the input hot path. - let id = f.scope.repertoire_ids.iter().next().unwrap(); - f.ui.library - .repertoire_mut(id) - .unwrap() - .set_prefix_disabled(&["d2d4".to_owned()], true) - .unwrap(); - assert!( - !active_learning_keys(&f.ui.library, &f.scope) - .unwrap() - .contains(&key) - ); - assert!(f.ui.play_uci_with_id_at("d2d4", "cached-independent".into(), start, NOW)); - assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); - assert!(f.attempts().is_empty()); - f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); - assert!(f.ui.request_hint_with_id_at("cached-preview".into(), start + WRONG_SHOWN, NOW)); - assert!(f.ui.play_uci_with_id_at("d2d4", "cached-replay".into(), start + WRONG_SHOWN, NOW)); - assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); - assert_eq!(f.attempts().len(), 1); - assert_eq!(f.attempts()[0].event_type, TrainingEventType::Previewed); - assert!(f.ui.pending_sounds.is_empty()); - } - - #[test] - fn known_unscheduled_answer_during_hint_is_neutral_but_outside_move_still_wrong() { - let mut f = Fixture::new( - "1. e4! (1. d4!! {[%csl Gd4]}) *", - LearningSide::White, - &["e2e4"], - "hint-alternative", - ); - let start = Instant::now(); - f.ui.tick_at(start, normal(), NOW); - assert!(f.ui.request_hint_with_id_at("preview-alternative".into(), start, NOW)); - let attempts = f.attempts().len(); - let snapshot = f.ui.session.clone(); - assert!(f.ui.play_uci_with_id_at("d2d4", "unscheduled-alternative".into(), start, NOW)); - assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); - assert_annotation_badge(&f.ui, "!!", Square::D4); - assert_eq!(f.ui.session, snapshot); - assert!(f.ui.pending_sounds.is_empty()); - f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); - assert_eq!(f.attempts().len(), attempts); - assert!(f.ui.can_input()); - assert!(f.ui.message.as_deref().unwrap().contains(tr( - "This move is in your repertoire, but is not a task in this session." - ))); - assert!(f.ui.play_uci_with_id_at( - "g1f3", - "outside-repertoire".into(), - start + WRONG_SHOWN, - NOW - )); - assert!(matches!(f.ui.playback, Some(Playback::Wrong { .. }))); - assert_eq!(f.ui.pending_sounds, [Sound::Wrong]); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert_eq!(f.attempts().len(), attempts); - } - - #[test] - fn authored_wrong_branch_has_its_own_annotations_only_after_it_is_played() { - let mut f = Fixture::new( - "1. e4! (1. d4?? {[%csl Rd4]}) e5 *", - LearningSide::White, - &["e2e4"], - "wrong-branch-annotations", - ); - let start = Instant::now(); - f.ui.tick_at(start, normal(), NOW); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert!(f.ui.play_uci_with_id_at("d2d4", "authored-wrong-branch".into(), start, NOW)); - assert_annotation_badge(&f.ui, "??", Square::D4); - assert_eq!( - f.ui.displayed_annotations().circles[0], - ( - Square::D4, - crate::game_view::shape_color(chess_core::ShapeColor::Red) - ) - ); - f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert!(f.ui.displayed_annotations().circles.is_empty()); - } - - #[test] - fn pgn_annotation_cursor_distinguishes_transposed_paths_and_repertoire_sources() { - let mut f = Fixture::new( - "1. Nf3 (1. g3 g6 2. Nf3 Nf6? {[%csl Rf6]} 3. Bg2) Nf6 2. g3 g6! {[%csl Gg6]} 3. Bg2 *", - LearningSide::White, - &["f1g2"], - "annotations-transposition", - ); - let id = f.ui.session.current_target().unwrap().repertoire_id.clone(); - let mut position_keys = Vec::new(); - for (path, badge, square) in [ - (["g1f3", "g8f6", "g2g3", "g7g6"], "!", Square::G6), - (["g2g3", "g7g6", "g1f3", "g8f6"], "?", Square::F6), - ] { - f.ui.set_displayed_path(Some(&ShownPrefix { - repertoire_id: id.clone(), - path: path.map(str::to_owned).to_vec(), - })); - let (_, node) = f.ui.displayed_node.as_ref().expect("exact PGN branch"); - f.ui.board_position = f.ui.annotation_games[&id].position(*node).unwrap().clone(); - position_keys.push(fen4(&f.ui.board_position)); - assert_annotation_badge(&f.ui, badge, square); - assert_eq!(f.ui.displayed_annotations().circles[0].0, square); - } - assert_eq!( - position_keys[0], position_keys[1], - "fixture must really transpose" - ); - let other_id = - f.ui.library - .create("Other annotations", &Game::new()) - .unwrap(); - f.ui.annotation_games.insert( - other_id.clone(), - chess_core::parse_str("1. Nf3 Nf6 2. g3 g6?? {[%csl Yg6]} *").game, - ); - f.ui.set_displayed_path(Some(&ShownPrefix { - repertoire_id: other_id.clone(), - path: ["g1f3", "g8f6", "g2g3", "g7g6"].map(str::to_owned).to_vec(), - })); - let (_, node) = f.ui.displayed_node.as_ref().unwrap(); - f.ui.board_position = f.ui.annotation_games[&other_id] - .position(*node) - .unwrap() - .clone(); - assert_annotation_badge(&f.ui, "??", Square::G6); - } - - #[test] - fn debug_moves_settles_prime_between_targets() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", - LearningSide::Black, - &["e7e5", "b8c6", "a7a6"], - "debug-prime-between-targets", - ); - f.ui.debug_moves("e7e5 settle b8c6 settle"); - assert!(f.ui.can_input()); - assert_eq!(f.ui.session.current_expected_uci(), Some("a7a6")); - f.ui.debug_moves("a7a6 settle"); - assert!(f.ui.is_finished()); - assert_eq!( - f.attempts() - .iter() - .filter(|attempt| attempt.event_type.is_independent()) - .count(), - 3 - ); - } - - #[test] - fn reinforcement_does_not_count_as_completed_main_target() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - &["g1f3"], - "reinforcement-progress", - ); - f.ui.session.context_policy.consider_leadup_moves = true; - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW); - assert_eq!( - f.ui.session.phase, - LearningSessionPhase::AwaitingContextIndependent - ); - answer_current(&mut f, start, NOW, "weak-e4-reinforcement"); - let e4 = key_for(&f.library, &f.scope, "e2e4"); - assert!(f.ui.session.completed_keys.contains(&e4)); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "g1f3" - ); - assert_eq!(main_task_progress(&f.ui.session), (0, 1)); - - answer_current(&mut f, start, NOW + 1, "main-nf3-target"); - assert_eq!(main_task_progress(&f.ui.session), (1, 1)); - } - - #[test] - fn automatic_context_has_three_separate_normal_timed_steps() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "context-normal", - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - assert_eq!(f.ui.visual_log, ["e2e4"]); - assert_eq!(f.ui.session.context_index, 0); - assert!(!f.ui.can_input()); - - tick_with_prime(&mut f.ui, start + Duration::from_millis(249), normal(), NOW); - assert_eq!(f.ui.session.context_index, 0); - assert!(f.attempts().is_empty()); - - tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); - assert_eq!(f.ui.session.context_index, 1); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]); - tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); - assert_eq!(f.ui.session.context_index, 1); - - tick_with_prime(&mut f.ui, start + normal() * 2, normal(), NOW); - assert_eq!(f.ui.session.context_index, 2); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]); - tick_with_prime(&mut f.ui, start + normal() * 3, normal(), NOW); - assert_eq!(f.ui.session.context_index, 3); - assert_eq!( - f.ui.session.phase, - LearningSessionPhase::AwaitingIndependent - ); - assert!(f.ui.can_input()); - assert_eq!(f.attempts().len(), 3); - assert_eq!( - trainer::repertoire::fen4(&f.ui.board_position), - key_for(&f.library, &f.scope, "b8c6").position_fen4 - ); - } - - #[test] - fn pause_after_second_step_resumes_with_third_without_duplicate() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "pause-after-second", - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); - assert_eq!(f.ui.session.context_index, 1); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]); - - assert!(f.ui.request_pause()); - assert!(f.ui.pause_requested); - assert!(matches!(f.ui.playback, Some(Playback::Automatic { .. }))); - assert_eq!(f.attempts().len(), 1); - tick_with_prime(&mut f.ui, start + normal() * 2, normal(), NOW); - assert!(f.ui.autoplay_paused()); - assert_eq!(f.ui.session.context_index, 2); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]); - assert_eq!(f.attempts().len(), 2); - assert!(!f.ui.can_input()); - - tick_with_prime(&mut f.ui, start + normal() * 10, normal(), NOW); - assert_eq!(f.ui.session.context_index, 2); - assert_eq!(f.attempts().len(), 2); - assert!(f.ui.continue_autoplay(start + normal() * 20)); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]); - assert_eq!(f.ui.session.context_index, 2); - assert_eq!(f.attempts().len(), 2); - tick_with_prime(&mut f.ui, start + normal() * 20, normal(), NOW); - assert_eq!(f.attempts().len(), 2); - - tick_with_prime(&mut f.ui, start + normal() * 21, normal(), NOW); - assert_eq!(f.ui.session.context_index, 3); - assert_eq!(f.attempts().len(), 3); - assert!(f.ui.can_input()); - assert!(f.ui.playback.is_none()); - } - - #[test] - fn autoplay_keyboard_controls_stop_without_new_attempts() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "autoplay-keyboard-stop", - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - let ctx = egui::Context::default(); - let press = |key: Key, - training: &mut LearningTrainingUi, - actions: &mut Vec| { - ctx.run_ui( - egui::RawInput { - events: vec![egui::Event::Key { - key, - physical_key: None, - pressed: true, - repeat: false, - modifiers: Modifiers::NONE, - }], - time: Some(0.0), - ..Default::default() - }, - |ui| training.keyboard(ui, actions), - ) - .drop_without_applying_deltas(); - }; - let mut actions = Vec::new(); - press(Key::P, &mut f.ui, &mut actions); - assert!(f.ui.pause_requested); - assert!(actions.is_empty()); - - tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); - assert!(f.ui.autoplay_paused()); - assert_eq!(f.attempts().len(), 1); - press(Key::Space, &mut f.ui, &mut actions); - assert!(matches!(f.ui.playback, Some(Playback::Automatic { .. }))); - assert_eq!(f.ui.session.context_index, 1); - assert_eq!(f.attempts().len(), 1); - - press(Key::Escape, &mut f.ui, &mut actions); - assert!(matches!(actions.as_slice(), [LearningTrainingAction::Back])); - assert!(f.ui.stopped); - assert!(f.ui.playback.is_none()); - assert!(!f.ui.can_input()); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]); - tick_with_prime(&mut f.ui, start + normal() * 20, normal(), NOW); - assert_eq!(f.attempts().len(), 1); - let data = f.store.load().unwrap(); - assert_eq!(data.learning.attempts.len(), 1); - assert_eq!( - data.session_snapshot(f.ui.session_id()) - .unwrap() - .context_index, - 1 - ); - } - - #[test] - fn animation_off_commits_every_context_step_without_skipping_store_calls() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "context-off", - ); - tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]); - assert_eq!(f.ui.session.context_index, 3); - assert!(f.ui.can_input()); - let attempts = f.attempts(); - assert_eq!(attempts.len(), 3); - assert_eq!( - attempts - .iter() - .map(|attempt| attempt.actual_uci.as_deref()) - .collect::>(), - [Some("e2e4"), Some("e7e5"), Some("g1f3")] - ); - assert!(attempts.iter().all(|attempt| { - attempt.event_type == TrainingEventType::AutoContext - && attempt.response_time_ms.is_none() - })); - } - - #[test] - fn legal_input_is_ignored_during_autoplay() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "autoplay-input", - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - assert!(!f.ui.play_uci_with_id_at( - "e7e5", - "blocked-input".to_owned(), - start + Duration::from_millis(20), - NOW, - )); - assert_eq!(f.ui.session.context_index, 0); - assert!(f.attempts().is_empty()); - assert_eq!(f.ui.visual_log, ["e2e4"]); - } - - #[test] - fn wrong_answer_replays_without_a_second_independent_error() { - let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "wrong-replay"); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - assert!(f.ui.play_uci_with_id_at( - "d2d4", - "wrong-d4".to_owned(), - start + Duration::from_millis(1500), - NOW, - )); - assert!(matches!(f.ui.playback, Some(Playback::Wrong { .. }))); - tick_with_prime( - &mut f.ui, - start + Duration::from_millis(1500) + WRONG_SHOWN, - normal(), - NOW, - ); - assert_eq!( - f.ui.session.phase, - LearningSessionPhase::AwaitingReplayAfterError - ); - assert_eq!( - f.ui.presentation.as_ref().unwrap().revealed_move.as_deref(), - Some("e2e4") - ); - - assert!(f.ui.play_uci_with_id_at( - "d2d4", - "wrong-replay-d4".to_owned(), - start + Duration::from_secs(3), - NOW, - )); - assert_eq!(f.attempts().len(), 1); - tick_with_prime( - &mut f.ui, - start + Duration::from_secs(3) + WRONG_SHOWN, - normal(), - NOW, - ); - assert!(f.ui.play_uci_with_id_at( - "e2e4", - "replay-e4".to_owned(), - start + Duration::from_secs(4), - NOW, - )); - tick_with_prime( - &mut f.ui, - start + Duration::from_secs(4) + normal(), - normal(), - NOW, - ); - assert!(f.ui.is_finished()); - let attempts = f.attempts(); - assert_eq!(attempts.len(), 2); - assert_eq!( - attempts[0].event_type, - TrainingEventType::IncorrectIndependent - ); - assert_eq!(attempts[0].response_time_ms, Some(1500)); - assert_eq!(attempts[1].event_type, TrainingEventType::ReplayAfterError); - assert_eq!(attempts[1].response_time_ms, None); - let item = f - .store - .load() - .unwrap() - .learning - .item(&key_for(&f.library, &f.scope, "e2e4")) - .unwrap() - .clone(); - assert_eq!(item.wrong_count, 1); - assert_eq!(item.correct_count, 0); - } - - #[test] - fn preview_is_idempotent_and_shown_move_is_not_success() { - let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "preview"); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - assert!(f.ui.request_hint_with_id_at( - "preview-e4".to_owned(), - start + Duration::from_millis(100), - NOW, - )); - assert_eq!(f.ui.session.phase, LearningSessionPhase::PreviewedReplay); - assert!(!f.ui.request_hint_with_id_at( - "preview-e4-again".to_owned(), - start + Duration::from_millis(200), - NOW, - )); - assert_eq!(f.attempts().len(), 1); - assert!(f.ui.play_uci_with_id_at( - "e2e4", - "play-preview-e4".to_owned(), - start + Duration::from_secs(1), - NOW, - )); - tick_with_prime( - &mut f.ui, - start + Duration::from_secs(1) + normal(), - normal(), - NOW, - ); - assert!(f.ui.is_finished()); - assert!( - f.ui.message - .as_deref() - .is_some_and(|text| text.contains("PREVIEWED")) - ); - let data = f.store.load().unwrap(); - assert_eq!(data.learning.attempts.len(), 2); - assert_eq!( - data.learning.attempts[0].event_type, - TrainingEventType::Previewed - ); - assert_eq!( - data.learning.attempts[1].event_type, - TrainingEventType::AutoContext - ); - let item = data - .learning - .item(&key_for(&f.library, &f.scope, "e2e4")) - .unwrap(); - assert_eq!(item.correct_count, 0); - assert_eq!(item.wrong_count, 0); - assert!(item.independent_response_times_ms.is_empty()); - } - - #[test] - fn duplicate_store_response_does_not_advance_the_ui_twice() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "duplicate", - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - assert!(f.ui.advance_context_with_id_at( - "duplicate-context".to_owned(), - start + normal(), - NOW, - )); - assert_eq!(f.ui.session.context_index, 1); - assert_eq!(f.attempts().len(), 1); - - f.ui.completed_attempt_ids.remove("duplicate-context"); - assert!(f.ui.advance_context_with_id_at( - "duplicate-context".to_owned(), - start + normal() * 2, - NOW, - )); - assert_eq!(f.ui.session.context_index, 1); - assert_eq!(f.attempts().len(), 1); - assert!(!f.ui.visual_log.contains(&"g1f3".to_owned())); - } - - #[test] - fn store_error_is_visible_blocking_and_retryable() { - let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "store-error"); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - let valid_store = f.ui.store.clone(); - f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); - assert!(f.ui.play_uci_with_id_at( - "e2e4", - "save-error-e4".to_owned(), - start + Duration::from_millis(100), - NOW, - )); - assert!(f.ui.has_unsaved()); - assert!(f.ui.save_error.is_some()); - assert!(!f.ui.can_input()); - assert!(!f.ui.is_finished()); - assert!(f.attempts().is_empty()); - assert!(!f.ui.play_uci_with_id_at( - "d2d4", - "blocked-after-save-error".to_owned(), - start + Duration::from_millis(200), - NOW, - )); - - f.ui.store = valid_store; - f.ui.retry_pending(start + Duration::from_millis(300)); - assert!(!f.ui.has_unsaved()); - assert!(matches!(f.ui.playback, Some(Playback::Accepted { .. }))); - tick_with_prime( - &mut f.ui, - start + Duration::from_millis(300) + normal(), - normal(), - NOW, - ); - assert!(f.ui.is_finished()); - assert_eq!(f.attempts().len(), 1); - } - - #[test] - fn reload_resumes_preview_and_partially_presented_context() { - let mut preview = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "resume-preview"); - let start = Instant::now(); - tick_with_prime(&mut preview.ui, start, normal(), NOW); - preview - .ui - .request_hint_with_id_at("resume-preview-event".to_owned(), start, NOW); - let id = preview.ui.session_id().to_owned(); - let resumed = LearningTrainingUi::new( - preview.library.clone(), - preview.store.clone(), - preview.scope.clone(), - SrsSettings::default(), - false, - false, - ) - .unwrap(); - assert_eq!(resumed.session_id(), id); - assert_eq!(resumed.session.phase, LearningSessionPhase::PreviewedReplay); - assert_eq!(preview.store.load().unwrap().learning.attempts.len(), 1); - - let mut context = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "resume-context", - ); - tick_with_prime(&mut context.ui, start, normal(), NOW); - tick_with_prime(&mut context.ui, start + normal(), normal(), NOW); - assert_eq!(context.ui.session.context_index, 1); - let id = context.ui.session_id().to_owned(); - drop(context.ui); - let mut resumed = LearningTrainingUi::new( - context.library.clone(), - context.store.clone(), - context.scope.clone(), - SrsSettings::default(), - false, - false, - ) - .unwrap(); - assert_eq!(resumed.session_id(), id); - assert_eq!(resumed.session.context_index, 1); - resumed.synchronous_commits = true; - tick_with_prime(&mut resumed, start + normal() * 2, Duration::ZERO, NOW); - assert_eq!(resumed.session.context_index, 3); - assert_eq!(context.store.load().unwrap().learning.attempts.len(), 3); - } - - #[test] - fn new_items_require_the_explicit_introduction_flag() { - let due = Fixture::new("1. e4 *", LearningSide::White, &[], "due-empty"); - assert!(due.ui.session.queue.is_empty()); - assert!(due.ui.is_finished()); - assert!(due.store.load().unwrap().learning.items.is_empty()); - - let introduced = Fixture::with_introduction( - "1. e4 *", - LearningSide::White, - &[], - "introduce-explicit", - true, - ); - assert_eq!(introduced.ui.session.queue.len(), 1); - assert!(introduced.store.load().unwrap().learning.items.is_empty()); - } - - #[test] - fn introduce_new_starts_separate_session_and_preserves_previewed_snapshot() { - let pgn = "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 *"; - let mut f = Fixture::with_introduction( - pgn, - LearningSide::White, - &[], - "introduce-preserves-preview", - true, - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW); - assert!(f.ui.request_hint_with_id_at( - "preview-before-new-introduction".to_owned(), - start, - NOW, - )); - let old_id = f.ui.session_id().to_owned(); - - let introduced = LearningTrainingUi::new( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - true, - false, - ) - .unwrap(); - - assert_ne!(introduced.session_id(), old_id); - assert_eq!(introduced.session.queue.len(), 6); - assert!( - introduced - .session - .queue - .iter() - .all(|target| target.key.expected_uci != "e2e4") - ); - let data = f.store.load().unwrap(); - assert_eq!(data.session_snapshots.len(), 2); - let old = data.session_snapshot(&old_id).unwrap(); - assert_eq!(old.phase, LearningSessionPhase::PreviewedReplay); - assert_eq!(old.queue.len(), 7); - assert!(data.session_snapshot(introduced.session_id()).is_some()); - } - - #[test] - fn review_in_order_second_cycle_restarts_progress_and_updates_srs() { - let mut f = Fixture::with_mode( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - &[], - "review-second-cycle", - QueueMode::ReviewInOrder, - LearningPriority::DepthFirst, - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW); - answer_current( - &mut f, - start + Duration::from_millis(10), - NOW, - "review-cycle0-e4", - ); - assert_eq!(f.ui.session.cycle, 0); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "g1f3" - ); - answer_current( - &mut f, - start + Duration::from_millis(20), - NOW + 1, - "review-cycle0-nf3", - ); - assert_eq!(f.ui.session.cycle, 1); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "e2e4" - ); - assert!(f.ui.session.completed_keys.is_empty()); - assert!(!f.ui.is_finished()); - - answer_current( - &mut f, - start + Duration::from_millis(30), - NOW + 24 * 60 * 60, - "review-cycle1-e4", - ); - assert_eq!(f.ui.session.cycle, 1); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "g1f3" - ); - assert_eq!(f.ui.session.completed_keys.len(), 1); - let e4 = key_for(&f.library, &f.scope, "e2e4"); - let item = f.store.load().unwrap().learning.item(&e4).unwrap().clone(); - assert_eq!(item.correct_count, 2); - assert!(item.next_review_at > Some(NOW + 24 * 60 * 60)); - } - - #[test] - fn least_recent_context_is_independent_once_and_new_pass_resumes() { - let mut f = Fixture::with_mode( - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", - LearningSide::White, - &[("e2e4", NOW - 10), ("g1f3", NOW - 100), ("f1b5", NOW - 50)], - "least-context-once", - QueueMode::LeastRecent, - LearningPriority::DepthFirst, - ); - assert_eq!( - f.ui.session.phase, - LearningSessionPhase::AwaitingContextIndependent - ); - assert_eq!(f.ui.session.current_expected_uci(), Some("e2e4")); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "g1f3" - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW); - assert!(f.ui.can_input()); - assert!(f.ui.playback.is_none()); - assert!(f.ui.visual_log.is_empty()); - assert!( - f.ui.message - .as_deref() - .unwrap() - .contains(tr("Automatic move/context")) - ); - - answer_current( - &mut f, - start + Duration::from_millis(10), - NOW, - "least-context-e4", - ); - assert_eq!( - f.ui.session.phase, - LearningSessionPhase::AwaitingIndependent - ); - assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); - answer_current( - &mut f, - start + Duration::from_millis(20), - NOW + 1, - "least-target-nf3", - ); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "f1b5" - ); - for expected in ["e2e4", "g1f3"] { - let key = key_for(&f.library, &f.scope, expected); - assert_eq!( - f.attempts() - .iter() - .filter(|attempt| { - attempt.item_key() == key && attempt.event_type.is_independent() - }) - .count(), - 1, - "context was checked twice for {expected}" - ); - } - answer_current( - &mut f, - start + Duration::from_millis(30), - NOW + 2, - "least-target-bb5", - ); - assert!(f.ui.is_finished()); - let attempts = f.attempts(); - for expected in ["e2e4", "g1f3", "f1b5"] { - let key = key_for(&f.library, &f.scope, expected); - assert_eq!( - attempts - .iter() - .filter(|attempt| { - attempt.item_key() == key && attempt.event_type.is_independent() - }) - .count(), - 1, - "duplicate independent review for {expected}" - ); - let item = f.store.load().unwrap().learning.item(&key).unwrap().clone(); - assert_eq!(item.correct_count, 2); - } - - let id = f.ui.session_id().to_owned(); - drop(f.ui); - let resumed = LearningTrainingUi::new_with_mode( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - false, - false, - QueueMode::LeastRecent, - ) - .unwrap(); - assert_eq!(resumed.session_id(), id); - assert_eq!(resumed.session.cycle, 1); - assert_eq!(resumed.session.session.mode, QueueMode::LeastRecent); - assert!(resumed.target_available()); - } - - #[test] - fn resume_is_scoped_by_mode_and_learning_priority() { - let mut f = Fixture::with_mode( - "1. e4 (1. d4 d5) e5 2. Nf3 *", - LearningSide::White, - &[], - "resume-mode-priority", - QueueMode::ReviewInOrder, - LearningPriority::MainLinesFirst, - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW); - answer_current(&mut f, start, NOW, "priority-review-first"); - let review_id = f.ui.session_id().to_owned(); - assert_eq!(f.ui.session.current_index, 1); - - let resumed = LearningTrainingUi::new_with_mode( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - false, - false, - QueueMode::ReviewInOrder, - ) - .unwrap(); - assert_eq!(resumed.session_id(), review_id); - assert_eq!(resumed.session.current_index, 1); - assert_eq!( - resumed.session.stats_scope.learning_priority, - LearningPriority::MainLinesFirst - ); - - let other_priority = LearningTrainingUi::new_with_mode( - f.library.clone(), - f.store.clone(), - f.scope - .clone() - .with_learning_priority(LearningPriority::DepthFirst), - SrsSettings::default(), - false, - false, - QueueMode::ReviewInOrder, - ) - .unwrap(); - assert_ne!(other_priority.session_id(), review_id); - assert_eq!( - other_priority.session.stats_scope.learning_priority, - LearningPriority::DepthFirst - ); - - let other_mode = LearningTrainingUi::new_with_mode( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - false, - false, - QueueMode::LeastRecent, - ) - .unwrap(); - assert_ne!(other_mode.session_id(), review_id); - assert_eq!(other_mode.session.session.mode, QueueMode::LeastRecent); - - let srs = LearningTrainingUi::new( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - false, - false, - ) - .unwrap(); - assert_ne!(srs.session_id(), review_id); - assert_eq!(srs.session.session.mode, QueueMode::SpacedRepetition); - assert!( - LearningTrainingUi::new_with_mode( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - true, - false, - QueueMode::ReviewInOrder, - ) - .is_err() - ); - assert_eq!( - queue_mode_label(QueueMode::SpacedRepetition), - tr("On schedule") - ); - assert_eq!( - queue_mode_label(QueueMode::ReviewInOrder), - tr("Review in order") - ); - assert_eq!( - queue_mode_label(QueueMode::LeastRecent), - tr("Least recent and unseen first") - ); - } - - #[test] - fn show_runs_at_mvp_window_sizes() { - let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "mvp-sizes"); - let settings = Settings::default(); - let ctx = egui::Context::default(); - ctx.set_visuals(egui::Visuals::light()); - for (width, height) in [(1400.0, 900.0), (640.0, 480.0)] { - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - time: Some(0.0), - ..Default::default() - }, - |ui| { - f.ui.show(ui, &settings, "Test repertoire"); - }, - ); - if width == 640.0 { - let background = egui::Visuals::light().window_fill(); - assert!( - output.shapes.iter().any(|clipped| { - let egui::Shape::Rect(shape) = &clipped.shape else { - return false; - }; - shape.fill == background - && shape.rect.min.x <= 0.0 - && shape.rect.max.x >= width - && shape.rect.min.y > 0.0 - && shape.rect.min.y <= height - 58.0 - && shape.rect.max.y >= height - 0.01 - }), - "the stacked background must cover the bottom of the viewport" - ); - } - output.drop_without_applying_deltas(); - } - assert!(f.ui.target_available()); - assert!(!f.ui.has_unsaved()); - } - fn wait_for_commit(ui: &mut LearningTrainingUi) { - let deadline = Instant::now() + Duration::from_secs(5); - while ui.commit_in_flight.is_some() { - assert!(Instant::now() < deadline, "commit worker did not finish"); - ui.poll_commit(Instant::now()); - std::thread::sleep(Duration::from_millis(1)); - } - } - - #[test] - fn async_commit_keeps_frames_responsive_under_store_lock_and_commits_once() { - let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "async-lock"); - f.ui.synchronous_commits = false; - tick_with_prime(&mut f.ui, Instant::now(), normal(), NOW); - let lock_path = f.store.path().with_file_name("learning.json.lock"); - let lock = std::fs::OpenOptions::new() - .read(true) - .write(true) - .open(lock_path) - .unwrap(); - lock.lock().unwrap(); - let unlock = std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(600)); - drop(lock); - }); - let start = Instant::now(); - assert!(f.ui.play_uci_with_id_at("e2e4", "async-answer".to_owned(), start, NOW)); - assert!( - start.elapsed() < Duration::from_millis(300), - "input waited for storage lock" - ); - assert!(f.ui.has_unsaved()); - assert!(f.ui.commit_in_flight.is_some()); - assert!(!f.ui.can_input()); - assert!( - !f.ui - .play_uci_with_id_at("e2e4", "async-answer".to_owned(), Instant::now(), NOW) - ); - f.ui.retry_pending(Instant::now()); - let ctx = egui::Context::default(); - let frame = Instant::now(); - ctx.run_ui(egui::RawInput::default(), |ui| { - f.ui.show(ui, &Settings::default(), "Test"); - }) - .drop_without_applying_deltas(); - assert!( - frame.elapsed() < Duration::from_millis(300), - "frame waited for storage lock" - ); - unlock.join().unwrap(); - wait_for_commit(&mut f.ui); - assert!(!f.ui.has_unsaved()); - assert!(matches!(f.ui.playback, Some(Playback::Accepted { .. }))); - assert_eq!(f.attempts().len(), 1); - let revision = f.ui.session.revision; - f.ui.poll_commit(Instant::now()); - f.ui.retry_pending(Instant::now()); - assert_eq!(f.ui.session.revision, revision); - assert_eq!(f.attempts().len(), 1); - } - - fn pointer_board_frame( - f: &mut Fixture, - ctx: &egui::Context, - time: f64, - events: Vec, - settings: &Settings, - ) -> egui::FullOutput { - let mut output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - vec2(800.0, 800.0), - )), - time: Some(time), - events, - ..Default::default() - }, - |ui| f.ui.board_ui(ui, settings), - ); - output.textures_delta.clear(); - output - } - - fn piece_meshes(output: &egui::FullOutput) -> Vec<(egui::TextureId, egui::Rect)> { - fn collect(shape: &egui::Shape, meshes: &mut Vec<(egui::TextureId, egui::Rect)>) { - match shape { - egui::Shape::Mesh(mesh) => meshes.push((mesh.texture_id, mesh.calc_bounds())), - egui::Shape::Rect(rect) => { - if let Some(brush) = &rect.brush { - meshes.push((brush.fill_texture_id, rect.rect)); - } - } - egui::Shape::Vec(shapes) => { - for shape in shapes { - collect(shape, meshes); - } - } - _ => {} - } - } - let mut meshes = Vec::new(); - for shape in &output.shapes { - collect(&shape.shape, &mut meshes); - } - meshes - } - - fn pointer_button(pos: egui::Pos2, pressed: bool) -> egui::Event { - egui::Event::PointerButton { - pos, - button: egui::PointerButton::Primary, - pressed, - modifiers: Modifiers::NONE, - } - } - - #[test] - fn pointer_move_stays_at_destination_during_async_save_without_a_second_animation() { - for drag in [true, false] { - for wrong in [false, true] { - for animation in [ - crate::settings::Animation::Normal, - crate::settings::Animation::Off, - ] { - let mut f = - Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "pointer-pending"); - f.ui.synchronous_commits = false; - let settings = Settings { - animation, - ..Settings::default() - }; - let duration = Duration::from_secs_f32(animation.seconds()); - f.ui.tick_at(Instant::now(), duration, NOW); - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - let from = egui::pos2(450.0, 650.0); - let to = egui::pos2(450.0, if wrong { 550.0 } else { 450.0 }); - let initial = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &settings); - let pawn = piece_meshes(&initial) - .into_iter() - .find(|(_, rect)| rect.contains(from)) - .expect("painted pawn at e2") - .0; - initial.drop_without_applying_deltas(); - pointer_board_frame( - &mut f, - &ctx, - 1.01, - vec![egui::Event::PointerMoved(from), pointer_button(from, true)], - &settings, - ) - .drop_without_applying_deltas(); - if drag { - pointer_board_frame( - &mut f, - &ctx, - 1.02, - vec![egui::Event::PointerMoved(to)], - &settings, - ) - .drop_without_applying_deltas(); - } else { - pointer_board_frame( - &mut f, - &ctx, - 1.02, - vec![pointer_button(from, false)], - &settings, - ) - .drop_without_applying_deltas(); - pointer_board_frame( - &mut f, - &ctx, - 1.03, - vec![egui::Event::PointerMoved(to), pointer_button(to, true)], - &settings, - ) - .drop_without_applying_deltas(); - } - let lock = std::fs::OpenOptions::new() - .read(true) - .write(true) - .open(f.store.path().with_file_name("learning.json.lock")) - .unwrap(); - lock.lock().unwrap(); - let released = pointer_board_frame( - &mut f, - &ctx, - 1.04, - vec![pointer_button(to, false)], - &settings, - ); - let assert_pawn_at_destination = |output: &egui::FullOutput| { - let meshes = piece_meshes(output); - assert!( - meshes - .iter() - .any(|(texture, rect)| *texture == pawn && rect.contains(to)), - "pawn not painted at destination" - ); - assert!( - !meshes - .iter() - .any(|(texture, rect)| *texture == pawn && rect.contains(from)), - "pawn snapped back to e2" - ); - }; - assert!(f.ui.has_unsaved(), "drag={drag} wrong={wrong}"); - assert!(!f.ui.can_input()); - assert!(f.ui.pending_sounds.is_empty()); - if drag { - assert_pawn_at_destination(&released); - } - released.drop_without_applying_deltas(); - let frame = Instant::now(); - let waiting = pointer_board_frame(&mut f, &ctx, 1.05, vec![], &settings); - assert!(frame.elapsed() < Duration::from_millis(300)); - if drag { - assert_pawn_at_destination(&waiting); - assert!( - f.ui.board - .animation_at(1.05) - .is_none_or(|(_, slides, _)| slides.is_empty()) - ); - } else if !duration.is_zero() { - assert!( - f.ui.board - .animation_at(1.05) - .unwrap() - .1 - .iter() - .any(|(_, source, _)| *source == Square::E2), - "click move must still animate" - ); - } - waiting.drop_without_applying_deltas(); - let waiting = pointer_board_frame(&mut f, &ctx, 2.0, vec![], &settings); - assert_pawn_at_destination(&waiting); - waiting.drop_without_applying_deltas(); - assert!( - f.ui.learning.attempts.is_empty(), - "unconfirmed answer affected learning data" - ); - drop(lock); - wait_for_commit(&mut f.ui); - let confirmed = pointer_board_frame(&mut f, &ctx, 2.01, vec![], &settings); - assert_pawn_at_destination(&confirmed); - confirmed.drop_without_applying_deltas(); - assert!( - f.ui.board.animation_at(2.01).is_none(), - "commit restarted the move animation" - ); - assert_eq!(f.attempts().len(), 1); - assert_eq!( - f.ui.pending_sounds, - [if wrong { Sound::Wrong } else { Sound::Move }] - ); - if wrong { - f.ui.tick_at(f.ui.playback_deadline().unwrap(), duration, NOW); - pointer_board_frame(&mut f, &ctx, 2.02, vec![], &settings) - .drop_without_applying_deltas(); - assert_eq!(fen4(&f.ui.board_position), fen4(&Chess::default())); - if !duration.is_zero() { - assert!( - f.ui.board - .animation_at(2.02) - .unwrap() - .1 - .iter() - .any(|(_, _, target)| *target == Square::E2), - "wrong move must return to source" - ); - } - } - } - } - } - } - - #[test] - fn dragged_special_moves_keep_auxiliary_effects_and_retry_does_not_move_again() { - let cases = [ - ( - "4k3/8/8/8/8/8/8/4K2R w K - 0 1", - "O-O", - "e1g1", - Square::E1, - Square::G1, - None, - false, - ), - ( - "4k3/8/8/3p4/4P3/8/8/4K3 w - - 0 1", - "exd5", - "e4d5", - Square::E4, - Square::D5, - Some(Square::D5), - false, - ), - ( - "4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 1", - "exd6", - "e5d6", - Square::E5, - Square::D6, - Some(Square::D5), - false, - ), - ( - "4k3/P7/8/8/8/8/8/4K3 w - - 0 1", - "a8=Q+", - "a7a8q", - Square::A7, - Square::A8, - None, - true, - ), - ]; - let center = |sq: Square| { - egui::pos2( - (u32::from(sq.file()) as f32 + 0.5) * 100.0, - (7.5 - u32::from(sq.rank()) as f32) * 100.0, - ) - }; - for (fen, san, uci, from, to, captured, promotion) in cases { - let pgn = format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. {san} *"); - let mut f = Fixture::new(&pgn, LearningSide::White, &[uci], "special-drag"); - f.ui.synchronous_commits = false; - f.ui.tick_at(Instant::now(), normal(), NOW); - let valid_store = f.ui.store.clone(); - f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - let settings = Settings::default(); - let initial = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &settings); - let captured_texture = captured.map(|sq| { - piece_meshes(&initial) - .into_iter() - .find(|(_, rect)| rect.contains(center(sq))) - .unwrap() - .0 - }); - initial.drop_without_applying_deltas(); - pointer_board_frame( - &mut f, - &ctx, - 1.01, - vec![ - egui::Event::PointerMoved(center(from)), - pointer_button(center(from), true), - ], - &settings, - ) - .drop_without_applying_deltas(); - pointer_board_frame( - &mut f, - &ctx, - 1.02, - vec![egui::Event::PointerMoved(center(to))], - &settings, - ) - .drop_without_applying_deltas(); - let released = pointer_board_frame( - &mut f, - &ctx, - 1.03, - vec![pointer_button(center(to), false)], - &settings, - ); - if uci == "e1g1" { - let (_, slides, _) = f.ui.board.animation_at(1.03).unwrap(); - assert_eq!(slides.len(), 1); - assert_eq!( - (slides[0].1, slides[0].2), - (Square::H1, Square::F1), - "only the rook should animate after a dragged castle" - ); - } - if let Some(texture) = captured_texture { - assert!( - piece_meshes(&released).iter().any( - |(id, rect)| *id == texture && rect.contains(center(captured.unwrap())) - ), - "captured piece must still fade out" - ); - } - released.drop_without_applying_deltas(); - if promotion { - assert!( - !f.ui.has_unsaved(), - "promotion must wait for the chosen piece" - ); - pointer_board_frame( - &mut f, - &ctx, - 1.04, - vec![pointer_button(center(to), true)], - &settings, - ) - .drop_without_applying_deltas(); - pointer_board_frame( - &mut f, - &ctx, - 1.05, - vec![pointer_button(center(to), false)], - &settings, - ) - .drop_without_applying_deltas(); - assert_eq!( - f.ui.board_position.board().piece_at(to).unwrap().role, - chess_core::shakmaty::Role::Queen - ); - } - assert!(f.ui.has_unsaved()); - let after = fen4(&f.ui.board_position); - wait_for_commit(&mut f.ui); - assert!(f.ui.save_error.is_some()); - assert!(f.attempts().is_empty()); - assert!(f.ui.pending_sounds.is_empty()); - pointer_board_frame(&mut f, &ctx, 1.1, vec![], &settings) - .drop_without_applying_deltas(); - let waiting = pointer_board_frame(&mut f, &ctx, 2.0, vec![], &settings); - if let Some(texture) = captured_texture { - assert!( - !piece_meshes(&waiting).iter().any( - |(id, rect)| *id == texture && rect.contains(center(captured.unwrap())) - ) - ); - } - waiting.drop_without_applying_deltas(); - f.ui.store = valid_store; - f.ui.retry_pending(Instant::now()); - f.ui.retry_pending(Instant::now()); - wait_for_commit(&mut f.ui); - pointer_board_frame(&mut f, &ctx, 2.01, vec![], &settings) - .drop_without_applying_deltas(); - assert_eq!(fen4(&f.ui.board_position), after); - assert!(f.ui.board.animation_at(2.01).is_none()); - assert_eq!(f.attempts().len(), 1); - assert_eq!(f.ui.pending_sounds, [Sound::Move]); - } - } - - #[test] - fn reused_context_retry_stays_silent_and_responsive_and_persists_once() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - &["e2e4", "g1f3"], - "reuse-retry", - ); - let at = Instant::now(); - tick_with_prime(&mut f.ui, at, normal(), NOW); - assert!(f.ui.play_uci_with_id_at("e2e4", "own-answer".into(), at, NOW)); - let position = fen4(&f.ui.board_position); - assert_eq!(std::mem::take(&mut f.ui.pending_sounds), [Sound::Move]); - let valid_store = f.ui.store.clone(); - f.ui.synchronous_commits = false; - f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); - f.ui.tick_at(at + normal(), normal(), NOW); - wait_for_commit(&mut f.ui); - assert!(f.ui.save_error.is_some()); - assert!(matches!( - f.ui.pending_commit.as_ref().unwrap().kind, - CommitKind::ReusedContext - )); - let reused_id = f.ui.pending_commit.as_ref().unwrap().attempts[0] - .client_attempt_id - .clone(); - assert_eq!(fen4(&f.ui.board_position), position); - assert!(f.ui.pending_sounds.is_empty()); - f.ui.store = valid_store; - let lock = std::fs::OpenOptions::new() - .read(true) - .write(true) - .open(f.store.path().with_file_name("learning.json.lock")) - .unwrap(); - lock.lock().unwrap(); - let unlock = std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(600)); - drop(lock); - }); - f.ui.retry_pending(Instant::now()); - f.ui.retry_pending(Instant::now()); - let frame = Instant::now(); - assert!(emitted_sounds(&mut f, &egui::Context::default(), &Settings::default()).is_empty()); - assert!( - frame.elapsed() < Duration::from_millis(300), - "reused context blocked the frame" - ); - assert_eq!(fen4(&f.ui.board_position), position); - assert!(!f.ui.can_input()); - unlock.join().unwrap(); - wait_for_commit(&mut f.ui); - assert!(f.ui.pending_sounds.is_empty()); - f.ui.debug_settle(); - assert_eq!(f.ui.visual_log, ["e7e5"]); - assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); - let attempts = f.attempts(); - assert_eq!(attempts.len(), 3); - assert_eq!( - attempts - .iter() - .filter(|event| event.client_attempt_id == reused_id) - .count(), - 1 - ); - assert_eq!( - attempts - .iter() - .filter(|event| event.event_type.is_independent()) - .count(), - 1 - ); - } - - #[test] - fn async_failed_commit_preserves_event_for_retry_without_double_counting() { - let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "async-retry"); - f.ui.synchronous_commits = false; - tick_with_prime(&mut f.ui, Instant::now(), normal(), NOW); - let valid_store = f.ui.store.clone(); - f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); - assert!(f.ui.play_uci_with_id_at("e2e4", "async-retry".to_owned(), Instant::now(), NOW)); - wait_for_commit(&mut f.ui); - assert!(f.ui.save_error.is_some()); - assert!(f.ui.has_unsaved()); - assert!(f.attempts().is_empty()); - f.ui.store = valid_store; - f.ui.retry_pending(Instant::now()); - f.ui.retry_pending(Instant::now()); - wait_for_commit(&mut f.ui); - assert!(!f.ui.has_unsaved()); - assert_eq!(f.attempts().len(), 1); - assert_eq!(f.attempts()[0].client_attempt_id, "async-retry"); - } -} diff --git a/apps/desktop/src/lib.rs b/apps/desktop/src/lib.rs index fbb7b73..0581eb2 100644 --- a/apps/desktop/src/lib.rs +++ b/apps/desktop/src/lib.rs @@ -30,16 +30,6 @@ mod game_view; mod graphics; mod i18n; mod large_db; -#[cfg(not(web))] -mod learning_branches; -#[cfg(not(web))] -mod learning_charts; -#[cfg(not(web))] -mod learning_context_controls; -#[cfg(not(web))] -mod learning_dashboard; -#[cfg(not(web))] -mod learning_training; mod library; mod maia_download; #[cfg(web)] @@ -48,6 +38,12 @@ mod notation; mod online; #[cfg(not(web))] mod online_ui; +#[cfg(not(web))] +mod opening_layout; +#[cfg(not(web))] +mod opening_lines; +#[cfg(not(web))] +mod opening_session; mod own_db; pub mod platform; mod play; @@ -56,10 +52,6 @@ mod prep_saved; mod prep_ui; mod reference; #[cfg(not(web))] -mod repertoire_editor; -#[cfg(not(web))] -mod repertoire_training; -#[cfg(not(web))] mod repertoire_ui; mod review; mod review_engine; diff --git a/apps/desktop/src/opening_layout.rs b/apps/desktop/src/opening_layout.rs new file mode 100644 index 0000000..61df871 --- /dev/null +++ b/apps/desktop/src/opening_layout.rs @@ -0,0 +1,498 @@ +//! What the three opening-training screens share (docs/design/opening-trainer-v2-spec.md +//! §1): the frame of the game screen, the card, the board's PGN marks and the texts +//! about moves, sides and dates. + +use chess_core::shakmaty::{Color, Square, uci::UciMove}; +use chess_core::{Annotation, CommentPart, Game, MoveKind, NodeId, parse_comment}; +use egui::{Color32, RichText, Ui, vec2}; +use trainer::repertoire::{LearningSide, RepertoireId, TrainingMode}; + +use crate::board::{Arrow, Badge}; +use crate::i18n::{tr, trf}; +use crate::settings::Settings; + +/// The panel's least width (the game's reference tab, `REF_MIN`). +const SIDE_LEAST: f32 = 320.0; +/// Under a stacked board: the panel's least height (`STACK_BOTTOM_MIN`). +const STACK_BOTTOM_MIN: f32 = 300.0; +const BOARD_MIN: f32 = 220.0; +/// Space between the blocks of the panel. +pub(crate) const GAP: f32 = 6.0; +/// The new moves of one session and of "10 more new". +pub(crate) const NEW_PER_SESSION: usize = 10; + +/// Header, side panel and board in the places of the game screen. The same panel id on +/// every screen of the section: switching screens never moves the board. +pub(crate) fn screen( + ui: &mut Ui, + this: &mut T, + header: impl FnOnce(&mut T, &mut Ui), + side: impl FnOnce(&mut T, &mut Ui), + board: impl FnOnce(&mut T, &mut Ui), +) { + egui::Panel::top("opening_header").show(ui, |ui| header(this, ui)); + let width = ui.available_width(); + let height = ui.available_height(); + let board_side = (height - 16.0).min(width - SIDE_LEAST - 24.0); + let board_stack = (width - 16.0).min(height - STACK_BOTTOM_MIN - 16.0); + let stacked = board_stack >= 1.25 * board_side; + let panel = if stacked { + let most = (height - BOARD_MIN - 16.0).max(STACK_BOTTOM_MIN); + let rest = (height - board_stack - 16.0).clamp(STACK_BOTTOM_MIN, most); + egui::Panel::bottom("opening_side_stacked") + .resizable(true) + .default_size(rest) + .size_range(STACK_BOTTOM_MIN..=most) + .show(ui, |ui| side(this, ui)) + } else { + let board = height - 16.0; + let most = (width - BOARD_MIN - 24.0).max(SIDE_LEAST); + let room = (width - board - 24.0).clamp(SIDE_LEAST, most); + egui::Panel::right("opening_side") + .resizable(true) + .default_size((width * 0.4).clamp(260.0, 460.0).min(room)) + .size_range(SIDE_LEAST..=most) + .show(ui, |ui| side(this, ui)) + }; + crate::widgets::check_panel("opening_side", &panel.response); + egui::CentralPanel::default().show(ui, |ui| { + let area = ui.available_rect_before_wrap(); + let side = area.width().min(area.height()).max(1.0).floor(); + let left = area.left() + ((area.width() - side) / 2.0).max(0.0).floor(); + let top = area.top() + ((area.height() - side) / 2.0).max(0.0).floor(); + let rect = egui::Rect::from_min_size(egui::pos2(left, top), vec2(side, side)); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| board(this, ui)); + }); +} + +/// The frame of a state card (the player's card of a game against the computer). +pub(crate) fn card(ui: &Ui, active: bool, alert: bool) -> egui::Frame { + let mut frame = egui::Frame::new() + .inner_margin(egui::Margin::symmetric(10, 6)) + .corner_radius(4) + .stroke(egui::Stroke::new( + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + )); + if active { + frame = frame.fill(ui.visuals().selection.bg_fill.gamma_multiply(0.35)); + } + if alert { + frame = frame.stroke(egui::Stroke::new(1.5, ui.visuals().error_fg_color)); + } + frame +} + +/// A block of a fixed height: whatever it holds, what follows never moves. +pub(crate) fn fixed_block(ui: &mut Ui, height: f32, add: impl FnOnce(&mut Ui) -> R) -> R { + let width = ui.available_width().max(1.0); + let (rect, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover()); + let mut child = ui.new_child( + egui::UiBuilder::new() + .max_rect(rect) + .layout(egui::Layout::top_down(egui::Align::Min)), + ); + child.set_clip_rect(rect.intersect(ui.clip_rect())); + add(&mut child) +} + +/// One line of text cut with "…", the whole text on hover. +pub(crate) fn line(ui: &mut Ui, text: impl Into) -> egui::Response { + let text = text.into(); + let hover = text.text().to_owned(); + let response = ui.add(egui::Label::new(text).truncate()); + if hover.is_empty() { + response + } else { + response.on_hover_text(hover) + } +} + +/// The trained colour of a repertoire, kept in the settings since 2.2.0 (an old "both +/// colours" repertoire opens for White). +pub(crate) fn side_of(settings: &Settings, id: &RepertoireId) -> LearningSide { + match settings.repertoire_modes.get(id.as_str()) { + Some((TrainingMode::Black, _)) => LearningSide::Black, + _ => LearningSide::White, + } +} + +pub(crate) fn set_side(settings: &mut Settings, id: &RepertoireId, side: LearningSide) { + let mode = match side { + LearningSide::White => TrainingMode::White, + LearningSide::Black => TrainingMode::Black, + }; + settings.repertoire_modes.insert( + id.to_string(), + (mode, trainer::repertoire::QueueMode::SpacedRepetition), + ); +} + +pub(crate) fn king(side: LearningSide) -> &'static str { + match side { + LearningSide::White => "♔", + LearningSide::Black => "♚", + } +} + +pub(crate) fn you_play(side: LearningSide) -> &'static str { + tr(match side { + LearningSide::White => "You play White", + LearningSide::Black => "You play Black", + }) +} + +pub(crate) fn orientation(side: LearningSide) -> Color { + side.color() +} + +/// "4. Ba4" or "4… Nf6" in the notation of the application. +pub(crate) fn move_text(game: &Game, node: NodeId) -> Option { + let (number, color) = game.move_number(node)?; + let san = crate::san::show(&game.game_move(node)?.san).into_owned(); + Some(match color { + Color::White => format!("{number}. {san}"), + Color::Black => format!("{number}… {san}"), + }) +} + +/// The symbol of a move's assessment (`!`, `?!` …) and its colour for text. +pub(crate) fn assessment(game: &Game, node: NodeId, dark: bool) -> Option<(&'static str, Color32)> { + let nag = game + .node(node)? + .nags() + .iter() + .copied() + .find(|nag| nag.is_move_assessment())?; + Some(( + nag.symbol()?, + crate::notation::assessment_text_color(nag, dark)?, + )) +} + +/// The node reached from the root by these UCI moves. +pub(crate) fn node_at(game: &Game, path: &[String]) -> Option { + let mut at = NodeId::ROOT; + for uci in path { + let mv = uci + .parse::() + .ok()? + .to_move(game.position(at)?) + .ok()?; + at = game.find_child(at, mv)?; + } + Some(at) +} + +/// The UCI moves from the root to a node. +pub(crate) fn uci_path(game: &Game, node: NodeId) -> Vec { + game.path(node) + .into_iter() + .skip(1) + .filter_map(|id| game.game_move(id).and_then(|mv| mv.uci())) + .collect() +} + +/// "C84 · Ruy Lopez: Closed": the most precise named position on the way to `node`. +pub(crate) fn opening_text(game: &Game, node: NodeId) -> String { + let keys: Vec = game + .path(node) + .into_iter() + .filter_map(|id| game.position(id)) + .map(chess_openings::key) + .collect(); + match chess_openings::deepest(&keys) { + Some((_, id)) => { + let opening = chess_openings::get(id); + format!("{} · {}", opening.eco, opening.name) + } + None => String::new(), + } +} + +/// The start a repertoire's lines share: the last move before the first branching. +pub(crate) fn common_start(game: &Game) -> NodeId { + let mut at = NodeId::ROOT; + while let [only] = game.children(at) { + at = *only; + } + at +} + +pub(crate) fn last_move(game: &Game, node: NodeId) -> Option<(Square, Square)> { + match game.game_move(node)?.kind { + MoveKind::Normal(mv) => Some(( + mv.from().unwrap_or_else(|| mv.to()), + crate::board::ui_target(&mv), + )), + MoveKind::Null => None, + } +} + +/// The lines of a repertoire: the paths of its last moves, without switched-off +/// branches, in PGN order. +pub(crate) fn lines(game: &Game, disabled: impl Fn(&[String]) -> bool) -> Vec> { + let mut out = Vec::new(); + let mut stack = vec![(NodeId::ROOT, Vec::new())]; + while let Some((node, path)) = stack.pop() { + let children: Vec<_> = game + .children(node) + .iter() + .filter_map(|child| { + let uci = game.game_move(*child)?.uci()?; + let mut next = path.clone(); + next.push(uci); + (!disabled(&next)).then_some((*child, next)) + }) + .collect(); + if children.is_empty() { + if !path.is_empty() { + out.push(path); + } + } else { + stack.extend(children.into_iter().rev()); + } + } + out +} + +/// The end of the local day: "today" in the counts includes everything due before it. +pub(crate) fn end_of_today() -> i64 { + use chrono::{Local, TimeZone}; + let now = Local::now(); + let tomorrow = now.date_naive().succ_opt().unwrap_or(now.date_naive()); + tomorrow + .and_hms_opt(0, 0, 0) + .and_then(|midnight| Local.from_local_datetime(&midnight).earliest()) + .map_or(now.timestamp() + 24 * 60 * 60, |midnight| { + midnight.timestamp() - 1 + }) +} + +pub(crate) fn now() -> i64 { + chrono::Local::now().timestamp() +} + +/// "today at 18:40", "tomorrow", "in 3 days", then a date as in the library. +pub(crate) fn when(at: i64, now: i64) -> String { + use chrono::{Local, TimeZone}; + let (Some(at), Some(now)) = ( + Local.timestamp_opt(at, 0).single(), + Local.timestamp_opt(now, 0).single(), + ) else { + return String::new(); + }; + let days = (at.date_naive() - now.date_naive()).num_days(); + match days { + ..=0 => trf("today at {time}", &[("time", &at.format("%H:%M"))]), + 1 => tr("tomorrow").to_owned(), + 2..=6 => trf("in {days} days", &[("days", &days)]), + _ => at.format("%d.%m.%Y").to_string(), + } +} + +#[derive(Default)] +pub(crate) struct BoardAnnotations { + pub(crate) arrows: Vec, + pub(crate) circles: Vec<(Square, Color32)>, + pub(crate) badge: Option, +} + +/// The marks of a PGN move on the board: its assessment badge, `[%cal]` arrows and +/// `[%csl]` squares. +pub(crate) fn pgn_annotations_at(game: &Game, at: NodeId) -> BoardAnnotations { + let mut out = BoardAnnotations::default(); + let Some(node) = game.node(at) else { + return out; + }; + let square = node.game_move().and_then(|game_move| match game_move.kind { + MoveKind::Normal(mv) => Some(crate::board::ui_target(&mv)), + MoveKind::Null => None, + }); + if let Some(square) = square { + out.badge = node + .nags() + .iter() + .copied() + .find(|nag| nag.is_move_assessment()) + .and_then(|nag| { + Some(Badge { + square, + text: nag.symbol()?, + color: crate::notation::assessment_color(nag)?, + }) + }); + } + for comment in node.comments_after() { + for part in parse_comment(comment) { + match part { + CommentPart::Annotation(Annotation::Arrows(list)) => { + out.arrows + .extend(list.into_iter().map(|(color, from, to)| Arrow { + from, + to, + color: crate::game_view::shape_color(color), + weight: 0.9, + })); + } + CommentPart::Annotation(Annotation::Squares(list)) => { + out.circles.extend( + list.into_iter() + .map(|(color, square)| (square, crate::game_view::shape_color(color))), + ); + } + CommentPart::Text(_) | CommentPart::Annotation(_) => {} + } + } + } + out +} + +/// The position after a node, for a board that only shows it. +pub(crate) fn position_of(game: &Game, node: NodeId) -> chess_core::shakmaty::Chess { + game.position(node) + .or_else(|| game.position(NodeId::ROOT)) + .cloned() + .unwrap_or_default() +} + +/// A board that only shows a position. +pub(crate) fn still_board( + ui: &mut Ui, + state: &mut crate::board::BoardState, + settings: &Settings, + pos: &chess_core::shakmaty::Chess, + orientation: Color, + last_move: Option<(Square, Square)>, + annotations: &BoardAnnotations, +) { + crate::board::BoardView { + pos, + orientation, + last_move, + arrows: &annotations.arrows, + circles: &annotations.circles, + badge: annotations.badge, + interactive: false, + show_coords: settings.show_coords, + theme: settings.board_theme.theme(), + pieces: settings.piece_set, + animation: settings.animation.seconds(), + premove: None, + auto_queen: false, + alert: None, + } + .show(ui, state); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pgn_node_badges_keep_the_existing_palette_and_special_move_destinations() { + for (nag, symbol) in [ + (1, "!"), + (2, "?"), + (3, "!!"), + (4, "??"), + (5, "!?"), + (6, "?!"), + ] { + let game = chess_core::parse_str(&format!("1. e4 ${nag} *")).game; + let node = game.main_child(NodeId::ROOT).unwrap(); + let badge = pgn_annotations_at(&game, node).badge.unwrap(); + assert_eq!(badge.text, symbol); + assert_eq!(badge.square, Square::E4); + assert_eq!( + badge.color, + crate::notation::assessment_color(chess_core::Nag(nag)).unwrap() + ); + } + for (fen, san, expected) in [ + ("4k3/8/8/8/8/8/8/4K2R w K - 0 1", "O-O!!", Square::G1), + ("4k3/P7/8/8/8/8/8/4K3 w - - 0 1", "a8=Q+!", Square::A8), + ] { + let game = + chess_core::parse_str(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. {san} *")) + .game; + let node = game.main_child(NodeId::ROOT).unwrap(); + assert_eq!( + pgn_annotations_at(&game, node).badge.unwrap().square, + expected + ); + } + let game = chess_core::parse_str("1. e4 $14 *").game; + let node = game.main_child(NodeId::ROOT).unwrap(); + assert!( + pgn_annotations_at(&game, node).badge.is_none(), + "position assessments are not move badges" + ); + } + + #[test] + fn pgn_shapes_of_a_move_become_arrows_and_circles() { + let game = chess_core::parse_str("1. e4 {[%cal Re2e4,Ge7e5] [%csl Ye4]} *").game; + let node = game.main_child(NodeId::ROOT).unwrap(); + let marks = pgn_annotations_at(&game, node); + assert_eq!(marks.arrows.len(), 2); + assert_eq!( + marks.arrows[0].color, + crate::game_view::shape_color(chess_core::ShapeColor::Red) + ); + assert_eq!( + marks.circles, + [( + Square::E4, + crate::game_view::shape_color(chess_core::ShapeColor::Yellow) + )] + ); + assert!(pgn_annotations_at(&game, NodeId::ROOT).badge.is_none()); + } + + #[test] + fn common_start_stops_before_the_first_branching() { + let game = chess_core::parse_str("1. e4 e5 2. Nf3 (2. Bc4) Nc6 *").game; + let start = common_start(&game); + assert_eq!(uci_path(&game, start), ["e2e4", "e7e5"]); + let game = chess_core::parse_str("1. e4 (1. d4) *").game; + assert_eq!(common_start(&game), NodeId::ROOT); + let game = chess_core::parse_str("*").game; + assert_eq!(common_start(&game), NodeId::ROOT); + } + + #[test] + fn lines_are_the_last_moves_in_pgn_order_without_switched_off_branches() { + let game = chess_core::parse_str("1. e4 e5 (1... c5 2. Nf3) 2. Nf3 (2. Bc4) *").game; + let all = lines(&game, |_| false); + assert_eq!( + all, + [ + vec!["e2e4", "e7e5", "g1f3"], + vec!["e2e4", "e7e5", "f1c4"], + vec!["e2e4", "c7c5", "g1f3"], + ] + .map(|line| line.into_iter().map(str::to_owned).collect::>()) + ); + let without_c5 = lines(&game, |path| { + path.starts_with(&["e2e4".into(), "c7c5".into()]) + }); + assert_eq!(without_c5.len(), 2); + let node = node_at(&game, &all[1]).unwrap(); + assert_eq!(uci_path(&game, node), all[1]); + assert_eq!(move_text(&game, node).as_deref(), Some("2. Bc4")); + let black = node_at(&game, &all[2][..2]).unwrap(); + assert_eq!(move_text(&game, black).as_deref(), Some("1… c5")); + } + + #[test] + fn dates_read_as_today_tomorrow_days_then_a_date() { + let at = 1_800_000_000; + assert!(when(at + 60, at).contains(':')); + assert_eq!(when(at + 24 * 3600, at), tr("tomorrow")); + assert!(when(at + 3 * 24 * 3600, at).contains('3')); + assert_eq!(when(at + 30 * 24 * 3600, at).len(), 10); + assert!(end_of_today() >= now()); + assert!(end_of_today() - now() < 24 * 3600 + 3600); + } +} diff --git a/apps/desktop/src/opening_lines.rs b/apps/desktop/src/opening_lines.rs new file mode 100644 index 0000000..a1f3b98 --- /dev/null +++ b/apps/desktop/src/opening_lines.rs @@ -0,0 +1,584 @@ +//! The «Lines» screen of opening training (spec §6.3): the repertoire's tree, read only, +//! to choose what to train and which branches to leave out. + +use std::collections::BTreeSet; +use std::sync::mpsc; + +use chess_core::shakmaty::Color; +use chess_core::{Game, NodeId}; +use egui::{Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2}; +use trainer::repertoire::{ + LearningData, LearningItemKey, LearningSide, Library, Repertoire, RepertoireId, StatsScope, + active_learning_memberships, +}; + +use crate::board::BoardState; +use crate::i18n::{tr, trf}; +use crate::opening_layout::{self as layout, GAP, pgn_annotations_at}; +use crate::settings::Settings; + +const SELECTED_H: f32 = 92.0; +const TOOL_H: f32 = 28.0; +const MAIN_W: f32 = 170.0; + +pub enum LinesAction { + Back, + OpenSettings, + /// Train the lines through this move (empty: every line). + Train { + through: Vec, + label: String, + }, + /// Switch a branch off (`true`) or on again, from the move at this path. + SetDisabled { + path: Vec, + disabled: bool, + }, +} + +/// The repertoire's own moves with their paths and which of them are learnt; computed +/// off the frame. +struct Counts { + moves: Vec<(Vec, LearningItemKey)>, + learnt: BTreeSet, +} + +pub struct OpeningLinesUi { + id: RepertoireId, + name: String, + side: LearningSide, + repertoire: Repertoire, + game: Game, + lines: Vec>, + cursor: NodeId, + scroll: bool, + orientation: Color, + board: BoardState, + counts: Option, + counting: Option>>, + error: Option, +} + +impl OpeningLinesUi { + pub fn new( + library: &Library, + learning: &LearningData, + id: RepertoireId, + side: LearningSide, + cursor: Option>, + ) -> Option { + let repertoire = library.repertoire(&id)?.clone(); + let game = repertoire.game(); + let cursor = cursor + .and_then(|path| layout::node_at(&game, &path)) + .unwrap_or(NodeId::ROOT); + let lines = layout::lines(&game, |path| repertoire.is_prefix_disabled(path)); + let mut this = Self { + id, + name: repertoire.name.clone(), + side, + repertoire, + game, + lines, + cursor, + scroll: true, + orientation: layout::orientation(side), + board: BoardState::default(), + counts: None, + counting: None, + error: None, + }; + this.count(library, learning); + Some(this) + } + + pub fn id(&self) -> &RepertoireId { + &self.id + } + + pub fn cursor_path(&self) -> Vec { + layout::uci_path(&self.game, self.cursor) + } + + /// The library changed (a branch switched off or on): recount, keep the move. + pub fn refresh(&mut self, library: &Library, learning: &LearningData) { + if let Some(repertoire) = library.repertoire(&self.id) { + self.repertoire = repertoire.clone(); + self.name = repertoire.name.clone(); + self.lines = layout::lines(&self.game, |path| repertoire.is_prefix_disabled(path)); + } + self.count(library, learning); + } + + fn count(&mut self, library: &Library, learning: &LearningData) { + let library = library.clone(); + let learning = learning.clone(); + let scope = StatsScope::for_repertoire(self.id.clone(), self.side, layout::now()); + let (tx, rx) = mpsc::channel(); + self.counting = Some(rx); + if let Err(error) = crate::platform::spawn("repertoire-lines-count", move || { + let result = active_learning_memberships(&library, &scope) + .map(|memberships| { + let learnt = memberships + .iter() + .filter(|membership| { + learning + .item(&membership.key) + .is_some_and(|item| item.is_learnt()) + }) + .map(|membership| membership.key.clone()) + .collect(); + Counts { + moves: memberships + .into_iter() + .map(|membership| (membership.path, membership.key)) + .collect(), + learnt, + } + }) + .map_err(|error| error.to_string()); + let _ = tx.send(result); + }) { + self.counting = None; + self.error = Some(error.to_string()); + } + } + + fn poll(&mut self) { + let Some(rx) = &self.counting else { + return; + }; + match rx.try_recv() { + Ok(Ok(counts)) => { + self.counts = Some(counts); + self.counting = None; + } + Ok(Err(error)) => { + self.error = Some(error); + self.counting = None; + } + Err(mpsc::TryRecvError::Empty) => {} + Err(mpsc::TryRecvError::Disconnected) => self.counting = None, + } + } + + /// The prefix that switches this path off, if any. + fn disabled_by(&self, path: &[String]) -> Option> { + self.repertoire + .disabled_prefixes + .iter() + .filter(|prefix| path.starts_with(prefix)) + .min_by_key(|prefix| prefix.len()) + .cloned() + } + + fn goto(&mut self, node: NodeId) { + if self.game.node(node).is_some() { + self.cursor = node; + self.scroll = true; + } + } + + fn keyboard(&mut self, ui: &Ui, actions: &mut Vec) { + if ui.ctx().egui_wants_keyboard_input() || crate::app::overlay_open(ui.ctx()) { + return; + } + let mut command = None; + ui.input_mut(|input| { + for (key, name) in [ + (Key::ArrowLeft, "back"), + (Key::ArrowRight, "forward"), + (Key::ArrowUp, "previous"), + (Key::ArrowDown, "next"), + (Key::Home, "home"), + (Key::End, "end"), + (Key::F, "flip"), + (Key::Enter, "train"), + (Key::Escape, "back_screen"), + ] { + if command.is_none() + && (input.consume_key(Modifiers::NONE, key) + || input.consume_key(Modifiers::SHIFT, key)) + { + command = Some(name); + } + } + if command.is_none() + && input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W)) + { + command = Some("back_screen"); + } + }); + let game = &self.game; + let cursor = self.cursor; + match command { + Some("back") => { + if let Some(parent) = game.parent(cursor) { + self.goto(parent); + } + } + Some("forward") => { + if let Some(next) = game.main_child(cursor) { + self.goto(next); + } + } + Some("previous") => { + if let Some(other) = game.prev_sibling(cursor) { + self.goto(other); + } + } + Some("next") => { + if let Some(other) = game.next_sibling(cursor) { + self.goto(other); + } + } + Some("home") => self.goto(NodeId::ROOT), + Some("end") => { + let end = game.line_end(cursor); + self.goto(end); + } + Some("flip") => self.orientation = self.orientation.other(), + Some("train") => actions.push(self.train_action()), + Some("back_screen") => actions.push(LinesAction::Back), + _ => {} + } + } + + fn train_action(&self) -> LinesAction { + let through = self.cursor_path(); + let label = self.path_label(self.cursor); + LinesAction::Train { through, label } + } + + /// "… 4. Ba4 Nf6": the moves to a node in the notation of the application. + fn path_label(&self, node: NodeId) -> String { + let mut words = Vec::new(); + for id in self.game.path(node).into_iter().skip(1) { + let Some(mv) = self.game.game_move(id) else { + continue; + }; + let san = crate::san::show(&mv.san).into_owned(); + match self.game.move_number(id) { + Some((number, Color::White)) => words.push(format!("{number}. {san}")), + Some((number, Color::Black)) if words.is_empty() => { + words.push(format!("{number}… {san}")) + } + _ => words.push(san), + } + } + words.join(" ") + } + + fn below(&self, path: &[String]) -> Option<(usize, usize, usize)> { + let counts = self.counts.as_ref()?; + let lines = self + .lines + .iter() + .filter(|line| line.starts_with(path)) + .count(); + let mine: Vec<_> = counts + .moves + .iter() + .filter(|(move_path, _)| move_path.starts_with(path)) + .collect(); + let learnt = mine + .iter() + .filter(|(_, key)| counts.learnt.contains(key)) + .count(); + Some((lines, mine.len(), learnt)) + } + + fn selected_block(&self, ui: &mut Ui, actions: &mut Vec) { + let path = self.cursor_path(); + let disabled = self.disabled_by(&path); + layout::fixed_block(ui, SELECTED_H, |ui| { + let inner = vec2(ui.available_width() - 20.0, SELECTED_H - 12.0); + layout::card(ui, false, false).show(ui, |ui| { + ui.set_min_size(inner); + ui.set_max_size(inner); + ui.spacing_mut().item_spacing.y = 4.0; + if self.cursor == NodeId::ROOT { + layout::line(ui, RichText::new(tr("Start position")).strong()); + } else { + let label = self.path_label(self.cursor); + // Cut on the left: the last moves matter. + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.set_max_height(20.0); + layout::line(ui, RichText::new(label).strong()); + }); + } + if disabled.is_some() { + layout::line( + ui, + RichText::new(tr("Not trained")).color(ui.visuals().warn_fg_color), + ); + } else { + let text = match self.below(&path) { + Some((lines, mine, learnt)) => trf( + "Below: {n} lines · {y} your moves · learned {x}", + &[("n", &lines), ("y", &mine), ("x", &learnt)], + ), + None => tr("Counting moves…").to_owned(), + }; + layout::line(ui, RichText::new(text).weak()); + } + ui.horizontal(|ui| { + let label = if self.cursor == NodeId::ROOT { + tr("Review all lines") + } else { + tr("Train this branch") + }; + let width = MAIN_W.min(ui.available_width() / 2.0 - 4.0); + let can_train = disabled.is_none() && !self.lines.is_empty(); + if ui + .add_enabled_ui(can_train, |ui| { + crate::widgets::primary_wide(ui, label, width) + }) + .inner + .on_hover_text("Enter") + .clicked() + { + actions.push(self.train_action()); + } + if self.cursor != NodeId::ROOT { + let (label, action) = match &disabled { + Some(prefix) => ( + tr("Train again"), + LinesAction::SetDisabled { + path: prefix.clone(), + disabled: false, + }, + ), + None => ( + tr("Don't train"), + LinesAction::SetDisabled { + path: path.clone(), + disabled: true, + }, + ), + }; + if ui + .add( + egui::Button::new(label) + .truncate() + .min_size(vec2(width, 30.0)), + ) + .clicked() + { + actions.push(action); + } + } + }); + }); + }); + } + + fn side(&mut self, ui: &mut Ui, actions: &mut Vec) { + let rect = ui.available_rect_before_wrap(); + let footer_h = TOOL_H + 12.0; + let footer = egui::Rect::from_min_max( + egui::pos2(rect.left(), (rect.bottom() - footer_h).max(rect.top())), + rect.max, + ); + let body = egui::Rect::from_min_max(rect.min, egui::pos2(rect.right(), footer.top())); + let mut clicked = None; + ui.scope_builder(egui::UiBuilder::new().max_rect(body), |ui| { + ui.set_clip_rect(body.intersect(ui.clip_rect())); + ui.spacing_mut().item_spacing.y = GAP; + ui.add_space(4.0); + let opening = layout::opening_text(&self.game, self.cursor); + layout::fixed_block(ui, 20.0, |ui| { + layout::line(ui, RichText::new(opening).weak()); + }); + let tree = (ui.available_height() - SELECTED_H - GAP).max(0.0); + let scroll = std::mem::take(&mut self.scroll); + let game = &self.game; + let cursor = self.cursor; + let response = layout::fixed_block(ui, tree, |ui| { + egui::ScrollArea::vertical() + .id_salt("opening_lines_tree") + .auto_shrink([false, false]) + .show(ui, |ui| { + crate::notation::Notation { + game, + cursor, + scroll_to_cursor: scroll, + marks: None, + preview: None, + translations: None, + editor: None, + read_only: true, + dim_until: None, + mistakes: None, + } + .show(ui) + }) + .inner + }); + clicked = response.clicked; + if let Some(error) = &self.error { + ui.colored_label(ui.visuals().warn_fg_color, error); + } + self.selected_block(ui, actions); + }); + if let Some(node) = clicked { + self.cursor = node; + } + ui.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| { + ui.separator(); + ui.horizontal(|ui| { + let icon = |s: &str| { + egui::Button::new(RichText::new(s).size(18.0)).min_size(vec2(0.0, TOOL_H)) + }; + let game = &self.game; + let mut target = None; + if ui.add(icon("⏮")).clicked() { + target = Some(NodeId::ROOT); + } + if ui.add(icon("◀")).clicked() { + target = game.parent(self.cursor); + } + if ui.add(icon("▶")).clicked() { + target = game.main_child(self.cursor); + } + if ui.add(icon("⏭")).clicked() { + target = Some(game.line_end(self.cursor)); + } + ui.separator(); + if ui + .add(icon("🔃")) + .on_hover_text(tr("Flip board (F)")) + .clicked() + { + self.orientation = self.orientation.other(); + } + if let Some(target) = target { + self.goto(target); + } + }); + }); + } + + pub fn show(&mut self, ui: &mut Ui, settings: &Settings) -> Vec { + self.poll(); + if self.counting.is_some() { + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(50)); + } + let mut actions = Vec::new(); + self.keyboard(ui, &mut actions); + let back = if ui.available_width() < 600.0 { + "⬅" + } else { + tr("⬅ Repertoires") + }; + let subtitle = trf( + "Lines · {n} lines · {y} your moves", + &[ + ("n", &self.lines.len()), + ( + "y", + &self + .counts + .as_ref() + .map_or_else(|| "…".to_owned(), |counts| counts.moves.len().to_string()), + ), + ], + ); + let name = self.name.clone(); + let mut header = (false, false); + layout::screen( + ui, + self, + |_, ui| header = crate::widgets::section_header_sub(ui, back, &name, &subtitle), + |this, ui| this.side(ui, &mut actions), + |this, ui| { + let position = layout::position_of(&this.game, this.cursor); + let marks = pgn_annotations_at(&this.game, this.cursor); + let last = layout::last_move(&this.game, this.cursor); + layout::still_board( + ui, + &mut this.board, + settings, + &position, + this.orientation, + last, + &marks, + ); + }, + ); + if header.0 { + actions.push(LinesAction::Back); + } + if header.1 { + actions.push(LinesAction::OpenSettings); + } + actions + } + + #[cfg_attr(not(test), allow(dead_code))] + pub fn debug_select(&mut self, path: &[String]) { + if let Some(node) = layout::node_at(&self.game, path) { + self.goto(node); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lines_ui(pgn: &str) -> (Library, OpeningLinesUi) { + let mut library = Library::default(); + let id = library + .create("Lines", &chess_core::parse_str(pgn).game) + .unwrap(); + let mut ui = OpeningLinesUi::new( + &library, + &LearningData::default(), + id, + LearningSide::White, + None, + ) + .unwrap(); + let deadline = web_time::Instant::now() + std::time::Duration::from_secs(5); + while ui.counting.is_some() && web_time::Instant::now() < deadline { + ui.poll(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + (library, ui) + } + + #[test] + fn counts_below_a_move_and_branches_switched_off() { + let (mut library, mut ui) = lines_ui("1. e4 e5 (1... c5 2. Nf3) 2. Nf3 (2. Bc4) *"); + assert_eq!(ui.below(&[]), Some((3, 4, 0))); + let c5 = ["e2e4".to_owned(), "c7c5".to_owned()]; + assert_eq!(ui.below(&c5), Some((1, 1, 0))); + ui.debug_select(&c5); + assert_eq!(ui.cursor_path(), c5); + assert_eq!(ui.path_label(ui.cursor), "1. e4 c5"); + assert!(matches!( + ui.train_action(), + LinesAction::Train { through, .. } if through == c5 + )); + let id = ui.id().clone(); + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&c5, true) + .unwrap(); + ui.refresh(&library, &LearningData::default()); + let deadline = web_time::Instant::now() + std::time::Duration::from_secs(5); + while ui.counting.is_some() && web_time::Instant::now() < deadline { + ui.poll(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(ui.lines.len(), 2); + assert_eq!( + ui.disabled_by(&[c5[0].clone(), c5[1].clone(), "g1f3".into()]), + Some(c5.to_vec()) + ); + assert_eq!(ui.below(&[]), Some((2, 3, 0))); + } +} diff --git a/apps/desktop/src/opening_session.rs b/apps/desktop/src/opening_session.rs new file mode 100644 index 0000000..e4c153e --- /dev/null +++ b/apps/desktop/src/opening_session.rs @@ -0,0 +1,2426 @@ +//! The «Session» screen of opening training (docs/design/opening-trainer-v2-spec.md §4–6): +//! the program plays the line up to the next question, shows a new move before asking +//! it, takes the answer on the board and records it in the background. + +use std::{ + collections::{BTreeMap, BTreeSet, HashMap, VecDeque}, + sync::{ + atomic::{AtomicU64, Ordering}, + mpsc, + }, + time::Duration, +}; + +use chess_core::shakmaty::{CastlingMode, Chess, Color, Move, Square, fen::Fen, uci::UciMove}; +use chess_core::{Game, NodeId}; +use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2}; +use trainer::repertoire::{ + AttemptApplication, LearningContextStep, LearningData, LearningItem, LearningItemKey, + LearningPresentation, LearningSessionError, LearningSessionPhase, LearningSessionSnapshot, + LearningSessionTarget, LearningSide, LearningStore, Library, PersistedSessionAttempt, + RepertoireId, SrsSettings, StatsScope, TrainingAttempt, TrainingEventType, + active_learning_keys, fen4, +}; +use web_time::{Instant, SystemTime, UNIX_EPOCH}; + +use crate::assets::Sound; +use crate::board::{Arrow, BoardState, BoardView}; +use crate::i18n::{tr, trf}; +use crate::opening_layout::{self as layout, BoardAnnotations, GAP, pgn_annotations_at}; +use crate::settings::Settings; + +const WRONG_SHOWN: Duration = Duration::from_millis(400); +/// How long «Correct» and «Got it» stay after the move's animation. +const FEEDBACK: Duration = Duration::from_millis(600); +const DEFAULT_ANIMATION: Duration = Duration::from_millis(250); +/// Mistakes listed under «Moves to remember». +const REMEMBER_ROWS: usize = 8; +const CARD_H: f32 = 64.0; +const LINE_H: f32 = 20.0; +const ROW_H: f32 = 30.0; +const TOOL_H: f32 = 28.0; +const LEFT_W: f32 = 150.0; +const MAIN_W: f32 = 170.0; +static NEXT_ID: AtomicU64 = AtomicU64::new(1); + +pub enum SessionAction { + /// Leave the session (to the repertoires, or to the lines it was started from). + Back, + OpenSettings, + Sound(Sound), + /// «10 more new»: the caller prepares the next new moves in the background. + MoreNew, +} + +/// What the session goes through. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SessionKind { + /// What is due today and up to ten new moves. + Daily, + /// Every move of every line, one pass. + ReviewAll, + /// Every move of the lines through `through` (UCI from the start). + Branch { through: Vec, label: String }, +} + +impl SessionKind { + pub fn subtitle(&self, side: LearningSide) -> String { + match self { + Self::Daily => match side { + LearningSide::White => tr("Training · you play White").to_owned(), + LearningSide::Black => tr("Training · you play Black").to_owned(), + }, + Self::ReviewAll => match side { + LearningSide::White => tr("Review all lines · you play White").to_owned(), + LearningSide::Black => tr("Review all lines · you play Black").to_owned(), + }, + Self::Branch { label, .. } => trf("Branch: {path}", &[("path", label)]), + } + } +} + +#[derive(Clone)] +struct VisualMove { + #[cfg_attr(not(test), allow(dead_code))] + uci: String, + before: Chess, + after: Chess, + from: Square, + to: Square, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PlayOutcome { + CorrectIndependent, + WrongIndependent, + WrongReplay, + ReplayAfterError, + /// The move after a hint or a revealed alternative. + PreviewedReplay, + /// A new move played after it was shown. + NewPlayed, +} + +#[derive(Clone)] +enum CommitKind { + Context, + ReusedContext, + Play { + visual: Box, + outcome: PlayOutcome, + shown_prefix: ShownPrefix, + }, + /// `new`: the first showing of a new move; otherwise a hint (or the move revealed + /// after another repertoire move). + Preview { + new: bool, + }, +} + +#[derive(Clone)] +struct ShownPrefix { + repertoire_id: RepertoireId, + path: Vec, +} + +#[derive(Clone)] +struct PendingCommit { + attempts: Vec, + kind: CommitKind, + /// The question the event answers (for the session's result). + target: Option, +} + +enum Playback { + Automatic { + current: Box, + remaining: VecDeque, + started_at: Instant, + duration: Duration, + }, + Wrong { + visual: Box, + until: Instant, + }, + Alternative { + visual: Box, + until: Instant, + }, + Accepted { + started_at: Instant, + duration: Duration, + outcome: PlayOutcome, + }, +} + +/// The numbers of the session's result. +#[derive(Default)] +struct Tally { + first_time: usize, + mistakes: usize, + hints: usize, + new_moves: usize, + missed: Vec, +} + +impl Tally { + fn any(&self) -> bool { + self.first_time + self.mistakes + self.hints + self.new_moves > 0 + } + + fn miss(&mut self, target: Option) { + if let Some(target) = target + && !self.missed.iter().any(|missed| missed.key == target.key) + { + self.missed.push(target); + } + } + + fn missed_key(&self, key: &LearningItemKey) -> bool { + self.missed.iter().any(|missed| &missed.key == key) + } +} + +/// The states of spec §4.2 (S0 is the caller's: before the session exists). +#[derive(Clone, Debug, PartialEq)] +enum State { + Watch, + NextLine, + New, + Yours, + YoursMore(String), + Correct, + Wrong, + Alternative, + GotIt, + Hint, + NewDone, + SaveError(String), + Failed(String), + Summary, +} + +/// Computed once when the result is shown. +struct Summary { + next_review: String, + more_new: usize, +} + +pub struct OpeningSessionUi { + library: Library, + store: LearningStore, + session: LearningSessionSnapshot, + learning: LearningData, + kind: SessionKind, + presentation: Option, + completed_attempt_ids: BTreeSet, + pending_commit: Option, + commit_in_flight: Option>>, + #[cfg(test)] + synchronous_commits: bool, + save_error: Option, + error: Option, + board: BoardState, + board_position: Chess, + // Parsed once in the training-start worker, never in a frame or save callback. + annotation_games: BTreeMap, + /// Active answers of this session's scope (a branch: of the branch). + repertoire_answers: BTreeSet, + /// Active answers of the whole repertoire, for the result. + repertoire_keys: BTreeSet, + /// The lines of a review, to count «line k of n». + lines: Vec>, + line: usize, + next_line_banner: bool, + // The visible node is independent of the session's already-advanced target. + displayed_node: Option<(RepertoireId, NodeId)>, + board_shown: bool, + pending_automatic: Option>, + shown_prefix: Option, + playback: Option, + needs_prepare: bool, + animation: Duration, + /// How long «Correct» and «Got it» stay after the move ([`FEEDBACK`]). + feedback: Duration, + ready_since: Option, + last_move: Option<(Square, Square)>, + orientation: Color, + /// The next frame puts the board in place without a slide (a skipped context). + jump: bool, + /// The move revealed after another repertoire move was played (S5a). + alternative_revealed: bool, + /// Left before the end: the result says «Session stopped». + stopped: bool, + exit_requested: bool, + /// Leave at the next frame (an exit asked during a save, nothing answered). + leave: bool, + /// Started from the «Lines» screen: going back leads there. + back_to_lines: bool, + current_key: Option, + tally: Tally, + summary: Option, + shown_state: State, + pending_sounds: Vec, + #[cfg(test)] + visual_log: Vec, +} + +impl OpeningSessionUi { + /// A new session (never a resumed one: every answer of an earlier session is already + /// recorded). Runs in a worker: it reads the store and parses the repertoire. + pub fn new( + library: Library, + store: LearningStore, + scope: StatsScope, + kind: SessionKind, + ) -> Result { + let data = store.load().map_err(|error| error.to_string())?; + let id = unique_id("learning-session"); + let srs = SrsSettings::default(); + let mut session = match &kind { + SessionKind::Daily => LearningSessionSnapshot::new_daily( + id, + &library, + &data.learning, + scope, + srs, + layout::NEW_PER_SESSION, + ), + SessionKind::ReviewAll => LearningSessionSnapshot::new_single_pass_review( + id, + &library, + &data.learning, + scope, + srs, + ), + SessionKind::Branch { through, .. } => LearningSessionSnapshot::new_branch_review( + id, + &library, + &data.learning, + scope, + srs, + through, + ), + } + .map_err(|error| error.to_string())?; + store + .save_session(&mut session) + .map_err(|error| error.to_string())?; + Self::from_session(library, store, data.learning, session, kind) + } + + /// «10 more new» after a finished daily session. Runs in a worker. + pub fn more_new( + library: Library, + store: LearningStore, + mut session: LearningSessionSnapshot, + orientation: Color, + ) -> Result { + let data = store.load().map_err(|error| error.to_string())?; + session + .introduce_more(&library, &data.learning, layout::NEW_PER_SESSION) + .map_err(|error| error.to_string())?; + store + .save_session(&mut session) + .map_err(|error| error.to_string())?; + let mut this = + Self::from_session(library, store, data.learning, session, SessionKind::Daily)?; + this.orientation = orientation; + Ok(this) + } + + fn from_session( + library: Library, + store: LearningStore, + learning: LearningData, + session: LearningSessionSnapshot, + kind: SessionKind, + ) -> Result { + let completed_attempt_ids = learning + .attempts + .iter() + .filter(|attempt| attempt.session_id == session.id()) + .map(|attempt| attempt.client_attempt_id.clone()) + .collect(); + let repertoire_answers = active_learning_keys(&library, &session.stats_scope) + .map_err(|error| error.to_string())?; + let mut whole = session.stats_scope.clone(); + whole.branch_root = None; + let repertoire_keys = if whole == session.stats_scope { + repertoire_answers.clone() + } else { + active_learning_keys(&library, &whole).map_err(|error| error.to_string())? + }; + let annotation_games: BTreeMap<_, _> = session + .stats_scope + .repertoire_ids + .iter() + .filter_map(|id| { + library + .repertoire(id) + .map(|repertoire| (id.clone(), repertoire.game())) + }) + .collect(); + let lines = session + .stats_scope + .repertoire_ids + .iter() + .filter_map(|id| Some((library.repertoire(id)?, annotation_games.get(id)?))) + .flat_map(|(repertoire, game)| { + layout::lines(game, |path| repertoire.is_prefix_disabled(path)) + }) + .filter(|line| match &kind { + SessionKind::Branch { through, .. } => line.starts_with(through), + SessionKind::Daily | SessionKind::ReviewAll => true, + }) + .collect(); + let orientation = layout::orientation(session.stats_scope.side); + Ok(Self { + library, + store, + session, + learning, + kind, + presentation: None, + completed_attempt_ids, + pending_commit: None, + commit_in_flight: None, + #[cfg(test)] + synchronous_commits: false, + save_error: None, + error: None, + board: BoardState::default(), + board_position: Chess::default(), + annotation_games, + repertoire_answers, + repertoire_keys, + lines, + line: 0, + next_line_banner: false, + displayed_node: None, + board_shown: false, + pending_automatic: None, + shown_prefix: None, + playback: None, + needs_prepare: true, + animation: DEFAULT_ANIMATION, + feedback: FEEDBACK, + ready_since: None, + last_move: None, + orientation, + jump: false, + alternative_revealed: false, + stopped: false, + exit_requested: false, + leave: false, + back_to_lines: false, + current_key: None, + tally: Tally::default(), + summary: None, + shown_state: State::Watch, + pending_sounds: Vec::new(), + #[cfg(test)] + visual_log: Vec::new(), + }) + } + + pub fn has_unsaved(&self) -> bool { + self.pending_commit.is_some() || self.save_error.is_some() + } + + pub fn target_available(&self) -> bool { + self.session.current_target().is_some() + } + + pub fn set_back_to_lines(&mut self, back_to_lines: bool) { + self.back_to_lines = back_to_lines; + } + + pub fn orientation(&self) -> Color { + self.orientation + } + + /// The finished session, for «10 more new». + pub fn snapshot(&self) -> &LearningSessionSnapshot { + &self.session + } + + #[cfg_attr(not(test), allow(dead_code))] + pub fn session_id(&self) -> &str { + self.session.id() + } + + fn is_finished(&self) -> bool { + self.session.phase == LearningSessionPhase::Finished + && self.playback.is_none() + && !self.has_unsaved() + } + + fn summary_visible(&self) -> bool { + (self.stopped || self.is_finished()) && !self.has_unsaved() + } + + fn can_input(&self) -> bool { + !self.has_unsaved() + && !self.stopped + && self.error.is_none() + && !self.needs_prepare + && self.playback.is_none() + && self.pending_automatic.is_none() + && self.session.current_target().is_some() + && matches!( + self.session.phase, + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent + | LearningSessionPhase::AwaitingReplayAfterError + | LearningSessionPhase::PreviewedReplay + ) + } + + fn can_hint(&self) -> bool { + self.can_input() + && self.session.phase == LearningSessionPhase::AwaitingIndependent + && !self.session.current_is_new(&self.learning) + } + + fn tick_at(&mut self, now: Instant, animation: Duration, happened_at: i64) { + self.animation = animation; + self.poll_commit(now); + if self.stopped || self.has_unsaved() { + return; + } + if self.board_shown + && let Some(steps) = self.pending_automatic.take() + { + self.start_next_automatic(steps, now); + } + if self.needs_prepare { + self.prepare_presentation(now); + } + loop { + if self.stopped || self.has_unsaved() || self.error.is_some() { + return; + } + if self.needs_prepare { + self.prepare_presentation(now); + continue; + } + let Some(deadline) = self.playback_deadline() else { + return; + }; + if now < deadline { + return; + } + match self.playback { + Some(Playback::Wrong { .. } | Playback::Alternative { .. }) => { + self.finish_temporary_move(now, happened_at); + } + Some(Playback::Accepted { .. }) => self.finish_accepted(now), + Some(Playback::Automatic { .. }) => { + let id = unique_id(self.session.id()); + self.advance_context_with_id_at(id, now, happened_at); + } + None => return, + } + if !animation.is_zero() { + return; + } + } + } + + fn playback_deadline(&self) -> Option { + match &self.playback { + Some(Playback::Automatic { + started_at, + duration, + .. + }) + | Some(Playback::Accepted { + started_at, + duration, + .. + }) => Some(*started_at + *duration), + Some(Playback::Wrong { until, .. } | Playback::Alternative { until, .. }) => { + Some(*until) + } + None => None, + } + } + + fn prepare_presentation(&mut self, now: Instant) { + let presentation = match self + .session + .presentation_with_learning(&self.library, &self.learning) + { + Ok(presentation) => presentation, + Err(error) => { + self.error = Some(error.to_string()); + self.needs_prepare = false; + self.ready_since = None; + return; + } + }; + self.error = None; + self.needs_prepare = false; + self.presentation = Some(presentation.clone()); + let Some(ref current) = presentation.current_position else { + self.ready_since = None; + self.pending_automatic = None; + return; + }; + let key = self + .session + .current_target() + .map(|target| target.key.clone()); + if key != self.current_key { + self.current_key = key; + self.alternative_revealed = false; + self.track_line(); + } + // A following task may extend the line that is already on the board. Keep + // its context journal, but do not rewind and animate those same moves again. + // The complete path and repertoire must match; a transposed FEN is not enough. + if self.reuse_shown_context(&presentation, now) { + return; + } + self.shown_prefix = None; + if !presentation.automatic_context.is_empty() { + let mut steps = VecDeque::new(); + for step in presentation.automatic_context { + match VisualMove::from_context(&step) { + Ok(_) => steps.push_back(step), + Err(error) => { + self.error = Some(error); + self.ready_since = None; + return; + } + } + } + self.ready_since = None; + let Some(first) = steps.front() else { + self.error = Some("automatic context has no visual step".to_owned()); + return; + }; + self.board_position = match parse_position(&first.from) { + Ok(position) => position, + Err(error) => { + self.error = Some(error); + return; + } + }; + self.set_displayed_context(self.session.context_index); + self.board_shown = false; + self.pending_automatic = Some(steps); + self.playback = None; + self.last_move = None; + return; + } + self.pending_automatic = None; + let position = match parse_position(current) { + Ok(position) => position, + Err(error) => { + self.error = Some(error); + self.ready_since = None; + return; + } + }; + if fen4(&self.board_position) != current.fen4 { + self.last_move = None; + } + self.board_position = position; + self.set_displayed_context(self.session.context_index); + self.playback = None; + self.next_line_banner = false; + match self.session.phase { + LearningSessionPhase::AwaitingIndependent + if self.session.current_is_new(&self.learning) => + { + // A new move is shown before it is asked (decision 2026-11-26). + self.ready_since = None; + let id = unique_id(self.session.id()); + self.preview_with_id_at(id, true, now, layout::now()); + } + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent => { + self.ready_since = Some(now); + } + LearningSessionPhase::AwaitingReplayAfterError + | LearningSessionPhase::PreviewedReplay => { + self.ready_since = None; + } + phase => { + self.ready_since = None; + self.error = Some(format!( + "learning session has no playable position in {phase:?}" + )); + } + } + } + + /// The line of the current question (1-based), for a review. + fn track_line(&mut self) { + if self.kind == SessionKind::Daily { + return; + } + let Some(target) = self.session.current_target() else { + return; + }; + let Some(index) = self + .lines + .iter() + .position(|line| line.starts_with(&target.path)) + else { + return; + }; + let line = index + 1; + if line > self.line { + self.next_line_banner = self.line > 0; + self.line = line; + } + } + + fn reuse_shown_context(&mut self, presentation: &LearningPresentation, at: Instant) -> bool { + let Some(prefix) = &self.shown_prefix else { + return false; + }; + let Some(target) = self.session.current_target() else { + return false; + }; + let Some(remaining) = prefix.path.len().checked_sub(self.session.context_index) else { + return false; + }; + if remaining == 0 + || target.repertoire_id != prefix.repertoire_id + || !presentation.target_path.starts_with(&prefix.path) + // An independent context question must still be asked. Only reuse a + // prefix that the core explicitly allows to be automatic in full. + || presentation.automatic_context.len() < remaining + || presentation.automatic_context[remaining - 1].to.fen4 != fen4(&self.board_position) + { + return false; + } + // These moves are already visible. Preserve each AUTO_CONTEXT event, + // but commit the whole prefix once instead of rereading/writing all + // history and rebuilding the presentation once per old move. + self.commit_context_batch(remaining, at) + } + + /// Records `count` automatic moves of the current line at once (moves already on the + /// board, or skipped by the user). + fn commit_context_batch(&mut self, count: usize, at: Instant) -> bool { + let mut next_session = self.session.clone(); + let mut attempts = Vec::with_capacity(count); + let happened_at = layout::now(); + for _ in 0..count { + let id = unique_id(next_session.id()); + match next_session.advance_context_with_learning( + &self.library, + &self.learning, + id, + happened_at, + ) { + Ok(attempt) => attempts.push(attempt), + Err(error) => { + self.error = Some(error.to_string()); + return true; + } + } + } + if attempts.is_empty() { + return false; + } + self.session = next_session; + self.ready_since = None; + self.pending_commit = Some(PendingCommit { + attempts, + kind: CommitKind::ReusedContext, + target: None, + }); + self.persist_pending(at); + true + } + + /// «Skip»: the position of the question at once, the skipped moves recorded as + /// shown. + fn skip_context(&mut self, now: Instant) -> bool { + if self.has_unsaved() || self.stopped { + return false; + } + let (count, last) = match (&self.playback, &self.pending_automatic) { + ( + Some(Playback::Automatic { + current, remaining, .. + }), + _, + ) => ( + remaining.len() + 1, + remaining + .back() + .map(VisualMove::from_context) + .unwrap_or_else(|| Ok((**current).clone())), + ), + (None, Some(steps)) => match steps.back() { + Some(step) => (steps.len(), VisualMove::from_context(step)), + None => return false, + }, + _ => return false, + }; + let last = match last { + Ok(last) => last, + Err(error) => { + self.error = Some(error); + return false; + } + }; + self.playback = None; + self.pending_automatic = None; + if !self.commit_context_batch(count, now) { + return false; + } + self.board_position = last.after.clone(); + self.set_displayed_context(self.session.context_index); + self.last_move = Some((last.from, last.to)); + self.jump = true; + true + } + + fn start_next_automatic(&mut self, mut remaining: VecDeque, now: Instant) { + let Some(step) = remaining.pop_front() else { + self.needs_prepare = true; + self.prepare_presentation(now); + return; + }; + let current = match VisualMove::from_context(&step) { + Ok(current) => current, + Err(error) => { + self.error = Some(error); + return; + } + }; + self.board_position = current.after.clone(); + self.set_displayed_context(self.session.context_index + 1); + self.last_move = Some((current.from, current.to)); + self.playback = Some(Playback::Automatic { + current: Box::new(current.clone()), + remaining, + started_at: now, + duration: self.animation.div_f32(step.speed_factor.max(0.01) as f32), + }); + #[cfg(test)] + self.visual_log.push(current.uci.clone()); + self.queue_sound(Sound::Move); + } + + fn advance_context_with_id_at( + &mut self, + client_attempt_id: String, + now: Instant, + happened_at: i64, + ) -> bool { + if self.has_unsaved() + || !matches!(self.playback, Some(Playback::Automatic { .. })) + || self.completed_attempt_ids.contains(&client_attempt_id) + { + return false; + } + let attempt = match self.session.advance_context_with_learning( + &self.library, + &self.learning, + client_attempt_id, + happened_at, + ) { + Ok(attempt) => attempt, + Err(error) => { + self.error = Some(error.to_string()); + return false; + } + }; + self.begin_commit(attempt, CommitKind::Context, now); + true + } + + fn finish_context(&mut self, now: Instant) { + let Some(Playback::Automatic { remaining, .. }) = self.playback.take() else { + self.error = Some("automatic context is missing its visual step".to_owned()); + return; + }; + self.start_next_automatic(remaining, now); + } + + fn play_move_at(&mut self, mv: Move, now: Instant, happened_at: i64) -> bool { + let id = unique_id(self.session.id()); + self.play_move_with_id_at(mv, id, now, happened_at) + } + + fn play_move_with_id_at( + &mut self, + mv: Move, + client_attempt_id: String, + now: Instant, + happened_at: i64, + ) -> bool { + if !self.can_input() || self.completed_attempt_ids.contains(&client_attempt_id) { + return false; + } + let Some(expected_uci) = self.session.current_expected_uci().map(str::to_owned) else { + return false; + }; + let before = self.board_position.clone(); + let uci = mv.to_uci(CastlingMode::Standard).to_string(); + let visual = VisualMove::new(uci.clone(), before, mv); + let phase = self.session.phase; + let independent = matches!( + phase, + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent + ); + let showing_new = self.session.showing_new; + let Some(target) = self.session.current_target().cloned() else { + return false; + }; + let Some(prefix) = target.path.get(..self.session.context_index) else { + return false; + }; + let mut path = prefix.to_vec(); + path.push(uci.clone()); + let shown_prefix = ShownPrefix { + repertoire_id: target.repertoire_id.clone(), + path, + }; + if !independent && uci != expected_uci { + let key = LearningItemKey::new(target.key.user_id.clone(), fen4(&visual.before), &uci); + if self.repertoire_answers.contains(&key) { + self.show_repertoire_alternative(visual, &shown_prefix, now); + return true; + } + self.set_displayed_path(Some(&shown_prefix)); + self.start_playback(visual, PlayOutcome::WrongReplay, now); + return true; + } + let response_time_ms = independent.then(|| { + self.ready_since.map_or(0, |ready| { + u64::try_from(now.saturating_duration_since(ready).as_millis()).unwrap_or(u64::MAX) + }) + }); + let attempt = match self.session.play_uci_with_learning_answers( + &self.library, + &self.learning, + &self.repertoire_answers, + &uci, + client_attempt_id, + happened_at, + response_time_ms, + ) { + Ok(attempt) => attempt, + Err(LearningSessionError::RepertoireAlternative { .. }) => { + self.show_repertoire_alternative(visual, &shown_prefix, now); + return true; + } + Err(error) => { + self.error = Some(error.to_string()); + return false; + } + }; + let outcome = match attempt.event_type { + TrainingEventType::CorrectIndependent => PlayOutcome::CorrectIndependent, + TrainingEventType::IncorrectIndependent => PlayOutcome::WrongIndependent, + TrainingEventType::ReplayAfterError => PlayOutcome::ReplayAfterError, + TrainingEventType::AutoContext if showing_new => PlayOutcome::NewPlayed, + TrainingEventType::AutoContext => PlayOutcome::PreviewedReplay, + TrainingEventType::Previewed | TrainingEventType::IllegalMove => { + self.error = Some("legal board input produced a non-play event".to_owned()); + return false; + } + }; + // The credited question: the played answer itself when it was another + // pending answer of this position. + let credited = if attempt.item_key() == target.key { + Some(target) + } else { + self.session + .queue + .iter() + .find(|candidate| candidate.key == attempt.item_key()) + .cloned() + }; + // The legal move is visible immediately, including while its event is + // being saved. Input stays blocked until persistence acknowledges it. + // In particular a dropped piece must not jump back to its source square. + self.board_position = visual.after.clone(); + self.set_displayed_path(Some(&shown_prefix)); + self.last_move = Some((visual.from, visual.to)); + self.begin_commit_for( + attempt, + CommitKind::Play { + visual: Box::new(visual), + outcome, + shown_prefix, + }, + credited, + now, + ); + true + } + + fn play_uci_with_id_at( + &mut self, + uci: &str, + client_attempt_id: String, + now: Instant, + happened_at: i64, + ) -> bool { + if !self.can_input() || self.completed_attempt_ids.contains(&client_attempt_id) { + return false; + } + let mv = uci + .parse::() + .ok() + .and_then(|uci| uci.to_move(&self.board_position).ok()); + let Some(mv) = mv else { + return false; + }; + self.play_move_with_id_at(mv, client_attempt_id, now, happened_at) + } + + fn start_playback(&mut self, visual: VisualMove, outcome: PlayOutcome, now: Instant) { + self.ready_since = None; + self.board_position = visual.after.clone(); + self.last_move = Some((visual.from, visual.to)); + match outcome { + PlayOutcome::WrongIndependent | PlayOutcome::WrongReplay => { + self.playback = Some(Playback::Wrong { + visual: Box::new(visual), + until: now + WRONG_SHOWN, + }); + self.queue_sound(Sound::Wrong); + } + PlayOutcome::CorrectIndependent + | PlayOutcome::ReplayAfterError + | PlayOutcome::PreviewedReplay + | PlayOutcome::NewPlayed => { + self.playback = Some(Playback::Accepted { + started_at: now, + duration: self.animation + self.feedback, + outcome, + }); + self.queue_sound(Sound::Move); + } + } + } + + fn show_repertoire_alternative( + &mut self, + visual: VisualMove, + shown_prefix: &ShownPrefix, + now: Instant, + ) { + self.ready_since = None; + self.board_position = visual.after.clone(); + self.set_displayed_path(Some(shown_prefix)); + self.last_move = Some((visual.from, visual.to)); + self.playback = Some(Playback::Alternative { + visual: Box::new(visual), + until: now + WRONG_SHOWN.max(self.animation), + }); + } + + fn finish_temporary_move(&mut self, now: Instant, happened_at: i64) { + let (visual, alternative) = match self.playback.take() { + Some(Playback::Wrong { visual, .. }) => (visual, false), + Some(Playback::Alternative { visual, .. }) => (visual, true), + _ => return, + }; + self.board_position = visual.before; + self.last_move = None; + self.needs_prepare = true; + self.prepare_presentation(now); + // Another move of the repertoire is no mistake, but «now play {san}» shows the + // answer: it is recorded as shown, not as known. + if alternative && self.session.phase == LearningSessionPhase::AwaitingIndependent { + self.alternative_revealed = true; + let id = unique_id(self.session.id()); + self.preview_with_id_at(id, false, now, happened_at); + } else if alternative { + self.alternative_revealed = true; + } + } + + fn finish_accepted(&mut self, now: Instant) { + let Some(Playback::Accepted { outcome, .. }) = self.playback.take() else { + return; + }; + if outcome == PlayOutcome::CorrectIndependent + && self.session.phase == LearningSessionPhase::Finished + { + self.queue_sound(Sound::Success); + } + self.alternative_revealed = false; + self.needs_prepare = true; + self.prepare_presentation(now); + } + + fn request_hint_with_id_at( + &mut self, + client_attempt_id: String, + now: Instant, + happened_at: i64, + ) -> bool { + if !self.can_hint() || self.completed_attempt_ids.contains(&client_attempt_id) { + return false; + } + self.preview_with_id_at(client_attempt_id, false, now, happened_at) + } + + fn preview_with_id_at( + &mut self, + client_attempt_id: String, + new: bool, + now: Instant, + happened_at: i64, + ) -> bool { + if self.has_unsaved() || self.completed_attempt_ids.contains(&client_attempt_id) { + return false; + } + let target = self.session.current_target().cloned(); + let result = if new { + self.session.preview_new(client_attempt_id, happened_at) + } else { + self.session.preview(client_attempt_id, happened_at) + }; + let attempt = match result { + Ok(Some(attempt)) => attempt, + Ok(None) => return false, + Err(error) => { + self.error = Some(error.to_string()); + return false; + } + }; + self.board.clear(); + self.begin_commit_for(attempt, CommitKind::Preview { new }, target, now); + true + } + + fn begin_commit(&mut self, attempt: TrainingAttempt, kind: CommitKind, now: Instant) { + self.begin_commit_for(attempt, kind, None, now); + } + + fn begin_commit_for( + &mut self, + attempt: TrainingAttempt, + kind: CommitKind, + target: Option, + now: Instant, + ) { + if self.pending_commit.is_some() { + self.save_error = + Some("another learning event is still waiting to be saved".to_owned()); + return; + } + self.pending_commit = Some(PendingCommit { + attempts: vec![attempt], + kind, + target, + }); + self.persist_pending(now); + } + + fn persist_pending(&mut self, _now: Instant) { + let Some(pending) = self.pending_commit.clone() else { + return; + }; + if self.commit_in_flight.is_some() { + return; + } + #[cfg(test)] + if self.synchronous_commits { + let result = self + .store + .apply_attempts_and_session(pending.attempts.clone(), &mut self.session) + .map_err(|error| error.to_string()); + self.finish_commit(result, _now); + return; + } + let store = self.store.clone(); + let mut session = self.session.clone(); + let (tx, rx) = mpsc::channel(); + self.commit_in_flight = Some(rx); + self.save_error = None; + if let Err(error) = crate::platform::spawn("learning-save-attempt", move || { + let result = store + .apply_attempts_and_session(pending.attempts, &mut session) + .map_err(|error| error.to_string()); + let _ = tx.send(result); + }) { + self.commit_in_flight = None; + self.save_error = Some(error.to_string()); + self.ready_since = None; + } + } + + fn poll_commit(&mut self, now: Instant) { + let Some(receiver) = &self.commit_in_flight else { + return; + }; + let result = match receiver.try_recv() { + Ok(result) => result, + Err(mpsc::TryRecvError::Empty) => return, + Err(mpsc::TryRecvError::Disconnected) => { + Err("learning save worker disconnected".to_owned()) + } + }; + self.commit_in_flight = None; + self.finish_commit(result, now); + } + + fn finish_commit(&mut self, result: Result, now: Instant) { + let Some(pending) = self.pending_commit.clone() else { + return; + }; + match result { + Ok(persisted) => { + let duplicate = persisted.application == AttemptApplication::Duplicate; + self.learning = persisted.learning; + self.session = persisted.session; + self.completed_attempt_ids.extend( + pending + .attempts + .iter() + .map(|attempt| attempt.client_attempt_id.clone()), + ); + self.pending_commit = None; + self.save_error = None; + if duplicate { + self.playback = None; + self.shown_prefix = None; + self.ready_since = None; + self.needs_prepare = true; + self.prepare_presentation(now); + self.finish_exit(); + return; + } + self.count(&pending); + match pending.kind { + CommitKind::Context => self.finish_context(now), + CommitKind::ReusedContext => self.needs_prepare = true, + CommitKind::Play { + visual, + outcome, + shown_prefix, + } => { + self.shown_prefix = (!matches!( + outcome, + PlayOutcome::WrongIndependent | PlayOutcome::WrongReplay + )) + .then_some(shown_prefix); + self.start_playback(*visual, outcome, now); + } + CommitKind::Preview { .. } => { + self.needs_prepare = true; + self.prepare_presentation(now); + } + } + self.finish_exit(); + } + Err(error) => { + self.save_error = Some(error.to_string()); + self.ready_since = None; + } + } + } + + /// The session's result counts recorded events only. + fn count(&mut self, pending: &PendingCommit) { + let target = pending.target.clone(); + match &pending.kind { + CommitKind::Play { outcome, .. } => match outcome { + PlayOutcome::CorrectIndependent => { + if target + .as_ref() + .is_none_or(|target| !self.tally.missed_key(&target.key)) + { + self.tally.first_time += 1; + } + } + PlayOutcome::WrongIndependent => { + self.tally.mistakes += 1; + self.tally.miss(target); + } + PlayOutcome::NewPlayed => self.tally.new_moves += 1, + PlayOutcome::WrongReplay + | PlayOutcome::ReplayAfterError + | PlayOutcome::PreviewedReplay => {} + }, + CommitKind::Preview { new: false } => { + self.tally.hints += 1; + self.tally.miss(target); + } + CommitKind::Preview { new: true } | CommitKind::Context | CommitKind::ReusedContext => { + } + } + } + + fn retry_pending(&mut self, now: Instant) { + if self.pending_commit.is_some() { + self.persist_pending(now); + } + } + + fn queue_sound(&mut self, sound: Sound) { + if sound == Sound::Move && self.pending_sounds.last() == Some(&Sound::Move) { + return; + } + self.pending_sounds.push(sound); + } + + /// Esc, «⬅», «× Finish»: every answer is already recorded, so no question; after + /// an answer the result shows what was done. + fn request_exit(&mut self, actions: &mut Vec) { + if self.summary_visible() { + actions.push(SessionAction::Back); + return; + } + if self.save_error.is_some() { + // «Finish» in S9 gives up the one answer that could not be saved. + self.pending_commit = None; + self.save_error = None; + self.commit_in_flight = None; + } + if self.has_unsaved() { + self.exit_requested = true; + return; + } + if self.tally.any() { + self.stop(); + } else { + actions.push(SessionAction::Back); + } + } + + fn stop(&mut self) { + self.stopped = true; + self.pending_automatic = None; + if let Some(Playback::Automatic { .. }) = self.playback { + self.playback = None; + } + self.ready_since = None; + } + + /// An exit asked while an answer was being saved. + fn finish_exit(&mut self) { + if std::mem::take(&mut self.exit_requested) { + if self.tally.any() { + self.stop(); + } else { + self.leave = true; + } + } + } + + fn keyboard(&mut self, ui: &Ui, actions: &mut Vec) { + if ui.ctx().egui_wants_keyboard_input() || crate::app::overlay_open(ui.ctx()) { + return; + } + let state = self.shown_state.clone(); + let more = self.more_new_count() > 0; + let busy = self.board.is_busy(); + let mut command = None; + ui.input_mut(|input| { + if input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W)) + || (!busy && input.consume_key(Modifiers::NONE, Key::Escape)) + { + command = Some("exit"); + } else if input.consume_key(Modifiers::NONE, Key::F) { + command = Some("flip"); + } else if input.consume_key(Modifiers::NONE, Key::H) { + command = Some("hint"); + } else if state == State::Summary && more && input.consume_key(Modifiers::NONE, Key::N) + { + command = Some("more"); + } else if matches!( + state, + State::Watch | State::NextLine | State::Summary | State::SaveError(_) + ) && (input.consume_key(Modifiers::NONE, Key::Enter) + || input.consume_key(Modifiers::NONE, Key::Space)) + { + command = Some("main"); + } + }); + match command { + Some("exit") => self.request_exit(actions), + Some("flip") => self.orientation = self.orientation.other(), + Some("hint") => { + let id = unique_id(self.session.id()); + self.request_hint_with_id_at(id, Instant::now(), layout::now()); + } + Some("more") => actions.push(SessionAction::MoreNew), + Some("main") => self.main_action(&state, actions), + _ => {} + } + } + + fn main_action(&mut self, state: &State, actions: &mut Vec) { + match state { + State::Watch | State::NextLine => { + self.skip_context(Instant::now()); + } + State::Summary => actions.push(SessionAction::Back), + State::SaveError(_) => self.retry_pending(Instant::now()), + _ => {} + } + } + + fn board_animation_seconds(&mut self, settings: &Settings) -> f32 { + if self.pending_automatic.is_some() || std::mem::take(&mut self.jump) { + return 0.0; + } + match &self.playback { + Some(Playback::Automatic { duration, .. }) => duration.as_secs_f32(), + _ => settings.animation.seconds(), + } + } + + fn set_displayed_context(&mut self, played: usize) { + let prefix = self.session.current_target().and_then(|target| { + Some(ShownPrefix { + repertoire_id: target.repertoire_id.clone(), + path: target.path.get(..played)?.to_vec(), + }) + }); + self.set_displayed_path(prefix.as_ref()); + } + + fn set_displayed_path(&mut self, prefix: Option<&ShownPrefix>) { + self.displayed_node = prefix.and_then(|prefix| { + let game = self.annotation_games.get(&prefix.repertoire_id)?; + let at = layout::node_at(game, &prefix.path)?; + Some((prefix.repertoire_id.clone(), at)) + }); + } + + /// The node on the board, when the board really shows it. + fn shown_node(&self) -> Option<(&Game, NodeId)> { + let (id, at) = self.displayed_node.as_ref()?; + let game = self.annotation_games.get(id)?; + // A visual wrong move outside the source tree must never inherit the + // expected move's badge or arrows merely because the task advanced. + (game.position(*at)? == &self.board_position).then_some((game, *at)) + } + + fn displayed_annotations(&self) -> BoardAnnotations { + match self.shown_node() { + Some((game, at)) => pgn_annotations_at(game, at), + None => BoardAnnotations::default(), + } + } + + /// The asked move's node in the PGN. + fn expected_node(&self) -> Option<(&Game, NodeId)> { + let target = self.session.current_target()?; + let game = self.annotation_games.get(&target.repertoire_id)?; + let path = target.path.get(..=self.session.context_index)?; + Some((game, layout::node_at(game, path)?)) + } + + fn expected_text(&self) -> String { + self.expected_node() + .and_then(|(game, node)| layout::move_text(game, node)) + .unwrap_or_default() + } + + /// «4. Ba4 !» of the move just played. + fn played_text(&self, dark: bool) -> String { + let Some((game, node)) = self.shown_node() else { + return String::new(); + }; + let mut text = layout::move_text(game, node).unwrap_or_default(); + if let Some((symbol, _)) = layout::assessment(game, node, dark) { + text.push_str(symbol); + } + text + } + + /// The move shown by an arrow: revealed by the core, or a new move about to be shown. + fn revealed_uci(&self) -> Option { + if self.playback.is_some() || self.pending_automatic.is_some() { + return None; + } + if let Some(uci) = self + .presentation + .as_ref() + .and_then(|presentation| presentation.revealed_move.clone()) + && self.session.phase != LearningSessionPhase::AwaitingIndependent + { + return Some(uci); + } + matches!(self.shown_state, State::New) + .then(|| self.session.current_expected_uci().map(str::to_owned)) + .flatten() + } + + fn state(&self) -> Option { + if let Some(error) = &self.save_error { + return Some(State::SaveError(error.clone())); + } + if let Some(error) = &self.error { + return Some(State::Failed(error.clone())); + } + if self.summary_visible() { + return Some(State::Summary); + } + match &self.playback { + Some(Playback::Automatic { .. }) => return Some(self.watch()), + Some(Playback::Wrong { .. }) => return Some(State::Wrong), + Some(Playback::Alternative { .. }) => return Some(State::Alternative), + Some(Playback::Accepted { outcome, .. }) => { + return Some(match outcome { + PlayOutcome::CorrectIndependent => State::Correct, + PlayOutcome::NewPlayed => State::NewDone, + PlayOutcome::ReplayAfterError + | PlayOutcome::PreviewedReplay + | PlayOutcome::WrongIndependent + | PlayOutcome::WrongReplay => State::GotIt, + }); + } + None => {} + } + if self.pending_automatic.is_some() { + return Some(self.watch()); + } + if let Some(pending) = &self.pending_commit { + return match pending.kind { + CommitKind::Preview { new: true } => Some(State::New), + // Between moves: the card keeps what it said. + _ => None, + }; + } + if self.needs_prepare { + return None; + } + Some(match self.session.phase { + LearningSessionPhase::AwaitingIndependent + if self.session.current_is_new(&self.learning) => + { + State::New + } + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent => self.yours(), + LearningSessionPhase::AwaitingReplayAfterError => State::Wrong, + LearningSessionPhase::PreviewedReplay if self.session.showing_new => State::New, + LearningSessionPhase::PreviewedReplay if self.alternative_revealed => { + State::Alternative + } + LearningSessionPhase::PreviewedReplay => State::Hint, + LearningSessionPhase::AdvancingContext => self.watch(), + LearningSessionPhase::Finished => State::Summary, + }) + } + + fn watch(&self) -> State { + if self.next_line_banner { + State::NextLine + } else { + State::Watch + } + } + + /// S3, or S3a when another answer of this position was already played. + fn yours(&self) -> State { + let position = fen4(&self.board_position); + let played: Vec = self + .session + .completed_keys + .iter() + .filter(|key| key.position_fen4 == position && self.repertoire_answers.contains(key)) + .filter_map(|key| { + let mv = key + .expected_uci + .parse::() + .ok()? + .to_move(&self.board_position) + .ok()?; + let san = chess_core::shakmaty::san::San::from_move(&self.board_position, mv); + Some(crate::san::show(&san.to_string()).into_owned()) + }) + .collect(); + if played.is_empty() { + State::Yours + } else { + State::YoursMore(played.join(", ")) + } + } + + fn more_new_count(&self) -> usize { + if self.kind != SessionKind::Daily { + return 0; + } + self.summary.as_ref().map_or(0, |summary| summary.more_new) + } + + fn compute_summary(&mut self) { + if self.summary.is_some() { + return; + } + let items: HashMap<&LearningItemKey, &LearningItem> = self + .learning + .items + .iter() + .map(|item| (&item.key, item)) + .collect(); + let today = layout::end_of_today(); + let now = layout::now(); + let mut due_today = 0usize; + let mut next: Option = None; + let mut unseen = 0usize; + for key in &self.repertoire_keys { + match items.get(key) { + Some(item) if item.introduced => { + if item.is_due(today) { + due_today += 1; + } else if let Some(at) = item.next_review_at { + next = Some(next.map_or(at, |old| old.min(at))); + } + } + _ => unseen += 1, + } + } + let next_review = if due_today > 0 { + trf("today, {n} more", &[("n", &due_today)]) + } else { + next.map(|at| layout::when(at, now)).unwrap_or_default() + }; + self.summary = Some(Summary { + next_review, + more_new: unseen.min(layout::NEW_PER_SESSION), + }); + } + + fn board_ui(&mut self, ui: &mut Ui, settings: &Settings) { + let interactive = self.can_input(); + let annotations = self.displayed_annotations(); + let mut arrows = annotations.arrows; + if let Some(mv) = self.revealed_uci().and_then(|uci| { + uci.parse::() + .ok() + .and_then(|uci| uci.to_move(&self.board_position).ok()) + }) { + arrows.push(Arrow { + from: mv.from().unwrap_or_else(|| mv.to()), + to: crate::board::ui_target(&mv), + color: Color32::from_rgba_unmultiplied(21, 120, 27, 190), + weight: 1.0, + }); + } + let alert = match &self.playback { + Some(Playback::Wrong { visual, .. }) => Some((visual.from, visual.to)), + _ => None, + }; + let animation = self.board_animation_seconds(settings); + let played = BoardView { + pos: &self.board_position, + orientation: self.orientation, + last_move: self.last_move, + arrows: &arrows, + circles: &annotations.circles, + badge: annotations.badge, + interactive, + show_coords: settings.show_coords, + theme: settings.board_theme.theme(), + pieces: settings.piece_set, + animation, + premove: None, + auto_queen: false, + alert, + } + .show(ui, &mut self.board); + if let Some(mv) = played { + self.play_move_at(mv, Instant::now(), layout::now()); + } + self.board_shown = true; + } + + /// The card's texts: title, instruction, title colour. + fn card_texts(&self, state: &State, dark: bool) -> (String, String, Option) { + let dash = |s: &str| s.to_owned(); + let review = self.kind != SessionKind::Daily; + match state { + State::Watch => ( + dash(tr("Watch")), + dash(tr("Moves up to your next question")), + None, + ), + State::NextLine => ( + dash(tr("Next line")), + trf("{k} of {n}", &[("k", &self.line), ("n", &self.lines.len())]), + None, + ), + State::New => ( + dash(tr("New move")), + trf( + "Play {san} — it is shown by the arrow", + &[("san", &self.expected_text())], + ), + None, + ), + State::Yours => ( + dash(tr("Your move")), + dash(tr("Play the move from your repertoire")), + None, + ), + State::YoursMore(played) => ( + dash(tr("Your move")), + trf("One more move of yours here, not {san}", &[("san", played)]), + None, + ), + State::Correct => ( + dash(tr("Correct!")), + self.played_text(dark), + crate::notation::assessment_text_color(chess_core::Nag(1), dark), + ), + State::NewDone => (dash(tr("New move")), self.played_text(dark), None), + State::Wrong => ( + dash(tr("Not this move")), + trf("Correct: {san}. Play it", &[("san", &self.expected_text())]), + None, + ), + State::Alternative => ( + dash(tr("This one is in your repertoire too")), + trf( + "Now the other one: play {san}", + &[("san", &self.expected_text())], + ), + None, + ), + State::GotIt => ( + dash(tr("Got it")), + if review { + self.played_text(dark) + } else { + trf( + "{move} will come back in this session", + &[("move", &self.played_text(dark))], + ) + }, + None, + ), + State::Hint => ( + dash(tr("Hint")), + if review { + trf("Play {san}", &[("san", &self.expected_text())]) + } else { + trf( + "Play {san}. It will come back in this session", + &[("san", &self.expected_text())], + ) + }, + None, + ), + State::SaveError(error) => { + (dash(tr("Could not save your answer")), error.clone(), None) + } + State::Failed(error) => ( + dash(tr("Could not continue the session")), + error.clone(), + None, + ), + State::Summary => ( + dash(if self.stopped { + tr("Session stopped") + } else { + tr("Session complete") + }), + dash(tr("Everything is saved")), + None, + ), + } + } + + fn counter(&self, state: &State) -> (String, &'static str) { + match &self.kind { + SessionKind::Daily => { + let left = if matches!(state, State::Summary) && !self.stopped { + 0 + } else { + self.session.remaining() + }; + (left.to_string(), tr("left")) + } + SessionKind::ReviewAll | SessionKind::Branch { .. } => { + let k = if self.is_finished() { + self.lines.len() + } else { + self.line.max(1).min(self.lines.len()) + }; + (format!("{k}/{}", self.lines.len()), tr("line")) + } + } + } + + fn state_card(&self, ui: &mut Ui, state: &State) { + let dark = ui.visuals().dark_mode; + let (title, instruction, title_color) = self.card_texts(state, dark); + let active = matches!(state, State::New | State::Yours | State::YoursMore(_)); + let alert = matches!(state, State::Wrong | State::SaveError(_) | State::Failed(_)); + let (count, label) = self.counter(state); + show_card( + ui, + &CardView { + title, + instruction, + title_color, + active, + alert, + count, + label, + }, + ); + } + + /// Block D: the comment of the last move on the board (in S2, S5, S7 already of + /// the asked move), or the nearest earlier one of the line. + fn comment(&self, ui: &mut Ui, state: &State) { + let start = if matches!( + state, + State::New | State::Wrong | State::Hint | State::Alternative + ) { + self.expected_node() + } else { + self.shown_node() + }; + let Some((game, start)) = start else { + return; + }; + let dark = ui.visuals().dark_mode; + let mut path = game.path(start); + while let Some(node) = path.pop() { + let Some(data) = game.node(node) else { + continue; + }; + let text = crate::notation::comment_text(data.comments_after()); + if text.trim().is_empty() { + continue; + } + egui::ScrollArea::vertical() + .id_salt("opening_comment") + .auto_shrink([false, false]) + .show(ui, |ui| { + if let Some(label) = layout::move_text(game, node) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + ui.label(RichText::new(label).strong()); + if let Some((symbol, color)) = layout::assessment(game, node, dark) { + ui.label(RichText::new(symbol).strong().color(color)); + } + }); + } + ui.add(egui::Label::new(text).wrap()); + }); + return; + } + } + + fn summary_body(&self, ui: &mut Ui) { + let row = |ui: &mut Ui, label: &str, value: String| { + ui.allocate_ui_with_layout( + vec2(ui.available_width(), 22.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + let width = (ui.available_width() - 60.0).max(0.0); + ui.allocate_ui_with_layout( + vec2(width, 22.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| layout::line(ui, label), + ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + layout::line(ui, RichText::new(value).strong()); + }); + }, + ); + }; + egui::ScrollArea::vertical() + .id_salt("opening_summary") + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + if self.kind != SessionKind::Daily { + let k = if self.stopped { + self.line.saturating_sub(1) + } else { + self.lines.len() + }; + row( + ui, + tr("Lines reviewed"), + trf("{k} of {n}", &[("k", &k), ("n", &self.lines.len())]), + ); + } + row( + ui, + tr("Correct first time"), + self.tally.first_time.to_string(), + ); + row(ui, tr("Mistakes"), self.tally.mistakes.to_string()); + if self.tally.hints > 0 { + row(ui, tr("Hints"), self.tally.hints.to_string()); + } + if self.tally.new_moves > 0 { + row( + ui, + tr("New moves learned"), + self.tally.new_moves.to_string(), + ); + } + ui.add_space(4.0); + ui.separator(); + ui.add_space(4.0); + if let Some(summary) = &self.summary + && !summary.next_review.is_empty() + { + row(ui, tr("Next review"), summary.next_review.clone()); + } + if self.tally.missed.is_empty() { + return; + } + ui.add_space(8.0); + ui.label(RichText::new(tr("Moves to remember")).strong()); + ui.add_space(2.0); + for target in self.tally.missed.iter().take(REMEMBER_ROWS) { + let Some(game) = self.annotation_games.get(&target.repertoire_id) else { + continue; + }; + let Some(node) = layout::node_at(game, &target.path) else { + continue; + }; + let after = game + .parent(node) + .and_then(|parent| layout::move_text(game, parent)); + ui.allocate_ui_with_layout( + vec2(ui.available_width(), 22.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + ui.label( + RichText::new(layout::move_text(game, node).unwrap_or_default()) + .strong(), + ); + if let Some(after) = after { + layout::line( + ui, + RichText::new(trf("after {path}", &[("path", &after)])).weak(), + ); + } + }, + ); + } + if self.tally.missed.len() > REMEMBER_ROWS { + ui.label( + RichText::new(trf( + "and {k} more", + &[("k", &(self.tally.missed.len() - REMEMBER_ROWS))], + )) + .weak(), + ); + } + }); + } + + fn side(&mut self, ui: &mut Ui, state: &State, actions: &mut Vec) { + let opening = self + .shown_node() + .map(|(game, node)| layout::opening_text(game, node)) + .unwrap_or_default(); + let (left, right) = match state { + State::Summary => { + let more = self.more_new_count(); + ( + (more > 0).then(|| { + ( + if more == layout::NEW_PER_SESSION { + tr("10 more new (N)").to_owned() + } else { + trf("{n} more new (N)", &[("n", &more)]) + }, + true, + ) + }), + Some(( + if self.back_to_lines { + tr("To lines (Enter)") + } else { + tr("To repertoires (Enter)") + } + .to_owned(), + true, + )), + ) + } + State::SaveError(_) => ( + Some((tr("Finish").to_owned(), true)), + Some((tr("Try again").to_owned(), true)), + ), + State::Watch | State::NextLine => ( + Some((tr("Hint (H)").to_owned(), false)), + Some((tr("Skip (Enter)").to_owned(), false)), + ), + _ => (Some((tr("Hint (H)").to_owned(), self.can_hint())), None), + }; + let clicked = side_panel( + ui, + |ui| self.state_card(ui, state), + &opening, + |ui| { + if *state == State::Summary { + self.summary_body(ui); + } else { + self.comment(ui, state); + } + }, + left, + right, + *state == State::Summary || matches!(state, State::SaveError(_)), + ); + match clicked { + Some(Clicked::Left) => match state { + State::Summary => actions.push(SessionAction::MoreNew), + State::SaveError(_) => self.request_exit(actions), + _ => { + let id = unique_id(self.session.id()); + self.request_hint_with_id_at(id, Instant::now(), layout::now()); + } + }, + Some(Clicked::Right) => self.main_action(state, actions), + Some(Clicked::Flip) => self.orientation = self.orientation.other(), + Some(Clicked::Finish) => self.request_exit(actions), + None => {} + } + } + + pub fn show(&mut self, ui: &mut Ui, settings: &Settings, name: &str) -> Vec { + let animation = Duration::from_secs_f32(settings.animation.seconds()); + self.tick_at(Instant::now(), animation, layout::now()); + if self.commit_in_flight.is_some() { + ui.ctx().request_repaint_after(Duration::from_millis(16)); + } else if let Some(deadline) = self.playback_deadline() { + ui.ctx() + .request_repaint_after(deadline.saturating_duration_since(Instant::now())); + } else if self.needs_prepare || self.pending_automatic.is_some() { + ui.ctx().request_repaint(); + } + if let Some(state) = self.state() { + self.shown_state = state; + } + if self.shown_state == State::Summary { + self.compute_summary(); + } + let mut actions = Vec::new(); + self.keyboard(ui, &mut actions); + let state = self.shown_state.clone(); + let subtitle = self.kind.subtitle(self.session.stats_scope.side); + let back = if ui.available_width() < 600.0 { + "⬅" + } else if self.back_to_lines { + tr("⬅ Lines") + } else { + tr("⬅ Repertoires") + }; + let mut header = (false, false); + layout::screen( + ui, + self, + |_, ui| header = crate::widgets::section_header_sub(ui, back, name, &subtitle), + |this, ui| this.side(ui, &state, &mut actions), + |this, ui| this.board_ui(ui, settings), + ); + if header.0 { + self.request_exit(&mut actions); + } + if header.1 { + actions.push(SessionAction::OpenSettings); + } + if std::mem::take(&mut self.leave) { + actions.push(SessionAction::Back); + } + actions.extend(self.pending_sounds.drain(..).map(SessionAction::Sound)); + actions + } + + pub fn debug_settle(&mut self) { + // Only this explicit QA hook waits. Normal frames poll workers without blocking. + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if self.commit_in_flight.is_some() { + self.poll_commit(Instant::now()); + if Instant::now() >= deadline { + return; + } + if self.commit_in_flight.is_some() { + std::thread::sleep(Duration::from_millis(1)); + continue; + } + } + if self.has_unsaved() { + return; + } + if self.pending_automatic.is_some() { + self.board_shown = true; + } + let at = self + .playback_deadline() + .map_or_else(Instant::now, |at| at.max(Instant::now())); + self.tick_at(at, Duration::ZERO, layout::now()); + if self.commit_in_flight.is_none() + && self.pending_automatic.is_none() + && !self.needs_prepare + && self.playback_deadline().is_none() + { + return; + } + if Instant::now() >= deadline { + return; + } + } + } + + pub fn debug_hint(&mut self) { + if self.needs_prepare { + self.debug_settle(); + } + let id = unique_id(self.session.id()); + self.request_hint_with_id_at(id, Instant::now(), layout::now()); + } + + /// QA (`CP_REPERTOIRE_MOVES`): UCI moves as from the board; `hint`, `settle`, + /// `skip`, `stop` (Esc), `answer` (the expected move), `wrong` (a move not in the + /// repertoire). + pub fn debug_moves(&mut self, moves: &str) { + if self.needs_prepare { + self.debug_settle(); + } + for text in moves.split_whitespace() { + match text { + "hint" => self.debug_hint(), + "settle" | "wait" => self.debug_settle(), + "skip" => { + self.skip_context(Instant::now()); + } + "stop" => { + let mut actions = Vec::new(); + self.request_exit(&mut actions); + } + "answer" => { + if let Some(uci) = self.session.current_expected_uci().map(str::to_owned) { + let id = unique_id(self.session.id()); + self.play_uci_with_id_at(&uci, id, Instant::now(), layout::now()); + } + } + "wrong" => { + if let Some(uci) = self.debug_wrong_move() { + let id = unique_id(self.session.id()); + self.play_uci_with_id_at(&uci, id, Instant::now(), layout::now()); + } + } + _ => { + let id = unique_id(self.session.id()); + self.play_uci_with_id_at(text, id, Instant::now(), layout::now()); + } + } + } + } + + /// A legal move that is no answer of the repertoire here. + fn debug_wrong_move(&self) -> Option { + use chess_core::shakmaty::Position; + let position = fen4(&self.board_position); + let user = self.session.current_target()?.key.user_id.clone(); + self.board_position + .legal_moves() + .into_iter() + .find_map(|mv| { + let uci = mv.to_uci(CastlingMode::Standard).to_string(); + let key = LearningItemKey::new(user.clone(), position.clone(), &uci); + (!self.repertoire_answers.contains(&key)).then_some(uci) + }) + } +} + +/// «Preparing…» (S0): the session's screen before the session exists, so the board +/// and the panel do not move when it comes. +pub fn show_preparing( + ui: &mut Ui, + settings: &Settings, + board: &mut BoardState, + view: &PreparingView<'_>, +) -> Vec { + let mut actions = Vec::new(); + if !ui.ctx().egui_wants_keyboard_input() + && !crate::app::overlay_open(ui.ctx()) + && ui.input_mut(|input| { + input.consume_key(Modifiers::NONE, Key::Escape) + || input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W)) + }) + { + actions.push(SessionAction::Back); + } + let back = if ui.available_width() < 600.0 { + "⬅" + } else { + view.back + }; + let mut header = (false, false); + layout::screen( + ui, + board, + |_, ui| header = crate::widgets::section_header_sub(ui, back, view.name, view.subtitle), + |_, ui| { + let clicked = side_panel( + ui, + |ui| { + show_card( + ui, + &CardView { + title: tr("Preparing…").to_owned(), + instruction: String::new(), + title_color: None, + active: false, + alert: false, + count: "—".to_owned(), + label: if view.lines { tr("line") } else { tr("left") }, + }, + ) + }, + "", + |_| {}, + Some((tr("Hint (H)").to_owned(), false)), + None, + false, + ); + if clicked == Some(Clicked::Finish) { + actions.push(SessionAction::Back); + } + }, + |board, ui| { + layout::still_board( + ui, + board, + settings, + view.position, + view.orientation, + view.last_move, + &BoardAnnotations::default(), + ) + }, + ); + if header.0 { + actions.push(SessionAction::Back); + } + if header.1 { + actions.push(SessionAction::OpenSettings); + } + actions +} + +pub struct PreparingView<'a> { + pub name: &'a str, + pub subtitle: &'a str, + pub back: &'a str, + pub position: &'a Chess, + pub orientation: Color, + pub last_move: Option<(Square, Square)>, + /// A review: the counter counts lines. + pub lines: bool, +} + +struct CardView { + title: String, + instruction: String, + title_color: Option, + active: bool, + alert: bool, + count: String, + label: &'static str, +} + +/// Block A: two lines on the left, the counter on the right; always 64 pt. +fn show_card(ui: &mut Ui, view: &CardView) { + layout::fixed_block(ui, CARD_H, |ui| { + let frame = layout::card(ui, view.active, view.alert); + let inner = vec2(ui.available_width() - 20.0, CARD_H - 12.0); + frame.show(ui, |ui| { + ui.set_min_size(inner); + ui.set_max_size(inner); + ui.horizontal(|ui| { + let counter_w = 64.0; + ui.allocate_ui_with_layout( + vec2((ui.available_width() - counter_w).max(0.0), inner.y), + egui::Layout::top_down(egui::Align::Min), + |ui| { + ui.spacing_mut().item_spacing.y = 2.0; + let mut title = RichText::new(&view.title).strong().size(15.0); + if let Some(color) = view.title_color { + title = title.color(color); + } + layout::line(ui, title); + layout::line(ui, RichText::new(&view.instruction).size(13.0)); + }, + ); + ui.with_layout(egui::Layout::top_down(egui::Align::Max), |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + ui.label(RichText::new(&view.count).monospace().size(24.0)); + ui.label(RichText::new(view.label).weak().size(11.0)); + }); + }); + }); + }); +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Clicked { + Left, + Right, + Flip, + Finish, +} + +/// The session's panel (spec §4.1): A card · B opening · D comment or result · E +/// actions · F tool row; every block keeps its height in every state. +#[allow(clippy::too_many_arguments)] +fn side_panel( + ui: &mut Ui, + card: impl FnOnce(&mut Ui), + opening: &str, + body: impl FnOnce(&mut Ui), + left: Option<(String, bool)>, + right: Option<(String, bool)>, + right_primary: bool, +) -> Option { + let mut clicked = None; + let rect = ui.available_rect_before_wrap(); + let footer_h = TOOL_H + 12.0; + let footer = egui::Rect::from_min_max( + egui::pos2(rect.left(), (rect.bottom() - footer_h).max(rect.top())), + rect.max, + ); + let body_rect = egui::Rect::from_min_max(rect.min, egui::pos2(rect.right(), footer.top())); + ui.scope_builder(egui::UiBuilder::new().max_rect(body_rect), |ui| { + ui.set_clip_rect(body_rect.intersect(ui.clip_rect())); + ui.spacing_mut().item_spacing.y = GAP; + ui.add_space(4.0); + card(ui); + layout::fixed_block(ui, LINE_H, |ui| { + layout::line(ui, RichText::new(opening).weak()); + }); + let rest = (ui.available_height() - ROW_H - GAP).max(0.0); + layout::fixed_block(ui, rest, body); + layout::fixed_block(ui, ROW_H, |ui| { + ui.horizontal(|ui| { + if let Some((label, enabled)) = left { + let response = ui.add_enabled( + enabled, + egui::Button::new(label) + .truncate() + .min_size(vec2(LEFT_W.min(ui.available_width() / 2.0), ROW_H)), + ); + if response.clicked() { + clicked = Some(Clicked::Left); + } + } + if let Some((label, enabled)) = right { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let width = MAIN_W.min(ui.available_width()); + let response = if right_primary { + ui.add_enabled_ui(enabled, |ui| { + crate::widgets::primary_wide(ui, &label, width) + }) + .inner + } else { + ui.add_enabled( + enabled, + egui::Button::new(label) + .truncate() + .min_size(vec2(width, ROW_H)), + ) + }; + if response.clicked() { + clicked = Some(Clicked::Right); + } + }); + } + }); + }); + }); + ui.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| { + ui.separator(); + ui.horizontal(|ui| { + let icon = |s: &str| { + egui::Button::new(RichText::new(s).size(18.0)).min_size(vec2(0.0, TOOL_H)) + }; + if ui + .add(icon("🔃")) + .on_hover_text(tr("Flip board (F)")) + .clicked() + { + clicked = Some(Clicked::Flip); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .add( + egui::Button::new(RichText::new(tr("× Finish")).size(14.0)) + .min_size(vec2(0.0, TOOL_H)), + ) + .on_hover_text(tr("Finish the session (Esc)")) + .clicked() + { + clicked = Some(Clicked::Finish); + } + }); + }); + }); + clicked +} + +impl VisualMove { + fn from_context(step: &LearningContextStep) -> Result { + let before = parse_position(&step.from)?; + let mv = step + .uci + .parse::() + .ok() + .and_then(|uci| uci.to_move(&before).ok()) + .ok_or_else(|| format!("automatic context move {} is not legal", step.uci))?; + Ok(Self::new(step.uci.clone(), before, mv)) + } + + fn new(uci: String, before: Chess, mv: Move) -> Self { + use chess_core::shakmaty::Position; + let from = mv.from().unwrap_or_else(|| mv.to()); + let to = crate::board::ui_target(&mv); + let mut after = before.clone(); + after.play_unchecked(mv); + Self { + uci, + before, + after, + from, + to, + } + } +} + +fn parse_position(position: &trainer::repertoire::LearningPosition) -> Result { + position + .fen + .parse::() + .map_err(|error| error.to_string())? + .into_position(CastlingMode::Standard) + .map_err(|error| error.to_string()) +} + +fn unique_id(prefix: &str) -> String { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |duration| duration.as_nanos()); + let sequence = NEXT_ID.fetch_add(1, Ordering::Relaxed); + format!("{prefix}-{nanos:x}-{}-{sequence:x}", std::process::id()) +} + +#[cfg(test)] +#[path = "opening_session_tests.rs"] +mod tests; diff --git a/apps/desktop/src/opening_session_tests.rs b/apps/desktop/src/opening_session_tests.rs new file mode 100644 index 0000000..6a2b614 --- /dev/null +++ b/apps/desktop/src/opening_session_tests.rs @@ -0,0 +1,2129 @@ +use std::path::PathBuf; + +use super::*; +use chess_core::shakmaty::Position; +use trainer::repertoire::{LearningStoreData, active_learning_memberships}; + +#[test] +fn status_growth_does_not_move_training_controls() { + let mut positions = Vec::new(); + for message in [ + "Your turn", + "Hint\nReplay the shown move\nNo independent success", + ] { + let ctx = egui::Context::default(); + let output = ctx.run_ui(egui::RawInput::default(), |ui| { + egui::CentralPanel::default().show(ui, |ui| { + layout::fixed_block(ui, 144.0, |ui| { + ui.label(message); + }); + positions.push(ui.button("Hint").rect.top()); + }); + }); + output.drop_without_applying_deltas(); + } + assert_eq!(positions[0], positions[1]); + assert!(positions[0] >= 144.0); +} + +const NOW: i64 = 1_800_000_000; +static NEXT_TEST: AtomicU64 = AtomicU64::new(1); + +struct TestDir(PathBuf); + +impl TestDir { + fn new(name: &str) -> Self { + let path = std::env::temp_dir().join(format!( + "cp-opening-session-{}-{}-{name}", + std::process::id(), + NEXT_TEST.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } + + fn store(&self) -> LearningStore { + LearningStore::new(self.0.join("learning.json")) + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +struct Fixture { + _dir: TestDir, + library: Library, + scope: StatsScope, + store: LearningStore, + ui: OpeningSessionUi, +} + +impl Fixture { + /// A daily session asking exactly `due`: every other move of the side is known and + /// not due. + fn new(pgn: &str, side: LearningSide, due: &[&str], name: &str) -> Self { + Self::with(pgn, side, due, &[], name, SessionKind::Daily) + } + + /// `due` are due, `new` never shown, every other move known and not due. + fn with( + pgn: &str, + side: LearningSide, + due: &[&str], + new: &[&str], + name: &str, + kind: SessionKind, + ) -> Self { + let dir = TestDir::new(name); + let mut library = Library::default(); + let id = library + .create("Test", &chess_core::parse_str(pgn).game) + .unwrap(); + let scope = StatsScope::for_repertoire(id, side, NOW); + let mut learning = LearningData::default(); + for membership in active_learning_memberships(&library, &scope).unwrap() { + let uci = membership.key.expected_uci.as_str(); + if new.contains(&uci) { + continue; + } + let item = learning.ensure_item(membership.key.clone()); + item.introduced = true; + if due.contains(&uci) { + item.next_review_at = Some(NOW); + } else { + item.correct_streak = 1; + item.correct_count = 1; + item.last_correct_at = Some(NOW - 24 * 60 * 60); + item.next_review_at = Some(NOW + 10 * 24 * 60 * 60); + } + } + let bytes = serde_json::to_vec_pretty(&LearningStoreData { + learning, + ..LearningStoreData::default() + }) + .unwrap(); + std::fs::write(dir.0.join("learning.json"), bytes).unwrap(); + let store = dir.store(); + let mut ui = + OpeningSessionUi::new(library.clone(), store.clone(), scope.clone(), kind).unwrap(); + ui.board_shown = true; + ui.synchronous_commits = true; + ui.feedback = Duration::ZERO; + Self { + _dir: dir, + library, + scope, + store, + ui, + } + } + + fn attempts(&self) -> Vec { + self.store.load().unwrap().learning.attempts + } +} + +fn key_for(library: &Library, scope: &StatsScope, expected: &str) -> LearningItemKey { + active_learning_memberships(library, scope) + .unwrap() + .into_iter() + .find(|membership| membership.key.expected_uci == expected) + .unwrap() + .key +} + +fn normal() -> Duration { + Duration::from_millis(250) +} + +fn answer_current(f: &mut Fixture, at: Instant, happened_at: i64, id: &str) { + let expected = f.ui.session.current_expected_uci().unwrap().to_owned(); + assert!(f.ui.play_uci_with_id_at(&expected, id.to_owned(), at, happened_at,)); + tick_with_prime(&mut f.ui, at, Duration::ZERO, happened_at); +} + +fn board_frame(f: &mut Fixture, ctx: &egui::Context, time: f64, settings: &Settings) { + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(800.0, 800.0), + )), + time: Some(time), + ..Default::default() + }, + |ui| f.ui.board_ui(ui, settings), + ) + .drop_without_applying_deltas(); +} + +fn tick_with_prime(ui: &mut OpeningSessionUi, at: Instant, animation: Duration, happened_at: i64) { + ui.tick_at(at, animation, happened_at); + if ui.pending_automatic.is_none() { + return; + } + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let settings = Settings::default(); + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(800.0, 800.0), + )), + time: Some(0.0), + ..Default::default() + }, + |root| ui.board_ui(root, &settings), + ) + .drop_without_applying_deltas(); + assert!(ui.board_shown); + assert!(ui.board.animation_at(0.0).is_none()); + ui.tick_at(at, animation, happened_at); +} + +fn automatic_duration(f: &Fixture) -> Duration { + match &f.ui.playback { + Some(Playback::Automatic { duration, .. }) => *duration, + _ => panic!("automatic playback expected"), + } +} + +fn assert_current_slide( + f: &Fixture, + time: f64, + expected_duration: Duration, + from: Square, + to: Square, +) { + let (duration, slides, remaining) = + f.ui.board + .animation_at(time) + .expect("the current BoardView transition"); + assert_eq!(remaining, 1.0, "the first visual frame must be at from"); + assert!( + (duration - f64::from(expected_duration.as_secs_f32())).abs() < 1e-6, + "animation {duration} does not match scheduler {}", + expected_duration.as_secs_f32() + ); + assert!( + slides + .iter() + .any(|(_, slide_from, slide_to)| *slide_from == from && *slide_to == to), + "missing {from}{to} in {slides:?}" + ); +} + +fn assert_adaptive_board_slides(f: &mut Fixture, first_ms: u128, last_ms: u128) { + let ctx = egui::Context::default(); + let settings = Settings::default(); + let start = Instant::now(); + f.ui.board_shown = false; + f.ui.tick_at(start, normal(), NOW); + board_frame(f, &ctx, 0.0, &settings); + assert!(f.ui.board.animation_at(0.0).is_none()); + + f.ui.tick_at(start, normal(), NOW); + let first = automatic_duration(f); + assert_eq!(first.as_millis(), first_ms); + assert_eq!(f.ui.playback_deadline(), Some(start + first)); + assert_eq!(f.ui.session.context_index, 0); + board_frame(f, &ctx, 0.01, &settings); + assert_current_slide(f, 0.01, first, Square::E2, Square::E4); + assert_eq!(f.ui.state(), Some(State::Watch)); + + tick_with_prime(&mut f.ui, start + first, normal(), NOW); + let last = automatic_duration(f); + assert_eq!(last.as_millis(), last_ms); + assert_eq!(f.ui.session.context_index, 1); + board_frame(f, &ctx, 0.02, &settings); + assert_current_slide(f, 0.02, last, Square::E7, Square::E5); + assert_eq!(f.ui.state(), Some(State::Watch)); + + tick_with_prime(&mut f.ui, start + first + last, normal(), NOW); + assert_eq!(f.ui.session.context_index, 2); + assert!(f.ui.can_input()); + board_frame(f, &ctx, 10.0, &settings); + assert!( + f.ui.board.animation_at(10.0).is_none(), + "the final position must not start a settings-duration slide" + ); + assert_eq!(f.attempts().len(), 2); +} + +#[test] +fn adaptive_board_animation_matches_actual_slides_and_starts_at_from() { + let mut fast = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + &["g1f3"], + "adaptive-fast", + ); + let e4 = key_for(&fast.library, &fast.scope, "e2e4"); + fast.ui.learning.ensure_item(e4).correct_streak = 3; + fast.ui.session.context_policy.use_fixed_piece_speed = false; + fast.ui.session.context_policy.move_speed_adjustment = 1.5; + assert_adaptive_board_slides(&mut fast, 83, 166); + + let mut slow = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + &["g1f3"], + "adaptive-slow", + ); + slow.ui.session.context_policy.use_fixed_piece_speed = false; + slow.ui.session.context_policy.move_speed_adjustment = 0.0; + assert_adaptive_board_slides(&mut slow, 1000, 1000); +} + +#[test] +fn next_target_continues_the_shown_line_without_reverse_slide() { + fn settle_to_input(f: &mut Fixture, at: Instant) { + let mut at = at; + for _ in 0..32 { + if f.ui.can_input() { + return; + } + let next = f.ui.playback_deadline().unwrap_or(at); + tick_with_prime(&mut f.ui, next, normal(), NOW); + at = next; + } + panic!("training did not reach independent input"); + } + + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", + LearningSide::Black, + &["e7e5", "b8c6", "a7a6"], + "next-target-prime", + ); + f.ui.session.context_policy.use_fixed_piece_speed = false; + f.ui.session.context_policy.move_speed_adjustment = 0.0; + let start = Instant::now(); + settle_to_input(&mut f, start); + assert_eq!(f.ui.session.current_expected_uci(), Some("e7e5")); + answer_current( + &mut f, + start + Duration::from_secs(1), + NOW, + "first-target-e5", + ); + + settle_to_input(&mut f, start + Duration::from_secs(1) + normal()); + assert_eq!(f.ui.session.current_expected_uci(), Some("b8c6")); + answer_current( + &mut f, + start + Duration::from_secs(3), + NOW + 1, + "second-target-nc6", + ); + + let prime_at = start + Duration::from_secs(3) + normal(); + // Every old move keeps its event, but a long visible prefix requires + // only one store transaction before the next opponent move. + let before_reuse = f.store.load().unwrap(); + for _ in 0..8 { + f.ui.tick_at(prime_at, normal(), NOW); + if f.ui.pending_automatic.is_some() { + break; + } + } + assert!(f.ui.pending_automatic.is_some()); + let after_reuse = f.store.load().unwrap(); + assert_eq!(after_reuse.revision, before_reuse.revision + 1); + let added = &after_reuse.learning.attempts[before_reuse.learning.attempts.len()..]; + assert_eq!(added.len(), 4); + assert!( + added + .iter() + .all(|event| event.event_type == TrainingEventType::AutoContext) + ); + assert_eq!(f.ui.session.context_index, 4); + assert!(!f.ui.board_shown); + let ctx = egui::Context::default(); + let settings = Settings::default(); + board_frame(&mut f, &ctx, 10.0, &settings); + assert!( + f.ui.board.animation_at(10.0).is_none(), + "prime must not animate the previous target backwards" + ); + + f.ui.tick_at(prime_at, normal(), NOW); + let duration = automatic_duration(&f); + assert_eq!(duration, Duration::from_millis(1000)); + board_frame(&mut f, &ctx, 10.01, &settings); + assert_current_slide(&f, 10.01, duration, Square::F1, Square::B5); + let (_, slides, _) = f.ui.board.animation_at(10.01).unwrap(); + assert!( + slides + .iter() + .all(|(_, from, to)| !(*from == Square::F3 && *to == Square::G1)), + "next target started with a reverse slide: {slides:?}" + ); + assert!(matches!( + &f.ui.playback, + Some(Playback::Automatic { remaining, .. }) if remaining.is_empty() + )); +} + +fn emitted_sounds(f: &mut Fixture, ctx: &egui::Context, settings: &Settings) -> Vec { + let mut sounds = Vec::new(); + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + vec2(960.0, 600.0), + )), + ..Default::default() + }, + |ui| { + sounds.extend( + f.ui.show(ui, settings, "Test") + .into_iter() + .filter_map(|action| { + if let SessionAction::Sound(sound) = action { + Some(sound) + } else { + None + } + }), + ); + }, + ) + .drop_without_applying_deltas(); + sounds +} + +#[test] +fn accepted_move_emits_once_and_next_task_only_animates_the_opponent_reply() { + for side in [LearningSide::White, LearningSide::Black] { + for animation in [ + crate::settings::Animation::Normal, + crate::settings::Animation::Off, + ] { + for replay in [false, true] { + let (due, reply, wrong) = match side { + LearningSide::White => (["e2e4", "g1f3"], "e7e5", "d2d4"), + LearningSide::Black => (["e7e5", "b8c6"], "g1f3", "d7d5"), + }; + let mut f = + Fixture::new("1. e4 e5 2. Nf3 Nc6 *", side, &due, "continuous-feedback"); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + let ctx = egui::Context::default(); + let settings = Settings { + animation, + ..Settings::default() + }; + let at = Instant::now() + Duration::from_secs(60); + let duration = Duration::from_secs_f32(animation.seconds()); + f.ui.animation = duration; + f.ui.pending_sounds.clear(); + f.ui.visual_log.clear(); + if replay { + assert!(f.ui.play_uci_with_id_at(wrong, "wrong".into(), at - WRONG_SHOWN, NOW)); + f.ui.tick_at(at, duration, NOW); + assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Wrong]); + } + assert!(f.ui.play_uci_with_id_at(due[0], "accepted".into(), at, NOW)); + let accepted_position = fen4(&f.ui.board_position); + assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Move]); + for _ in 0..8 { + f.ui.tick_at(at + duration, duration, NOW); + assert_eq!( + fen4(&f.ui.board_position), + accepted_position, + "accepted move must not rewind" + ); + if f.ui.pending_automatic.is_some() { + break; + } + } + assert!(f.ui.pending_automatic.is_some()); + // The prime frame is silent; a separate later frame emits the + // opponent move, so queue coalescing cannot conceal a duplicate. + assert!(emitted_sounds(&mut f, &ctx, &settings).is_empty()); + assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Move]); + assert_eq!(f.ui.visual_log, [reply]); + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some(due[1])); + let attempts = f.attempts(); + assert_eq!( + attempts + .iter() + .filter(|event| event.event_type.is_independent()) + .count(), + 1 + ); + assert!(attempts.iter().any(|event| event.expected_uci == due[0] + && event.event_type == TrainingEventType::AutoContext)); + assert_eq!( + attempts + .iter() + .filter(|event| event.event_type == TrainingEventType::ReplayAfterError) + .count(), + usize::from(replay) + ); + } + } + } +} + +#[test] +fn shown_context_requires_the_same_history_and_never_bypasses_a_question() { + let mut f = Fixture::new( + "1. Nf3 Nf6 2. g3 g6 3. Bg2 *", + LearningSide::White, + &["f1g2"], + "context-identity", + ); + let presentation = + f.ui.session + .presentation_with_learning(&f.library, &f.ui.learning) + .unwrap(); + f.ui.board_position = parse_position(&presentation.automatic_context[3].to).unwrap(); + let id = f.ui.session.current_target().unwrap().repertoire_id.clone(); + // Even with an identical final position, a different move order must not + // reuse context. A matching FEN alone cannot establish repetition history. + f.ui.shown_prefix = Some(ShownPrefix { + repertoire_id: id.clone(), + path: vec!["g2g3".into(), "g7g6".into(), "g1f3".into(), "g8f6".into()], + }); + assert!(!f.ui.reuse_shown_context(&presentation, Instant::now())); + assert!(f.attempts().is_empty()); + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + &["g1f3"], + "context-question", + ); + let presentation = + f.ui.session + .presentation_with_learning(&f.library, &f.ui.learning) + .unwrap(); + f.ui.board_position = parse_position(&presentation.automatic_context[1].to).unwrap(); + f.ui.shown_prefix = Some(ShownPrefix { + repertoire_id: f.ui.session.current_target().unwrap().repertoire_id.clone(), + path: vec!["e2e4".into(), "e7e5".into()], + }); + f.ui.session.context_policy.consider_leadup_moves = true; + let question = + f.ui.session + .presentation_with_learning(&f.library, &f.ui.learning) + .unwrap(); + assert_eq!( + question.phase, + LearningSessionPhase::AwaitingContextIndependent + ); + assert!(!f.ui.reuse_shown_context(&question, Instant::now())); + f.ui.prepare_presentation(Instant::now()); + assert!(f.ui.can_input()); + assert_eq!(f.ui.session.current_expected_uci(), Some("e2e4")); + assert!(f.attempts().is_empty()); +} + +fn assert_annotation_badge(ui: &OpeningSessionUi, text: &str, square: Square) { + let annotation = ui.displayed_annotations(); + let badge = annotation.badge.expect("PGN move badge"); + assert_eq!(badge.text, text); + assert_eq!(badge.square, square); +} + +#[test] +fn pgn_annotations_follow_visible_user_and_automatic_moves_not_the_next_task() { + let mut f = Fixture::with( + "1. e4!! {[%cal Re2e4,Ge7e5] [%csl Ye4,Re5]} e5?! {[%cal Bg1f3]} 2. Nf3! {[%csl Gf3]} Nc6 *", + LearningSide::White, + &["e2e4", "g1f3"], + &[], + "visible-pgn-annotations", + SessionKind::ReviewAll, + ); + let original = + f.ui.library + .repertoire(f.scope.repertoire_ids.iter().next().unwrap()) + .unwrap() + .pgn + .clone(); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.displayed_annotations().arrows.is_empty()); + // A hint reveals the expected move, not that future node's annotations. + assert!(f.ui.request_hint_with_id_at("annotation-hint".into(), start, NOW)); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.displayed_annotations().arrows.is_empty()); + assert!(f.ui.play_uci_with_id_at("e2e4", "annotation-e4".into(), start, NOW)); + assert_eq!( + f.ui.session.current_target().unwrap().key.expected_uci, + "g1f3" + ); + assert_annotation_badge(&f.ui, "!!", Square::E4); + let annotation = f.ui.displayed_annotations(); + assert_eq!(annotation.arrows.len(), 2); + assert_eq!(annotation.circles.len(), 2); + assert!( + annotation + .arrows + .iter() + .any(|arrow| arrow.from == Square::E2 + && arrow.to == Square::E4 + && arrow.color == crate::game_view::shape_color(chess_core::ShapeColor::Red)) + ); + // Verify the helper's data actually reaches the rendered BoardView. + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let output = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &Settings::default()); + assert!(output.shapes.iter().any( + |shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == "!!") + )); + output.drop_without_applying_deltas(); + f.ui.tick_at(start + normal(), normal(), NOW); + assert_annotation_badge(&f.ui, "!!", Square::E4); + assert!(f.ui.visual_log.is_empty(), "reused e4 must not play again"); + for _ in 0..8 { + tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); + if matches!(f.ui.playback, Some(Playback::Automatic { .. })) { + break; + } + } + assert_eq!(f.ui.visual_log, ["e7e5"]); + assert_annotation_badge(&f.ui, "?!", Square::E5); + assert_eq!(f.ui.displayed_annotations().arrows[0].from, Square::G1); + f.ui.tick_at(f.ui.playback_deadline().unwrap(), normal(), NOW); + assert!(f.ui.can_input()); + assert_annotation_badge(&f.ui, "?!", Square::E5); + assert!( + f.ui.displayed_annotations().circles.is_empty(), + "future Nf3 circle leaked before the answer" + ); + assert!(f.ui.play_uci_with_id_at( + "g1f3", + "annotation-nf3".into(), + start + Duration::from_secs(1), + NOW + )); + assert_annotation_badge(&f.ui, "!", Square::F3); + assert_eq!(f.ui.displayed_annotations().circles[0].0, Square::F3); + f.ui.debug_settle(); + assert_annotation_badge(&f.ui, "!", Square::F3); + assert_eq!( + f.ui.library + .repertoire(f.scope.repertoire_ids.iter().next().unwrap()) + .unwrap() + .pgn, + original + ); +} + +#[test] +fn pgn_annotations_clear_for_wrong_moves_and_survive_failed_async_save_and_retry() { + let mut f = Fixture::new( + "1. e4!! {[%csl Ge4]} *", + LearningSide::White, + &["e2e4"], + "annotations-retry", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + assert!(f.ui.play_uci_with_id_at("d2d4", "annotations-wrong".into(), start, NOW)); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.displayed_annotations().circles.is_empty()); + f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); + assert!(f.ui.can_input()); + assert!(f.ui.displayed_annotations().badge.is_none()); + // Another wrong move during replay must not inherit the revealed e4 badge. + assert!(f.ui.play_uci_with_id_at( + "d2d4", + "annotations-wrong-replay".into(), + start + WRONG_SHOWN, + NOW + )); + assert!(f.ui.displayed_annotations().badge.is_none()); + f.ui.tick_at(start + WRONG_SHOWN * 2, normal(), NOW); + let store = f.ui.store.clone(); + f.ui.synchronous_commits = false; + f.ui.store = LearningStore::with_legacy(store.path(), store.path()); + assert!(f.ui.play_uci_with_id_at( + "e2e4", + "annotations-replay".into(), + start + WRONG_SHOWN * 2, + NOW + )); + assert!(f.ui.has_unsaved()); + assert_annotation_badge(&f.ui, "!!", Square::E4); + wait_for_commit(&mut f.ui); + assert!(f.ui.save_error.is_some()); + assert_annotation_badge(&f.ui, "!!", Square::E4); + f.ui.store = store; + f.ui.retry_pending(Instant::now()); + wait_for_commit(&mut f.ui); + assert_annotation_badge(&f.ui, "!!", Square::E4); + assert_eq!( + f.attempts() + .iter() + .filter(|attempt| attempt.event_type.is_independent()) + .count(), + 1 + ); + assert_eq!( + f.attempts().last().unwrap().event_type, + TrainingEventType::ReplayAfterError + ); +} + +#[test] +fn alternative_answer_credits_actual_move_and_completed_answer_is_silent_and_neutral() { + let mut f = Fixture::new( + "1. e4! (1. d4!! {[%csl Gd4]}) *", + LearningSide::White, + &["e2e4", "d2d4"], + "alternative-answers", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + let original = f.ui.session.current_expected_uci().unwrap().to_owned(); + let (played, badge, square) = if original == "e2e4" { + ("d2d4", "!!", Square::D4) + } else { + ("e2e4", "!", Square::E4) + }; + let initial_position = f.ui.board_position.clone(); + assert_eq!( + f.ui.session + .pending_answers_for_position(&fen4(&initial_position)) + .len(), + 2 + ); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + assert_eq!(f.ui.state(), Some(State::Yours)); + assert!(f.ui.play_uci_with_id_at(played, "actual-alternative".into(), start, NOW)); + assert_annotation_badge(&f.ui, badge, square); + assert_eq!(f.attempts().len(), 1); + assert_eq!(f.attempts()[0].expected_uci, played); + assert_eq!( + f.attempts()[0].event_type, + TrainingEventType::CorrectIndependent + ); + assert_eq!(f.ui.session.current_expected_uci(), Some(original.as_str())); + assert_eq!(std::mem::take(&mut f.ui.pending_sounds), [Sound::Move]); + f.ui.tick_at(start + normal(), normal(), NOW); + assert_eq!(f.ui.board_position, initial_position); + // S3a: the other answer of this position is still asked. + let played_san = if played == "d2d4" { "d4" } else { "e4" }; + assert_eq!(f.ui.state(), Some(State::YoursMore(played_san.to_owned()))); + assert!(f.ui.play_uci_with_id_at(played, "repeat-alternative".into(), start + normal(), NOW)); + assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); + assert_eq!(f.ui.state(), Some(State::Alternative)); + assert_annotation_badge(&f.ui, badge, square); + assert!(f.ui.save_error.is_none() && f.ui.error.is_none()); + assert!(emitted_sounds(&mut f, &ctx, &Settings::default()).is_empty()); + f.ui.tick_at(start + normal() + WRONG_SHOWN, normal(), NOW); + assert_eq!(f.ui.board_position, initial_position); + assert!(f.ui.can_input()); + assert!(f.ui.displayed_annotations().badge.is_none()); + // «Now the other one: play …» shows the answer: recorded as shown, not as an + // error and not as known. + let attempts = f.attempts(); + assert_eq!(attempts.len(), 2); + assert_eq!(attempts[1].event_type, TrainingEventType::Previewed); + assert_eq!(attempts[1].expected_uci, original); + assert_eq!(f.ui.state(), Some(State::Alternative)); + assert_eq!(f.ui.revealed_uci().as_deref(), Some(original.as_str())); + assert_eq!(f.ui.tally.mistakes, 0); + assert_eq!(f.ui.session.remaining(), 1); + assert!(emitted_sounds(&mut f, &ctx, &Settings::default()).is_empty()); +} + +#[test] +fn move_input_uses_the_startup_answer_snapshot_in_independent_and_replay_phases() { + let mut f = Fixture::new( + "1. e4 (1. d4) *", + LearningSide::White, + &["e2e4"], + "cached-repertoire-answers", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + let key = key_for(&f.library, &f.scope, "d2d4"); + assert!(f.ui.repertoire_answers.contains(&key)); + // The production library is immutable for the UI's lifetime. Change it + // only here to detect any accidental rebuilding in the input hot path. + let id = f.scope.repertoire_ids.iter().next().unwrap(); + f.ui.library + .repertoire_mut(id) + .unwrap() + .set_prefix_disabled(&["d2d4".to_owned()], true) + .unwrap(); + assert!( + !active_learning_keys(&f.ui.library, &f.scope) + .unwrap() + .contains(&key) + ); + assert!(f.ui.play_uci_with_id_at("d2d4", "cached-independent".into(), start, NOW)); + assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); + assert!(f.attempts().is_empty()); + f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); + // The answer was revealed after the other move: no second preview. + assert_eq!(f.ui.session.phase, LearningSessionPhase::PreviewedReplay); + assert!( + !f.ui + .request_hint_with_id_at("cached-preview".into(), start + WRONG_SHOWN, NOW) + ); + assert!(f.ui.play_uci_with_id_at("d2d4", "cached-replay".into(), start + WRONG_SHOWN, NOW)); + assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); + assert_eq!(f.attempts().len(), 1); + assert_eq!(f.attempts()[0].event_type, TrainingEventType::Previewed); + assert!(f.ui.pending_sounds.is_empty()); +} + +#[test] +fn known_unscheduled_answer_during_hint_is_neutral_but_outside_move_still_wrong() { + let mut f = Fixture::new( + "1. e4! (1. d4!! {[%csl Gd4]}) *", + LearningSide::White, + &["e2e4"], + "hint-alternative", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + assert!(f.ui.request_hint_with_id_at("preview-alternative".into(), start, NOW)); + let attempts = f.attempts().len(); + let snapshot = f.ui.session.clone(); + assert!(f.ui.play_uci_with_id_at("d2d4", "unscheduled-alternative".into(), start, NOW)); + assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); + assert_annotation_badge(&f.ui, "!!", Square::D4); + assert_eq!(f.ui.session, snapshot); + assert!(f.ui.pending_sounds.is_empty()); + f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); + assert_eq!(f.attempts().len(), attempts); + assert!(f.ui.can_input()); + assert_eq!(f.ui.state(), Some(State::Alternative)); + assert!(f.ui.play_uci_with_id_at( + "g1f3", + "outside-repertoire".into(), + start + WRONG_SHOWN, + NOW + )); + assert!(matches!(f.ui.playback, Some(Playback::Wrong { .. }))); + assert_eq!(f.ui.pending_sounds, [Sound::Wrong]); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert_eq!(f.attempts().len(), attempts); +} + +#[test] +fn authored_wrong_branch_has_its_own_annotations_only_after_it_is_played() { + let mut f = Fixture::new( + "1. e4! (1. d4?? {[%csl Rd4]}) e5 *", + LearningSide::White, + &["e2e4"], + "wrong-branch-annotations", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.play_uci_with_id_at("d2d4", "authored-wrong-branch".into(), start, NOW)); + assert_annotation_badge(&f.ui, "??", Square::D4); + assert_eq!( + f.ui.displayed_annotations().circles[0], + ( + Square::D4, + crate::game_view::shape_color(chess_core::ShapeColor::Red) + ) + ); + f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.displayed_annotations().circles.is_empty()); +} + +#[test] +fn pgn_annotation_cursor_distinguishes_transposed_paths_and_repertoire_sources() { + let mut f = Fixture::new( + "1. Nf3 (1. g3 g6 2. Nf3 Nf6? {[%csl Rf6]} 3. Bg2) Nf6 2. g3 g6! {[%csl Gg6]} 3. Bg2 *", + LearningSide::White, + &["f1g2"], + "annotations-transposition", + ); + let id = f.ui.session.current_target().unwrap().repertoire_id.clone(); + let mut position_keys = Vec::new(); + for (path, badge, square) in [ + (["g1f3", "g8f6", "g2g3", "g7g6"], "!", Square::G6), + (["g2g3", "g7g6", "g1f3", "g8f6"], "?", Square::F6), + ] { + f.ui.set_displayed_path(Some(&ShownPrefix { + repertoire_id: id.clone(), + path: path.map(str::to_owned).to_vec(), + })); + let (_, node) = f.ui.displayed_node.as_ref().expect("exact PGN branch"); + f.ui.board_position = f.ui.annotation_games[&id].position(*node).unwrap().clone(); + position_keys.push(fen4(&f.ui.board_position)); + assert_annotation_badge(&f.ui, badge, square); + assert_eq!(f.ui.displayed_annotations().circles[0].0, square); + } + assert_eq!( + position_keys[0], position_keys[1], + "fixture must really transpose" + ); + let other_id = + f.ui.library + .create("Other annotations", &Game::new()) + .unwrap(); + f.ui.annotation_games.insert( + other_id.clone(), + chess_core::parse_str("1. Nf3 Nf6 2. g3 g6?? {[%csl Yg6]} *").game, + ); + f.ui.set_displayed_path(Some(&ShownPrefix { + repertoire_id: other_id.clone(), + path: ["g1f3", "g8f6", "g2g3", "g7g6"].map(str::to_owned).to_vec(), + })); + let (_, node) = f.ui.displayed_node.as_ref().unwrap(); + f.ui.board_position = f.ui.annotation_games[&other_id] + .position(*node) + .unwrap() + .clone(); + assert_annotation_badge(&f.ui, "??", Square::G6); +} + +#[test] +fn debug_moves_settles_prime_between_targets() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", + LearningSide::Black, + &["e7e5", "b8c6", "a7a6"], + "debug-prime-between-targets", + ); + f.ui.debug_moves("e7e5 settle b8c6 settle"); + assert!(f.ui.can_input()); + assert_eq!(f.ui.session.current_expected_uci(), Some("a7a6")); + f.ui.debug_moves("a7a6 settle"); + assert!(f.ui.is_finished()); + assert_eq!( + f.attempts() + .iter() + .filter(|attempt| attempt.event_type.is_independent()) + .count(), + 3 + ); +} + +#[test] +fn automatic_context_has_three_separate_normal_timed_steps() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::Black, + &["b8c6"], + "context-normal", + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert_eq!(f.ui.visual_log, ["e2e4"]); + assert_eq!(f.ui.session.context_index, 0); + assert!(!f.ui.can_input()); + + tick_with_prime(&mut f.ui, start + Duration::from_millis(249), normal(), NOW); + assert_eq!(f.ui.session.context_index, 0); + assert!(f.attempts().is_empty()); + + tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); + assert_eq!(f.ui.session.context_index, 1); + assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]); + tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); + assert_eq!(f.ui.session.context_index, 1); + + tick_with_prime(&mut f.ui, start + normal() * 2, normal(), NOW); + assert_eq!(f.ui.session.context_index, 2); + assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]); + tick_with_prime(&mut f.ui, start + normal() * 3, normal(), NOW); + assert_eq!(f.ui.session.context_index, 3); + assert_eq!( + f.ui.session.phase, + LearningSessionPhase::AwaitingIndependent + ); + assert!(f.ui.can_input()); + assert_eq!(f.attempts().len(), 3); + assert_eq!( + trainer::repertoire::fen4(&f.ui.board_position), + key_for(&f.library, &f.scope, "b8c6").position_fen4 + ); +} + +#[test] +fn animation_off_commits_every_context_step_without_skipping_store_calls() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::Black, + &["b8c6"], + "context-off", + ); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]); + assert_eq!(f.ui.session.context_index, 3); + assert!(f.ui.can_input()); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 3); + assert_eq!( + attempts + .iter() + .map(|attempt| attempt.actual_uci.as_deref()) + .collect::>(), + [Some("e2e4"), Some("e7e5"), Some("g1f3")] + ); + assert!(attempts.iter().all(|attempt| { + attempt.event_type == TrainingEventType::AutoContext && attempt.response_time_ms.is_none() + })); +} + +#[test] +fn legal_input_is_ignored_during_autoplay() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::Black, + &["b8c6"], + "autoplay-input", + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert!(!f.ui.play_uci_with_id_at( + "e7e5", + "blocked-input".to_owned(), + start + Duration::from_millis(20), + NOW, + )); + assert_eq!(f.ui.session.context_index, 0); + assert!(f.attempts().is_empty()); + assert_eq!(f.ui.visual_log, ["e2e4"]); +} + +#[test] +fn wrong_answer_replays_without_a_second_independent_error() { + let mut f = Fixture::with( + "1. e4 *", + LearningSide::White, + &["e2e4"], + &[], + "wrong-replay", + SessionKind::ReviewAll, + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert!(f.ui.play_uci_with_id_at( + "d2d4", + "wrong-d4".to_owned(), + start + Duration::from_millis(1500), + NOW, + )); + assert!(matches!(f.ui.playback, Some(Playback::Wrong { .. }))); + tick_with_prime( + &mut f.ui, + start + Duration::from_millis(1500) + WRONG_SHOWN, + normal(), + NOW, + ); + assert_eq!( + f.ui.session.phase, + LearningSessionPhase::AwaitingReplayAfterError + ); + assert_eq!( + f.ui.presentation.as_ref().unwrap().revealed_move.as_deref(), + Some("e2e4") + ); + + assert!(f.ui.play_uci_with_id_at( + "d2d4", + "wrong-replay-d4".to_owned(), + start + Duration::from_secs(3), + NOW, + )); + assert_eq!(f.attempts().len(), 1); + tick_with_prime( + &mut f.ui, + start + Duration::from_secs(3) + WRONG_SHOWN, + normal(), + NOW, + ); + assert!(f.ui.play_uci_with_id_at( + "e2e4", + "replay-e4".to_owned(), + start + Duration::from_secs(4), + NOW, + )); + tick_with_prime( + &mut f.ui, + start + Duration::from_secs(4) + normal(), + normal(), + NOW, + ); + assert!(f.ui.is_finished()); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 2); + assert_eq!( + attempts[0].event_type, + TrainingEventType::IncorrectIndependent + ); + assert_eq!(attempts[0].response_time_ms, Some(1500)); + assert_eq!(attempts[1].event_type, TrainingEventType::ReplayAfterError); + assert_eq!(attempts[1].response_time_ms, None); + let item = f + .store + .load() + .unwrap() + .learning + .item(&key_for(&f.library, &f.scope, "e2e4")) + .unwrap() + .clone(); + assert_eq!(item.wrong_count, 1); + assert_eq!(item.correct_count, 0); +} + +#[test] +fn preview_is_idempotent_and_shown_move_is_not_success() { + let mut f = Fixture::with( + "1. e4 *", + LearningSide::White, + &["e2e4"], + &[], + "preview", + SessionKind::ReviewAll, + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert!(f.ui.request_hint_with_id_at( + "preview-e4".to_owned(), + start + Duration::from_millis(100), + NOW, + )); + assert_eq!(f.ui.session.phase, LearningSessionPhase::PreviewedReplay); + assert!(!f.ui.request_hint_with_id_at( + "preview-e4-again".to_owned(), + start + Duration::from_millis(200), + NOW, + )); + assert_eq!(f.attempts().len(), 1); + assert!(f.ui.play_uci_with_id_at( + "e2e4", + "play-preview-e4".to_owned(), + start + Duration::from_secs(1), + NOW, + )); + tick_with_prime( + &mut f.ui, + start + Duration::from_secs(1) + normal(), + normal(), + NOW, + ); + assert!(f.ui.is_finished()); + assert_eq!(f.ui.tally.hints, 1); + let data = f.store.load().unwrap(); + assert_eq!(data.learning.attempts.len(), 2); + assert_eq!( + data.learning.attempts[0].event_type, + TrainingEventType::Previewed + ); + assert_eq!( + data.learning.attempts[1].event_type, + TrainingEventType::AutoContext + ); + let item = data + .learning + .item(&key_for(&f.library, &f.scope, "e2e4")) + .unwrap(); + assert_eq!(item.correct_count, 0); + assert_eq!(item.wrong_count, 0); + assert!(item.independent_response_times_ms.is_empty()); +} + +#[test] +fn duplicate_store_response_does_not_advance_the_ui_twice() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::Black, + &["b8c6"], + "duplicate", + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert!( + f.ui.advance_context_with_id_at("duplicate-context".to_owned(), start + normal(), NOW,) + ); + assert_eq!(f.ui.session.context_index, 1); + assert_eq!(f.attempts().len(), 1); + + f.ui.completed_attempt_ids.remove("duplicate-context"); + assert!(f.ui.advance_context_with_id_at( + "duplicate-context".to_owned(), + start + normal() * 2, + NOW, + )); + assert_eq!(f.ui.session.context_index, 1); + assert_eq!(f.attempts().len(), 1); + assert!(!f.ui.visual_log.contains(&"g1f3".to_owned())); +} + +#[test] +fn store_error_is_visible_blocking_and_retryable() { + let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "store-error"); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + let valid_store = f.ui.store.clone(); + f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); + assert!(f.ui.play_uci_with_id_at( + "e2e4", + "save-error-e4".to_owned(), + start + Duration::from_millis(100), + NOW, + )); + assert!(f.ui.has_unsaved()); + assert!(f.ui.save_error.is_some()); + assert!(!f.ui.can_input()); + assert!(!f.ui.is_finished()); + assert!(f.attempts().is_empty()); + assert!(!f.ui.play_uci_with_id_at( + "d2d4", + "blocked-after-save-error".to_owned(), + start + Duration::from_millis(200), + NOW, + )); + + f.ui.store = valid_store; + f.ui.retry_pending(start + Duration::from_millis(300)); + assert!(!f.ui.has_unsaved()); + assert!(matches!(f.ui.playback, Some(Playback::Accepted { .. }))); + tick_with_prime( + &mut f.ui, + start + Duration::from_millis(300) + normal(), + normal(), + NOW, + ); + assert!(f.ui.is_finished()); + assert_eq!(f.attempts().len(), 1); +} + +/// Runs one frame of the whole screen at a window size; returns the side panel's rect. +fn screen_frame( + ui: &mut OpeningSessionUi, + ctx: &egui::Context, + size: egui::Vec2, + events: Vec, +) -> (Vec, egui::Rect) { + let mut actions = Vec::new(); + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), + time: Some(0.0), + events, + ..Default::default() + }, + |root| actions = ui.show(root, &Settings::default(), "Test repertoire"), + ) + .drop_without_applying_deltas(); + let panel = egui::containers::panel::PanelState::load(ctx, egui::Id::new("opening_side")) + .or_else(|| { + egui::containers::panel::PanelState::load(ctx, egui::Id::new("opening_side_stacked")) + }) + .map(|state| state.outer_rect) + .unwrap_or(egui::Rect::NOTHING); + (actions, panel) +} + +fn key(key: Key) -> egui::Event { + egui::Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers: Modifiers::NONE, + } +} + +#[test] +fn the_panel_takes_the_game_screens_place_at_both_reference_sizes() { + for (size, left) in [(vec2(1400.0, 900.0), 940.0), (vec2(960.0, 600.0), 576.0)] { + let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "geometry"); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let mut rects = Vec::new(); + for _ in 0..3 { + rects.push(screen_frame(&mut f.ui, &ctx, size, Vec::new()).1); + } + assert!( + (rects[2].left() - left).abs() <= 1.0, + "panel at {} in {size:?}", + rects[2].left() + ); + assert_eq!(rects[1], rects[2]); + // A question, a wrong move and its replay: the panel never moves. + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + assert!(f.ui.play_uci_with_id_at("d2d4", "geometry-wrong".into(), Instant::now(), NOW)); + assert_eq!(screen_frame(&mut f.ui, &ctx, size, Vec::new()).1, rects[2]); + assert!(f.ui.state() == Some(State::Wrong)); + } +} + +#[test] +fn a_new_move_is_shown_before_it_is_asked_and_counts_once_played() { + let mut f = Fixture::with( + "1. e4 {The king's pawn.} e5 *", + LearningSide::White, + &[], + &["e2e4"], + "new-move-shown", + SessionKind::Daily, + ); + assert_eq!(f.ui.session.remaining(), 1); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + // Shown at once: PREVIEWED recorded, the arrow and the comment visible, no hint. + let attempts = f.attempts(); + assert_eq!(attempts.len(), 1); + assert_eq!(attempts[0].event_type, TrainingEventType::Previewed); + assert!(f.ui.session.showing_new); + assert_eq!(f.ui.state(), Some(State::New)); + assert_eq!(f.ui.revealed_uci().as_deref(), Some("e2e4")); + assert!(!f.ui.can_hint()); + assert!(f.ui.can_input()); + let (game, node) = f.ui.expected_node().unwrap(); + assert_eq!( + crate::notation::comment_text(game.node(node).unwrap().comments_after()), + "The king's pawn." + ); + let (title, instruction, _) = f.ui.card_texts(&State::New, true); + assert_eq!(title, tr("New move")); + assert!(instruction.contains("1. e4"), "{instruction}"); + assert!(f.ui.play_uci_with_id_at("e2e4", "play-new".into(), Instant::now(), NOW)); + assert_eq!(f.ui.state(), Some(State::NewDone)); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + assert!(f.ui.is_finished()); + assert_eq!(f.ui.session.remaining(), 0); + assert_eq!(f.ui.tally.new_moves, 1); + assert_eq!( + f.ui.tally.mistakes + f.ui.tally.hints + f.ui.tally.first_time, + 0 + ); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 2); + assert_eq!(attempts[1].event_type, TrainingEventType::AutoContext); +} + +#[test] +fn a_daily_session_brings_mistakes_and_hints_back_and_its_numbers_agree() { + // White's moves: e4, Nf3, Bb5, then O-O after a6 Ba4 Nf6 is new. + let pgn = "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O *"; + let mut f = Fixture::with( + pgn, + LearningSide::White, + &["e2e4", "g1f3", "f1b5"], + &["b5a4", "e1g1"], + "daily-numbers", + SessionKind::Daily, + ); + let at = Instant::now(); + assert_eq!(f.ui.session.remaining(), 5); + tick_with_prime(&mut f.ui, at, Duration::ZERO, NOW); + // e4: a mistake, then the replay. It comes back: still 5 to go. + assert_eq!(f.ui.session.current_expected_uci(), Some("e2e4")); + assert!(f.ui.play_uci_with_id_at("d2d4", "e4-wrong".into(), at, NOW)); + tick_with_prime(&mut f.ui, at + WRONG_SHOWN, Duration::ZERO, NOW); + assert_eq!(f.ui.state(), Some(State::Wrong)); + answer_current(&mut f, at + WRONG_SHOWN, NOW, "e4-replay"); + assert_eq!(f.ui.session.remaining(), 5); + // Nf3: a hint, then the move. It comes back too. + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); + assert!(f.ui.request_hint_with_id_at("nf3-hint".into(), at, NOW)); + assert_eq!(f.ui.state(), Some(State::Hint)); + answer_current(&mut f, at, NOW, "nf3-after-hint"); + assert_eq!(f.ui.session.remaining(), 5); + // Bb5 right; the new moves are shown and played. + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some("f1b5")); + answer_current(&mut f, at, NOW, "bb5"); + assert_eq!(f.ui.session.remaining(), 4); + for _ in 0..2 { + f.ui.debug_settle(); + assert_eq!(f.ui.state(), Some(State::New)); + let uci = f.ui.session.current_expected_uci().unwrap().to_owned(); + answer_current(&mut f, at, NOW, &format!("new-{uci}")); + } + assert_eq!(f.ui.session.remaining(), 2); + // The returned two, answered right this time. + for expected in ["e2e4", "g1f3"] { + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some(expected)); + answer_current(&mut f, at, NOW, &format!("again-{expected}")); + } + f.ui.debug_settle(); + assert!(f.ui.is_finished()); + assert_eq!(f.ui.state(), Some(State::Summary)); + let tally = &f.ui.tally; + assert_eq!( + ( + tally.first_time, + tally.mistakes, + tally.hints, + tally.new_moves + ), + (1, 1, 1, 2) + ); + assert_eq!( + tally + .missed + .iter() + .map(|target| target.key.expected_uci.as_str()) + .collect::>(), + ["e2e4", "g1f3"] + ); + let independent = f + .attempts() + .iter() + .filter(|attempt| attempt.event_type.is_independent()) + .count(); + // e4 wrong, e4 right, Nf3 right, Bb5 right. + assert_eq!(independent, 4); + f.ui.compute_summary(); + let summary = f.ui.summary.as_ref().unwrap(); + assert_eq!(summary.more_new, 0); + assert!(!summary.next_review.is_empty()); + assert_eq!(f.ui.counter(&State::Summary).0, "0"); +} + +#[test] +fn leaving_keeps_every_answer_and_shows_what_was_done() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 *", + LearningSide::White, + &["e2e4", "g1f3"], + "leave", + ); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let size = vec2(1400.0, 900.0); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + // Nothing answered: straight back, no question. + let mut early = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "leave-early"); + tick_with_prime(&mut early.ui, Instant::now(), Duration::ZERO, NOW); + screen_frame(&mut early.ui, &ctx, size, Vec::new()); + let (actions, _) = screen_frame(&mut early.ui, &ctx, size, vec![key(Key::Escape)]); + assert!(matches!(actions.as_slice(), [SessionAction::Back])); + // One answer: the result, «Session stopped», and the answer is in the store. + answer_current(&mut f, Instant::now(), NOW, "leave-e4"); + screen_frame(&mut f.ui, &ctx, size, Vec::new()); + let (actions, _) = screen_frame(&mut f.ui, &ctx, size, vec![key(Key::Escape)]); + assert!( + actions + .iter() + .all(|action| !matches!(action, SessionAction::Back)) + ); + screen_frame(&mut f.ui, &ctx, size, Vec::new()); + assert_eq!(f.ui.shown_state, State::Summary); + assert_eq!( + f.ui.card_texts(&State::Summary, true).0, + tr("Session stopped") + ); + assert_eq!(f.ui.counter(&State::Summary).0, "1"); + assert!(!f.ui.can_input()); + let before = f.attempts().len(); + let (actions, _) = screen_frame(&mut f.ui, &ctx, size, vec![key(Key::Enter)]); + assert!(matches!(actions.as_slice(), [SessionAction::Back])); + assert_eq!(f.attempts().len(), before); + assert_eq!( + f.attempts() + .iter() + .filter(|attempt| attempt.event_type == TrainingEventType::CorrectIndependent) + .count(), + 1 + ); +} + +#[test] +fn skip_puts_the_question_at_once_and_records_the_moves_shown() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 *", + LearningSide::White, + &["f1b5"], + "skip", + ); + let at = Instant::now(); + tick_with_prime(&mut f.ui, at, normal(), NOW); + assert_eq!(f.ui.state(), Some(State::Watch)); + assert_eq!(f.ui.visual_log, ["e2e4"]); + assert!(f.ui.skip_context(at)); + tick_with_prime(&mut f.ui, at, normal(), NOW); + assert!(f.ui.can_input()); + assert_eq!(f.ui.state(), Some(State::Yours)); + assert_eq!(f.ui.session.current_expected_uci(), Some("f1b5")); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 4); + assert!( + attempts + .iter() + .all(|attempt| attempt.event_type == TrainingEventType::AutoContext) + ); + assert_eq!( + fen4(&f.ui.board_position), + key_for(&f.library, &f.scope, "f1b5").position_fen4 + ); + assert_eq!(f.ui.visual_log, ["e2e4"], "skipped moves are not animated"); +} + +#[test] +fn correct_stays_six_hundred_ms_after_the_move() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 *", + LearningSide::White, + &["e2e4", "g1f3"], + "feedback", + ); + f.ui.feedback = FEEDBACK; + let at = Instant::now(); + tick_with_prime(&mut f.ui, at, normal(), NOW); + assert!(f.ui.play_uci_with_id_at("e2e4", "feedback-e4".into(), at, NOW)); + assert_eq!(f.ui.playback_deadline(), Some(at + normal() + FEEDBACK)); + f.ui.tick_at(at + normal(), normal(), NOW); + assert_eq!(f.ui.state(), Some(State::Correct)); + f.ui.tick_at(at + normal() + FEEDBACK, normal(), NOW); + assert_ne!(f.ui.state(), Some(State::Correct)); +} + +#[test] +fn ten_more_new_continues_the_finished_session_with_new_moves_only() { + let moves = [ + "Nf3", "Nf6", "g3", "g6", "Bg2", "Bg7", "O-O", "O-O", "d3", "d6", "e4", "e5", "Nc3", "Nc6", + "a3", "a6", "h3", "h6", "Be3", "Be6", "Qd2", "Qd7", "Rab1", "Rab8", "b4", "b5", + ]; + let mut pgn = String::new(); + for (index, pair) in moves.chunks(2).enumerate() { + pgn.push_str(&format!("{}. {} {} ", index + 1, pair[0], pair[1])); + } + pgn.push('*'); + let mut f = Fixture::with( + &pgn, + LearningSide::White, + &[], + &[ + "g1f3", "g2g3", "f1g2", "e1g1", "d2d3", "e2e4", "b1c3", "a2a3", "h2h3", "c1e3", "d1d2", + "a1b1", "b2b4", + ], + "more-new", + SessionKind::Daily, + ); + assert_eq!(f.ui.session.remaining(), layout::NEW_PER_SESSION); + for index in 0..layout::NEW_PER_SESSION { + f.ui.debug_settle(); + assert_eq!(f.ui.state(), Some(State::New), "move {index}"); + answer_current(&mut f, Instant::now(), NOW, &format!("more-{index}")); + } + f.ui.debug_settle(); + assert!(f.ui.is_finished()); + f.ui.compute_summary(); + assert_eq!(f.ui.more_new_count(), 3); + let snapshot = f.ui.snapshot().clone(); + let mut more = + OpeningSessionUi::more_new(f.library.clone(), f.store.clone(), snapshot, Color::Black) + .unwrap(); + assert_eq!(more.session.remaining(), 3); + assert_eq!(more.orientation(), Color::Black); + assert_eq!(more.session.id(), f.ui.session.id()); + more.synchronous_commits = true; + more.board_shown = true; + more.debug_settle(); + assert_eq!(more.state(), Some(State::New)); + assert_eq!(more.session.current_expected_uci(), Some("d1d2")); +} + +#[test] +fn a_review_counts_lines_and_announces_the_next_one() { + let mut f = Fixture::with( + "1. e4 e5 2. Nf3 (2. Bc4) *", + LearningSide::White, + &[], + &[], + "review-lines", + SessionKind::ReviewAll, + ); + assert_eq!(f.ui.lines.len(), 2); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + assert_eq!(f.ui.counter(&State::Yours).0, "1/2"); + answer_current(&mut f, Instant::now(), NOW, "review-e4"); + f.ui.debug_settle(); + let at = Instant::now(); + assert!(f.ui.play_uci_with_id_at("g1f3", "review-nf3".into(), at, NOW)); + // Bc4 is in the second line; its context starts again from the beginning. + f.ui.tick_at(at + Duration::from_secs(1), normal(), NOW); + assert!(f.ui.pending_automatic.is_some()); + assert_eq!(f.ui.line, 2); + assert!(f.ui.next_line_banner); + assert_eq!(f.ui.state(), Some(State::NextLine)); + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some("f1c4")); + answer_current(&mut f, Instant::now(), NOW, "review-bc4"); + f.ui.debug_settle(); + assert!(f.ui.is_finished()); + assert_eq!(f.ui.counter(&State::Summary).0, "2/2"); + f.ui.compute_summary(); + assert_eq!(f.ui.more_new_count(), 0, "no «10 more new» after a review"); +} + +#[test] +fn a_new_session_never_resumes_an_unfinished_one() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 *", + LearningSide::White, + &["e2e4", "g1f3"], + "no-resume", + ); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + answer_current(&mut f, Instant::now(), NOW, "first-e4"); + let old = f.ui.session_id().to_owned(); + let again = OpeningSessionUi::new( + f.library.clone(), + f.store.clone(), + f.scope.clone(), + SessionKind::Daily, + ) + .unwrap(); + assert_ne!(again.session_id(), old); + // The unfinished snapshot is kept in the file, untouched. + let data = f.store.load().unwrap(); + assert!(data.session_snapshot(&old).is_some()); + assert_eq!(again.session.remaining(), 1); +} + +fn wait_for_commit(ui: &mut OpeningSessionUi) { + let deadline = Instant::now() + Duration::from_secs(5); + while ui.commit_in_flight.is_some() { + assert!(Instant::now() < deadline, "commit worker did not finish"); + ui.poll_commit(Instant::now()); + std::thread::sleep(Duration::from_millis(1)); + } +} + +#[test] +fn async_commit_keeps_frames_responsive_under_store_lock_and_commits_once() { + let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "async-lock"); + f.ui.synchronous_commits = false; + tick_with_prime(&mut f.ui, Instant::now(), normal(), NOW); + let lock_path = f.store.path().with_file_name("learning.json.lock"); + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(lock_path) + .unwrap(); + lock.lock().unwrap(); + let unlock = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(600)); + drop(lock); + }); + let start = Instant::now(); + assert!(f.ui.play_uci_with_id_at("e2e4", "async-answer".to_owned(), start, NOW)); + assert!( + start.elapsed() < Duration::from_millis(300), + "input waited for storage lock" + ); + assert!(f.ui.has_unsaved()); + assert!(f.ui.commit_in_flight.is_some()); + assert!(!f.ui.can_input()); + assert!( + !f.ui + .play_uci_with_id_at("e2e4", "async-answer".to_owned(), Instant::now(), NOW) + ); + f.ui.retry_pending(Instant::now()); + let ctx = egui::Context::default(); + let frame = Instant::now(); + ctx.run_ui(egui::RawInput::default(), |ui| { + f.ui.show(ui, &Settings::default(), "Test"); + }) + .drop_without_applying_deltas(); + assert!( + frame.elapsed() < Duration::from_millis(300), + "frame waited for storage lock" + ); + unlock.join().unwrap(); + wait_for_commit(&mut f.ui); + assert!(!f.ui.has_unsaved()); + assert!(matches!(f.ui.playback, Some(Playback::Accepted { .. }))); + assert_eq!(f.attempts().len(), 1); + let revision = f.ui.session.revision; + f.ui.poll_commit(Instant::now()); + f.ui.retry_pending(Instant::now()); + assert_eq!(f.ui.session.revision, revision); + assert_eq!(f.attempts().len(), 1); +} + +fn pointer_board_frame( + f: &mut Fixture, + ctx: &egui::Context, + time: f64, + events: Vec, + settings: &Settings, +) -> egui::FullOutput { + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + vec2(800.0, 800.0), + )), + time: Some(time), + events, + ..Default::default() + }, + |ui| f.ui.board_ui(ui, settings), + ); + output.textures_delta.clear(); + output +} + +fn piece_meshes(output: &egui::FullOutput) -> Vec<(egui::TextureId, egui::Rect)> { + fn collect(shape: &egui::Shape, meshes: &mut Vec<(egui::TextureId, egui::Rect)>) { + match shape { + egui::Shape::Mesh(mesh) => meshes.push((mesh.texture_id, mesh.calc_bounds())), + egui::Shape::Rect(rect) => { + if let Some(brush) = &rect.brush { + meshes.push((brush.fill_texture_id, rect.rect)); + } + } + egui::Shape::Vec(shapes) => { + for shape in shapes { + collect(shape, meshes); + } + } + _ => {} + } + } + let mut meshes = Vec::new(); + for shape in &output.shapes { + collect(&shape.shape, &mut meshes); + } + meshes +} + +fn pointer_button(pos: egui::Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + } +} + +#[test] +fn pointer_move_stays_at_destination_during_async_save_without_a_second_animation() { + for drag in [true, false] { + for wrong in [false, true] { + for animation in [ + crate::settings::Animation::Normal, + crate::settings::Animation::Off, + ] { + let mut f = + Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "pointer-pending"); + f.ui.synchronous_commits = false; + let settings = Settings { + animation, + ..Settings::default() + }; + let duration = Duration::from_secs_f32(animation.seconds()); + f.ui.tick_at(Instant::now(), duration, NOW); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let from = egui::pos2(450.0, 650.0); + let to = egui::pos2(450.0, if wrong { 550.0 } else { 450.0 }); + let initial = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &settings); + let pawn = piece_meshes(&initial) + .into_iter() + .find(|(_, rect)| rect.contains(from)) + .expect("painted pawn at e2") + .0; + initial.drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.01, + vec![egui::Event::PointerMoved(from), pointer_button(from, true)], + &settings, + ) + .drop_without_applying_deltas(); + if drag { + pointer_board_frame( + &mut f, + &ctx, + 1.02, + vec![egui::Event::PointerMoved(to)], + &settings, + ) + .drop_without_applying_deltas(); + } else { + pointer_board_frame( + &mut f, + &ctx, + 1.02, + vec![pointer_button(from, false)], + &settings, + ) + .drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.03, + vec![egui::Event::PointerMoved(to), pointer_button(to, true)], + &settings, + ) + .drop_without_applying_deltas(); + } + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(f.store.path().with_file_name("learning.json.lock")) + .unwrap(); + lock.lock().unwrap(); + let released = pointer_board_frame( + &mut f, + &ctx, + 1.04, + vec![pointer_button(to, false)], + &settings, + ); + let assert_pawn_at_destination = |output: &egui::FullOutput| { + let meshes = piece_meshes(output); + assert!( + meshes + .iter() + .any(|(texture, rect)| *texture == pawn && rect.contains(to)), + "pawn not painted at destination" + ); + assert!( + !meshes + .iter() + .any(|(texture, rect)| *texture == pawn && rect.contains(from)), + "pawn snapped back to e2" + ); + }; + assert!(f.ui.has_unsaved(), "drag={drag} wrong={wrong}"); + assert!(!f.ui.can_input()); + assert!(f.ui.pending_sounds.is_empty()); + if drag { + assert_pawn_at_destination(&released); + } + released.drop_without_applying_deltas(); + let frame = Instant::now(); + let waiting = pointer_board_frame(&mut f, &ctx, 1.05, vec![], &settings); + assert!(frame.elapsed() < Duration::from_millis(300)); + if drag { + assert_pawn_at_destination(&waiting); + assert!( + f.ui.board + .animation_at(1.05) + .is_none_or(|(_, slides, _)| slides.is_empty()) + ); + } else if !duration.is_zero() { + assert!( + f.ui.board + .animation_at(1.05) + .unwrap() + .1 + .iter() + .any(|(_, source, _)| *source == Square::E2), + "click move must still animate" + ); + } + waiting.drop_without_applying_deltas(); + let waiting = pointer_board_frame(&mut f, &ctx, 2.0, vec![], &settings); + assert_pawn_at_destination(&waiting); + waiting.drop_without_applying_deltas(); + assert!( + f.ui.learning.attempts.is_empty(), + "unconfirmed answer affected learning data" + ); + drop(lock); + wait_for_commit(&mut f.ui); + let confirmed = pointer_board_frame(&mut f, &ctx, 2.01, vec![], &settings); + assert_pawn_at_destination(&confirmed); + confirmed.drop_without_applying_deltas(); + assert!( + f.ui.board.animation_at(2.01).is_none(), + "commit restarted the move animation" + ); + assert_eq!(f.attempts().len(), 1); + assert_eq!( + f.ui.pending_sounds, + [if wrong { Sound::Wrong } else { Sound::Move }] + ); + if wrong { + f.ui.tick_at(f.ui.playback_deadline().unwrap(), duration, NOW); + pointer_board_frame(&mut f, &ctx, 2.02, vec![], &settings) + .drop_without_applying_deltas(); + assert_eq!(fen4(&f.ui.board_position), fen4(&Chess::default())); + if !duration.is_zero() { + assert!( + f.ui.board + .animation_at(2.02) + .unwrap() + .1 + .iter() + .any(|(_, _, target)| *target == Square::E2), + "wrong move must return to source" + ); + } + } + } + } + } +} + +#[test] +fn dragged_special_moves_keep_auxiliary_effects_and_retry_does_not_move_again() { + let cases = [ + ( + "4k3/8/8/8/8/8/8/4K2R w K - 0 1", + "O-O", + "e1g1", + Square::E1, + Square::G1, + None, + false, + ), + ( + "4k3/8/8/3p4/4P3/8/8/4K3 w - - 0 1", + "exd5", + "e4d5", + Square::E4, + Square::D5, + Some(Square::D5), + false, + ), + ( + "4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 1", + "exd6", + "e5d6", + Square::E5, + Square::D6, + Some(Square::D5), + false, + ), + ( + "4k3/P7/8/8/8/8/8/4K3 w - - 0 1", + "a8=Q+", + "a7a8q", + Square::A7, + Square::A8, + None, + true, + ), + ]; + let center = |sq: Square| { + egui::pos2( + (u32::from(sq.file()) as f32 + 0.5) * 100.0, + (7.5 - u32::from(sq.rank()) as f32) * 100.0, + ) + }; + for (fen, san, uci, from, to, captured, promotion) in cases { + let pgn = format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. {san} *"); + let mut f = Fixture::new(&pgn, LearningSide::White, &[uci], "special-drag"); + f.ui.synchronous_commits = false; + f.ui.tick_at(Instant::now(), normal(), NOW); + let valid_store = f.ui.store.clone(); + f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let settings = Settings::default(); + let initial = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &settings); + let captured_texture = captured.map(|sq| { + piece_meshes(&initial) + .into_iter() + .find(|(_, rect)| rect.contains(center(sq))) + .unwrap() + .0 + }); + initial.drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.01, + vec![ + egui::Event::PointerMoved(center(from)), + pointer_button(center(from), true), + ], + &settings, + ) + .drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.02, + vec![egui::Event::PointerMoved(center(to))], + &settings, + ) + .drop_without_applying_deltas(); + let released = pointer_board_frame( + &mut f, + &ctx, + 1.03, + vec![pointer_button(center(to), false)], + &settings, + ); + if uci == "e1g1" { + let (_, slides, _) = f.ui.board.animation_at(1.03).unwrap(); + assert_eq!(slides.len(), 1); + assert_eq!( + (slides[0].1, slides[0].2), + (Square::H1, Square::F1), + "only the rook should animate after a dragged castle" + ); + } + if let Some(texture) = captured_texture { + assert!( + piece_meshes(&released) + .iter() + .any(|(id, rect)| *id == texture && rect.contains(center(captured.unwrap()))), + "captured piece must still fade out" + ); + } + released.drop_without_applying_deltas(); + if promotion { + assert!( + !f.ui.has_unsaved(), + "promotion must wait for the chosen piece" + ); + pointer_board_frame( + &mut f, + &ctx, + 1.04, + vec![pointer_button(center(to), true)], + &settings, + ) + .drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.05, + vec![pointer_button(center(to), false)], + &settings, + ) + .drop_without_applying_deltas(); + assert_eq!( + f.ui.board_position.board().piece_at(to).unwrap().role, + chess_core::shakmaty::Role::Queen + ); + } + assert!(f.ui.has_unsaved()); + let after = fen4(&f.ui.board_position); + wait_for_commit(&mut f.ui); + assert!(f.ui.save_error.is_some()); + assert!(f.attempts().is_empty()); + assert!(f.ui.pending_sounds.is_empty()); + pointer_board_frame(&mut f, &ctx, 1.1, vec![], &settings).drop_without_applying_deltas(); + let waiting = pointer_board_frame(&mut f, &ctx, 2.0, vec![], &settings); + if let Some(texture) = captured_texture { + assert!( + !piece_meshes(&waiting) + .iter() + .any(|(id, rect)| *id == texture && rect.contains(center(captured.unwrap()))) + ); + } + waiting.drop_without_applying_deltas(); + f.ui.store = valid_store; + f.ui.retry_pending(Instant::now()); + f.ui.retry_pending(Instant::now()); + wait_for_commit(&mut f.ui); + pointer_board_frame(&mut f, &ctx, 2.01, vec![], &settings).drop_without_applying_deltas(); + assert_eq!(fen4(&f.ui.board_position), after); + assert!(f.ui.board.animation_at(2.01).is_none()); + assert_eq!(f.attempts().len(), 1); + assert_eq!(f.ui.pending_sounds, [Sound::Move]); + } +} + +#[test] +fn reused_context_retry_stays_silent_and_responsive_and_persists_once() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + &["e2e4", "g1f3"], + "reuse-retry", + ); + let at = Instant::now(); + tick_with_prime(&mut f.ui, at, normal(), NOW); + assert!(f.ui.play_uci_with_id_at("e2e4", "own-answer".into(), at, NOW)); + let position = fen4(&f.ui.board_position); + assert_eq!(std::mem::take(&mut f.ui.pending_sounds), [Sound::Move]); + let valid_store = f.ui.store.clone(); + f.ui.synchronous_commits = false; + f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); + f.ui.tick_at(at + normal(), normal(), NOW); + wait_for_commit(&mut f.ui); + assert!(f.ui.save_error.is_some()); + assert!(matches!( + f.ui.pending_commit.as_ref().unwrap().kind, + CommitKind::ReusedContext + )); + let reused_id = f.ui.pending_commit.as_ref().unwrap().attempts[0] + .client_attempt_id + .clone(); + assert_eq!(fen4(&f.ui.board_position), position); + assert!(f.ui.pending_sounds.is_empty()); + f.ui.store = valid_store; + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(f.store.path().with_file_name("learning.json.lock")) + .unwrap(); + lock.lock().unwrap(); + let unlock = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(600)); + drop(lock); + }); + f.ui.retry_pending(Instant::now()); + f.ui.retry_pending(Instant::now()); + let frame = Instant::now(); + assert!(emitted_sounds(&mut f, &egui::Context::default(), &Settings::default()).is_empty()); + assert!( + frame.elapsed() < Duration::from_millis(300), + "reused context blocked the frame" + ); + assert_eq!(fen4(&f.ui.board_position), position); + assert!(!f.ui.can_input()); + unlock.join().unwrap(); + wait_for_commit(&mut f.ui); + assert!(f.ui.pending_sounds.is_empty()); + f.ui.debug_settle(); + assert_eq!(f.ui.visual_log, ["e7e5"]); + assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 3); + assert_eq!( + attempts + .iter() + .filter(|event| event.client_attempt_id == reused_id) + .count(), + 1 + ); + assert_eq!( + attempts + .iter() + .filter(|event| event.event_type.is_independent()) + .count(), + 1 + ); +} + +#[test] +fn async_failed_commit_preserves_event_for_retry_without_double_counting() { + let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "async-retry"); + f.ui.synchronous_commits = false; + tick_with_prime(&mut f.ui, Instant::now(), normal(), NOW); + let valid_store = f.ui.store.clone(); + f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); + assert!(f.ui.play_uci_with_id_at("e2e4", "async-retry".to_owned(), Instant::now(), NOW)); + wait_for_commit(&mut f.ui); + assert!(f.ui.save_error.is_some()); + assert!(f.ui.has_unsaved()); + assert!(f.attempts().is_empty()); + f.ui.store = valid_store; + f.ui.retry_pending(Instant::now()); + f.ui.retry_pending(Instant::now()); + wait_for_commit(&mut f.ui); + assert!(!f.ui.has_unsaved()); + assert_eq!(f.attempts().len(), 1); + assert_eq!(f.attempts()[0].client_attempt_id, "async-retry"); +} diff --git a/apps/desktop/src/repertoire_editor.rs b/apps/desktop/src/repertoire_editor.rs deleted file mode 100644 index a3bebfc..0000000 --- a/apps/desktop/src/repertoire_editor.rs +++ /dev/null @@ -1,1070 +0,0 @@ -use chess_core::shakmaty::{Chess, Color, Position, san::SanPlus, uci::UciMove}; -use chess_core::{Game, MoveKind, NodeId}; -use egui::{RichText, Ui}; -use trainer::repertoire::{ - LearningData, LearningItemKey, LearningSide, Library, LibraryStore, MoveLearningAnalytics, - MoveLearningStatus, Repertoire, RepertoireError, RepertoireId, RepertoireTree, SrsSettings, - StatsScope, scoped_move_learning_analytics, -}; - -use crate::board::{BoardState, BoardView}; -use crate::i18n::tr; -use crate::settings::Settings; - -#[derive(Debug)] -pub enum RepertoireEditorAction { - Close, - OpenSettings, - Cancel, - Applied { - repertoire_id: RepertoireId, - library: Library, - }, - Error(String), -} - -pub struct RepertoireEditorUi { - original: Library, - draft: Library, - repertoire_id: RepertoireId, - tree: RepertoireTree, - selected: NodeId, - board: BoardState, - learning: Option, - analytics_cache: Option, String>>, - error: Option, -} - -impl RepertoireEditorUi { - pub fn new(library: &Library, repertoire_id: RepertoireId) -> Result { - let repertoire = library - .repertoire(&repertoire_id) - .ok_or_else(|| RepertoireError::NotFound(repertoire_id.clone()))?; - let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); - let selected = tree.root(); - Ok(Self { - original: library.clone(), - draft: library.clone(), - repertoire_id, - tree, - selected, - board: BoardState::default(), - learning: None, - analytics_cache: None, - error: None, - }) - } - - pub fn set_learning(&mut self, learning: &LearningData) { - self.learning = Some(learning.clone()); - self.analytics_cache = None; - } - - pub fn has_unsaved(&self) -> bool { - self.draft.repertoire(&self.repertoire_id) != self.original.repertoire(&self.repertoire_id) - } - - pub fn show( - &mut self, - ui: &mut Ui, - settings: &Settings, - library_store: &LibraryStore, - ) -> Vec { - let mut actions = Vec::new(); - let mut commands = Vec::new(); - egui::Panel::top("repertoire_editor_header").show(ui, |ui| { - self.show_header(ui, &mut commands); - }); - let available = ui.available_rect_before_wrap(); - let width = available.width(); - let height = available.height(); - if width < 900.0 && height > width { - let panel_height = (height * 0.52).clamp(340.0, 520.0); - let board_rect = egui::Rect::from_min_max( - available.min, - egui::pos2(available.right(), available.bottom() - panel_height), - ); - let panel_rect = egui::Rect::from_min_max( - egui::pos2(available.left(), board_rect.bottom()), - available.max, - ); - ui.scope_builder(egui::UiBuilder::new().max_rect(board_rect), |ui| { - egui::CentralPanel::default().show(ui, |ui| self.show_board(ui, settings)); - }); - ui.scope_builder(egui::UiBuilder::new().max_rect(panel_rect), |ui| { - ui.set_clip_rect(panel_rect); - egui::Frame::side_top_panel(ui.style()) - .show(ui, |ui| self.show_panel(ui, &mut commands)); - }); - } else { - egui::Panel::right("repertoire_workspace_side") - .resizable(true) - .default_size((width * 0.42).clamp(420.0, 560.0)) - .size_range(360.0..=(width - 220.0).max(360.0)) - .show(ui, |ui| self.show_panel(ui, &mut commands)); - egui::CentralPanel::default().show(ui, |ui| self.show_board(ui, settings)); - } - for command in commands { - match command { - EditorCommand::Close => actions.push(RepertoireEditorAction::Close), - EditorCommand::OpenSettings => actions.push(RepertoireEditorAction::OpenSettings), - EditorCommand::Cancel => { - self.cancel(); - actions.push(RepertoireEditorAction::Cancel); - } - EditorCommand::Save => match self.save(library_store) { - Ok(library) => actions.push(RepertoireEditorAction::Applied { - repertoire_id: self.repertoire_id.clone(), - library, - }), - Err(error) => { - self.error = Some(error.clone()); - actions.push(RepertoireEditorAction::Error(error)); - } - }, - EditorCommand::Select(node) => self.select(node), - EditorCommand::SetMainAnswer => { - if let Err(error) = self.set_selected_main_answer() { - self.error = Some(error.clone()); - actions.push(RepertoireEditorAction::Error(error)); - } - } - EditorCommand::ClearMainAnswer => { - self.clear_selected_main_answer(); - } - EditorCommand::SetDisabled(disabled) => { - if let Err(error) = self.set_selected_disabled(disabled) { - self.error = Some(error.clone()); - actions.push(RepertoireEditorAction::Error(error)); - } - } - EditorCommand::SetDepth(depth) => { - if let Some(repertoire) = self.draft.repertoire_mut(&self.repertoire_id) { - repertoire.set_max_plies(depth); - self.analytics_cache = None; - self.error = None; - } - } - } - } - actions - } - - fn show_header(&self, ui: &mut Ui, commands: &mut Vec) { - let compact = ui.available_width() < 600.0; - ui.horizontal(|ui| { - ui.set_min_height(26.0); - if ui - .button(format!("← {}", tr("Back to repertoire"))) - .clicked() - { - commands.push(EditorCommand::Close); - } - ui.separator(); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::widgets::settings_button(ui, compact).clicked() { - commands.push(EditorCommand::OpenSettings); - } - ui.separator(); - ui.add_enabled_ui(self.has_unsaved(), |ui| { - if ui.button(tr("Save")).clicked() { - commands.push(EditorCommand::Save); - } - }); - if ui.button(tr("Cancel")).clicked() { - commands.push(EditorCommand::Cancel); - } - if let Some(repertoire) = self.draft.repertoire(&self.repertoire_id) { - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - ui.add( - egui::Label::new(RichText::new(&repertoire.name).heading()).truncate(), - ) - .on_hover_text(&repertoire.name); - }); - } - }); - }); - } - - fn show_board(&mut self, ui: &mut Ui, settings: &Settings) { - let position = self - .tree - .position(self.selected) - .cloned() - .unwrap_or_default(); - let last_move = self - .tree - .game() - .game_move(self.selected) - .and_then(|game_move| match game_move.kind { - MoveKind::Normal(mv) => Some(( - mv.from().unwrap_or_else(|| mv.to()), - crate::board::ui_target(&mv), - )), - MoveKind::Null => None, - }); - let side = ui - .available_width() - .min(ui.available_height()) - .max(1.0) - .floor(); - let available = ui.available_size(); - let offset = egui::vec2( - ((available.x - side) / 2.0).max(0.0).floor(), - ((available.y - side) / 2.0).max(0.0).floor(), - ); - let rect = egui::Rect::from_min_size(ui.cursor().min + offset, egui::vec2(side, side)); - let orientation = settings - .repertoire_modes - .get(self.repertoire_id.as_str()) - .map_or(Color::White, |(mode, _)| match mode { - trainer::repertoire::TrainingMode::Black => Color::Black, - trainer::repertoire::TrainingMode::White - | trainer::repertoire::TrainingMode::Both => Color::White, - }); - ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { - BoardView { - pos: &position, - orientation, - last_move, - arrows: &[], - circles: &[], - badge: None, - interactive: false, - show_coords: settings.show_coords, - theme: settings.board_theme.theme(), - pieces: settings.piece_set, - animation: settings.animation.seconds(), - premove: None, - auto_queen: false, - alert: None, - } - .show(ui, &mut self.board); - }); - } - - fn show_panel(&mut self, ui: &mut Ui, commands: &mut Vec) { - let tree_height = (ui.available_height() * 0.55).max(160.0); - ui.allocate_ui_with_layout( - egui::vec2(ui.available_width(), tree_height), - egui::Layout::top_down(egui::Align::Min), - |ui| { - egui::ScrollArea::vertical() - .id_salt("repertoire_editor_tree") - .max_height(tree_height) - .auto_shrink([false, false]) - .show(ui, |ui| self.show_tree(ui, commands)); - }, - ); - ui.separator(); - egui::ScrollArea::vertical() - .auto_shrink([false, false]) - .show(ui, |ui| { - ui.set_width(ui.available_width()); - if let Some(error) = self.error.clone() { - ui.add( - egui::Label::new(RichText::new(&error).color(ui.visuals().error_fg_color)) - .truncate(), - ) - .on_hover_text(error); - ui.separator(); - } - if let Some(repertoire) = self.draft.repertoire(&self.repertoire_id) { - let mut unlimited = repertoire.max_plies == u32::MAX; - if ui.checkbox(&mut unlimited, tr("No depth limit")).changed() { - commands.push(EditorCommand::SetDepth(if unlimited { - u32::MAX - } else { - 20 - })); - } - if !unlimited { - let mut depth = if repertoire.max_plies == u32::MAX { - 20 - } else { - repertoire.max_plies - }; - ui.horizontal(|ui| { - ui.label(tr("Depth")); - if ui - .add(egui::DragValue::new(&mut depth).range(0..=u32::MAX - 1)) - .changed() - { - commands.push(EditorCommand::SetDepth(depth)); - } - ui.label(tr("plies")); - }); - } - } - ui.separator(); - self.show_selected(ui, commands); - ui.separator(); - egui::CollapsingHeader::new(tr("Move analytics")) - .id_salt("repertoire_editor_analytics") - .show(ui, |ui| self.show_analytics(ui)); - }); - } - - fn show_selected(&self, ui: &mut Ui, commands: &mut Vec) { - let Some((position_fen4, expected_uci, _)) = self.selected_move_parts() else { - ui.label(tr("Select a move in the PGN tree")); - return; - }; - let game = self.tree.game(); - if let Some(label) = game.move_label(self.selected) { - ui.strong(crate::san::show(&label)); - } - let main_answer = game - .parent(self.selected) - .and_then(|parent| self.effective_main_answer(parent)); - let is_main = main_answer.as_deref() == Some(expected_uci.as_str()); - if let Some(main_answer) = main_answer { - let label = game - .position_before(self.selected) - .and_then(|position| san_for_uci(position, &main_answer)) - .unwrap_or_else(|| "—".to_owned()); - ui.label(format!("{}: {label}", tr("Preferred move"))); - } - let has_override = self - .draft - .repertoire(&self.repertoire_id) - .and_then(|repertoire| repertoire.main_answer_override(&position_fen4)) - .is_some(); - ui.add( - egui::Label::new(tr( - "All enabled variations are trained. The preferred move only affects their order.", - )) - .wrap(), - ); - let disabled = self - .draft - .repertoire(&self.repertoire_id) - .zip(self.tree.path(self.selected)) - .is_some_and(|(repertoire, path)| repertoire.is_prefix_disabled(path)); - ui.horizontal_wrapped(|ui| { - if ui - .add_enabled(!is_main, egui::Button::new(tr("Prefer this move"))) - .clicked() - { - commands.push(EditorCommand::SetMainAnswer); - } - if ui - .add_enabled(has_override, egui::Button::new(tr("PGN order"))) - .clicked() - { - commands.push(EditorCommand::ClearMainAnswer); - } - if ui - .button(if disabled { - tr("Enable") - } else { - tr("Disable") - }) - .clicked() - { - commands.push(EditorCommand::SetDisabled(!disabled)); - } - }); - if disabled { - ui.label(tr("Disabled for training")); - } - } - - fn show_tree(&self, ui: &mut Ui, commands: &mut Vec) { - ui.strong(tr("PGN tree")); - let root = self.tree.root(); - if ui - .add(egui::Button::selectable(self.selected == root, tr("Initial position")).truncate()) - .clicked() - { - commands.push(EditorCommand::Select(root)); - } - for row in tree_rows(&self.tree) { - let Some(label) = self.tree.game().move_label(row.node) else { - continue; - }; - let mut label = crate::san::show(&label).into_owned(); - if row.variation { - label = format!("↳ {label}"); - } - if self - .tree - .game() - .parent(row.node) - .and_then(|parent| self.tree.position_key(parent)) - .and_then(|position| { - self.draft - .repertoire(&self.repertoire_id)? - .main_answer_override(position) - }) - .zip(self.tree.game().game_move(row.node).and_then(|mv| mv.uci())) - .is_some_and(|(main, uci)| main == uci) - { - label.push_str(&format!(" · {}", tr("preferred"))); - } - if self - .draft - .repertoire(&self.repertoire_id) - .zip(self.tree.path(row.node)) - .is_some_and(|(repertoire, path)| repertoire.is_prefix_disabled(path)) - { - label.push_str(&format!(" · {}", tr("disabled"))); - } - ui.horizontal(|ui| { - let indentation = (row.indentation as f32 * 14.0).min(ui.available_width() * 0.35); - ui.add_space(indentation); - if ui - .add_sized( - [ui.available_width(), 24.0], - egui::Button::selectable(self.selected == row.node, "") - .left_text(label) - .truncate(), - ) - .clicked() - { - commands.push(EditorCommand::Select(row.node)); - } - }); - } - } - - fn show_analytics(&mut self, ui: &mut Ui) { - if self.selected == self.tree.root() { - ui.label(tr("Select a move to see its learning analytics")); - return; - } - if self.learning.is_none() { - ui.label(tr("Shared learning data is not connected")); - return; - } - match self.selected_analytics() { - Ok(Some(analytics)) => { - show_move_analytics(ui, &analytics, self.tree.game(), self.selected) - } - Ok(None) => { - ui.label(tr("No learning data for this move")); - } - Err(error) => { - ui.colored_label(ui.visuals().error_fg_color, error); - } - } - } - - fn select(&mut self, node: NodeId) { - if self.tree.game().is_attached(node) { - self.selected = node; - self.board.clear(); - self.analytics_cache = None; - } - } - - fn cancel(&mut self) { - self.draft = self.original.clone(); - self.selected = self.tree.root(); - self.board.clear(); - self.analytics_cache = None; - self.error = None; - } - - fn save(&mut self, library_store: &LibraryStore) -> Result { - let draft = self - .draft - .repertoire(&self.repertoire_id) - .cloned() - .ok_or_else(|| tr("Repertoire not found").to_owned())?; - let original = self - .original - .repertoire(&self.repertoire_id) - .cloned() - .ok_or_else(|| tr("Repertoire not found").to_owned())?; - let mut updated = original; - updated.max_plies = draft.max_plies; - updated.disabled_prefixes = draft.disabled_prefixes; - updated.main_answer_overrides = draft.main_answer_overrides; - let mut saved = self.original.clone(); - let slot = saved - .repertoire_mut(&self.repertoire_id) - .ok_or_else(|| tr("Repertoire not found").to_owned())?; - *slot = updated; - library_store - .save(&mut saved) - .map_err(|error| error.to_string())?; - self.original = saved.clone(); - self.draft = saved.clone(); - self.analytics_cache = None; - self.error = None; - Ok(saved) - } - - fn selected_move_parts(&self) -> Option<(String, String, LearningSide)> { - let game = self.tree.game(); - let parent = game.parent(self.selected)?; - let expected_uci = game.game_move(self.selected)?.uci()?; - let position_fen4 = self.tree.position_key(parent)?.to_owned(); - let side = LearningSide::from(game.position(parent)?.turn()); - Some((position_fen4, expected_uci, side)) - } - - fn set_selected_main_answer(&mut self) -> Result<(), String> { - let (position_fen4, expected_uci, side) = self - .selected_move_parts() - .ok_or_else(|| tr("Select a move in the PGN tree").to_owned())?; - self.assign_main_answer_checked(&position_fen4, &expected_uci, side) - } - - fn assign_main_answer_checked( - &mut self, - position_fen4: &str, - expected_uci: &str, - side: LearningSide, - ) -> Result<(), String> { - let repertoire = self - .draft - .repertoire_mut(&self.repertoire_id) - .ok_or_else(|| tr("Repertoire not found").to_owned())?; - repertoire - .set_main_answer_override(position_fen4, expected_uci, side) - .map_err(|_| { - tr("The selected move cannot be the main answer for this position").to_owned() - })?; - self.analytics_cache = None; - self.error = None; - Ok(()) - } - - fn clear_selected_main_answer(&mut self) { - let Some((position_fen4, _, _)) = self.selected_move_parts() else { - return; - }; - if let Some(repertoire) = self.draft.repertoire_mut(&self.repertoire_id) { - repertoire.clear_main_answer_override(&position_fen4); - self.analytics_cache = None; - self.error = None; - } - } - - fn set_selected_disabled(&mut self, disabled: bool) -> Result<(), String> { - let path = self - .tree - .path(self.selected) - .filter(|path| !path.is_empty()) - .map(<[String]>::to_vec) - .ok_or_else(|| tr("Select a move in the PGN tree").to_owned())?; - let repertoire = self - .draft - .repertoire_mut(&self.repertoire_id) - .ok_or_else(|| tr("Repertoire not found").to_owned())?; - if disabled { - repertoire - .set_prefix_disabled(&path, true) - .map_err(|_| tr("The selected PGN branch cannot be disabled").to_owned())?; - } else { - let blocking: Vec> = repertoire - .disabled_prefixes - .iter() - .filter(|prefix| path.starts_with(prefix)) - .cloned() - .collect(); - for prefix in blocking { - repertoire - .set_prefix_disabled(&prefix, false) - .map_err(|_| tr("The selected PGN branch cannot be enabled").to_owned())?; - } - } - self.analytics_cache = None; - self.error = None; - Ok(()) - } - - fn effective_main_answer(&self, parent: NodeId) -> Option { - let repertoire = self.draft.repertoire(&self.repertoire_id)?; - effective_main_answer(repertoire, &self.tree, parent) - } - - fn selected_analytics(&mut self) -> Result, String> { - if self.analytics_cache.is_none() { - let result = self.compute_selected_analytics(); - self.analytics_cache = Some(result); - } - self.analytics_cache.clone().unwrap_or(Ok(None)) - } - - fn compute_selected_analytics(&self) -> Result, String> { - let Some(learning) = &self.learning else { - return Ok(None); - }; - let Some((position_fen4, expected_uci, side)) = self.selected_move_parts() else { - return Ok(None); - }; - let key = LearningItemKey::local(position_fen4, expected_uci); - let mut scope = StatsScope::for_repertoire(self.repertoire_id.clone(), side, now()); - scope.only_active = false; - let analytics = - scoped_move_learning_analytics(&self.draft, learning, &scope, &SrsSettings::default()) - .map_err(|error| error.to_string())?; - Ok(analytics.into_iter().find(|item| item.key == key)) - } -} - -#[derive(Clone, Copy)] -enum EditorCommand { - Close, - OpenSettings, - Cancel, - Save, - Select(NodeId), - SetMainAnswer, - ClearMainAnswer, - SetDisabled(bool), - SetDepth(u32), -} - -#[derive(Clone, Copy)] -struct TreeRow { - node: NodeId, - indentation: u32, - variation: bool, -} - -fn tree_rows(tree: &RepertoireTree) -> Vec { - fn append(game: &Game, parent: NodeId, indentation: u32, rows: &mut Vec) { - for (index, child) in game.children(parent).iter().copied().enumerate() { - let variation = index > 0; - let child_indentation = indentation + u32::from(variation); - rows.push(TreeRow { - node: child, - indentation: child_indentation, - variation, - }); - append(game, child, child_indentation, rows); - } - } - - let mut rows = Vec::new(); - append(tree.game(), tree.root(), 0, &mut rows); - rows -} - -fn effective_main_answer( - repertoire: &Repertoire, - tree: &RepertoireTree, - parent: NodeId, -) -> Option { - let position_fen4 = tree.position_key(parent)?; - let mut candidates = Vec::new(); - for transposition in tree.transpositions(parent) { - if tree.path(*transposition).is_none() { - continue; - } - for child in tree.game().children(*transposition) { - if tree.path(*child).is_none() { - continue; - } - let Some(uci) = tree.game().game_move(*child).and_then(|mv| mv.uci()) else { - continue; - }; - if !candidates.contains(&uci) { - candidates.push(uci); - } - } - } - repertoire - .main_answer_override(position_fen4) - .filter(|override_uci| candidates.iter().any(|uci| uci == override_uci)) - .map(str::to_owned) - .or_else(|| candidates.into_iter().next()) -} - -fn show_move_analytics( - ui: &mut Ui, - analytics: &MoveLearningAnalytics, - game: &Game, - selected: NodeId, -) { - egui::Grid::new("repertoire_editor_move_analytics") - .num_columns(2) - .spacing([12.0, 4.0]) - .show(ui, |ui| { - ui.label(tr("Status")); - ui.label(move_status_label(analytics.status)); - ui.end_row(); - ui.label(tr("Accuracy")); - ui.label( - analytics - .accuracy_percent - .map_or_else(|| "—".to_owned(), |value| format!("{value:.0} %")), - ); - ui.end_row(); - ui.label(tr("Correct streak")); - ui.label(analytics.correct_streak.to_string()); - ui.end_row(); - ui.label(tr("Wrong streak")); - ui.label(analytics.wrong_streak.to_string()); - ui.end_row(); - ui.label(tr("Next due")); - ui.label(format_time(analytics.next_review_at)); - ui.end_row(); - ui.label(tr("Response median")); - ui.label( - analytics - .response_time_median_ms - .map_or_else(|| "—".to_owned(), format_duration_ms), - ); - ui.end_row(); - }); - ui.horizontal_wrapped(|ui| { - ui.label(format!("{}:", tr("Wrong moves"))); - if analytics.wrong_move_histogram.is_empty() { - ui.label("—"); - } else { - for (uci, stats) in &analytics.wrong_move_histogram { - let label = game - .position_before(selected) - .and_then(|position| san_for_uci(position, uci)) - .unwrap_or_else(|| tr("Unknown move").to_owned()); - ui.label(format!("{label} × {}", stats.count)); - } - } - }); -} - -fn move_status_label(status: MoveLearningStatus) -> &'static str { - tr(match status { - MoveLearningStatus::Unseen => "Unseen", - MoveLearningStatus::Learning => "Learning", - MoveLearningStatus::LearntFresh => "Learnt", - MoveLearningStatus::Uncertain => "Uncertain", - }) -} - -fn san_for_uci(position: &Chess, uci: &str) -> Option { - let mv = uci.parse::().ok()?.to_move(position).ok()?; - Some(crate::san::show(&SanPlus::from_move(position.clone(), mv).to_string()).into_owned()) -} - -fn format_duration_ms(milliseconds: f64) -> String { - if milliseconds >= 1000.0 { - format!("{:.2} s", milliseconds / 1000.0) - } else { - format!("{milliseconds:.0} ms") - } -} - -fn format_time(at: Option) -> String { - at.and_then(|at| chrono::DateTime::from_timestamp(at, 0)) - .map(|at| { - at.with_timezone(&chrono::Local) - .format("%Y-%m-%d %H:%M") - .to_string() - }) - .unwrap_or_else(|| "—".to_owned()) -} - -fn now() -> i64 { - chrono::Local::now().timestamp() -} - -#[cfg(test)] -mod tests { - use std::path::{Path, PathBuf}; - use std::sync::atomic::{AtomicU64, Ordering}; - - use trainer::repertoire::{LearningStore, LearningStoreData, WrongMoveStats, fen4}; - - use super::*; - - static NEXT_TEST: AtomicU64 = AtomicU64::new(1); - - struct TestDir(PathBuf); - - impl TestDir { - fn new(name: &str) -> Self { - let path = std::env::temp_dir().join(format!( - "cp-repertoire-editor-{}-{}-{name}", - std::process::id(), - NEXT_TEST.fetch_add(1, Ordering::Relaxed) - )); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - Self(path) - } - - fn join(&self, path: impl AsRef) -> PathBuf { - self.0.join(path) - } - } - - impl Drop for TestDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } - } - - fn library() -> (Library, RepertoireId) { - let mut library = Library::default(); - let id = library - .create( - "King and queen pawn", - &chess_core::parse_str("1. e4 (1. d4) e5 *").game, - ) - .unwrap(); - (library, id) - } - - fn child(editor: &RepertoireEditorUi, index: usize) -> NodeId { - editor.tree.game().children(editor.tree.root())[index] - } - - #[test] - fn depth_controls_hide_unlimited_sentinel_and_keep_odd_half_moves() { - let (library, id) = library(); - let mut editor = RepertoireEditorUi::new(&library, id.clone()).unwrap(); - for depth in [u32::MAX, 7] { - editor - .draft - .repertoire_mut(&id) - .unwrap() - .set_max_plies(depth); - let ctx = egui::Context::default(); - let mut commands = Vec::new(); - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(420.0, 600.0), - )), - ..Default::default() - }, - |ui| editor.show_panel(ui, &mut commands), - ); - let texts: Vec<_> = output - .shapes - .iter() - .filter_map(|clipped| { - if let egui::Shape::Text(shape) = &clipped.shape { - Some(shape.galley.text().to_owned()) - } else { - None - } - }) - .collect(); - assert!(texts.iter().any(|text| text == "No depth limit")); - assert!(!texts.iter().any(|text| text.contains("4294967295"))); - if depth == 7 { - assert!(texts.iter().any(|text| text == "7")); - assert!(texts.iter().any(|text| text == "plies")); - } - assert!(commands.is_empty()); - assert_eq!(editor.draft.repertoire(&id).unwrap().max_plies, depth); - output.drop_without_applying_deltas(); - } - } - - #[test] - fn main_answer_assignment_is_validated_and_clear_restores_pgn_default() { - let (library, id) = library(); - let mut editor = RepertoireEditorUi::new(&library, id.clone()).unwrap(); - let root_fen = fen4(editor.tree.game().start().position()); - let pgn = library.repertoire(&id).unwrap().pgn.clone(); - - let wrong_side = editor - .assign_main_answer_checked(&root_fen, "d2d4", LearningSide::Black) - .unwrap_err(); - assert!(!wrong_side.contains("d2d4")); - let missing_move = editor - .assign_main_answer_checked(&root_fen, "c2c4", LearningSide::White) - .unwrap_err(); - assert!(!missing_move.contains("c2c4")); - assert!( - editor - .draft - .repertoire(&id) - .unwrap() - .main_answer_overrides - .is_empty() - ); - - editor.select(child(&editor, 1)); - editor.set_selected_main_answer().unwrap(); - assert_eq!( - editor - .draft - .repertoire(&id) - .unwrap() - .main_answer_override(&root_fen), - Some("d2d4") - ); - assert_eq!( - editor.effective_main_answer(editor.tree.root()).as_deref(), - Some("d2d4") - ); - assert_eq!(editor.tree.game().children(editor.tree.root()).len(), 2); - assert_eq!(editor.draft.repertoire(&id).unwrap().pgn, pgn); - - editor.clear_selected_main_answer(); - assert_eq!( - editor - .draft - .repertoire(&id) - .unwrap() - .main_answer_override(&root_fen), - None - ); - assert_eq!( - editor.effective_main_answer(editor.tree.root()).as_deref(), - Some("e2e4") - ); - assert_eq!(editor.tree.game().children(editor.tree.root()).len(), 2); - assert_eq!(editor.draft.repertoire(&id).unwrap().pgn, pgn); - } - - #[test] - fn depth_disable_and_override_roundtrip_preserve_source_and_shared_learning() { - let dir = TestDir::new("roundtrip"); - let source = dir.join("source.pgn"); - let source_bytes = b"[Event \"Original\"]\n\n1. e4 (1. d4) e5 *\n"; - std::fs::write(&source, source_bytes).unwrap(); - let (mut library, id) = library(); - let second = library - .create( - "Shared transposition", - &chess_core::parse_str("1. e4 (1. d4) e5 *").game, - ) - .unwrap(); - library.repertoire_mut(&id).unwrap().path = Some(source.clone()); - let original_pgn = library.repertoire(&id).unwrap().pgn.clone(); - let library_store = LibraryStore::new(dir.join("library.json")); - library_store.save(&mut library).unwrap(); - - let mut learning = LearningData::default(); - let root_fen = fen4(library.repertoire(&id).unwrap().game().start().position()); - let key = LearningItemKey::local(root_fen.clone(), "d2d4"); - let shared_item = { - let item = learning.ensure_item(key.clone()); - item.introduced = true; - item.correct_streak = 4; - item.correct_count = 7; - item.wrong_count = 2; - item.next_review_at = Some(1_900_000_000); - item.independent_response_times_ms = vec![500, 700, 900]; - item.wrong_move_histogram.insert( - "c2c4".into(), - WrongMoveStats { - count: 2, - last_at: 1_800_000_000, - }, - ); - item.clone() - }; - let learning_store = LearningStore::new(dir.join("learning.json")); - let learning_data = LearningStoreData { - learning: learning.clone(), - ..LearningStoreData::default() - }; - std::fs::write( - learning_store.path(), - serde_json::to_vec_pretty(&learning_data).unwrap(), - ) - .unwrap(); - let learning_bytes = std::fs::read(learning_store.path()).unwrap(); - - let mut editor = RepertoireEditorUi::new(&library, id.clone()).unwrap(); - editor.set_learning(&learning); - editor.select(child(&editor, 1)); - editor.set_selected_main_answer().unwrap(); - editor.set_selected_disabled(true).unwrap(); - editor.draft.repertoire_mut(&id).unwrap().set_max_plies(7); - assert_eq!( - editor - .draft - .repertoire(&id) - .unwrap() - .main_answer_override(&root_fen), - Some("d2d4") - ); - assert_eq!( - editor.effective_main_answer(editor.tree.root()).as_deref(), - Some("d2d4") - ); - - let analytics = editor.selected_analytics().unwrap().unwrap(); - assert_eq!(analytics.key, key); - assert_eq!(analytics.correct_streak, 4); - assert_eq!(analytics.correct_count, 7); - assert_eq!(analytics.response_time_median_ms, Some(700.0)); - - let saved = editor.save(&library_store).unwrap(); - assert!(!editor.has_unsaved()); - assert_eq!(saved.repertoire(&id).unwrap().max_plies, 7); - assert_eq!(saved.repertoire(&id).unwrap().disabled_prefixes.len(), 1); - assert_eq!(saved.repertoire(&id).unwrap().pgn, original_pgn); - assert!(saved.repertoire(&second).is_some()); - assert_eq!(std::fs::read(&source).unwrap(), source_bytes); - assert_eq!( - std::fs::read(learning_store.path()).unwrap(), - learning_bytes - ); - - editor.set_selected_disabled(false).unwrap(); - assert_eq!( - editor - .draft - .repertoire(&id) - .unwrap() - .main_answer_override(&root_fen), - Some("d2d4") - ); - let saved = editor.save(&library_store).unwrap(); - assert!(saved.repertoire(&id).unwrap().disabled_prefixes.is_empty()); - assert_eq!(saved.repertoire(&id).unwrap().pgn, original_pgn); - assert_eq!(std::fs::read(&source).unwrap(), source_bytes); - assert_eq!( - std::fs::read(learning_store.path()).unwrap(), - learning_bytes - ); - - let loaded = library_store.load().unwrap(); - assert_eq!(loaded.repertoire(&id).unwrap().max_plies, 7); - assert!(loaded.repertoire(&id).unwrap().disabled_prefixes.is_empty()); - assert_eq!(loaded.repertoire(&id).unwrap().pgn, original_pgn); - let restored_learning = learning_store.load().unwrap(); - assert_eq!(restored_learning.learning.item(&key), Some(&shared_item)); - } - - #[test] - fn cancel_restores_the_whole_draft_without_saving() { - let dir = TestDir::new("cancel"); - let (mut library, id) = library(); - let library_store = LibraryStore::new(dir.join("library.json")); - library_store.save(&mut library).unwrap(); - let before = std::fs::read(library_store.path()).unwrap(); - let original = library.repertoire(&id).unwrap().clone(); - let mut editor = RepertoireEditorUi::new(&library, id.clone()).unwrap(); - editor.select(child(&editor, 1)); - editor.set_selected_main_answer().unwrap(); - editor.set_selected_disabled(true).unwrap(); - editor.draft.repertoire_mut(&id).unwrap().set_max_plies(3); - assert!(editor.has_unsaved()); - - editor.cancel(); - - assert!(!editor.has_unsaved()); - assert_eq!(editor.draft.repertoire(&id), Some(&original)); - assert_eq!(editor.selected, editor.tree.root()); - assert_eq!(std::fs::read(library_store.path()).unwrap(), before); - } - - #[test] - fn rav_rows_are_indented_without_flattening_the_mainline() { - let (library, id) = library(); - let editor = RepertoireEditorUi::new(&library, id).unwrap(); - let rows = tree_rows(&editor.tree); - assert_eq!(rows.len(), 3); - assert_eq!(rows[0].indentation, 0); - assert!(!rows[0].variation); - assert_eq!(rows[1].indentation, 0); - assert!(!rows[1].variation); - assert_eq!(rows[2].indentation, 1); - assert!(rows[2].variation); - } -} diff --git a/apps/desktop/src/repertoire_training.rs b/apps/desktop/src/repertoire_training.rs deleted file mode 100644 index b31d060..0000000 --- a/apps/desktop/src/repertoire_training.rs +++ /dev/null @@ -1,1604 +0,0 @@ -#![allow(dead_code)] - -use std::{sync::mpsc, time::Duration}; - -use chess_core::shakmaty::{Chess, Color, Move, Position, Square, uci::UciMove}; -use chess_core::{Annotation, CommentPart, MoveKind, parse_comment}; -use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2}; -use trainer::repertoire::{ - Candidate, QueueMode, Repertoire, RepertoireTree, SessionError, SrsPolicy, StatsData, - StatsStore, TrainingMode, TrainingScope, TrainingSession, TrainingVerdict, -}; - -use crate::assets::Sound; -use crate::board::{Arrow, Badge, BoardState, BoardView}; -use crate::i18n::{tr, trf}; -use crate::settings::Settings; - -const WRONG_SHOWN: Duration = Duration::from_millis(400); - -pub enum TrainingAction { - Back, - Sound(Sound), - Toast(String), -} - -struct Flash { - after: Chess, - from: Square, - to: Square, - until: web_time::Instant, - wrong: bool, -} - -struct NextPathJob { - generation: u64, - rx: mpsc::Receiver<(u64, Result)>, -} - -#[derive(Default)] -pub(crate) struct BoardAnnotations { - pub(crate) arrows: Vec, - pub(crate) circles: Vec<(Square, Color32)>, - pub(crate) badge: Option, -} - -pub struct TrainingUi { - repertoire: Repertoire, - saved_stats: StatsData, - discard_requested: bool, - next_job: Option, - next_generation: u64, - mode: TrainingMode, - queue_mode: QueueMode, - policy: SrsPolicy, - session: TrainingSession, - store: StatsStore, - board: BoardState, - flipped: bool, - positions: Vec, - position_path_len: usize, - position_task_start: usize, - task_start: usize, - task_origin: Chess, - view_ply: usize, - flash: Option, - hint: Option<(Square, Square)>, - message: Option, - save_error: Option, - confirm_discard: bool, - completed_targets: usize, - target_limit: usize, -} - -impl TrainingUi { - #[cfg(test)] - pub fn new( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - store: StatsStore, - flipped: bool, - ) -> Result { - let policy = initial_policy(repertoire, &scope, mode, queue_mode, &stats); - Self::new_with_policy( - repertoire, scope, mode, queue_mode, stats, store, flipped, policy, - ) - } - - pub fn new_random( - repertoire: &Repertoire, - mode: TrainingMode, - stats: StatsData, - store: StatsStore, - flipped: bool, - ) -> Result { - let session = TrainingSession::new_random(repertoire, mode, stats, now())?; - let task_origin = if session.scope().include_context { - repertoire.game().start().position().clone() - } else { - session.scope_start_position().clone() - }; - let mut training = Self { - repertoire: repertoire.clone(), - saved_stats: session.stats().clone(), - discard_requested: false, - next_job: None, - next_generation: 0, - mode, - queue_mode: QueueMode::Practice, - policy: SrsPolicy::Due, - session, - store, - board: BoardState::default(), - flipped: match mode { - TrainingMode::White => false, - TrainingMode::Black => true, - TrainingMode::Both => flipped, - }, - positions: Vec::new(), - position_path_len: usize::MAX, - position_task_start: usize::MAX, - task_start: 0, - task_origin, - view_ply: 0, - flash: None, - hint: None, - message: None, - save_error: None, - confirm_discard: false, - completed_targets: 0, - target_limit: usize::MAX, - }; - training.save(); - Ok(training) - } - - #[allow(clippy::too_many_arguments, dead_code)] - pub fn new_with_policy( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - store: StatsStore, - flipped: bool, - policy: SrsPolicy, - ) -> Result { - let target_limit = target_count(repertoire, &scope, mode, queue_mode, policy, &stats); - let saved_stats = stats.clone(); - let session = if queue_mode == QueueMode::SpacedRepetition { - TrainingSession::scoped_srs(repertoire, scope, mode, stats, now(), policy)? - } else { - TrainingSession::scoped(repertoire, scope, mode, queue_mode, stats, now())? - }; - let task_origin = if session.scope().include_context { - repertoire.game().start().position().clone() - } else { - session.scope_start_position().clone() - }; - Ok(Self { - repertoire: repertoire.clone(), - saved_stats, - discard_requested: false, - next_job: None, - next_generation: 0, - mode, - queue_mode, - policy, - session, - store, - board: BoardState::default(), - flipped: match mode { - TrainingMode::White => false, - TrainingMode::Black => true, - TrainingMode::Both => flipped, - }, - positions: Vec::new(), - position_path_len: usize::MAX, - position_task_start: usize::MAX, - task_start: 0, - task_origin, - view_ply: 0, - flash: None, - hint: None, - message: None, - save_error: None, - confirm_discard: false, - completed_targets: 0, - target_limit, - }) - } - - fn is_path_practice(&self) -> bool { - self.mode == TrainingMode::Both || self.queue_mode == QueueMode::Practice - } - - pub fn repertoire_id(&self) -> &trainer::repertoire::RepertoireId { - &self.repertoire.id - } - - pub fn target_available(&self) -> bool { - !self.session.is_done() - && (self.session.target().is_some() - || (self.is_path_practice() && !self.session.candidates().is_empty())) - } - - pub fn stats(&self) -> &StatsData { - &self.saved_stats - } - - pub fn has_unsaved(&self) -> bool { - self.save_error.is_some() - } - - pub fn is_finished(&self) -> bool { - self.session.is_done() - } - - fn refresh_positions(&mut self) { - if self.position_path_len == self.session.path().len() - && self.position_task_start == self.task_start - { - return; - } - self.position_path_len = self.session.path().len(); - self.position_task_start = self.task_start; - self.positions.clear(); - // Replay the actual section from its full starting position. FEN4 is an - // identity key only: it deliberately omits move counters and history. - let mut position = self.task_origin.clone(); - self.positions.push(position.clone()); - for played in &self.session.path()[self.task_start..] { - let Some(mv) = played - .uci - .parse::() - .ok() - .and_then(|uci| uci.to_move(&position).ok()) - else { - self.positions.clear(); - self.positions.push(self.session.position().clone()); - self.view_ply = 0; - return; - }; - position.play_unchecked(mv); - self.positions.push(position.clone()); - } - self.view_ply = self.view_ply.min(self.positions.len().saturating_sub(1)); - if self.view_ply == 0 && !self.positions.is_empty() { - self.view_ply = self.positions.len() - 1; - } - } - - fn go_end(&mut self) { - self.view_ply = self.positions.len().saturating_sub(1); - } - - fn save(&mut self) { - match self.store.save(self.session.stats_mut()) { - Ok(()) => { - self.saved_stats = self.session.stats().clone(); - self.save_error = None; - } - Err(error) => self.save_error = Some(error.to_string()), - } - } - - fn play(&mut self, mv: Move) { - if self.is_finished() - || self.flash.is_some() - || self.save_error.is_some() - || self.next_job.is_some() - { - return; - } - let mut after = self.session.position().clone(); - after.play_unchecked(mv); - let from = mv.from().unwrap_or_else(|| mv.to()); - let to = crate::board::ui_target(&mv); - let verdict = self.session.play(mv, now()); - match verdict { - Ok(TrainingVerdict::Right | TrainingVerdict::Finished) => { - self.completed_targets += usize::from(self.mode != TrainingMode::Both); - self.hint = None; - self.message = Some( - if self.queue_mode == QueueMode::SpacedRepetition - && self.session.attempts().last().is_some_and(|a| a.hinted) - { - tr("Accepted · it will be repeated sooner").to_owned() - } else { - tr("Move accepted").to_owned() - }, - ); - self.update_task_start(); - self.save(); - self.refresh_positions(); - self.go_end(); - } - Ok(TrainingVerdict::Wrong) => { - self.message = Some(tr("This move is not in the enabled repertoire. Try another move or show a hint.").to_owned()); - self.flash = Some(Flash { - after, - from, - to, - until: web_time::Instant::now() + WRONG_SHOWN, - wrong: true, - }); - self.save(); - } - Ok(TrainingVerdict::TryAgain) => { - self.message = - Some(tr("Choose a move from your repertoire or show a hint.").to_owned()); - } - Ok(TrainingVerdict::Done) => {} - Err(error) => self.message = Some(error.to_string()), - } - } - - fn restart(&mut self) { - if self.save_error.is_some() || self.next_job.is_some() { - return; - } - match self.session.restart(now()) { - Ok(()) => self.after_run_reset(), - Err(error) => self.message = Some(error.to_string()), - } - } - - fn next_path(&mut self) { - if self.save_error.is_some() || self.next_job.is_some() || !self.is_path_practice() { - return; - } - let prepared = match self.session.prepare_next_path() { - Ok(prepared) => prepared, - Err(error) => { - self.message = Some(error.to_string()); - return; - } - }; - let repertoire = self.repertoire.clone(); - let (tx, rx) = mpsc::channel(); - self.next_generation = self.next_generation.wrapping_add(1); - let generation = self.next_generation; - self.next_job = Some(NextPathJob { generation, rx }); - if let Err(error) = crate::platform::spawn("repertoire-training-next", move || { - let result = prepared - .run(&repertoire, now()) - .map_err(|error| error.to_string()); - let _ = tx.send((generation, result)); - }) { - self.next_job = None; - self.message = Some(error.to_string()); - } - } - - fn poll_next(&mut self) { - let (generation, result) = { - let Some(job) = &self.next_job else { - return; - }; - match job.rx.try_recv() { - Ok(result) => result, - Err(mpsc::TryRecvError::Empty) => return, - Err(mpsc::TryRecvError::Disconnected) => ( - job.generation, - Err("next-path worker stopped without a result".to_owned()), - ), - } - }; - self.apply_next(generation, result); - } - - fn apply_next(&mut self, generation: u64, result: Result) { - if generation != self.next_generation - || self - .next_job - .as_ref() - .is_none_or(|job| job.generation != generation) - { - return; - } - self.next_job = None; - match result { - Ok(session) => { - self.session = session; - self.after_run_reset(); - self.save(); - } - Err(error) => self.message = Some(error.to_string()), - } - } - - #[cfg(test)] - fn deliver_next(&mut self) { - let (generation, result) = self - .next_job - .as_ref() - .expect("a pending next-path job") - .rx - .recv_timeout(Duration::from_secs(5)) - .expect("next-path worker result"); - self.apply_next(generation, result); - } - - fn after_run_reset(&mut self) { - self.completed_targets = 0; - self.target_limit = target_count( - &self.repertoire, - self.session.scope(), - self.mode, - self.queue_mode, - self.policy, - self.session.stats(), - ); - self.task_start = 0; - self.task_origin = if self.session.scope().include_context { - self.repertoire.game().start().position().clone() - } else { - self.session.scope_start_position().clone() - }; - self.flash = None; - self.hint = None; - self.message = None; - self.position_path_len = usize::MAX; - self.position_task_start = usize::MAX; - self.view_ply = 0; - self.board.clear(); - self.refresh_positions(); - self.go_end(); - } - - fn update_task_start(&mut self) { - if self.is_path_practice() { - return; - } - if self.session.target().is_some() { - self.task_origin = if self.session.scope().include_context { - self.repertoire.game().start().position().clone() - } else { - self.session.position().clone() - }; - } - self.task_start = match self.session.target() { - Some(target) if self.session.scope().include_context => { - self.session.path().len().saturating_sub(target.path.len()) - } - Some(_) => self.session.path().len(), - None => self.task_start, - }; - } - - fn keyboard(&mut self, ui: &Ui, actions: &mut Vec) { - if ui.ctx().egui_wants_keyboard_input() || self.next_job.is_some() { - return; - } - let mut command = None; - ui.input_mut(|input| { - if input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W)) - || (!self.board.is_busy() && input.consume_key(Modifiers::NONE, Key::Escape)) - { - command = Some("back"); - } else if input.consume_key(Modifiers::NONE, Key::F) { - command = Some("flip"); - } else if input.consume_key(Modifiers::NONE, Key::L) - || input.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) - { - command = Some("engine"); - } else if self.is_finished() && input.consume_key(Modifiers::NONE, Key::Enter) { - command = Some(if self.is_path_practice() { - "next" - } else { - "restart" - }); - } else if input.consume_key(Modifiers::NONE, Key::ArrowLeft) { - command = Some("left"); - } else if input.consume_key(Modifiers::NONE, Key::ArrowRight) { - command = Some("right"); - } else if input.consume_key(Modifiers::NONE, Key::Home) { - command = Some("home"); - } else if input.consume_key(Modifiers::NONE, Key::End) { - command = Some("end"); - } - }); - match command { - Some("back") => { - if self.save_error.is_some() { - self.confirm_discard = true; - } else { - actions.push(TrainingAction::Back); - } - } - Some("flip") => self.flipped = !self.flipped, - Some("engine") => actions.push(TrainingAction::Toast( - tr("The engine is off while training").to_owned(), - )), - Some("restart") => self.restart(), - Some("next") => self.next_path(), - Some("left") => self.view_ply = self.view_ply.saturating_sub(1), - Some("right") => { - self.view_ply = (self.view_ply + 1).min(self.positions.len().saturating_sub(1)); - } - Some("home") => self.view_ply = 0, - Some("end") => self.go_end(), - _ => {} - } - } - - fn board(&mut self, ui: &mut Ui, settings: &Settings, actions: &mut Vec) { - self.refresh_positions(); - let normal = self - .positions - .get(self.view_ply) - .cloned() - .unwrap_or_else(|| self.session.position().clone()); - let (position, alert) = match &self.flash { - Some(flash) => ( - flash.after.clone(), - flash.wrong.then_some((flash.from, flash.to)), - ), - None => (normal, None), - }; - let last_move = self.flash.as_ref().map(|f| (f.from, f.to)).or_else(|| { - self.view_ply.checked_sub(1).and_then(|index| { - let mv = self.session.path().get(self.task_start + index)?; - let before = self.positions.get(index)?; - let mv = mv.uci.parse::().ok()?.to_move(before).ok()?; - Some(( - mv.from().unwrap_or_else(|| mv.to()), - crate::board::ui_target(&mv), - )) - }) - }); - let annotations = if self.view_ply + 1 == self.positions.len() { - pgn_annotations(&self.session) - } else { - BoardAnnotations::default() - }; - let mut arrows = annotations.arrows; - arrows.extend(self.hint.map(|(from, to)| Arrow { - from, - to, - color: Color32::from_rgba_unmultiplied(21, 120, 27, 190), - weight: 1.0, - })); - let circles = annotations.circles; - let area = ui.available_rect_before_wrap(); - let side = area.width().min(area.height()).max(1.0).floor(); - let left = area.left() + ((area.width() - side) / 2.0).max(0.0).floor(); - let top = area.top() + ((area.height() - side) / 2.0).max(0.0).floor(); - let rect = egui::Rect::from_min_size(egui::pos2(left, top), vec2(side, side)); - ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { - let view = BoardView { - pos: &position, - orientation: if self.flipped { - Color::Black - } else { - Color::White - }, - last_move, - arrows: &arrows, - circles: &circles, - badge: annotations.badge, - interactive: !self.is_finished() - && self.flash.is_none() - && self.save_error.is_none() - && self.next_job.is_none() - && self.view_ply + 1 == self.positions.len(), - show_coords: settings.show_coords, - theme: settings.board_theme.theme(), - pieces: settings.piece_set, - animation: settings.animation.seconds(), - premove: None, - auto_queen: false, - alert, - }; - if let Some(mv) = view.show(ui, &mut self.board) { - if self.view_ply + 1 == self.positions.len() { - self.play(mv); - if self.flash.is_some() { - if self.flash.as_ref().is_some_and(|f| f.wrong) { - actions.push(TrainingAction::Sound(Sound::Wrong)); - } - } else if self.is_finished() { - actions.push(TrainingAction::Sound(Sound::Success)); - } else { - actions.push(TrainingAction::Sound(Sound::Move)); - } - } else { - self.go_end(); - } - } - }); - } - - fn task_card(&self, ui: &mut Ui) { - let frame = card(ui, self.flash.as_ref().is_some_and(|f| f.wrong)); - frame.show(ui, |ui| { - ui.set_width(ui.available_width()); - let position = self.session.position(); - let heading = if self.is_path_practice() { - tr("Continue the variation").to_owned() - } else { - trf( - "Task {current} of {total}", - &[ - ( - "current", - &(self.completed_targets + 1).min(self.target_limit.max(1)), - ), - ("total", &self.target_limit), - ], - ) - }; - ui.label(RichText::new(heading).strong().size(15.0)); - ui.label( - RichText::new(if position.turn() == Color::White { - tr("♔ White to move") - } else { - tr("♚ Black to move") - }) - .strong(), - ); - ui.label(tr(if self.mode == TrainingMode::Both { - "Play both sides. Any enabled move is accepted." - } else { - "Your turn: play any move from your repertoire. The program will reply." - })); - if self.session.candidates().len() > 1 { - ui.label(tr("Several continuations are available. Choose the variation you want to practise.")); - } - }); - } - - fn user_card(&mut self, ui: &mut Ui) { - let alert = self.flash.as_ref().is_some_and(|f| f.wrong); - card(ui, alert).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label( - RichText::new(trf( - "Mistakes: {n}", - &[("n", &self.session.total_mistakes())], - )) - .size(15.0), - ); - if let Some(message) = &self.message { - ui.label(RichText::new(message).color(if alert { - ui.visuals().error_fg_color - } else { - ui.visuals().text_color() - })); - } - if self.session.hinted() { - ui.label(RichText::new(tr("With hint")).weak()); - } - if self.session.may_hint() - && self.hint.is_none() - && self.flash.is_none() - && ui.link(tr("I don't remember — show a move")).clicked() - && let Some(candidate) = self.session.hint(now()) - { - self.hint = move_squares(&candidate); - self.save(); - } - }); - } - - fn preparing(&self, ui: &mut Ui) { - card(ui, false).show(ui, |ui| { - ui.horizontal(|ui| { - ui.spinner(); - ui.label(tr("Preparing the training session…")); - }); - }); - } - - fn result(&mut self, ui: &mut Ui, actions: &mut Vec) { - card(ui, false).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label( - RichText::new(if self.is_path_practice() { - tr("Branch complete") - } else { - tr("Training complete") - }) - .strong() - .size(17.0), - ); - if let Some(message) = &self.message { - ui.label(message); - } - if self.is_path_practice() { - let played = self - .session - .path() - .iter() - .filter(|mv| !mv.automatic) - .count(); - ui.label(trf( - "Your moves: {n} · mistakes: {m}", - &[("n", &played), ("m", &self.session.total_mistakes())], - )); - ui.label(if self.session.hinted() { - tr("With hint") - } else { - tr("Without hint") - }); - } else { - let correct = self.session.attempts().iter().filter(|a| a.correct).count(); - ui.label(trf( - "Tasks: {n} · correct: {c} · wrong attempts: {w} · with hint: {h}", - &[ - ("n", &self.completed_targets), - ("c", &correct), - ("w", &self.session.total_mistakes()), - ( - "h", - &self.session.attempts().iter().filter(|a| a.hinted).count(), - ), - ], - )); - } - ui.add_space(6.0); - ui.horizontal_wrapped(|ui| { - if self.is_path_practice() { - if crate::widgets::primary(ui, tr("Next variation")) - .on_hover_text("Enter") - .clicked() - { - self.next_path(); - } - if ui.button(tr("Repeat path")).clicked() { - self.restart(); - } - } else if crate::widgets::primary(ui, tr("↻ Again")) - .on_hover_text("Enter") - .clicked() - { - self.restart(); - } - if ui.button(tr("Back to repertoire")).clicked() { - actions.push(TrainingAction::Back); - } - }); - }); - } - - fn save_strip(&mut self, ui: &mut Ui) { - let Some(error) = self.save_error.clone() else { - return; - }; - egui::Frame::new() - .fill(ui.visuals().extreme_bg_color) - .stroke(egui::Stroke::new(1.0, ui.visuals().error_fg_color)) - .inner_margin(egui::Margin::symmetric(8, 6)) - .show(ui, |ui| { - ui.label( - RichText::new(trf("Could not save changes: {error}", &[("error", &error)])) - .color(ui.visuals().error_fg_color), - ); - ui.horizontal_wrapped(|ui| { - if ui.button(tr("Retry")).clicked() { - self.save(); - } - if self.confirm_discard { - if ui.button(tr("Leave without saving")).clicked() { - self.discard_requested = true; - } - } else if ui.button(tr("Back to repertoire")).clicked() { - self.confirm_discard = true; - } - }); - if self.confirm_discard { - ui.label( - RichText::new(tr( - "Only the events that could not be saved will be discarded", - )) - .weak(), - ); - } - }); - } - - pub fn show( - &mut self, - ui: &mut Ui, - settings: &Settings, - name: &str, - mut manager: impl FnMut(&mut Ui), - ) -> Vec { - self.poll_next(); - let mut actions = Vec::new(); - if self.next_job.is_some() { - ui.ctx().request_repaint_after(Duration::from_millis(50)); - } - if let Some(flash) = &self.flash { - let left = flash - .until - .saturating_duration_since(web_time::Instant::now()); - if left.is_zero() { - self.flash = None; - } else { - ui.ctx().request_repaint_after(left); - } - } - self.keyboard(ui, &mut actions); - egui::Panel::top("repertoire_training_header").show(ui, |ui| { - ui.horizontal(|ui| { - if ui - .add_enabled( - self.next_job.is_none(), - egui::Button::new(format!("← {}", tr("Back to repertoire"))), - ) - .clicked() - { - if self.save_error.is_some() { - self.confirm_discard = true; - } else { - actions.push(TrainingAction::Back); - } - } - ui.separator(); - ui.label(mode_label(self.mode)); - ui.add(egui::Label::new(RichText::new(name).heading()).truncate()) - .on_hover_text(name); - }); - }); - let width = ui.available_width(); - let height = ui.available_height(); - let stacked = width < 900.0 && height > width; - if stacked { - let available = ui.available_rect_before_wrap(); - let panel_height = (height * 0.52).clamp(340.0, 520.0); - let board_rect = egui::Rect::from_min_max( - available.min, - egui::pos2(available.right(), available.bottom() - panel_height), - ); - let side_rect = egui::Rect::from_min_max( - egui::pos2(available.left(), board_rect.bottom()), - available.max, - ); - ui.scope_builder(egui::UiBuilder::new().max_rect(board_rect), |ui| { - egui::CentralPanel::default().show(ui, |ui| self.board(ui, settings, &mut actions)); - }); - ui.scope_builder(egui::UiBuilder::new().max_rect(side_rect), |ui| { - ui.set_clip_rect(side_rect); - egui::Frame::side_top_panel(ui.style()) - .show(ui, |ui| self.side(ui, &mut actions, &mut manager)); - }); - } else { - let side = egui::Panel::right("repertoire_workspace_side") - .resizable(true) - .default_size((width * 0.42).clamp(420.0, 560.0)) - .size_range(360.0..=(width - 220.0).max(360.0)) - .show(ui, |ui| self.side(ui, &mut actions, &mut manager)); - crate::widgets::check_panel("repertoire_training_side", &side.response); - egui::CentralPanel::default().show(ui, |ui| self.board(ui, settings, &mut actions)); - } - if self.next_job.is_some() { - self.discard_requested = false; - actions.retain(|action| !matches!(action, TrainingAction::Back)); - } - if self.save_error.is_some() && !self.discard_requested { - if actions - .iter() - .any(|action| matches!(action, TrainingAction::Back)) - { - self.confirm_discard = true; - } - actions.retain(|action| !matches!(action, TrainingAction::Back)); - } - if std::mem::take(&mut self.discard_requested) { - actions.push(TrainingAction::Back); - } - actions - } - - fn side( - &mut self, - ui: &mut Ui, - actions: &mut Vec, - manager: &mut impl FnMut(&mut Ui), - ) { - ui.spacing_mut().item_spacing.y = 8.0; - self.save_strip(ui); - if self.next_job.is_some() { - self.preparing(ui); - } else if self.is_finished() { - self.result(ui, actions); - } else { - self.task_card(ui); - self.user_card(ui); - } - if self.next_job.is_none() { - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - if ui - .add_sized([30.0, 26.0], egui::Button::new("🔃")) - .on_hover_text(tr("Flip board (F)")) - .clicked() - { - self.flipped = !self.flipped; - } - if !self.is_finished() && ui.button(tr("↻ Restart")).clicked() { - self.restart(); - } - }); - } - if self.next_job.is_none() - && self.view_ply + 1 < self.positions.len() - && ui - .link(tr("Viewing an earlier position · back to training — End")) - .clicked() - { - self.go_end(); - } - ui.separator(); - manager(ui); - } - - pub fn debug_hint(&mut self) { - if self.next_job.is_some() { - return; - } - if let Some(candidate) = self.session.hint(now()) { - self.hint = move_squares(&candidate); - self.save(); - } - } - - pub fn debug_moves(&mut self, moves: &str) { - for text in moves.split_whitespace() { - match text { - "hint" => self.debug_hint(), - "next" => { - self.next_path(); - #[cfg(test)] - if self.next_job.is_some() { - self.deliver_next(); - } - } - "repeat" => self.restart(), - _ => {} - } - if matches!(text, "hint" | "next" | "repeat") { - continue; - } - self.flash = None; - self.refresh_positions(); - let mv = text - .parse::() - .ok() - .and_then(|uci| uci.to_move(self.session.position()).ok()); - if let Some(mv) = mv { - self.play(mv); - } else { - self.message = Some(tr("Illegal move in the current position").to_owned()); - } - } - self.refresh_positions(); - self.go_end(); - } -} - -#[cfg(test)] -fn initial_policy( - repertoire: &Repertoire, - scope: &TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: &StatsData, -) -> SrsPolicy { - if queue_mode != QueueMode::SpacedRepetition { - return SrsPolicy::Due; - } - let tree = RepertoireTree::new(repertoire); - let due = stats.srs_queue(&tree, &repertoire.id, mode, now(), scope, SrsPolicy::Due); - if due.is_empty() { - SrsPolicy::Introduce - } else { - SrsPolicy::Due - } -} - -fn target_count( - repertoire: &Repertoire, - scope: &TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - policy: SrsPolicy, - stats: &StatsData, -) -> usize { - if mode == TrainingMode::Both || queue_mode == QueueMode::Practice { - return usize::MAX; - } - let tree = RepertoireTree::new(repertoire); - if queue_mode == QueueMode::SpacedRepetition { - stats - .srs_queue(&tree, &repertoire.id, mode, now(), scope, policy) - .len() - } else { - stats - .scoped_queue(&tree, &repertoire.id, mode, queue_mode, now(), scope) - .len() - } -} - -fn card(ui: &Ui, alert: bool) -> egui::Frame { - egui::Frame::new() - .inner_margin(egui::Margin::symmetric(10, 6)) - .corner_radius(4) - .stroke(egui::Stroke::new( - if alert { 1.5 } else { 1.0 }, - if alert { - ui.visuals().error_fg_color - } else { - ui.visuals().widgets.noninteractive.bg_stroke.color - }, - )) -} - -fn move_squares(candidate: &Candidate) -> Option<(Square, Square)> { - Some(( - candidate.mv.from().unwrap_or_else(|| candidate.mv.to()), - crate::board::ui_target(&candidate.mv), - )) -} - -fn pgn_annotations(session: &TrainingSession) -> BoardAnnotations { - pgn_annotations_at(session.game(), session.current_node()) -} - -pub(crate) fn pgn_annotations_at( - game: &chess_core::Game, - at: chess_core::NodeId, -) -> BoardAnnotations { - let mut out = BoardAnnotations::default(); - let Some(node) = game.node(at) else { - return out; - }; - let square = node.game_move().and_then(|game_move| match game_move.kind { - MoveKind::Normal(mv) => Some(crate::board::ui_target(&mv)), - MoveKind::Null => None, - }); - if let Some(square) = square { - out.badge = node - .nags() - .iter() - .copied() - .find(|nag| nag.is_move_assessment()) - .and_then(|nag| { - Some(Badge { - square, - text: nag.symbol()?, - color: crate::notation::assessment_color(nag)?, - }) - }); - } - for comment in node.comments_after() { - for part in parse_comment(comment) { - match part { - CommentPart::Annotation(Annotation::Arrows(list)) => { - out.arrows - .extend(list.into_iter().map(|(color, from, to)| Arrow { - from, - to, - color: crate::game_view::shape_color(color), - weight: 0.9, - })); - } - CommentPart::Annotation(Annotation::Squares(list)) => { - out.circles.extend( - list.into_iter() - .map(|(color, square)| (square, crate::game_view::shape_color(color))), - ); - } - CommentPart::Text(_) | CommentPart::Annotation(_) => {} - } - } - } - out -} - -pub fn mode_label(mode: TrainingMode) -> &'static str { - tr(match mode { - TrainingMode::White => "White", - TrainingMode::Black => "Black", - TrainingMode::Both => "Both", - }) -} - -pub fn now() -> i64 { - chrono::Local::now().timestamp() -} - -#[cfg(test)] -mod tests { - use super::*; - use chess_core::parse_str; - - fn training(pgn: &str, mode: TrainingMode, name: &str) -> TrainingUi { - training_queue( - pgn, - mode, - name, - QueueMode::ReviewInOrder, - TrainingScope::whole(), - ) - } - fn training_queue( - pgn: &str, - mode: TrainingMode, - name: &str, - queue: QueueMode, - scope: TrainingScope, - ) -> TrainingUi { - let game = parse_str(pgn).game; - let mut library = trainer::repertoire::Library::default(); - let id = library.create("Test", &game).unwrap(); - let store = StatsStore::new(std::env::temp_dir().join(format!( - "cp-desktop-training-{}-{name}-{}.json", - std::process::id(), - std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() - ))); - TrainingUi::new( - library.repertoire(&id).unwrap(), - scope, - mode, - queue, - StatsData::default(), - store, - false, - ) - .unwrap() - } - - fn assert_board_matches_session(training: &TrainingUi) { - let shown = training.positions.last().unwrap(); - assert_eq!( - trainer::repertoire::fen4(shown), - training.session.position_key() - ); - assert_eq!(training.view_ply + 1, training.positions.len()); - assert_eq!(shown.fullmoves(), training.session.position().fullmoves()); - assert_eq!(shown.halfmoves(), training.session.position().halfmoves()); - } - - #[test] - fn pgn_node_badges_keep_the_existing_palette_and_special_move_destinations() { - for (nag, symbol) in [ - (1, "!"), - (2, "?"), - (3, "!!"), - (4, "??"), - (5, "!?"), - (6, "?!"), - ] { - let game = chess_core::parse_str(&format!("1. e4 ${nag} *")).game; - let node = game.main_child(chess_core::NodeId::ROOT).unwrap(); - let badge = pgn_annotations_at(&game, node).badge.unwrap(); - assert_eq!(badge.text, symbol); - assert_eq!(badge.square, Square::E4); - assert_eq!( - badge.color, - crate::notation::assessment_color(chess_core::Nag(nag)).unwrap() - ); - } - for (fen, san, expected) in [ - ("4k3/8/8/8/8/8/8/4K2R w K - 0 1", "O-O!!", Square::G1), - ("4k3/P7/8/8/8/8/8/4K3 w - - 0 1", "a8=Q+!", Square::A8), - ] { - let game = - chess_core::parse_str(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. {san} *")) - .game; - let node = game.main_child(chess_core::NodeId::ROOT).unwrap(); - assert_eq!( - pgn_annotations_at(&game, node).badge.unwrap().square, - expected - ); - } - let game = chess_core::parse_str("1. e4 $14 *").game; - let node = game.main_child(chess_core::NodeId::ROOT).unwrap(); - assert!( - pgn_annotations_at(&game, node).badge.is_none(), - "position assessments are not move badges" - ); - } - - #[test] - fn pgn_badges_and_shapes_are_shown_for_the_current_move() { - use chess_core::{Nag, ShapeColor}; - - let mut training = training( - "1. e4!! {[%cal Re2e4,Ge7e5] [%csl Ye4,Re5]} e5?! {[%cal Bg1f3]} *", - TrainingMode::Both, - "annotations", - ); - training.debug_moves("e2e4"); - let annotations = pgn_annotations(&training.session); - let badge = annotations.badge.unwrap(); - assert_eq!(badge.text, "!!"); - assert_eq!(badge.square, Square::E4); - assert_eq!( - badge.color, - crate::notation::assessment_color(Nag::BRILLIANT_MOVE).unwrap() - ); - assert_eq!(annotations.arrows.len(), 2); - assert!(annotations.arrows.iter().any(|arrow| { - arrow.from == Square::E2 - && arrow.to == Square::E4 - && arrow.color == crate::game_view::shape_color(ShapeColor::Red) - })); - assert!(annotations.arrows.iter().any(|arrow| { - arrow.from == Square::E7 - && arrow.to == Square::E5 - && arrow.color == crate::game_view::shape_color(ShapeColor::Green) - })); - assert_eq!(annotations.circles.len(), 2); - assert!(annotations.circles.iter().any(|(square, color)| { - *square == Square::E4 && *color == crate::game_view::shape_color(ShapeColor::Yellow) - })); - assert!(annotations.circles.iter().any(|(square, color)| { - *square == Square::E5 && *color == crate::game_view::shape_color(ShapeColor::Red) - })); - - training.debug_moves("e7e5"); - let annotations = pgn_annotations(&training.session); - assert_eq!(annotations.badge.unwrap().text, "?!"); - assert!(annotations.arrows.iter().any(|arrow| { - arrow.from == Square::G1 - && arrow.to == Square::F3 - && arrow.color == crate::game_view::shape_color(ShapeColor::Blue) - })); - } - - #[test] - fn practice_accepts_users_branch_and_keeps_board_in_sync_for_both_single_colors() { - let pgn = "1. e4 (1. d4 d5 2. c4) e5 (1... c5 2. Nf3) 2. Bc4 *"; - let mut white = training_queue( - pgn, - TrainingMode::White, - "practice-white", - QueueMode::Practice, - TrainingScope::whole(), - ); - assert!(white.target_available()); - assert!(white.session.may_hint()); - white.debug_moves("d2d4 c2c4"); - assert!(white.is_finished()); - assert_eq!(white.session.total_mistakes(), 0); - assert_board_matches_session(&white); - white.debug_moves("next"); - assert!(!white.is_finished()); - assert_board_matches_session(&white); - - let mut black = training_queue( - pgn, - TrainingMode::Black, - "practice-black", - QueueMode::Practice, - TrainingScope::whole().with_context(false), - ); - assert!(black.target_available()); - black.debug_moves("c7c5"); - assert!(black.is_finished()); - assert_board_matches_session(&black); - black.debug_moves("repeat"); - assert!(!black.is_finished()); - assert_board_matches_session(&black); - } - - #[test] - fn replay_preserves_fen_counters_and_move_numbers() { - let mut training = training( - "[SetUp \"1\"]\n[FEN \"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 7 17\"]\n\n17. Nf3 Nf6 18. Nc3 Nc6 *", - TrainingMode::Both, - "fen-counters", - ); - training.debug_moves("g1f3 g8f6 b1c3 b8c6"); - assert!(training.is_finished()); - assert_board_matches_session(&training); - assert_eq!( - training - .positions - .iter() - .map(|p| p.fullmoves().get()) - .collect::>(), - vec![17, 17, 18, 18, 19] - ); - assert_eq!(training.positions[0].halfmoves(), 7); - assert_eq!(training.positions.last().unwrap().halfmoves(), 11); - } - - #[test] - fn explicit_due_does_not_silently_introduce_new_targets() { - let mut training = training("1. e4 e5 *", TrainingMode::White, "explicit-due"); - let due = TrainingUi::new_with_policy( - &training.repertoire, - TrainingScope::whole(), - TrainingMode::White, - QueueMode::SpacedRepetition, - StatsData::default(), - training.store.clone(), - false, - SrsPolicy::Due, - ) - .unwrap(); - assert!(!due.target_available()); - training.debug_moves("e2e4"); - assert!(training.is_finished()); - } - - #[test] - fn context_hidden_sections_replay_from_their_actual_start() { - let seed = training( - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", - TrainingMode::White, - "hidden-context", - ); - let mut training = TrainingUi::new( - &seed.repertoire, - TrainingScope::from_prefix(vec!["e2e4".into(), "e7e5".into(), "g1f3".into()]) - .with_context(false), - TrainingMode::White, - QueueMode::ReviewInOrder, - StatsData::default(), - seed.store.clone(), - false, - ) - .unwrap(); - training.debug_moves("g1f3"); - assert_board_matches_session(&training); - assert_eq!(training.positions[0].fullmoves().get(), 3); - training.debug_moves("f1b5"); - assert!(training.is_finished()); - assert_board_matches_session(&training); - assert_eq!(training.positions.last().unwrap().fullmoves().get(), 4); - } - - #[test] - fn one_side_targets_have_independent_paths_and_current_boards() { - let mut training = training( - "1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 *", - TrainingMode::White, - "sections", - ); - training.debug_moves("e2e4"); - assert_eq!(training.session.target().unwrap().expected_uci, "g1f3"); - assert_eq!(training.task_start, 2); - assert_board_matches_session(&training); - - training.debug_moves("g1f3"); - assert_eq!(training.session.target().unwrap().expected_uci, "d2d4"); - assert_eq!(training.task_start, 6); - assert_board_matches_session(&training); - - training.debug_moves("d2d4"); - assert!(training.is_finished()); - assert_board_matches_session(&training); - let section = &training.session.path()[training.task_start..]; - assert_eq!(section.last().unwrap().uci, "c5d4"); - } - - #[test] - fn pgn_answers_one_side_but_both_has_no_automatic_moves() { - let pgn = "1. e4 e5 2. Nf3 Nc6 *"; - let mut black = training(pgn, TrainingMode::Black, "pgn-black"); - assert_eq!(black.session.path().len(), 1); - assert_eq!(black.session.path()[0].uci, "e2e4"); - assert!(black.session.path()[0].automatic); - black.debug_moves("e7e5"); - assert!( - black - .session - .path() - .iter() - .any(|played| { played.uci == "g1f3" && played.automatic }) - ); - assert!( - black - .session - .path() - .iter() - .filter(|played| !played.automatic) - .all(|played| played.uci == "e7e5") - ); - - let mut both = training(pgn, TrainingMode::Both, "pgn-both"); - assert!(both.session.path().is_empty()); - both.debug_moves("e2e4 e7e5 g1f3 b8c6"); - assert!(both.is_finished()); - assert!(both.session.path().iter().all(|played| !played.automatic)); - } - - #[test] - fn both_next_path_and_result_finish_on_the_actual_last_move() { - let mut training = training( - "1. e4 e5 (1... c5) 2. Nf3 (2. c4) *", - TrainingMode::Both, - "next-path", - ); - training.debug_moves("e2e4 c7c5"); - assert!(training.is_finished()); - assert_board_matches_session(&training); - - training.debug_moves("next e2e4 e7e5 c2c4"); - assert!(training.is_finished()); - assert_eq!(training.session.path().last().unwrap().uci, "c2c4"); - assert_board_matches_session(&training); - } - - #[test] - fn random_next_saves_its_cursor_without_a_move_and_repeat_does_not_advance_it() { - let fixture = training( - "1. e4 e5 (1... c5) 2. Nf3 (2. c4) *", - TrainingMode::Both, - "random-cursor-save", - ); - let mut random = TrainingUi::new_random( - &fixture.repertoire, - TrainingMode::Both, - StatsData::default(), - fixture.store.clone(), - false, - ) - .unwrap(); - assert!(random.save_error.is_none()); - assert_eq!(random.session.queue_mode(), QueueMode::Practice); - let initial = serde_json::to_value(random.session.stats()).unwrap(); - assert_eq!(initial["random_practice_cursors"][0]["position"], 1); - assert_eq!( - serde_json::to_value(random.store.load().unwrap()).unwrap(), - initial - ); - - random.debug_moves("next"); - assert!(random.save_error.is_none()); - assert!(random.session.attempts().is_empty()); - assert_board_matches_session(&random); - let next = serde_json::to_value(random.session.stats()).unwrap(); - assert_eq!(next["random_practice_cursors"][0]["position"], 2); - assert_eq!( - serde_json::to_value(random.store.load().unwrap()).unwrap(), - next - ); - - random.debug_moves("repeat"); - assert_eq!(serde_json::to_value(random.session.stats()).unwrap(), next); - assert_board_matches_session(&random); - } - - #[test] - fn async_next_blocks_duplicate_work_and_applies_delivery_exactly_once() { - let fixture = training( - "1. e4 e5 (1... c5) 2. Nf3 (2. c4) *", - TrainingMode::Both, - "async-next-delivery", - ); - let mut random = TrainingUi::new_random( - &fixture.repertoire, - TrainingMode::Both, - StatsData::default(), - fixture.store.clone(), - false, - ) - .unwrap(); - random.debug_moves(""); - let old_path = random.session.path().to_vec(); - let old_scope = random.session.scope().clone(); - let old_positions = random.positions.clone(); - let old_stats = serde_json::to_vec(random.session.stats()).unwrap(); - let generation = random.next_generation; - - random.next_path(); - assert!(random.next_job.is_some()); - assert_eq!(random.next_generation, generation.wrapping_add(1)); - assert_eq!(random.session.path(), old_path); - assert_eq!(random.positions, old_positions); - assert_eq!( - serde_json::to_vec(random.session.stats()).unwrap(), - old_stats - ); - random.next_path(); - assert_eq!(random.next_generation, generation.wrapping_add(1)); - random.restart(); - assert_eq!(random.session.scope(), &old_scope); - assert_eq!(random.session.path(), old_path); - - random.deliver_next(); - assert!(random.next_job.is_none()); - assert!(random.session.attempts().is_empty()); - assert_board_matches_session(&random); - let delivered_stats = serde_json::to_value(random.session.stats()).unwrap(); - assert_eq!(delivered_stats["random_practice_cursors"][0]["position"], 2); - assert_eq!( - serde_json::to_value(random.store.load().unwrap()).unwrap(), - delivered_stats - ); - let delivered_path = random.session.path().to_vec(); - random.poll_next(); - assert_eq!(random.session.path(), delivered_path); - assert_eq!( - serde_json::to_value(random.session.stats()).unwrap(), - delivered_stats - ); - } - - #[test] - fn async_next_computation_error_preserves_the_current_session() { - let mut training = training_queue( - "1. e4 e5 *", - TrainingMode::Both, - "async-next-error", - QueueMode::Practice, - TrainingScope::from_prefix(vec!["e2e4".into()]), - ); - training.debug_moves(""); - let old_path = training.session.path().to_vec(); - let old_scope = training.session.scope().clone(); - let old_positions = training.positions.clone(); - let old_stats = serde_json::to_vec(training.session.stats()).unwrap(); - training.repertoire.pgn = parse_str("1. d4 d5 *").game.to_pgn(); - - training.next_path(); - training.deliver_next(); - assert!(training.next_job.is_none()); - assert!( - training - .message - .as_ref() - .is_some_and(|message| message.contains("invalid training scope")) - ); - assert_eq!(training.session.path(), old_path); - assert_eq!(training.session.scope(), &old_scope); - assert_eq!(training.positions, old_positions); - assert_eq!( - serde_json::to_vec(training.session.stats()).unwrap(), - old_stats - ); - assert_board_matches_session(&training); - } - - #[test] - fn async_next_save_error_remains_visible_after_successful_computation() { - let fixture = training( - "1. e4 e5 (1... c5) 2. Nf3 *", - TrainingMode::Both, - "async-next-save-error", - ); - let mut random = TrainingUi::new_random( - &fixture.repertoire, - TrainingMode::Both, - StatsData::default(), - fixture.store.clone(), - false, - ) - .unwrap(); - let mut external = random.store.load().unwrap(); - random.store.save(&mut external).unwrap(); - - random.next_path(); - random.deliver_next(); - assert!(random.next_job.is_none()); - assert!(random.save_error.is_some()); - assert!(random.has_unsaved()); - assert_eq!(random.session.stats().revision, 1); - assert_board_matches_session(&random); - } - - #[test] - fn late_mainline_scope_end_is_accepted() { - let game = - parse_str("1. e4 e5 (1... c5) 2. Nf3 (2. c4) Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O *").game; - let mut library = trainer::repertoire::Library::default(); - let id = library.create("Scoped", &game).unwrap(); - let repertoire = library.repertoire(&id).unwrap(); - let end = [ - "e2e4", "e7e5", "g1f3", "b8c6", "f1b5", "a7a6", "b5a4", "g8f6", - ] - .map(str::to_owned) - .to_vec(); - let tree = RepertoireTree::new(repertoire); - let actual = tree - .game() - .mainline() - .into_iter() - .filter_map(|node| tree.game().game_move(node).and_then(|mv| mv.uci())) - .take(end.len()) - .collect::>(); - assert_eq!(actual, end); - assert!(tree.node_at_path(&end).is_some()); - let scope = - TrainingScope::between(["e2e4", "e7e5", "g1f3"].map(str::to_owned).to_vec(), end); - TrainingSession::scoped( - repertoire, - scope, - TrainingMode::White, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - } -} diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs index 6cb4ba5..623b470 100644 --- a/apps/desktop/src/repertoire_ui.rs +++ b/apps/desktop/src/repertoire_ui.rs @@ -1,33 +1,39 @@ +//! Opening training (docs/design/opening-trainer-v2-spec.md): the «Repertoires» screen +//! with its card and dialogs, and the way to the «Session» and «Lines» screens. + use std::collections::{BTreeSet, HashMap}; use std::path::{Path, PathBuf}; use std::sync::{ Arc, - atomic::{AtomicBool, Ordering}, + atomic::{AtomicBool, AtomicU64, Ordering}, mpsc::{self, Receiver, Sender}, }; +use std::time::Duration; -use chess_core::shakmaty::{Position, uci::UciMove}; +use chess_core::shakmaty::{Chess, Color, Position, Square}; use chess_core::{Game, NodeId, PgnDatabase, Severity}; -use egui::{Key, Modifiers, RichText, Ui}; +use egui::{Key, Modifiers, RichText, Ui, vec2}; use trainer::repertoire::{ - LearningAggregate, LearningItemKey, LearningPriority, LearningSessionPhase, - LearningSessionSnapshot, LearningSide, LearningStore, LearningStoreData, Library, LibraryStore, - MergeReport, QueueMode, RepertoireId, RepertoireTree, ResetImpactProjection, - ScopedLearningAggregate, SrsSettings, StatsScope, TrainingMode, TrainingScope, + LearningData, LearningItemKey, LearningSide, LearningStore, LearningStoreData, Library, + LibraryStore, MergeReport, RepertoireId, ResetImpactProjection, SrsSettings, StatsScope, active_learning_keys, aggregate_scope, fen4, reset_impact, }; +use web_time::Instant; -use crate::board::{BoardState, BoardView}; +use crate::board::BoardState; use crate::i18n::{tr, trf}; -use crate::learning_dashboard::{LearningDashboardAction, LearningDashboardUi}; -use crate::learning_training::{LearningTrainingAction as TrainingAction, LearningTrainingUi}; -use crate::repertoire_editor::{RepertoireEditorAction, RepertoireEditorUi}; +use crate::opening_layout::{self as layout, BoardAnnotations, GAP, NEW_PER_SESSION}; +use crate::opening_lines::{LinesAction, OpeningLinesUi}; +use crate::opening_session::{ + OpeningSessionUi, PreparingView, SessionAction, SessionKind, show_preparing, +}; use crate::settings::Settings; pub enum RepertoireAction { Close, OpenSettings, Sound(crate::assets::Sound), + #[allow(dead_code)] Toast(String), SettingsChanged, Added { @@ -37,94 +43,211 @@ pub enum RepertoireAction { }, } -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -struct OpeningLabel { - eco: String, - name: String, +const CARD_H: f32 = 166.0; +const ROW_H: f32 = 24.0; +const HEADER_H: f32 = 26.0; +const MESSAGE_H: f32 = 20.0; +const BOTTOM_H: f32 = 30.0; +const BOTTOM_W: f32 = 150.0; +const MAIN_W: f32 = 170.0; +const LINES_W: f32 = 110.0; +const THIRD_W: f32 = 150.0; +const DIALOG_W: f32 = 460.0; +/// A session appears at once when it is ready this fast; otherwise «Preparing…». +const PREPARING_SHOWN_AFTER: Duration = Duration::from_millis(300); +const MESSAGE_SHOWN: Duration = Duration::from_secs(6); +/// Seconds per question in «About {t} min». +const SECONDS_PER_MOVE: usize = 20; +const WARNING_ROWS: usize = 3; +static NEXT_JOB: AtomicU64 = AtomicU64::new(1); + +/// What the table and the board need of a repertoire, from its PGN (indexed off the +/// frame). +#[derive(Clone)] +struct RowIndex { + start: Chess, + last_move: Option<(Square, Square)>, + has_moves: bool, } -struct LibraryRow { - id: RepertoireId, - name: String, - openings: Vec, +/// The counts of a repertoire for its colour, "today" meaning until the end of the day. +#[derive(Clone, Debug, Default, PartialEq)] +struct RowStats { + total: usize, + due: usize, + unseen: usize, + learning: usize, + learnt: usize, + /// The next review after today and how many moves are due that day. + next: Option<(i64, usize)>, } -const OPENING_LINES: usize = 5; -const ROW_VERTICAL_PADDING: f32 = 8.0; -const ROW_BOTTOM_PADDING: f32 = 4.0; -const TITLE_HEIGHT: f32 = 24.0; -const TITLE_GAP: f32 = 12.0; -const OPENING_HEIGHT: f32 = 20.0; -const OPENING_GAP: f32 = 2.0; - -impl LibraryRow { - fn height() -> f32 { - ROW_VERTICAL_PADDING - + ROW_BOTTOM_PADDING - + TITLE_HEIGHT - + TITLE_GAP - + OPENING_HEIGHT * OPENING_LINES as f32 - + OPENING_GAP * (OPENING_LINES - 1) as f32 +impl RowStats { + fn new_today(&self) -> usize { + self.unseen.min(NEW_PER_SESSION) } - fn visible_openings(&self) -> &[OpeningLabel] { - &self.openings[..self.openings.len().min(OPENING_LINES)] + fn today(&self) -> usize { + self.due + self.new_today() } } +#[derive(Clone, Debug, PartialEq, Eq)] +struct StatsKey { + library_revision: u64, + learning_revision: u64, + sides: Vec<(RepertoireId, LearningSide)>, + day: i64, +} + +/// The card's states (spec §3). +#[derive(Clone, Debug, PartialEq)] +enum CardState { + Review { due: usize, new: usize }, + OnlyNew { new: usize }, + Done { next: Option<(i64, usize)> }, + Empty, + OtherColor, + Counting, + Failed(String), +} + +fn card_state(has_moves: Option, stats: Option<&Result>) -> CardState { + match stats { + None => CardState::Counting, + Some(Err(error)) => CardState::Failed(error.clone()), + Some(Ok(stats)) if stats.total == 0 => { + if has_moves == Some(true) { + CardState::OtherColor + } else { + CardState::Empty + } + } + Some(Ok(stats)) if stats.due > 0 => CardState::Review { + due: stats.due, + new: stats.new_today(), + }, + Some(Ok(stats)) if stats.unseen > 0 => CardState::OnlyNew { + new: stats.new_today(), + }, + Some(Ok(stats)) => CardState::Done { next: stats.next }, + } +} + +/// A PGN read for «Import PGN» or «Add PGN to this repertoire». struct ImportPreview { library: Library, id: RepertoireId, - records: usize, + base_revision: u64, + games: usize, + /// Lines of the result, and before the merge (an added file). + lines: usize, + lines_before: usize, + /// Own moves for White and for Black. + own: [usize; 2], + suggested: LearningSide, + default_name: String, + warnings: Vec, report: MergeReport, - name: String, +} + +impl ImportPreview { + fn own(&self, side: LearningSide) -> usize { + match side { + LearningSide::White => self.own[0], + LearningSide::Black => self.own[1], + } + } +} + +struct ImportDialog { + job: u64, + /// `None`: a new repertoire. target: Option, -} - -struct LibraryLoadError { - message: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -struct AggregateKey { - id: RepertoireId, + preview: Option, + name: String, side: LearningSide, - library_revision: u64, - learning_revision: u64, - minute: i64, + error: Option, + cancel: Arc, +} + +enum Dialog { + Import(ImportDialog), + New { + name: String, + side: LearningSide, + error: Option, + }, + Rename { + id: RepertoireId, + name: String, + error: Option, + select_all: bool, + }, + Color { + id: RepertoireId, + to: LearningSide, + job: u64, + count: Option, + }, + Reset { + id: RepertoireId, + job: u64, + impact: Option<(ResetImpactProjection, BTreeSet)>, + busy: bool, + }, + Delete { + id: RepertoireId, + }, +} + +enum Screen { + Repertoires, + Session(Box), + Lines(Box), +} + +struct Preparing { + job: u64, + since: Instant, + id: RepertoireId, + name: String, + kind: SessionKind, +} + +struct Message { + text: String, + error: bool, + until: Option, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum StartKind { - Review, - IntroduceNew, - Unavailable, -} - -struct SharedReset { - impact: Option, - keys: BTreeSet, - confirmed: bool, - busy: bool, +enum MenuItem { + Train, + ReviewAll, + Lines, + Rename, + SwitchColor, + AddPgn, + Export, + Reset, + Delete, } enum Event { - Aggregated(AggregateKey, Box>), + Indexed(u64, HashMap), + Stats(StatsKey, HashMap>), + Imported(u64, Result), + Exported(Result, String>), + SessionReady(u64, Result, String>), + LinesReady(u64, Option>), + LearningLoaded(Result), + OtherSide(u64, Result), ResetImpact( u64, - Box), String>>, + Result<(ResetImpactProjection, BTreeSet), String>, ), - LearningReset(u64, Box>), - ReviewReset(u64, Box>), - Indexed( - u64, - HashMap>, - HashMap>, - HashMap, - ), - TrainingReady(u64, Result, String>), - Imported(Result), - Exported(Result<(), String>), + ResetDone(u64, Result), } struct AddFromGame { @@ -132,19 +255,7 @@ struct AddFromGame { at: NodeId, selected: Option, name: String, -} - -#[cfg(test)] -#[derive(Clone, Copy, Debug, Default)] -struct TestLayout { - status: Option, - message: Option, - retry: Option, - cancel: Option, - table: Option, - reset_review: Option, - editor: Option, - action_buttons: [Option; 3], + side: LearningSide, } pub struct RepertoireUi { @@ -154,46 +265,31 @@ pub struct RepertoireUi { learning: LearningStoreData, library_error: Option, learning_error: Option, - error: Option, selected: Option, - initial_selection_pending: bool, - parameters_open: bool, + index: HashMap, + index_job: u64, + stats: HashMap>, + stats_key: Option, + screen: Screen, + /// The «Lines» screen a branch session was started from. + lines_return: Option>, + preparing: Option, + lines_job: Option, + /// The answers are being read again after a session. + learning_loading: bool, + dialog: Option, + message: Option, + search: String, scroll_to_selected: bool, - tree: Option>, - trees: HashMap>, - openings: HashMap>, - variant_counts: HashMap, - aggregates: HashMap>>, - index_generation: u64, - indexing: bool, - preparing: bool, - training_generation: u64, - board: BoardState, - side: LearningSide, - queue: QueueMode, - priority: LearningPriority, - shared_reset: Option, - reset_generation: u64, - review_reset_pending: bool, - training: Option, - training_visible: bool, - training_name: String, - editor: Option, - editor_id: Option, - dashboard: Option, return_to_game: Option, add: Option, - edit_name: Option<(Option, String)>, - delete: Option, - search: String, - import: Option, - cancel: Option>, + board: BoardState, tx: Sender, rx: Receiver, + initial_selection_pending: bool, debug_start: Option, debug_pending_moves: Option, - #[cfg(test)] - debug_layout: TestLayout, + debug_menu: bool, } impl RepertoireUi { @@ -201,16 +297,16 @@ impl RepertoireUi { let (library_store, learning_store) = stores(); Self::with_stores(library_store, learning_store) } + fn with_stores(library_store: LibraryStore, learning_store: LearningStore) -> Self { let (library, library_error) = match load_library(&library_store) { Ok(data) => (data, None), - Err(e) => (Library::default(), Some(e.message)), + Err(error) => (Library::default(), Some(error)), }; let (learning, learning_error) = match learning_store.load() { Ok(data) => (data, None), - Err(e) => (LearningStoreData::default(), Some(e.to_string())), + Err(error) => (LearningStoreData::default(), Some(error.to_string())), }; - let selected = library.repertoires.first().map(|r| r.id.clone()); let (tx, rx) = mpsc::channel(); let mut this = Self { library_store, @@ -219,140 +315,57 @@ impl RepertoireUi { learning, library_error, learning_error, - error: None, - selected, - initial_selection_pending: true, - parameters_open: false, + selected: None, + index: HashMap::new(), + index_job: 0, + stats: HashMap::new(), + stats_key: None, + screen: Screen::Repertoires, + lines_return: None, + preparing: None, + lines_job: None, + learning_loading: false, + dialog: None, + message: None, + search: String::new(), scroll_to_selected: true, - tree: None, - trees: HashMap::new(), - openings: HashMap::new(), - variant_counts: HashMap::new(), - aggregates: HashMap::new(), - index_generation: 0, - indexing: false, - preparing: false, - training_generation: 0, - board: BoardState::default(), - side: LearningSide::White, - queue: QueueMode::SpacedRepetition, - priority: LearningPriority::default(), - shared_reset: None, - reset_generation: 0, - review_reset_pending: false, - training: None, - training_visible: false, - training_name: String::new(), - editor: None, - editor_id: None, - dashboard: None, return_to_game: None, add: None, - edit_name: None, - delete: None, - search: String::new(), - import: None, - cancel: None, + board: BoardState::default(), tx, rx, + initial_selection_pending: true, debug_start: None, debug_pending_moves: None, - #[cfg(test)] - debug_layout: TestLayout::default(), + debug_menu: false, }; - this.rebuild_tree(); + this.selected = this.sorted_ids().first().cloned(); + this.reindex(); this } pub fn has_unsaved(&self) -> bool { - self.training - .as_ref() - .is_some_and(LearningTrainingUi::has_unsaved) - || self - .editor - .as_ref() - .is_some_and(RepertoireEditorUi::has_unsaved) - } - pub fn resolve_unsaved(&mut self) { - if self - .training - .as_ref() - .is_some_and(LearningTrainingUi::has_unsaved) - { - self.training_visible = true; + match &self.screen { + Screen::Session(session) => session.has_unsaved(), + Screen::Repertoires | Screen::Lines(_) => false, } } - fn open_dashboard(&mut self) { - if self.has_unsaved() || self.training_visible || self.preparing || self.editor.is_some() { - return; - } - self.dashboard = Some(match self.selected.clone() { - Some(id) if self.library.repertoire(&id).is_some() => { - LearningDashboardUi::new_for_repertoire( - self.library.clone(), - self.learning_store.clone(), - id, - self.side, - ) - } - _ => LearningDashboardUi::new(self.library.clone(), self.learning_store.clone()), - }); - } - fn open_editor(&mut self) { - if self.has_unsaved() || self.training_visible || self.preparing || self.editor.is_some() { - return; - } - let Some(id) = self.selected.clone() else { - return; - }; - match RepertoireEditorUi::new(&self.library, id.clone()) { - Ok(mut editor) => { - editor.set_learning(&self.learning.learning); - self.editor = Some(editor); - self.editor_id = Some(id); - self.error = None; - } - Err(error) => self.error = Some(error.to_string()), - } - } - fn close_editor(&mut self) { - self.editor = None; - self.editor_id = None; - } - fn handle_editor_action(&mut self, action: RepertoireEditorAction) -> Option { - match action { - RepertoireEditorAction::OpenSettings => return Some(RepertoireAction::OpenSettings), - RepertoireEditorAction::Close | RepertoireEditorAction::Cancel => self.close_editor(), - RepertoireEditorAction::Applied { - repertoire_id, - library, - } => { - let current = self.editor_id.as_ref() == Some(&repertoire_id) - && self.selected.as_ref() == Some(&repertoire_id) - && self.library.revision.saturating_add(1) == library.revision; - if current { - self.library = library; - self.error = None; - self.rebuild_tree(); - } - self.close_editor(); - } - RepertoireEditorAction::Error(error) => self.error = Some(error), - } - None - } + + /// The window is being closed with an answer not saved: show the session. + pub fn resolve_unsaved(&mut self) {} + pub fn open_library(&mut self) { - self.preparing = false; self.scroll_to_selected = true; - if self.training.is_some() { - self.reload_learning(); + if !matches!(self.screen, Screen::Session(_)) { + self.screen = Screen::Repertoires; } - self.training_visible = false; } - pub fn open_from_toast(&mut self, id: RepertoireId, title: String, settings: &Settings) { + + pub fn open_from_toast(&mut self, id: RepertoireId, title: String, _settings: &Settings) { self.return_to_game = Some(title); - self.select(id, settings); + self.select(id); } + pub fn open_add_from_game(&mut self, source: Game, at: NodeId, title: String) { self.return_to_game = Some(title); let start = fen4(source.start().position()); @@ -360,265 +373,161 @@ impl RepertoireUi { .library .repertoires .iter() - .find(|r| { - self.trees - .get(&r.id) - .is_some_and(|tree| fen4(tree.game().start().position()) == start) - }) + .find(|r| fen4(r.game().start().position()) == start) .map(|r| r.id.clone()); + // The colour of the move chosen in the game. + let side = match source.position_before(at).map(|p| p.turn()) { + Some(Color::Black) => LearningSide::Black, + _ => LearningSide::White, + }; self.add = Some(AddFromGame { source, at, selected, name: String::new(), + side, }); } - fn select(&mut self, id: RepertoireId, settings: &Settings) { + + fn sorted_ids(&self) -> Vec { + let mut rows: Vec<_> = self + .library + .repertoires + .iter() + .map(|r| (r.name.to_lowercase(), r.id.clone())) + .collect(); + rows.sort(); + rows.into_iter().map(|(_, id)| id).collect() + } + + fn select(&mut self, id: RepertoireId) { self.initial_selection_pending = false; - if self - .editor - .as_ref() - .is_some_and(RepertoireEditorUi::has_unsaved) - { - return; + if self.library.repertoire(&id).is_some() { + self.selected = Some(id); + self.scroll_to_selected = true; } - self.close_editor(); - self.preparing = false; - self.training_visible = false; - self.training = None; - self.scroll_to_selected = true; - self.selected = Some(id.clone()); - let (side, queue) = settings - .repertoire_modes - .get(id.as_str()) - .map(|(mode, queue)| { - let side = match mode { - TrainingMode::Black => LearningSide::Black, - TrainingMode::White | TrainingMode::Both => LearningSide::White, - }; - (side, *queue) - }) - .unwrap_or((LearningSide::White, QueueMode::SpacedRepetition)); - self.side = side; - self.queue = match queue { - QueueMode::ReviewInOrder | QueueMode::LeastRecent => queue, - QueueMode::Practice | QueueMode::SpacedRepetition => QueueMode::SpacedRepetition, - }; - self.priority = settings - .repertoire_priorities - .get(id.as_str()) - .copied() - .unwrap_or_default(); - self.invalidate_reset_jobs(); - self.update_selected_tree(); } - fn update_selected_tree(&mut self) { - self.tree = self - .selected + + fn selected_name(&self) -> String { + self.selected .as_ref() - .and_then(|id| self.trees.get(id)) - .cloned(); + .and_then(|id| self.library.repertoire(id)) + .map(|r| r.name.clone()) + .unwrap_or_default() } - fn rebuild_tree(&mut self) { - self.invalidate_reset_jobs(); - self.aggregates.clear(); - self.variant_counts.clear(); - self.index_generation += 1; - self.indexing = true; - self.preparing = false; - self.trees.clear(); - self.openings.clear(); - self.update_selected_tree(); - let generation = self.index_generation; + + fn show_message(&mut self, text: impl Into, error: bool) { + self.message = Some(Message { + text: text.into(), + error, + until: (!error).then(|| Instant::now() + MESSAGE_SHOWN), + }); + } + + fn reindex(&mut self) { + self.index_job = next_job(); + let job = self.index_job; let repertoires = self.library.repertoires.clone(); let tx = self.tx.clone(); if let Err(error) = crate::platform::spawn("repertoire-index", move || { - let mut trees = HashMap::new(); - let mut openings = HashMap::new(); - let mut variant_counts = HashMap::new(); - for r in repertoires { - let tree = Arc::new(RepertoireTree::from_game(r.game(), u32::MAX, Vec::new())); - openings.insert(r.id.clone(), opening_labels(&tree)); - variant_counts.insert(r.id.clone(), pgn_route_count(&tree)); - trees.insert(r.id.clone(), tree); - } - let _ = tx.send(Event::Indexed(generation, trees, openings, variant_counts)); + let index = repertoires + .into_iter() + .map(|r| { + let game = r.game(); + let start = layout::common_start(&game); + ( + r.id.clone(), + RowIndex { + start: layout::position_of(&game, start), + last_move: layout::last_move(&game, start), + has_moves: !game.children(NodeId::ROOT).is_empty(), + }, + ) + }) + .collect(); + let _ = tx.send(Event::Indexed(job, index)); }) { - self.indexing = false; - self.error = Some(error.to_string()); + self.show_message(error.to_string(), true); } } + + fn sides(&self, settings: &Settings) -> Vec<(RepertoireId, LearningSide)> { + self.sorted_ids() + .into_iter() + .map(|id| { + let side = layout::side_of(settings, &id); + (id, side) + }) + .collect() + } + + /// Recount in the background when the library, the answers, a colour or the day + /// changed; the previous numbers stay meanwhile. + fn request_stats(&mut self, settings: &Settings) { + if self.library_error.is_some() || self.learning_error.is_some() { + return; + } + let today = layout::end_of_today(); + let key = StatsKey { + library_revision: self.library.revision, + learning_revision: self.learning.revision, + sides: self.sides(settings), + day: today, + }; + if self.stats_key.as_ref() == Some(&key) { + return; + } + self.stats_key = Some(key.clone()); + let library = self.library.clone(); + let learning = self.learning.learning.clone(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-stats", move || { + let stats = key + .sides + .iter() + .map(|(id, side)| (id.clone(), row_stats(&library, &learning, id, *side, today))) + .collect(); + let _ = tx.send(Event::Stats(key, stats)); + }) { + self.show_message(error.to_string(), true); + } + } + + fn reload_learning(&mut self) { + self.learning_loading = true; + let store = self.learning_store.clone(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-learning-load", move || { + let _ = tx.send(Event::LearningLoaded( + store.load().map_err(|error| error.to_string()), + )); + }) { + self.learning_loading = false; + self.show_message(error.to_string(), true); + } + } + + /// Writes the library; on success it is the one shown. fn persist(&mut self, mut library: Library) -> bool { - if self.library_error.is_some() - || self - .editor - .as_ref() - .is_some_and(RepertoireEditorUi::has_unsaved) - { + if self.library_error.is_some() { return false; } match self.library_store.save(&mut library) { Ok(()) => { self.library = library; - self.error = None; - self.close_editor(); - self.trees.clear(); - self.rebuild_tree(); + self.reindex(); true } - Err(e) => { - self.error = Some(e.to_string()); + Err(error) => { + self.show_message( + trf("Could not save: {e}", &[("e", &error.to_string())]), + true, + ); false } } } - fn reload_learning(&mut self) { - match self.learning_store.load() { - Ok(data) => { - self.learning = data; - self.learning_error = None; - if let Some(editor) = &mut self.editor { - editor.set_learning(&self.learning.learning); - } - } - Err(error) => self.learning_error = Some(error.to_string()), - } - } - fn invalidate_reset_jobs(&mut self) { - self.reset_generation = self.reset_generation.wrapping_add(1); - self.shared_reset = None; - self.review_reset_pending = false; - } - fn begin_shared_reset(&mut self, scope: StatsScope) { - if self.has_unsaved() || self.preparing { - return; - } - self.invalidate_reset_jobs(); - let generation = self.reset_generation; - self.shared_reset = Some(SharedReset { - impact: None, - keys: BTreeSet::new(), - confirmed: false, - busy: false, - }); - let library = self.library.clone(); - let tx = self.tx.clone(); - if let Err(error) = crate::platform::spawn("repertoire-reset-impact", move || { - let result = reset_impact(&library, &scope) - .map_err(|error| error.to_string()) - .and_then(|impact| { - active_learning_keys(&library, &scope) - .map(|keys| (impact, keys)) - .map_err(|error| error.to_string()) - }); - let _ = tx.send(Event::ResetImpact(generation, Box::new(result))); - }) { - self.shared_reset = None; - self.error = Some(error.to_string()); - } - } - fn cancel_shared_reset(&mut self) { - self.reset_generation = self.reset_generation.wrapping_add(1); - self.shared_reset = None; - } - fn confirm_shared_reset(&mut self) { - if self.has_unsaved() || self.preparing { - return; - } - let Some(state) = &mut self.shared_reset else { - return; - }; - if !state.confirmed || state.busy || state.impact.is_none() || state.keys.is_empty() { - return; - } - state.busy = true; - let generation = self.reset_generation; - let keys = state.keys.clone(); - let store = self.learning_store.clone(); - let tx = self.tx.clone(); - if let Err(error) = crate::platform::spawn("repertoire-shared-reset", move || { - let result = store - .reset_learning(keys) - .map_err(|error| error.to_string()) - .and_then(|_| store.load().map_err(|error| error.to_string())); - let _ = tx.send(Event::LearningReset(generation, Box::new(result))); - }) { - if let Some(state) = &mut self.shared_reset { - state.busy = false; - } - self.error = Some(error.to_string()); - } - } - fn matches_review_snapshot(&self, snapshot: &LearningSessionSnapshot) -> bool { - self.selected.as_ref().is_some_and(|id| { - snapshot.session.mode == self.queue - && snapshot.stats_scope.repertoire_ids.len() == 1 - && snapshot.stats_scope.repertoire_ids.contains(id) - && snapshot.stats_scope.side == self.side - && snapshot.stats_scope.max_depth - == self - .library - .repertoire(id) - .map(|repertoire| repertoire.max_plies) - && snapshot.stats_scope.only_active - && snapshot.stats_scope.branch_root.is_none() - && snapshot.stats_scope.learning_priority == self.priority - }) - } - fn has_review_snapshot(&self) -> bool { - self.learning - .session_snapshots - .iter() - .any(|snapshot| self.matches_review_snapshot(snapshot)) - } - fn has_unfinished_review_snapshot(&self) -> bool { - self.learning.session_snapshots.iter().any(|snapshot| { - snapshot.phase != LearningSessionPhase::Finished - && self.matches_review_snapshot(snapshot) - }) - } - fn selected_start_kind(&self, summary: &LearningAggregate) -> StartKind { - if self.queue == QueueMode::SpacedRepetition && self.has_unfinished_review_snapshot() { - StartKind::Review - } else { - mode_start_kind(self.queue, summary) - } - } - fn review_snapshot(&self) -> Option { - self.learning - .session_snapshots - .iter() - .filter(|snapshot| self.matches_review_snapshot(snapshot)) - .max_by_key(|snapshot| snapshot.revision) - .cloned() - } - fn reset_review_cursor(&mut self) { - if self.queue == QueueMode::SpacedRepetition - || self.has_unsaved() - || self.preparing - || self.review_reset_pending - { - return; - } - let Some(mut snapshot) = self.review_snapshot() else { - return; - }; - self.invalidate_reset_jobs(); - let generation = self.reset_generation; - self.review_reset_pending = true; - let store = self.learning_store.clone(); - let tx = self.tx.clone(); - if let Err(error) = crate::platform::spawn("repertoire-review-reset", move || { - let result = store - .reset_review_order(&mut snapshot) - .map_err(|error| error.to_string()) - .and_then(|_| store.load().map_err(|error| error.to_string())); - let _ = tx.send(Event::ReviewReset(generation, Box::new(result))); - }) { - self.review_reset_pending = false; - self.error = Some(error.to_string()); - } - } + fn checked_name(&self, name: &str, excluding: Option<&RepertoireId>) -> Result { let name = name.split_whitespace().collect::>().join(" "); if name.is_empty() { @@ -640,162 +549,203 @@ impl RepertoireUi { } Ok(name) } - fn start(&mut self, settings: &mut Settings) { - if self.learning_error.is_some() - || self.library_error.is_some() - || self.has_unsaved() - || self.preparing - { + + fn start(&mut self, kind: SessionKind, settings: &Settings) { + if self.preparing.is_some() || self.has_unsaved() { return; } - let Some((id, name)) = self - .selected - .as_ref() - .and_then(|id| self.library.repertoire(id)) - .map(|r| (r.id.clone(), r.name.clone())) - else { + let Some(id) = self.selected.clone() else { return; }; - let Some((scope, summary)) = self - .selected_aggregate() - .map(|scoped| (scoped.scope.clone(), scoped.summary.clone())) - else { - return; - }; - let kind = self.selected_start_kind(&summary); - if kind == StartKind::Unavailable { - return; - } - let introduce_new = - self.queue == QueueMode::SpacedRepetition && kind == StartKind::IntroduceNew; - let scope = if self.queue == QueueMode::SpacedRepetition { - scope - } else { - scope.with_learning_priority(self.priority) - }; - let queue = self.queue; - let mode = training_mode(self.side); - let context_policy = settings - .repertoire_context_policies - .get(id.as_str()) - .copied() - .unwrap_or_default(); + let name = self.selected_name(); + let side = layout::side_of(settings, &id); + let scope = StatsScope::for_repertoire(id.clone(), side, layout::end_of_today()); let library = self.library.clone(); let store = self.learning_store.clone(); + let job = next_job(); let tx = self.tx.clone(); - self.training_generation += 1; - let generation = self.training_generation; - settings - .repertoire_modes - .insert(id.to_string(), (mode, queue)); - settings - .repertoire_priorities - .insert(id.to_string(), self.priority); - self.close_editor(); - self.invalidate_reset_jobs(); - self.training_name = name; - self.scroll_to_selected = true; - self.preparing = true; - if let Err(error) = crate::platform::spawn("repertoire-training-start", move || { - let result = LearningTrainingUi::new_with_policy( - library, - store, - scope, - SrsSettings::default(), - introduce_new, - false, - queue, - context_policy, - ) - .map(Box::new) - .map_err(|e| e.to_string()); - let _ = tx.send(Event::TrainingReady(generation, result)); - }) { - self.preparing = false; - self.error = Some(error.to_string()); - } - } - fn import_path( - &mut self, - path: PathBuf, - target: Option, - ctx: Option, - ) { - if self.cancel.is_some() { - return; - } - let cancel = Arc::new(AtomicBool::new(false)); - self.cancel = Some(cancel.clone()); - let tx = self.tx.clone(); - let base = self.library.clone(); - let result = crate::platform::spawn("repertoire-import", move || { - let result = read_import(&path, target, base, &cancel); - let _ = tx.send(Event::Imported(result)); - if let Some(ctx) = ctx { - ctx.request_repaint(); + let session_kind = kind.clone(); + let slow = debug_slow(); + if let Err(error) = crate::platform::spawn("repertoire-session-start", move || { + if let Some(slow) = slow { + std::thread::sleep(slow); } - }); - if let Err(e) = result { - self.cancel = None; - self.error = Some(e.to_string()); - } - } - fn pick_import(&mut self, target: Option, ctx: &egui::Context) { - if self.cancel.is_some() { + let result = OpeningSessionUi::new(library, store, scope, session_kind).map(Box::new); + let _ = tx.send(Event::SessionReady(job, result)); + }) { + self.show_message(error.to_string(), true); return; } + self.preparing = Some(Preparing { + job, + since: Instant::now(), + id, + name, + kind, + }); + } + + fn more_new(&mut self) { + let Screen::Session(session) = &self.screen else { + return; + }; + let Some(id) = self.selected.clone() else { + return; + }; + let snapshot = session.snapshot().clone(); + let orientation = session.orientation(); + let library = self.library.clone(); + let store = self.learning_store.clone(); + let job = next_job(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-session-more", move || { + let result = + OpeningSessionUi::more_new(library, store, snapshot, orientation).map(Box::new); + let _ = tx.send(Event::SessionReady(job, result)); + }) { + self.show_message(error.to_string(), true); + return; + } + self.preparing = Some(Preparing { + job, + since: Instant::now(), + id, + name: self.selected_name(), + kind: SessionKind::Daily, + }); + } + + fn open_lines(&mut self, settings: &Settings, cursor: Option>) { + let Some(id) = self.selected.clone() else { + return; + }; + let side = layout::side_of(settings, &id); + let library = self.library.clone(); + let learning = self.learning.learning.clone(); + let job = next_job(); + self.lines_job = Some(job); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-lines", move || { + let lines = OpeningLinesUi::new(&library, &learning, id, side, cursor).map(Box::new); + let _ = tx.send(Event::LinesReady(job, lines)); + }) { + self.lines_job = None; + self.show_message(error.to_string(), true); + } + } + + fn pick_import(&mut self, target: Option, ctx: &egui::Context) { + let job = next_job(); let cancel = Arc::new(AtomicBool::new(false)); - self.cancel = Some(cancel.clone()); + let base = self.library.clone(); let tx = self.tx.clone(); let ctx = ctx.clone(); - let base = self.library.clone(); - if let Err(e) = crate::platform::spawn("repertoire-import-dialog", move || { - let result = rfd::FileDialog::new() + let worker_cancel = cancel.clone(); + let worker_target = target.clone(); + if let Err(error) = crate::platform::spawn("repertoire-import-dialog", move || { + let picked = rfd::FileDialog::new() .add_filter("PGN", &["pgn", "PGN"]) - .pick_file() - .ok_or_else(|| tr("Cancelled").to_owned()) - .and_then(|path| read_import(&path, target, base, &cancel)); - let _ = tx.send(Event::Imported(result)); + .pick_file(); + let Some(path) = picked else { + let _ = tx.send(Event::Imported(job, Err(String::new()))); + ctx.request_repaint(); + return; + }; + let _ = tx.send(Event::Imported( + job, + read_import(&path, worker_target, base, &worker_cancel), + )); ctx.request_repaint(); }) { - self.cancel = None; - self.error = Some(e.to_string()); + self.show_message(error.to_string(), true); + return; } + self.dialog = Some(Dialog::Import(ImportDialog { + job, + target, + preview: None, + name: String::new(), + side: LearningSide::White, + error: None, + cancel, + })); } - fn confirm_import(&mut self, settings: &Settings) -> bool { - let Some(preview) = self.import.take() else { + + fn import_path(&mut self, path: PathBuf, target: Option) { + let job = next_job(); + let cancel = Arc::new(AtomicBool::new(false)); + let base = self.library.clone(); + let tx = self.tx.clone(); + let worker_cancel = cancel.clone(); + let worker_target = target.clone(); + if let Err(error) = crate::platform::spawn("repertoire-import", move || { + let _ = tx.send(Event::Imported( + job, + read_import(&path, worker_target, base, &worker_cancel), + )); + }) { + self.show_message(error.to_string(), true); + return; + } + self.dialog = Some(Dialog::Import(ImportDialog { + job, + target, + preview: None, + name: String::new(), + side: LearningSide::White, + error: None, + cancel, + })); + } + + /// Imports what the dialog shows. Returns whether it was saved. + fn confirm_import(&mut self, settings: &mut Settings) -> bool { + let Some(Dialog::Import(dialog)) = &self.dialog else { return false; }; - let result = self.merge_import(&preview); - match result { - Ok((library, id)) if self.persist(library.clone()) => { - self.select(id, settings); - true + let Some(preview) = &dialog.preview else { + return false; + }; + if preview.base_revision != self.library.revision { + let error = tr("The library changed; import the PGN again").to_owned(); + if let Some(Dialog::Import(dialog)) = &mut self.dialog { + dialog.error = Some(error); } - Ok(_) => { - self.import = Some(preview); - false - } - Err(e) => { - self.error = Some(e); - self.import = Some(preview); - false - } - } - } - fn merge_import(&self, preview: &ImportPreview) -> Result<(Library, RepertoireId), String> { - if preview.library.revision != self.library.revision { - return Err(tr("The library changed; import the PGN again").to_owned()); + return false; } let mut library = preview.library.clone(); - if preview.target.is_none() { - let name = self.checked_name(&preview.name, None)?; - library - .rename(&preview.id, name) - .map_err(|e| e.to_string())?; + let id = preview.id.clone(); + let target = dialog.target.clone(); + let side = dialog.side; + if target.is_none() { + match self.checked_name(&dialog.name, None) { + Ok(name) => { + if let Err(error) = library.rename(&id, name) { + if let Some(Dialog::Import(dialog)) = &mut self.dialog { + dialog.error = Some(error.to_string()); + } + return false; + } + } + Err(error) => { + if let Some(Dialog::Import(dialog)) = &mut self.dialog { + dialog.error = Some(error); + } + return false; + } + } } - Ok((library, preview.id.clone())) + if !self.persist(library) { + return false; + } + if target.is_none() { + layout::set_side(settings, &id, side); + } + self.dialog = None; + self.select(id); + true } + fn export(&mut self, ctx: Option) { let Some(r) = self .selected @@ -807,156 +757,317 @@ impl RepertoireUi { let pgn = r.pgn.clone(); let name = format!("{}.pgn", r.name.replace(['/', '\\'], "_")); let tx = self.tx.clone(); - if let Err(e) = crate::platform::spawn("repertoire-export", move || { - let result = if let Some(path) = std::env::var_os("CP_REPERTOIRE_EXPORT_FILE") + if let Err(error) = crate::platform::spawn("repertoire-export", move || { + let path = std::env::var_os("CP_REPERTOIRE_EXPORT_FILE") .map(PathBuf::from) .or_else(|| { rfd::FileDialog::new() .set_file_name(name) .add_filter("PGN", &["pgn"]) .save_file() - }) { - chess_core::pgn::store::write_atomic(&path, pgn.as_bytes()) - .map_err(|e| e.to_string()) - } else { - Ok(()) + }); + let result = match path { + Some(path) => chess_core::pgn::store::write_atomic(&path, pgn.as_bytes()) + .map(|()| Some(path)) + .map_err(|error| error.to_string()), + None => Ok(None), }; let _ = tx.send(Event::Exported(result)); if let Some(ctx) = ctx { ctx.request_repaint(); } }) { - self.error = Some(e.to_string()); + self.show_message(error.to_string(), true); } } + + fn open_color_dialog(&mut self, settings: &Settings) { + let Some(id) = self.selected.clone() else { + return; + }; + let to = match layout::side_of(settings, &id) { + LearningSide::White => LearningSide::Black, + LearningSide::Black => LearningSide::White, + }; + let job = next_job(); + let library = self.library.clone(); + let tx = self.tx.clone(); + let scope = StatsScope::for_repertoire(id.clone(), to, layout::now()); + if let Err(error) = crate::platform::spawn("repertoire-other-side", move || { + let count = active_learning_keys(&library, &scope) + .map(|keys| keys.len()) + .map_err(|error| error.to_string()); + let _ = tx.send(Event::OtherSide(job, count)); + }) { + self.show_message(error.to_string(), true); + return; + } + self.dialog = Some(Dialog::Color { + id, + to, + job, + count: None, + }); + } + + fn open_reset_dialog(&mut self, settings: &Settings) { + let Some(id) = self.selected.clone() else { + return; + }; + let scope = + StatsScope::for_repertoire(id.clone(), layout::side_of(settings, &id), layout::now()); + let job = next_job(); + let library = self.library.clone(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-reset-impact", move || { + let result = reset_impact(&library, &scope) + .and_then(|impact| { + active_learning_keys(&library, &scope).map(|keys| (impact, keys)) + }) + .map_err(|error| error.to_string()); + let _ = tx.send(Event::ResetImpact(job, result)); + }) { + self.show_message(error.to_string(), true); + return; + } + self.dialog = Some(Dialog::Reset { + id, + job, + impact: None, + busy: false, + }); + } + + fn confirm_reset(&mut self) { + let Some(Dialog::Reset { + job, + impact: Some((_, keys)), + busy, + .. + }) = &mut self.dialog + else { + return; + }; + if *busy { + return; + } + *busy = true; + let job = *job; + let keys = keys.clone(); + let store = self.learning_store.clone(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-reset", move || { + let result = store + .reset_learning(keys) + .map_err(|error| error.to_string()) + .and_then(|_| store.load().map_err(|error| error.to_string())); + let _ = tx.send(Event::ResetDone(job, result)); + }) { + self.dialog = None; + self.show_message(error.to_string(), true); + } + } + + fn delete_selected(&mut self) { + let Some(Dialog::Delete { id }) = &self.dialog else { + return; + }; + let id = id.clone(); + let order = self.sorted_ids(); + let position = order.iter().position(|other| *other == id); + let mut library = self.library.clone(); + if let Err(error) = library.delete(&id) { + self.show_message(error.to_string(), true); + return; + } + if !self.persist(library) { + return; + } + self.dialog = None; + let order = self.sorted_ids(); + self.selected = position + .and_then(|position| order.get(position.min(order.len().saturating_sub(1)))) + .cloned(); + self.scroll_to_selected = true; + } + fn poll(&mut self, settings: &mut Settings) { if self.initial_selection_pending { self.initial_selection_pending = false; - if let Some(id) = self.selected.clone() { - self.select(id, settings); - } } while let Ok(event) = self.rx.try_recv() { match event { - Event::Aggregated(key, result) => { - if self.current_aggregate_key().as_ref() == Some(&key) - && let Err(error) = &*result - { - self.error = Some(error.clone()); - } - if let Some(value) = self.aggregates.get_mut(&key) { - *value = Some(*result); + Event::Indexed(job, index) => { + if job == self.index_job { + self.index = index; } } - Event::ResetImpact(generation, result) => { - if generation != self.reset_generation { + Event::Stats(key, stats) => { + if self.stats_key.as_ref() == Some(&key) { + self.stats = stats; + } + } + Event::Imported(job, result) => { + let Some(Dialog::Import(dialog)) = &mut self.dialog else { + continue; + }; + if dialog.job != job { continue; } - match *result { - Ok((impact, keys)) => { - if let Some(state) = &mut self.shared_reset { - state.impact = Some(impact); - state.keys = keys; - } - } - Err(error) => { - self.shared_reset = None; - self.error = Some(error); - } - } - } - Event::LearningReset(generation, result) => { - if generation != self.reset_generation { - continue; - } - match *result { - Ok(data) => { - self.learning = data; - self.learning_error = None; - self.shared_reset = None; - self.aggregates.clear(); - self.training = None; - self.training_visible = false; - self.reset_generation = self.reset_generation.wrapping_add(1); - } - Err(error) => { - if let Some(state) = &mut self.shared_reset { - state.busy = false; - } - self.error = Some(error); - } - } - } - Event::ReviewReset(generation, result) => { - if generation != self.reset_generation { - continue; - } - self.review_reset_pending = false; - match *result { - Ok(data) => { - self.learning = data; - self.learning_error = None; - self.aggregates.clear(); - self.training = None; - self.training_visible = false; - self.reset_generation = self.reset_generation.wrapping_add(1); - } - Err(error) => self.error = Some(error), - } - } - Event::Indexed(generation, trees, openings, variant_counts) => { - if generation == self.index_generation { - self.trees = trees; - self.openings = openings; - self.variant_counts = variant_counts; - self.indexing = false; - self.update_selected_tree(); - } - } - Event::TrainingReady(generation, result) => { - if generation != self.training_generation || !self.preparing { - continue; - } - self.preparing = false; match result { - Ok(training) if training.target_available() => { - self.training = Some(*training); - self.training_visible = true; + Ok(preview) => { + dialog.name = preview.default_name.clone(); + dialog.side = preview.suggested; + if let Some(target) = &dialog.target { + dialog.side = layout::side_of(settings, target); + } + dialog.preview = Some(preview); + } + // The file chooser was closed. + Err(error) if error.is_empty() => self.dialog = None, + Err(error) => { + self.dialog = None; + self.show_message(error, true); + } + } + } + Event::Exported(Ok(Some(path))) => { + self.show_message(trf("Saved to {path}", &[("path", &path.display())]), false) + } + Event::Exported(Ok(None)) => {} + Event::Exported(Err(error)) => { + self.show_message(trf("Could not save: {e}", &[("e", &error)]), true) + } + Event::SessionReady(job, result) => { + if self.preparing.as_ref().is_none_or(|p| p.job != job) { + continue; + } + self.preparing = None; + match result { + Ok(mut session) if session.target_available() => { + if let Screen::Lines(lines) = + std::mem::replace(&mut self.screen, Screen::Repertoires) + { + self.lines_return = Some(lines); + } + session.set_back_to_lines(self.lines_return.is_some()); + self.screen = Screen::Session(session); if let Some(moves) = self.debug_pending_moves.take() { self.debug_moves(&moves); } } - Ok(_) => self.error = Some(tr("No targets in this mode").to_owned()), - Err(error) => self.error = Some(error), + Ok(_) => { + self.screen_back_from_session(); + self.show_message(tr("Nothing to train here right now"), false); + } + Err(error) => { + self.screen_back_from_session(); + self.show_message(error, true); + } } } - Event::Imported(result) => { - let cancelled = self - .cancel - .take() - .is_some_and(|c| c.load(Ordering::Relaxed)); - if cancelled { + Event::LinesReady(job, lines) => { + if self.lines_job != Some(job) { continue; } - match result { - Ok(preview) => self.import = Some(preview), - Err(e) => self.error = Some(e), + self.lines_job = None; + if let Some(mut lines) = lines { + if let Ok(path) = std::env::var("CP_REPERTOIRE_LINE") { + let path: Vec = + path.split_whitespace().map(str::to_owned).collect(); + lines.debug_select(&path); + } + self.screen = Screen::Lines(lines); + } + } + Event::LearningLoaded(Ok(data)) => { + self.learning_loading = false; + self.learning = data; + self.learning_error = None; + } + Event::LearningLoaded(Err(error)) => { + self.learning_loading = false; + self.learning_error = Some(error); + } + Event::OtherSide(job, result) => { + if let Some(Dialog::Color { + job: expected, + count, + .. + }) = &mut self.dialog + && *expected == job + { + match result { + Ok(value) => *count = Some(value), + Err(error) => { + self.dialog = None; + self.show_message(error, true); + } + } + } + } + Event::ResetImpact(job, result) => { + if let Some(Dialog::Reset { + job: expected, + impact, + .. + }) = &mut self.dialog + && *expected == job + { + match result { + Ok(value) => *impact = Some(value), + Err(error) => { + self.dialog = None; + self.show_message(error, true); + } + } + } + } + Event::ResetDone(job, result) => { + if !matches!(&self.dialog, Some(Dialog::Reset { job: expected, .. }) if *expected == job) + { + continue; + } + self.dialog = None; + match result { + Ok(data) => { + self.learning = data; + self.learning_error = None; + } + Err(error) => self.show_message(error, true), } } - Event::Exported(Err(e)) => self.error = Some(e), - Event::Exported(Ok(())) => {} } } - if self.import.is_some() && std::env::var_os("CP_REPERTOIRE_CONFIRM_IMPORT").is_some() { + if std::env::var_os("CP_REPERTOIRE_CONFIRM_IMPORT").is_some() + && matches!(&self.dialog, Some(Dialog::Import(d)) if d.preview.is_some()) + { self.confirm_import(settings); } - if self.cancel.is_none() - && self.import.is_none() + if let Some(message) = &self.message + && message.until.is_some_and(|until| Instant::now() >= until) + { + self.message = None; + } + if self.preparing.is_none() + && self.dialog.is_none() && let Some(what) = self.debug_start.take() { self.debug_open(&what, settings); } + self.request_stats(settings); } + + fn screen_back_from_session(&mut self) { + self.screen = match self.lines_return.take() { + Some(lines) => Screen::Lines(lines), + None if matches!(self.screen, Screen::Lines(_)) => { + std::mem::replace(&mut self.screen, Screen::Repertoires) + } + None => Screen::Repertoires, + }; + } + pub fn show(&mut self, ui: &mut Ui, settings: &mut Settings) -> Vec { self.poll(settings); let mut actions = Vec::new(); @@ -964,1039 +1075,983 @@ impl RepertoireUi { let background = ui.visuals().window_fill(); ui.painter_at(available) .rect_filled(available, 0.0, background); - #[cfg(test)] - { - self.debug_layout.editor = None; + if self.preparing.is_some() || self.lines_job.is_some() { + ui.ctx().request_repaint_after(Duration::from_millis(50)); } - if self.training_visible && self.training.is_some() { - let mut training = self.training.take().expect("checked training session"); - let name = self.training_name.clone(); - let emitted = training.show(ui, settings, &name); - if self.training_visible { - self.training = Some(training); - } - for action in emitted { + if let Some(preparing) = &self.preparing + && preparing.since.elapsed() >= PREPARING_SHOWN_AFTER + { + let side = layout::side_of(settings, &preparing.id); + let index = self.index.get(&preparing.id); + let start = index.map(|row| row.start.clone()).unwrap_or_default(); + let subtitle = preparing.kind.subtitle(side); + let view = PreparingView { + name: &preparing.name, + subtitle: &subtitle, + back: if matches!(self.screen, Screen::Lines(_)) { + tr("⬅ Lines") + } else { + tr("⬅ Repertoires") + }, + position: &start, + orientation: layout::orientation(side), + last_move: index.and_then(|row| row.last_move), + lines: preparing.kind != SessionKind::Daily, + }; + for action in show_preparing(ui, settings, &mut self.board, &view) { match action { - TrainingAction::Back => { - self.reload_learning(); - self.training_visible = false; - self.scroll_to_selected = true; + SessionAction::Back => { + self.preparing = None; + self.screen_back_from_session(); } - TrainingAction::OpenSettings => actions.push(RepertoireAction::OpenSettings), - TrainingAction::Sound(sound) => actions.push(RepertoireAction::Sound(sound)), - TrainingAction::Toast(text) => actions.push(RepertoireAction::Toast(text)), + SessionAction::OpenSettings => actions.push(RepertoireAction::OpenSettings), + SessionAction::Sound(_) | SessionAction::MoreNew => {} } } return actions; } - if self.editor.is_some() { - #[cfg(test)] - { - self.debug_layout.editor = Some(ui.available_rect_before_wrap()); + match std::mem::replace(&mut self.screen, Screen::Repertoires) { + Screen::Session(mut session) => { + let name = self.selected_name(); + let emitted = session.show(ui, settings, &name); + self.screen = Screen::Session(session); + for action in emitted { + match action { + SessionAction::Back => { + self.reload_learning(); + self.screen_back_from_session(); + if let Screen::Lines(lines) = &mut self.screen { + lines.refresh(&self.library, &self.learning.learning); + } + self.scroll_to_selected = true; + } + SessionAction::OpenSettings => actions.push(RepertoireAction::OpenSettings), + SessionAction::Sound(sound) => actions.push(RepertoireAction::Sound(sound)), + SessionAction::MoreNew => self.more_new(), + } + } + return actions; } - let mut editor = self.editor.take().expect("checked repertoire editor"); - let emitted = editor.show(ui, settings, &self.library_store); - for action in emitted { - actions.extend(self.handle_editor_action(action)); + Screen::Lines(mut lines) => { + let emitted = lines.show(ui, settings); + self.screen = Screen::Lines(lines); + for action in emitted { + self.lines_action(action, settings, &mut actions); + } + return actions; } - if self.editor_id.is_some() { - self.editor = Some(editor); - } - return actions; + Screen::Repertoires => {} } - if self.dashboard.is_some() { - let mut dashboard = self.dashboard.take().expect("checked learning dashboard"); - let emitted = dashboard.show(ui, settings); - let close = emitted.contains(&LearningDashboardAction::Close); - if emitted.contains(&LearningDashboardAction::OpenSettings) { - actions.push(RepertoireAction::OpenSettings); - } - if close { - self.reload_learning(); - } else { - self.dashboard = Some(dashboard); - } - return actions; - } - if !ui.ctx().egui_wants_keyboard_input() - && !crate::app::overlay_open(ui.ctx()) - && self.add.is_none() - && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) - { - actions.push(RepertoireAction::Close); - } - egui::Panel::top("repertoire_header").show(ui, |ui| { - let back = if self.return_to_game.is_some() { - tr("← To game") - } else { - tr("← Databases") - }; - let (back, settings) = - crate::widgets::section_header(ui, back, tr("Opening training (α version)")); - if back { - actions.push(RepertoireAction::Close); - } - if settings { - actions.push(RepertoireAction::OpenSettings); - } - }); - self.show_workspace(ui, settings, &mut actions); - self.show_add(ui, &mut actions); - self.parameters_window(ui.ctx(), settings, &mut actions); + self.repertoires_screen(ui, settings, &mut actions); + self.show_dialog(ui.ctx(), settings, &mut actions); + self.show_add(ui, settings, &mut actions); actions } - fn errors(&mut self, ui: &mut Ui) { - let (rect, _) = - ui.allocate_exact_size(egui::vec2(ui.available_width(), 24.0), egui::Sense::hover()); - let mut status = ui.new_child( - egui::UiBuilder::new() - .max_rect(rect) - .layout(egui::Layout::left_to_right(egui::Align::Center)), - ); - let ui = &mut status; - ui.set_clip_rect(rect); - #[cfg(test)] - { - self.debug_layout.status = Some(rect); - self.debug_layout.message = None; - self.debug_layout.retry = None; - self.debug_layout.cancel = None; - } - let error = self - .library_error - .clone() - .or_else(|| self.learning_error.clone()) - .or_else(|| self.error.clone()); - let background = if self.indexing { - Some(tr("Indexing variations and ECO names…")) - } else if self.preparing { - Some(tr("Preparing the training session…")) - } else if self.cancel.is_some() { - Some(tr("Importing PGN…")) - } else { - None - }; - if background.is_some() { - ui.ctx() - .request_repaint_after(std::time::Duration::from_millis(100)); - } - let mut retry = false; - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if error.is_some() { - let response = ui.button(tr("Retry")); - retry = response.clicked(); - #[cfg(test)] - { - self.debug_layout.retry = Some(response.rect); - } + + fn lines_action( + &mut self, + action: LinesAction, + settings: &mut Settings, + actions: &mut Vec, + ) { + match action { + LinesAction::Back => { + self.screen = Screen::Repertoires; + self.scroll_to_selected = true; } - if self.cancel.is_some() { - let response = ui.button(tr("Cancel")); - if response.clicked() - && let Some(cancel) = &self.cancel - { - cancel.store(true, Ordering::Relaxed); - } - #[cfg(test)] - { - self.debug_layout.cancel = Some(response.rect); - } - } - if background.is_some() { - ui.add(egui::Spinner::new().size(16.0)); - } - if let Some(text) = error.as_deref().or(background) { - let hover = text.to_owned(); - let text = if error.is_some() { - RichText::new(text).color(ui.visuals().error_fg_color) + LinesAction::OpenSettings => actions.push(RepertoireAction::OpenSettings), + LinesAction::Train { through, label } => { + let kind = if through.is_empty() { + SessionKind::ReviewAll } else { - RichText::new(text) + SessionKind::Branch { through, label } }; - let response = ui.add(egui::Label::new(text).truncate().halign(egui::Align::Min)); - #[cfg(test)] + self.start(kind, settings); + } + LinesAction::SetDisabled { path, disabled } => { + let Screen::Lines(lines) = &self.screen else { + return; + }; + let id = lines.id().clone(); + let mut library = self.library.clone(); + let Some(repertoire) = library.repertoire_mut(&id) else { + return; + }; + if let Err(error) = repertoire.set_prefix_disabled(&path, disabled) { + self.show_message(error.to_string(), true); + return; + } + if self.persist(library) + && let Screen::Lines(lines) = &mut self.screen { - self.debug_layout.message = Some(response.rect); + lines.refresh(&self.library, &self.learning.learning); } - response.on_hover_text(hover); } - }); - if retry { - match load_library(&self.library_store) { - Ok(data) => { - self.library = data; - self.library_error = None; - self.rebuild_tree(); - } - Err(e) => self.library_error = Some(e.message), - } - self.reload_learning(); - self.error = None; } } - fn show_library(&mut self, ui: &mut Ui, settings: &Settings) { - self.errors(ui); - egui::Panel::bottom("repertoire_library_footer") - .resizable(false) - .exact_size(44.0) - .show(ui, |ui| { - ui.add_space(4.0); - ui.horizontal_wrapped(|ui| { - if ui - .add_sized([120.0, 28.0], egui::Button::new(tr("+ Create"))) - .clicked() - { - self.edit_name = Some((None, String::new())); - } - if ui - .add_enabled( - self.cancel.is_none() && self.library_error.is_none(), - egui::Button::new(tr("Import PGN…")).min_size(egui::vec2(120.0, 28.0)), + + fn keyboard(&mut self, ui: &Ui, settings: &mut Settings, actions: &mut Vec) { + if ui.ctx().egui_wants_keyboard_input() + || crate::app::overlay_open(ui.ctx()) + || self.dialog.is_some() + || self.add.is_some() + { + return; + } + let mut command = None; + ui.input_mut(|input| { + if input.consume_key(Modifiers::NONE, Key::Escape) { + command = Some("close"); + } else if input.consume_key(Modifiers::NONE, Key::ArrowDown) { + command = Some("down"); + } else if input.consume_key(Modifiers::NONE, Key::ArrowUp) { + command = Some("up"); + } else if input.consume_key(Modifiers::NONE, Key::Enter) { + command = Some("main"); + } + }); + let rows = self.visible_ids(); + let current = self + .selected + .as_ref() + .and_then(|id| rows.iter().position(|row| row == id)); + match command { + Some("close") => actions.push(RepertoireAction::Close), + Some("down") => { + let next = current.map_or(0, |i| (i + 1).min(rows.len().saturating_sub(1))); + if let Some(id) = rows.get(next).cloned() { + self.select(id); + } + } + Some("up") => { + let next = current.map_or(0, |i| i.saturating_sub(1)); + if let Some(id) = rows.get(next).cloned() { + self.select(id); + } + } + Some("main") => self.main_action(ui.ctx(), settings), + _ => {} + } + } + + fn visible_ids(&self) -> Vec { + let search = self.search.to_lowercase(); + self.sorted_ids() + .into_iter() + .filter(|id| { + self.library + .repertoire(id) + .is_some_and(|r| r.name.to_lowercase().contains(&search)) + }) + .collect() + } + + fn selected_card(&self) -> CardState { + let Some(id) = &self.selected else { + return CardState::Counting; + }; + if let Some(error) = self.library_error.clone().or(self.learning_error.clone()) { + return CardState::Failed(error); + } + card_state( + self.index.get(id).map(|row| row.has_moves), + self.stats.get(id), + ) + } + + /// The card's main button. + fn main_action(&mut self, ctx: &egui::Context, settings: &mut Settings) { + match self.selected_card() { + CardState::Review { .. } | CardState::OnlyNew { .. } => { + self.start(SessionKind::Daily, settings) + } + CardState::Done { .. } => self.start(SessionKind::ReviewAll, settings), + CardState::Empty => { + let target = self.selected.clone(); + self.pick_import(target, ctx); + } + CardState::OtherColor => self.open_color_dialog(settings), + CardState::Counting => {} + CardState::Failed(_) => self.retry_load(), + } + } + + fn retry_load(&mut self) { + match load_library(&self.library_store) { + Ok(library) => { + self.library = library; + self.library_error = None; + self.reindex(); + } + Err(error) => self.library_error = Some(error), + } + match self.learning_store.load() { + Ok(data) => { + self.learning = data; + self.learning_error = None; + } + Err(error) => self.learning_error = Some(error.to_string()), + } + self.stats_key = None; + self.stats.clear(); + } + + fn menu_item(&mut self, item: MenuItem, ctx: &egui::Context, settings: &mut Settings) { + match item { + MenuItem::Train => self.main_action(ctx, settings), + MenuItem::ReviewAll => self.start(SessionKind::ReviewAll, settings), + MenuItem::Lines => self.open_lines(settings, None), + MenuItem::Rename => { + if let Some(id) = self.selected.clone() { + self.dialog = Some(Dialog::Rename { + name: self.selected_name(), + id, + error: None, + select_all: true, + }); + } + } + MenuItem::SwitchColor => self.open_color_dialog(settings), + MenuItem::AddPgn => { + let target = self.selected.clone(); + self.pick_import(target, ctx); + } + MenuItem::Export => self.export(Some(ctx.clone())), + MenuItem::Reset => self.open_reset_dialog(settings), + MenuItem::Delete => { + if let Some(id) = self.selected.clone() { + self.dialog = Some(Dialog::Delete { id }); + } + } + } + } + + fn repertoires_screen( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + actions: &mut Vec, + ) { + self.keyboard(ui, settings, actions); + let back = if self.return_to_game.is_some() { + tr("⬅ To game") + } else { + tr("⬅ Library") + }; + let back = if ui.available_width() < 600.0 { + "⬅" + } else { + back + }; + let count = self.library.repertoires.len(); + let subtitle = if count == 0 { + String::new() + } else { + trf("{n} repertoires", &[("n", &count)]) + }; + let mut header = (false, false); + let mut menu = None; + layout::screen( + ui, + self, + |_, ui| { + header = crate::widgets::section_header_sub( + ui, + back, + tr("Opening training (α version)"), + &subtitle, + ) + }, + |this, ui| menu = this.panel(ui, settings), + |this, ui| this.preview_board(ui, settings), + ); + if header.0 { + actions.push(RepertoireAction::Close); + } + if header.1 { + actions.push(RepertoireAction::OpenSettings); + } + if let Some(item) = menu { + self.menu_item(item, ui.ctx(), settings); + } + } + + fn preview_board(&mut self, ui: &mut Ui, settings: &Settings) { + let row = self.selected.as_ref().and_then(|id| self.index.get(id)); + let position = row.map(|row| row.start.clone()).unwrap_or_default(); + let last_move = row.and_then(|row| row.last_move); + let side = self + .selected + .as_ref() + .map_or(LearningSide::White, |id| layout::side_of(settings, id)); + layout::still_board( + ui, + &mut self.board, + settings, + &position, + layout::orientation(side), + last_move, + &BoardAnnotations::default(), + ); + } + + /// The right panel; returns a chosen menu item (or the card's buttons). + fn panel(&mut self, ui: &mut Ui, settings: &Settings) -> Option { + let mut chosen = None; + let rect = ui.available_rect_before_wrap(); + ui.spacing_mut().item_spacing.y = GAP; + if self.library.repertoires.is_empty() { + self.empty_panel(ui, rect); + return None; + } + ui.add_space(4.0); + chosen = chosen.or(self.card(ui, settings)); + if self.library.repertoires.len() > 8 { + layout::fixed_block(ui, 24.0, |ui| { + ui.add( + egui::TextEdit::singleline(&mut self.search) + .hint_text(tr("Search")) + .desired_width(f32::INFINITY), + ); + }); + } + let table_h = (ui.available_height() - MESSAGE_H - BOTTOM_H - 3.0 * GAP).max(HEADER_H); + let table = layout::fixed_block(ui, table_h, |ui| self.table(ui, settings)); + chosen = chosen.or(table); + layout::fixed_block(ui, MESSAGE_H, |ui| self.message_strip(ui)); + layout::fixed_block(ui, BOTTOM_H, |ui| { + ui.horizontal(|ui| { + if ui + .add_enabled( + self.library_error.is_none(), + egui::Button::new(tr("Import PGN…")) + .truncate() + .min_size(vec2(BOTTOM_W, BOTTOM_H)), + ) + .clicked() + { + self.pick_import(None, ui.ctx()); + } + if ui + .add_enabled( + self.library_error.is_none(), + egui::Button::new(tr("New repertoire")) + .truncate() + .min_size(vec2(BOTTOM_W, BOTTOM_H)), + ) + .clicked() + { + self.dialog = Some(Dialog::New { + name: String::new(), + side: LearningSide::White, + error: None, + }); + } + }); + }); + chosen + } + + fn empty_panel(&mut self, ui: &mut Ui, rect: egui::Rect) { + let height = 200.0; + let top = rect.top() + ((rect.height() - height) / 2.0).max(0.0); + let area = + egui::Rect::from_min_size(egui::pos2(rect.left(), top), vec2(rect.width(), height)); + ui.scope_builder( + egui::UiBuilder::new() + .max_rect(area) + .layout(egui::Layout::top_down(egui::Align::Center)), + |ui| { + ui.heading(tr("No repertoires yet")); + ui.add_space(6.0); + ui.add( + egui::Label::new(RichText::new(tr("A repertoire is your opening moves as a PGN with variations. Import a file, or open any game, pick a move and choose “Add to repertoire…”.")).weak()) + .wrap(), + ); + ui.add_space(12.0); + if ui + .add_enabled_ui(self.library_error.is_none(), |ui| { + crate::widgets::primary_wide(ui, tr("Import PGN…"), BOTTOM_W) + }) + .inner + .clicked() + { + self.pick_import(None, ui.ctx()); + } + if ui + .add_enabled( + self.library_error.is_none(), + egui::Button::new(tr("New repertoire")).min_size(vec2(BOTTOM_W, 30.0)), + ) + .clicked() + { + self.dialog = Some(Dialog::New { + name: String::new(), + side: LearningSide::White, + error: None, + }); + } + if let Some(error) = &self.library_error { + ui.add_space(8.0); + ui.add( + egui::Label::new( + RichText::new(trf("Could not read the repertoires: {e}", &[("e", error)])) + .color(ui.visuals().warn_fg_color), ) - .clicked() - { - self.pick_import(None, ui.ctx()); + .wrap(), + ); + } + }, + ); + } + + fn card(&mut self, ui: &mut Ui, settings: &Settings) -> Option { + let Some(id) = self.selected.clone() else { + layout::fixed_block(ui, CARD_H, |_| {}); + return None; + }; + let state = self.selected_card(); + let stats = self + .stats + .get(&id) + .and_then(|stats| stats.as_ref().ok()) + .cloned(); + let side = layout::side_of(settings, &id); + let name = self.selected_name(); + let mut chosen = None; + layout::fixed_block(ui, CARD_H, |ui| { + let inner = vec2(ui.available_width() - 20.0, CARD_H - 12.0); + layout::card(ui, false, false).show(ui, |ui| { + ui.set_min_size(inner); + ui.set_max_size(inner); + ui.spacing_mut().item_spacing.y = 7.0; + let width = ui.available_width(); + // 1. The name and the colour. + layout::fixed_block(ui, 26.0, |ui| { + ui.horizontal(|ui| { + let you = format!("{} {}", layout::king(side), layout::you_play(side)); + let you_w = text_width(ui, &you, 14.0) + 8.0; + ui.allocate_ui_with_layout( + vec2((width - you_w).max(0.0), 26.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| layout::line(ui, RichText::new(&name).heading()), + ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(RichText::new(you).weak()); + }); + }); + }); + // 2. Today. + let (today, note) = card_texts(&state, side); + layout::fixed_block(ui, 22.0, |ui| { + let mut text = RichText::new(today).strong().size(15.0); + if matches!(state, CardState::Failed(_)) { + text = text.color(ui.visuals().warn_fg_color); } + layout::line(ui, text); + }); + // 3. Progress. + layout::fixed_block(ui, 28.0, |ui| progress(ui, stats.as_ref())); + // 4. A quiet explanation. + layout::fixed_block(ui, 20.0, |ui| { + layout::line(ui, RichText::new(note).weak()); + }); + // 5. Buttons. + layout::fixed_block(ui, 30.0, |ui| { + ui.horizontal(|ui| { + let (label, enabled, item) = main_button(&state, side); + let third = matches!(state, CardState::OnlyNew { .. }); + let gap = ui.spacing().item_spacing.x; + let room = ui.available_width(); + let (main_w, lines_w, third_w) = + if MAIN_W + LINES_W + THIRD_W + 2.0 * gap <= room || !third { + (MAIN_W, LINES_W, THIRD_W) + } else { + let rest = ((room - MAIN_W - 2.0 * gap) / 2.0).max(60.0); + (MAIN_W.min(room / 2.0), rest, rest) + }; + let response = ui + .add_enabled_ui(enabled, |ui| { + crate::widgets::primary_wide(ui, &label, main_w) + }) + .inner; + let response = if matches!(state, CardState::Counting) { + response.on_disabled_hover_text(tr("Counting moves…")) + } else { + response + }; + if response.clicked() { + chosen = item; + } + if ui + .add_enabled( + !matches!(state, CardState::Empty | CardState::Failed(_)), + egui::Button::new(tr("Lines…")) + .truncate() + .min_size(vec2(lines_w, 30.0)), + ) + .clicked() + { + chosen = Some(MenuItem::Lines); + } + if third + && ui + .add( + egui::Button::new(tr("Review all lines")) + .truncate() + .min_size(vec2(third_w, 30.0)), + ) + .clicked() + { + chosen = Some(MenuItem::ReviewAll); + } + }); }); }); - self.name_editor(ui, settings); - if self.import.is_some() { - self.import_preview(ui, settings); - } - if self.library.repertoires.is_empty() { - ui.heading(tr("No repertoires yet")); - ui.label(tr("Create an empty one or import PGN. You can also select a move in any game and choose “Add to repertoire…”.")); - } - if self.library.repertoires.len() > 8 { - ui.add(egui::TextEdit::singleline(&mut self.search).hint_text(tr("Search"))); - } - if let Some(id) = self.delete.clone() { - ui.separator(); - ui.label(tr( - "Delete repertoire? Source PGN files and learning history will not change.", - )); - ui.horizontal(|ui| { - if ui.button(tr("Cancel")).clicked() { - self.delete = None; - } - if ui.button(tr("Delete")).clicked() { - let mut library = self.library.clone(); - if library.delete(&id).is_ok() && self.persist(library) { - self.delete = None; - self.selected = None; - self.update_selected_tree(); - if let Some(next) = self.library.repertoires.first().map(|r| r.id.clone()) { - self.select(next, settings); - } else { - self.training_visible = false; - self.training = None; - } - } - } - }); - } + }); + chosen + } - let mut rows: Vec<_> = self - .library - .repertoires - .iter() - .filter(|r| r.name.to_lowercase().contains(&self.search.to_lowercase())) - .map(|r| LibraryRow { - id: r.id.clone(), - name: r.name.clone(), - openings: self.openings.get(&r.id).cloned().unwrap_or_default(), - }) - .collect(); - rows.sort_by_key(|r| r.name.to_lowercase()); - let scroll_row = if self.scroll_to_selected { + fn table(&mut self, ui: &mut Ui, settings: &Settings) -> Option { + let rows = self.visible_ids(); + let scroll_row = if std::mem::take(&mut self.scroll_to_selected) { rows.iter() - .position(|r| Some(&r.id) == self.selected.as_ref()) + .position(|id| Some(id) == self.selected.as_ref()) } else { None }; let mut clicked = None; - let mut import = None; - let mut export = None; - let mut edit = None; - ui.add_space(8.0); - let compact = ui.available_width() < 480.0; + let mut double = false; + let mut chosen = None; + let open_menu = std::mem::take(&mut self.debug_menu); ui.style_mut().interaction.selectable_labels = false; - #[cfg(test)] - let table_top = ui.next_widget_position(); - #[cfg(test)] - let table_width = ui.available_width(); let mut table = egui_extras::TableBuilder::new(ui) - .id_salt("repertoire_table") + .id_salt("opening_repertoires") .striped(true) .sense(egui::Sense::click()) .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) - .column(egui_extras::Column::remainder().at_least(120.0).clip(true)) - .column(egui_extras::Column::exact(52.0)) - .column(egui_extras::Column::exact(if compact { - 60.0 - } else { - 70.0 - })) - .column(egui_extras::Column::exact(28.0)); + .column(egui_extras::Column::remainder().at_least(80.0).clip(true)) + .column(egui_extras::Column::exact(22.0)) + .column(egui_extras::Column::exact(58.0)) + .column(egui_extras::Column::exact(70.0)) + .column(egui_extras::Column::exact(26.0)); if let Some(index) = scroll_row { - table = table.scroll_to_row(index, Some(egui::Align::Center)); - self.scroll_to_selected = false; + table = table.scroll_to_row(index, None); } table - .header(26.0, |mut header| { - for (column, key) in ["Name", "ECO", "Variants", ""].into_iter().enumerate() { + .header(HEADER_H, |mut header| { + header.col(|ui| { + ui.add(egui::Label::new(RichText::new(tr("Name")).strong()).truncate()); + }); + header.col(|_| {}); + for key in ["Today", "Learned"] { header.col(|ui| { - if column == 2 { - ui.with_layout( - egui::Layout::right_to_left(egui::Align::Center), - |ui| { - ui.add( - egui::Label::new(RichText::new(tr(key)).strong()) - .truncate(), - ); - }, - ); - } else { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add(egui::Label::new(RichText::new(tr(key)).strong()).truncate()); - } + }); }); } + header.col(|_| {}); }) .body(|body| { - body.rows(LibraryRow::height(), rows.len(), |mut row| { - let r = &rows[row.index()]; - row.set_selected(self.selected.as_ref() == Some(&r.id)); + body.rows(ROW_H, rows.len(), |mut row| { + let id = &rows[row.index()]; + let Some(repertoire) = self.library.repertoire(id) else { + return; + }; + let side = layout::side_of(settings, id); + let stats = self.stats.get(id); + row.set_selected(self.selected.as_ref() == Some(id)); row.col(|ui| { - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - ui.spacing_mut().item_spacing.y = OPENING_GAP; - ui.add_space(ROW_VERTICAL_PADDING); - table_text_line( - ui, - RichText::new(&r.name).strong().size(16.0), - TITLE_HEIGHT, - ) - .on_hover_text(&r.name); - ui.add_space(TITLE_GAP - OPENING_GAP); - for (index, opening) in r.visible_openings().iter().enumerate() { - let more = - index + 1 == OPENING_LINES && r.openings.len() > OPENING_LINES; - let text = if more { - format!("{} …", opening.name) - } else { - opening.name.clone() - }; - let response = table_text_line( - ui, - RichText::new(text).size(14.0), - OPENING_HEIGHT, - ); - if more { - response.on_hover_text( - r.openings - .iter() - .map(|opening| { - format!("{} {}", opening.eco, opening.name) - }) - .collect::>() - .join("\n"), - ); - } else { - response.on_hover_text(&opening.name); + layout::line(ui, repertoire.name.as_str()); + }); + row.col(|ui| { + ui.label(layout::king(side)) + .on_hover_text(layout::you_play(side)); + }); + row.col(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + match stats { + Some(Ok(stats)) if stats.today() > 0 => { + ui.label(stats.today().to_string()).on_hover_text(trf( + "{n} to review, {m} new", + &[("n", &stats.due), ("m", &stats.new_today())], + )); + } + Some(_) => { + ui.label(RichText::new("—").weak()); + } + None => { + ui.label(RichText::new("…").weak()); } } }); }); row.col(|ui| { - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - ui.spacing_mut().item_spacing.y = OPENING_GAP; - ui.add_space(ROW_VERTICAL_PADDING); - table_text_line( - ui, - RichText::new(" ").strong().size(16.0), - TITLE_HEIGHT, - ); - ui.add_space(TITLE_GAP - OPENING_GAP); - if r.openings.is_empty() { - table_text_line( - ui, - RichText::new("—").size(14.0).weak(), - OPENING_HEIGHT, - ); - } else { - for (index, opening) in r.visible_openings().iter().enumerate() { - let more = index + 1 == OPENING_LINES - && r.openings.len() > OPENING_LINES; - let text = if more { - format!("{} …", opening.eco) - } else { - opening.eco.clone() - }; - table_text_line( - ui, - RichText::new(text).size(14.0), - OPENING_HEIGHT, - ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + match stats { + Some(Ok(stats)) if stats.total > 0 => { + ui.label(format!("{}/{}", stats.learnt, stats.total)); + } + Some(_) => { + ui.label(RichText::new("—").weak()); + } + None => { + ui.label(RichText::new("…").weak()); } } }); }); + let mut opened = false; row.col(|ui| { - count_cell(ui, self.variant_counts.get(&r.id).copied()); - }); - row.col(|ui| { - ui.menu_button("⋯", |ui| { - if ui - .add_enabled( - !self.has_unsaved() && !self.preparing, - egui::Button::new(tr("Edit")), - ) - .clicked() - { - edit = Some(r.id.clone()); - ui.close(); - } - if ui.button(tr("Rename")).clicked() { - self.edit_name = Some((Some(r.id.clone()), r.name.clone())); - ui.close(); - } - if ui.button(tr("Import PGN into this repertoire…")).clicked() { - import = Some(r.id.clone()); - ui.close(); - } - if ui.button(tr("Export PGN…")).clicked() { - export = Some(r.id.clone()); - ui.close(); - } - if ui.button(tr("Delete…")).clicked() { - self.delete = Some(r.id.clone()); - ui.close(); - } - }); - }); - if row.response().clicked() { - clicked = Some(r.id.clone()); - } - }); - }); - #[cfg(test)] - { - let table_bottom = ui.next_widget_position(); - self.debug_layout.table = Some(egui::Rect::from_min_max( - table_top, - egui::pos2(table_top.x + table_width, table_bottom.y), - )); - } - if let Some(id) = clicked { - self.select(id, settings); - } - if let Some(id) = edit { - self.select(id, settings); - self.open_editor(); - } - if let Some(id) = import { - self.pick_import(Some(id), ui.ctx()); - } - if let Some(id) = export { - self.select(id, settings); - self.export(Some(ui.ctx().clone())); - } - } - fn name_editor(&mut self, ui: &mut Ui, settings: &Settings) { - let Some((id, mut name)) = self.edit_name.clone() else { - return; - }; - let mut save = false; - let mut cancel = false; - ui.horizontal_wrapped(|ui| { - let response = ui.add( - egui::TextEdit::singleline(&mut name) - .char_limit(120) - .hint_text(tr("Name")), - ); - save = ui.button(tr("Save")).clicked() - || response.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)); - cancel = ui.button(tr("Cancel")).clicked(); - }); - self.edit_name = Some((id.clone(), name.clone())); - if cancel { - self.edit_name = None; - } - if save { - self.save_name(id, &name, settings); - } - } - fn save_name(&mut self, id: Option, name: &str, settings: &Settings) { - match self.checked_name(name, id.as_ref()) { - Ok(name) => { - let mut library = self.library.clone(); - let result = if let Some(id) = id { - library.rename(&id, name).map(|()| id) - } else { - library.create_empty(name) - }; - match result { - Ok(id) if self.persist(library.clone()) => { - self.edit_name = None; - self.select(id, settings); - } - Ok(_) => {} - Err(e) => self.error = Some(e.to_string()), - } - } - Err(e) => self.error = Some(e), - } - } - fn import_preview(&mut self, ui: &mut Ui, settings: &Settings) { - let Some(preview) = self.import.as_mut() else { - return; - }; - ui.separator(); - ui.strong(tr("Import PGN…")); - if preview.target.is_none() { - ui.add( - egui::TextEdit::singleline(&mut preview.name) - .char_limit(120) - .hint_text(tr("Name")), - ); - } - ui.label(format!( - "{}: {} · {}: {}", - tr("Games"), - preview.records, - tr("New moves"), - preview.report.added_nodes - )); - ui.horizontal(|ui| { - if ui.button(tr("Cancel")).clicked() { - self.import = None; - } - if ui.button(tr("Add")).clicked() { - self.confirm_import(settings); - } - }); - } - fn show_workspace( - &mut self, - ui: &mut Ui, - settings: &mut Settings, - actions: &mut Vec, - ) { - let width = ui.available_width(); - let height = ui.available_height(); - let stacked = width < 900.0 && height > width; - if stacked { - let available = ui.available_rect_before_wrap(); - let panel_height = (height * 0.52).clamp(340.0, 520.0); - let board_rect = egui::Rect::from_min_max( - available.min, - egui::pos2(available.right(), available.bottom() - panel_height), - ); - let side_rect = egui::Rect::from_min_max( - egui::pos2(available.left(), board_rect.bottom()), - available.max, - ); - ui.scope_builder(egui::UiBuilder::new().max_rect(board_rect), |ui| { - egui::CentralPanel::default().show(ui, |ui| self.preview_board(ui, settings)); - }); - ui.scope_builder(egui::UiBuilder::new().max_rect(side_rect), |ui| { - ui.set_clip_rect(side_rect); - egui::Frame::side_top_panel(ui.style()) - .show(ui, |ui| self.workspace_panel(ui, settings, actions)); - }); - } else { - let width = ui.available_width(); - egui::Panel::right("repertoire_workspace_side") - .resizable(true) - .default_size((width * 0.42).clamp(420.0, 560.0)) - .size_range(360.0..=(width - 220.0).max(360.0)) - .show(ui, |ui| self.workspace_panel(ui, settings, actions)); - egui::CentralPanel::default().show(ui, |ui| self.preview_board(ui, settings)); - } - } - fn workspace_panel( - &mut self, - ui: &mut Ui, - settings: &mut Settings, - actions: &mut Vec, - ) { - ui.set_width(ui.available_width()); - let selected = self - .selected - .as_ref() - .and_then(|id| self.library.repertoire(id).cloned()) - .map(|r| (r.id.clone(), r)); - if let Some((id, r)) = selected { - ui.add_enabled_ui(!self.preparing, |ui| { - let previous_side = self.side; - let previous_queue = self.queue; - let previous_priority = self.priority; - ui.add(egui::Label::new(RichText::new(&r.name).heading()).truncate()) - .on_hover_text(&r.name); - ui.add_space(6.0); - egui::Grid::new("repertoire_selected_controls") - .num_columns(2) - .spacing([12.0, 6.0]) - .show(ui, |ui| { - ui.label(tr("Color")); - ui.horizontal(|ui| { - for side in [LearningSide::White, LearningSide::Black] { - ui.selectable_value( - &mut self.side, - side, - learning_side_label(side), - ); - } - }); - ui.end_row(); - ui.label(tr("Mode")); - egui::ComboBox::from_id_salt("repertoire_learning_mode") - .selected_text(queue_mode_label(self.queue)) - .width(220.0) - .truncate() - .show_ui(ui, |ui| { - for queue in [ - QueueMode::SpacedRepetition, - QueueMode::ReviewInOrder, - QueueMode::LeastRecent, - ] { - ui.selectable_value( - &mut self.queue, - queue, - queue_mode_label(queue), - ); - } - }); - ui.end_row(); - }); - ui.add_space(8.0); - let aggregate = self - .selected_aggregate() - .map(|scoped| scoped.summary.clone()); - let resume = self.queue == QueueMode::SpacedRepetition - && self.has_unfinished_review_snapshot(); - let kind = aggregate - .as_ref() - .map_or(StartKind::Unavailable, |summary| { - self.selected_start_kind(summary) - }); - let ready = kind != StartKind::Unavailable - && !self.preparing - && self.learning_error.is_none() - && self.library_error.is_none(); - let cta = match (self.queue, kind) { - (QueueMode::SpacedRepetition, StartKind::Review) if resume => tr("Continue"), - _ => tr("Train"), - }; - self.statistics_panel(ui); - if r.max_plies != u32::MAX { - ui.label(RichText::new(tr("Training scope: selected part")).weak()); - } - ui.add_space(8.0); - let button_width = (ui.available_width() - 16.0) / 3.0; - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 8.0; - ui.add_enabled_ui(ready, |ui| { - let response = crate::widgets::primary_wide(ui, cta, button_width); - let response = if kind == StartKind::Unavailable - && aggregate.as_ref().is_some_and(|s| s.total > 0) - && self.learning_error.is_none() - && self.library_error.is_none() - { - response.on_disabled_hover_text(tr( - "Nothing is due yet. Choose a review mode to practise now.", - )) - } else { - response - }; - #[cfg(test)] - { - self.debug_layout.action_buttons[0] = Some(response.rect); + let button = ui.add(egui::Button::new("⋯").frame(false)); + let mut popup = egui::Popup::menu(&button); + if open_menu && self.selected.as_ref() == Some(id) { + popup = popup.open_memory(Some(egui::SetOpenCommand::Bool(true))); } - if response.clicked() { - self.start(settings); - if self.preparing { - actions.push(RepertoireAction::SettingsChanged); - } + if let Some(item) = + popup + .show(|ui| menu_items(ui, side, stats)) + .and_then(|inner| { + opened = true; + inner.inner + }) + { + chosen = Some(item); } }); - let parameters = ui.add( - egui::Button::new(tr("Parameters")) - .min_size(egui::vec2(button_width, 30.0)), - ); - if parameters.clicked() { - self.parameters_open = true; - } - #[cfg(test)] + let response = row.response(); + if let Some(item) = egui::Popup::context_menu(&response) + .show(|ui| menu_items(ui, side, stats)) + .and_then(|inner| { + opened = true; + inner.inner + }) { - self.debug_layout.action_buttons[1] = Some(parameters.rect); + chosen = Some(item); } - let response = ui.add_enabled( - !self.has_unsaved() && !self.preparing, - egui::Button::new(tr("Statistics")) - .min_size(egui::vec2(button_width, 30.0)), - ); - #[cfg(test)] - { - self.debug_layout.action_buttons[2] = Some(response.rect); + if opened && self.selected.as_ref() != Some(id) { + clicked = Some(id.clone()); } if response.clicked() { - self.open_dashboard(); + clicked = Some(id.clone()); + } + if response.double_clicked() { + clicked = Some(id.clone()); + double = true; } }); - self.shared_reset_panel(ui); - let preferences_changed = previous_side != self.side - || previous_queue != self.queue - || previous_priority != self.priority; - if previous_side != self.side || previous_queue != self.queue { - settings - .repertoire_modes - .insert(id.to_string(), (training_mode(self.side), self.queue)); - } - if previous_priority != self.priority { - settings - .repertoire_priorities - .insert(id.to_string(), self.priority); - } - if preferences_changed { - self.close_editor(); - self.invalidate_reset_jobs(); - actions.push(RepertoireAction::SettingsChanged); - } }); + if let Some(id) = clicked { + self.selected = Some(id); } - ui.separator(); - self.show_library(ui, settings); + if double { + chosen = Some(MenuItem::Train); + } + chosen } - fn parameters_window( + + fn message_strip(&mut self, ui: &mut Ui) { + let Some(message) = &self.message else { + return; + }; + let mut close = false; + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + close = crate::widgets::small_close_button(ui).clicked(); + let mut text = RichText::new(&message.text); + text = if message.error { + text.color(ui.visuals().warn_fg_color) + } else { + text.weak() + }; + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + layout::line(ui, text); + }); + }); + }); + if close { + self.message = None; + } + } + + fn show_dialog( &mut self, ctx: &egui::Context, settings: &mut Settings, actions: &mut Vec, ) { - if !self.parameters_open { - return; - } - let Some(id) = self.selected.clone() else { - self.parameters_open = false; + let Some(dialog) = self.dialog.take() else { return; }; - let name = self + let names: HashMap = self .library - .repertoire(&id) - .map(|r| r.name.clone()) - .unwrap_or_default(); - let aggregate = self.selected_aggregate().map(|a| a.summary.clone()); - let previous_priority = self.priority; - let mut close = false; - let modal = egui::Modal::new(egui::Id::new("repertoire_parameters")).show(ctx, |ui| { - ui.set_width((ctx.content_rect().width() - 40.0).clamp(240.0, 440.0)); - ui.heading(tr("Training parameters")); - ui.add(egui::Label::new(egui::RichText::new(&name).strong()).truncate()) - .on_hover_text(&name); - ui.add( - egui::Label::new( - egui::RichText::new(tr("Changes apply to new sessions. Continuing a saved session keeps its previous settings.")).weak(), - ) - .wrap(), - ); - ui.separator(); - egui::ScrollArea::vertical() - .id_salt("repertoire_parameters_scroll") - .max_height((ctx.content_rect().height() - 200.0).max(100.0)) - .auto_shrink([false, true]) - .show(ui, |ui| { - if self.queue != QueueMode::SpacedRepetition { - ui.label(tr("Learning priority")); - egui::ComboBox::from_id_salt("repertoire_learning_priority") - .selected_text(learning_priority_label(self.priority)) - .width(280.0) - .truncate() - .show_ui(ui, |ui| { - for priority in [ - LearningPriority::DepthFirst, - LearningPriority::BreadthOverDepth, - LearningPriority::MainLinesFirst, - LearningPriority::CommonPositionsFirst, - ] { - ui.selectable_value( - &mut self.priority, - priority, - learning_priority_label(priority), - ); - } - }); - ui.separator(); - } - let mut context_policy = settings - .repertoire_context_policies - .get(id.as_str()) - .copied() - .unwrap_or_default(); - if crate::learning_context_controls::show(ui, &mut context_policy) { - settings - .repertoire_context_policies - .insert(id.to_string(), context_policy); - actions.push(RepertoireAction::SettingsChanged); - } - ui.separator(); - if self.queue == QueueMode::ReviewInOrder { - let enabled = self.has_review_snapshot() - && !self.review_reset_pending - && !self.has_unsaved(); - let response = - ui.add_enabled(enabled, egui::Button::new(tr("Reset Review Order"))); - #[cfg(test)] - { - self.debug_layout.reset_review = Some(response.rect); - } - if response.clicked() { - self.reset_review_cursor(); - } - } - let enabled = aggregate.as_ref().is_some_and(|summary| summary.total > 0) - && !self.has_unsaved() - && !self.preparing; - if ui - .add_enabled(enabled, egui::Button::new(tr("Reset learning progress…"))) - .clicked() - && let Some(scope) = - self.selected_aggregate().map(|scoped| scoped.scope.clone()) - { - self.begin_shared_reset(scope); - close = true; - } - }); - ui.separator(); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - close |= ui.button(tr("Close")).clicked(); - }); - }); - if self.priority != previous_priority { - settings - .repertoire_priorities - .insert(id.to_string(), self.priority); - self.invalidate_reset_jobs(); - actions.push(RepertoireAction::SettingsChanged); - } - if close || modal.should_close() { - self.parameters_open = false; - } - } - fn current_aggregate_key(&self) -> Option { - Some(AggregateKey { - id: self.selected.clone()?, - side: self.side, - library_revision: self.library.revision, - learning_revision: self.learning.revision, - minute: now() / 60, - }) - } - fn selected_aggregate(&mut self) -> Option<&ScopedLearningAggregate> { - let key = self.current_aggregate_key()?; - self.request_aggregate(key.clone()); - self.aggregates.get(&key)?.as_ref()?.as_ref().ok() - } - fn request_aggregate(&mut self, key: AggregateKey) { - if self.aggregates.contains_key(&key) { - return; - } - if self.aggregates.iter().any(|(pending, value)| { - let mut comparable = pending.clone(); - comparable.minute = key.minute; - value.is_none() && comparable == key - }) { - return; - } - let max_depth = self - .library - .repertoire(&key.id) - .map(|repertoire| repertoire.max_plies); - let scope = - StatsScope::for_repertoire(key.id.clone(), key.side, now()).with_max_depth(max_depth); - let library = self.library.clone(); - let learning = self.learning.learning.clone(); - let tx = self.tx.clone(); - let job_key = key.clone(); - self.aggregates.retain(|old, value| { - old.library_revision == key.library_revision - && old.learning_revision == key.learning_revision - && (value.is_none() || old.minute >= key.minute - 1) - }); - self.aggregates.insert(key.clone(), None); - if let Err(error) = crate::platform::spawn("repertoire-aggregate", move || { - let result = aggregate_scope(&library, &learning, &scope, &SrsSettings::default()) - .map_err(|error| error.to_string()); - let _ = tx.send(Event::Aggregated(job_key, Box::new(result))); - }) { - self.aggregates.remove(&key); - self.error = Some(error.to_string()); - } - } - fn preview_board(&mut self, ui: &mut Ui, settings: &Settings) { - let pos = self - .tree - .as_ref() - .and_then(|tree| tree.game().position(NodeId::ROOT)) - .cloned() - .unwrap_or_default(); - let side = ui - .available_width() - .min(ui.available_height()) - .max(1.0) - .floor(); - let available = ui.available_size(); - let offset = egui::vec2( - ((available.x - side) / 2.0).max(0.0).floor(), - ((available.y - side) / 2.0).max(0.0).floor(), - ); - let rect = egui::Rect::from_min_size(ui.cursor().min + offset, egui::vec2(side, side)); - ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { - BoardView { - pos: &pos, - orientation: self.side.color(), - last_move: None, - arrows: &[], - circles: &[], - badge: None, - interactive: false, - show_coords: settings.show_coords, - theme: settings.board_theme.theme(), - pieces: settings.piece_set, - animation: settings.animation.seconds(), - premove: None, - auto_queen: false, - alert: None, - } - .show(ui, &mut self.board); - }); - } - fn statistics_panel(&mut self, ui: &mut Ui) { - let summary = self - .selected_aggregate() - .map(|scoped| scoped.summary.clone()); - if summary.as_ref().is_some_and(|summary| summary.total == 0) { - ui.strong(tr("No moves to train")); - ui.label(tr("Add variations in the editor or import PGN")); - return; - } - let count = |metric: fn(&LearningAggregate) -> usize| { - summary - .as_ref() - .map_or_else(|| "…".to_owned(), |summary| metric(summary).to_string()) - }; - ui.strong(trf( - "Learnt {learnt} of {total} moves", - &[ - ("learnt", &count(|summary| summary.learnt)), - ("total", &count(|summary| summary.total)), - ], - )) - .on_hover_text(tr("A move is learnt after 3 correct answers in a row without hints. Only main replies for the selected colour count; shared positions count once. A wrong answer resets the streak.")); - ui.label(trf( - "Unseen: {unseen} · Due now: {due}", - &[ - ("unseen", &count(|summary| summary.unseen)), - ("due", &count(|summary| summary.due)), - ], - )); - if summary.is_none() { - ui.ctx() - .request_repaint_after(std::time::Duration::from_millis(100)); - } - } - fn shared_reset_panel(&mut self, ui: &mut Ui) { - let Some(state) = &self.shared_reset else { - return; - }; - let impact = state.impact.clone(); - let busy = state.busy; - ui.separator(); - let Some(impact) = impact else { - ui.spinner(); - ui.ctx() - .request_repaint_after(std::time::Duration::from_millis(100)); - return; - }; - ui.label(format!( - "{}: {} · {}: {}", - tr("Learning items"), - impact.reset_count, - tr("Shared"), - impact.shared_count - )); - let names = impact - .affected_repertoires + .repertoires .iter() - .map(|repertoire| repertoire.name.as_str()) - .collect::>() - .join(", "); - ui.add( - egui::Label::new(format!( - "{}: {}", - tr("Affected repertoires"), - if names.is_empty() { "—" } else { &names } - )) - .wrap(), - ); - ui.label( - RichText::new(tr( - "Progress in other repertoires will also become Unseen. PGN files will not change.", - )) - .weak(), - ); - let mut confirmed = state.confirmed; - ui.add_enabled_ui(!busy, |ui| { - ui.checkbox( - &mut confirmed, - tr("I understand that shared progress will be reset"), - ); - }); - if let Some(state) = &mut self.shared_reset { - state.confirmed = confirmed; - } - let mut cancel = false; - let mut confirm = false; - ui.horizontal(|ui| { - cancel = ui - .add_enabled(!busy, egui::Button::new(tr("Cancel"))) - .clicked(); - confirm = ui - .add_enabled( - confirmed && !busy && impact.reset_count > 0, - egui::Button::new(tr("Reset shared learning data")), - ) - .clicked(); - if busy { - ui.spinner(); - ui.ctx() - .request_repaint_after(std::time::Duration::from_millis(100)); + .map(|r| (r.id.clone(), r.name.clone())) + .collect(); + let name_of = |id: &RepertoireId| names.get(id).cloned().unwrap_or_default(); + let mut keep = true; + let mut result = None; + let enter = ctx.input(|input| input.key_pressed(Key::Enter)); + let mut dialog = dialog; + let modal = egui::Modal::new(egui::Id::new("opening_dialog")).show(ctx, |ui| { + ui.set_width(DIALOG_W); + match &mut dialog { + Dialog::Import(import) => { + result = import_dialog(ui, import, name_of, enter); + } + Dialog::New { name, side, error } => { + ui.heading(tr("New repertoire")); + ui.add_space(8.0); + name_field(ui, name, error, false); + side_choice(ui, side); + ui.add_space(4.0); + ui.add( + egui::Label::new(RichText::new(tr("Moves are added from a PGN file or with “Add to repertoire…” in any game.")).weak()) + .wrap(), + ); + result = dialog_buttons(ui, tr("Create"), true, None, enter); + } + Dialog::Rename { + name, + error, + select_all, + .. + } => { + ui.heading(tr("Rename repertoire")); + ui.add_space(8.0); + name_field(ui, name, error, std::mem::take(select_all)); + result = dialog_buttons(ui, tr("Save"), true, None, enter); + } + Dialog::Color { id, to, count, .. } => { + let name = name_of(id); + ui.heading(match to { + LearningSide::Black => trf("Play “{name}” as Black?", &[("name", &name)]), + LearningSide::White => trf("Play “{name}” as White?", &[("name", &name)]), + }); + ui.add_space(8.0); + let count = count.map_or_else(|| "…".to_owned(), |n| n.to_string()); + ui.add( + egui::Label::new(match to { + LearningSide::Black => trf( + "You will be asked Black's moves: {y}. Progress for White is kept and comes back if you switch again.", + &[("y", &count)], + ), + LearningSide::White => trf( + "You will be asked White's moves: {y}. Progress for Black is kept and comes back if you switch again.", + &[("y", &count)], + ), + }) + .wrap(), + ); + result = dialog_buttons(ui, tr("Switch"), true, None, enter); + } + Dialog::Reset { id, impact, busy, .. } => { + let name = name_of(id); + ui.heading(trf("Reset progress of “{name}”?", &[("name", &name)])); + ui.add_space(8.0); + match impact { + None => { + ui.label(RichText::new(tr("Counting moves…")).weak()); + } + Some((impact, keys)) => { + ui.add( + egui::Label::new(trf( + "All {y} moves of this repertoire become new again: answers and review dates are erased.", + &[("y", &keys.len())], + )) + .wrap(), + ); + ui.add( + egui::Label::new(tr("The moves themselves and PGN files do not change.")) + .wrap(), + ); + let others: Vec<_> = impact + .affected_repertoires + .iter() + .filter(|other| other.id != *id) + .collect(); + if impact.shared_count > 0 && !others.is_empty() { + let names = others + .iter() + .map(|other| other.name.as_str()) + .collect::>() + .join(", "); + ui.add( + egui::Label::new( + RichText::new(trf( + "{s} of these moves are also in: {names}. They become new there too.", + &[("s", &impact.shared_count), ("names", &names)], + )) + .color(ui.visuals().warn_fg_color), + ) + .wrap(), + ); + } + } + } + let ready = impact.as_ref().is_some_and(|(_, keys)| !keys.is_empty()) && !*busy; + result = dialog_buttons(ui, tr("Reset"), ready, Some(()), enter); + } + Dialog::Delete { id } => { + let name = name_of(id); + ui.heading(trf("Delete “{name}”?", &[("name", &name)])); + ui.add_space(8.0); + ui.add( + egui::Label::new(tr( + "The repertoire leaves this list. PGN files on disk do not change.", + )) + .wrap(), + ); + ui.add( + egui::Label::new(tr( + "Your answers are kept: import the same PGN again and the progress returns.", + )) + .wrap(), + ); + result = dialog_buttons(ui, tr("Delete"), true, Some(()), enter); + } } }); - if cancel { - self.cancel_shared_reset(); + if modal.should_close() && result.is_none() { + result = Some(false); } - if confirm { - self.confirm_shared_reset(); + match result { + Some(false) => { + if let Dialog::Import(import) = &dialog { + import.cancel.store(true, Ordering::Relaxed); + } + keep = false; + } + Some(true) => { + self.dialog = Some(dialog); + self.confirm_dialog(settings, actions); + return; + } + None => {} + } + if keep { + self.dialog = Some(dialog); } } - fn show_add(&mut self, ui: &mut Ui, actions: &mut Vec) { + + fn confirm_dialog(&mut self, settings: &mut Settings, actions: &mut Vec) { + match self.dialog.take() { + Some(Dialog::Import(import)) => { + self.dialog = Some(Dialog::Import(import)); + self.confirm_import(settings); + } + Some(Dialog::New { name, side, .. }) => match self.checked_name(&name, None) { + Ok(name) => { + let mut library = self.library.clone(); + match library.create_empty(name.clone()) { + Ok(id) => { + if self.persist(library) { + layout::set_side(settings, &id, side); + actions.push(RepertoireAction::SettingsChanged); + self.select(id); + } else { + self.dialog = Some(Dialog::New { + name, + side, + error: None, + }); + } + } + Err(error) => { + self.dialog = Some(Dialog::New { + name, + side, + error: Some(error.to_string()), + }) + } + } + } + Err(error) => { + self.dialog = Some(Dialog::New { + name, + side, + error: Some(error), + }) + } + }, + Some(Dialog::Rename { id, name, .. }) => match self.checked_name(&name, Some(&id)) { + Ok(checked) => { + let mut library = self.library.clone(); + match library.rename(&id, checked) { + Ok(()) => { + if !self.persist(library) { + self.dialog = Some(Dialog::Rename { + id, + name, + error: None, + select_all: false, + }); + } + } + Err(error) => { + self.dialog = Some(Dialog::Rename { + id, + name, + error: Some(error.to_string()), + select_all: false, + }) + } + } + } + Err(error) => { + self.dialog = Some(Dialog::Rename { + id, + name, + error: Some(error), + select_all: false, + }) + } + }, + Some(Dialog::Color { id, to, .. }) => { + layout::set_side(settings, &id, to); + actions.push(RepertoireAction::SettingsChanged); + } + Some(dialog @ Dialog::Reset { .. }) => { + self.dialog = Some(dialog); + self.confirm_reset(); + } + Some(dialog @ Dialog::Delete { .. }) => { + self.dialog = Some(dialog); + self.delete_selected(); + } + None => {} + } + } + + fn show_add( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + actions: &mut Vec, + ) { let Some(mut add) = self.add.take() else { return; }; let mut cancel = false; let mut commit = false; + let start = fen4(add.source.start().position()); + let candidates: Vec<(RepertoireId, String)> = self + .library + .repertoires + .iter() + .filter(|r| { + self.index.contains_key(&r.id) && fen4(r.game().start().position()) == start + }) + .map(|r| (r.id.clone(), r.name.clone())) + .collect(); egui::Modal::new(egui::Id::new("add_to_repertoire")).show(ui.ctx(), |ui| { ui.set_max_width(450.0); ui.heading(tr("Add to repertoire")); ui.label(prefix_label(&add.source, add.at)); - let start = fen4(add.source.start().position()); - for r in &self.library.repertoires { - if self - .trees - .get(&r.id) - .is_some_and(|tree| fen4(tree.game().start().position()) == start) - { - ui.radio_value(&mut add.selected, Some(r.id.clone()), &r.name); - } + for (id, name) in &candidates { + ui.radio_value(&mut add.selected, Some(id.clone()), name); } ui.radio_value(&mut add.selected, None, tr("New repertoire")); if add.selected.is_none() { @@ -2005,17 +2060,17 @@ impl RepertoireUi { .char_limit(120) .hint_text(tr("Name")), ); + side_choice(ui, &mut add.side); } ui.horizontal(|ui| { cancel = ui.button(tr("Cancel")).clicked(); - commit = ui - .add_enabled(!self.indexing, egui::Button::new(tr("Add"))) - .clicked(); + commit = ui.button(tr("Add")).clicked(); }); }); if commit { let result = (|| { let mut library = self.library.clone(); + let new = add.selected.is_none(); let id = if let Some(id) = &add.selected { id.clone() } else { @@ -2031,55 +2086,63 @@ impl RepertoireUi { .repertoire(&id) .map(|r| r.name.clone()) .unwrap_or_default(); - Ok::<_, String>((library, id, name, report)) + Ok::<_, String>((library, id, name, report, new)) })(); match result { - Ok((library, id, name, report)) if self.persist(library.clone()) => { + Ok((library, id, name, report, new)) if self.persist(library.clone()) => { + if new { + layout::set_side(settings, &id, add.side); + actions.push(RepertoireAction::SettingsChanged); + } actions.push(RepertoireAction::Added { id, name, report }); return; } Ok(_) => {} - Err(e) => self.error = Some(e), + Err(error) => self.show_message(error, true), } } if !cancel { self.add = Some(add); } } + pub fn debug_import(&mut self, path: PathBuf) { - self.import_path(path, None, None); + let target = + std::env::var_os("CP_REPERTOIRE_IMPORT_INTO").and_then(|_| self.selected.clone()); + self.import_path(path, target); } - pub fn debug_confirm_import(&mut self, settings: &Settings) -> bool { - self.confirm_import(settings) + + /// `CP_REPERTOIRE_CONFIRM_IMPORT`: confirmed in `poll`, where the chosen colour can + /// be written to the settings. + pub fn debug_confirm_import(&mut self, _settings: &Settings) -> bool { + false } + pub fn debug_export(&mut self) { self.export(None); } + pub fn debug_rename(&mut self, name: String, _settings: &Settings) -> bool { let Some(id) = self.selected.clone() else { return false; }; let mut library = self.library.clone(); - if let Err(e) = library.rename(&id, name) { - self.error = Some(e.to_string()); + if let Err(error) = library.rename(&id, name) { + self.show_message(error.to_string(), true); return false; } self.persist(library) } + pub fn debug_delete(&mut self, _settings: &Settings) -> bool { let Some(id) = self.selected.clone() else { return false; }; - let mut library = self.library.clone(); - if library.delete(&id).is_err() { - return false; - } - if !self.persist(library) { - return false; - } - self.selected = None; - true + self.dialog = Some(Dialog::Delete { id }); + self.delete_selected(); + self.dialog.is_none() } + pub fn debug_add_from_game(&mut self, source: Game, at: NodeId, title: String, target: String) { self.open_add_from_game(source, at, title); if let Some(add) = &mut self.add { @@ -2087,55 +2150,535 @@ impl RepertoireUi { add.selected = None; } } + + /// QA hooks (docs/qa/opening-trainer-v2-devhooks.md): `CP_REPERTOIRE=`, after + /// `CP_REPERTOIRE_SELECT=`. pub fn debug_open(&mut self, what: &str, settings: &mut Settings) { - if let Some(id) = self.selected.clone() { - self.select(id, settings); - } - match what { - "library" | "detail" => {} - "dashboard" => self.open_dashboard(), - "editor" => self.open_editor(), - "white" | "black" => { - if self.selected.is_none() || self.cancel.is_some() { - self.debug_start = Some(what.to_owned()); - return; - } - self.side = if what == "black" { - LearningSide::Black - } else { - LearningSide::White - }; - if self.selected_aggregate().is_none() { - self.debug_start = Some(what.to_owned()); - return; - } - self.start(settings); + if let Ok(name) = std::env::var("CP_REPERTOIRE_SELECT") { + let name = name.to_lowercase(); + if let Some(id) = self + .library + .repertoires + .iter() + .find(|r| r.name.to_lowercase().contains(&name)) + .map(|r| r.id.clone()) + { + self.select(id); } + } + let ready = self + .selected + .as_ref() + .is_some_and(|id| self.stats.contains_key(id) && self.index.contains_key(id)); + let needs_stats = !matches!(what, "library" | "detail" | "new" | "message"); + if needs_stats && !ready && !self.library.repertoires.is_empty() { + self.debug_start = Some(what.to_owned()); + return; + } + let ctx = egui::Context::default(); + match what { + "white" | "black" => { + if let Some(id) = self.selected.clone() { + let side = if what == "black" { + LearningSide::Black + } else { + LearningSide::White + }; + if layout::side_of(settings, &id) != side { + layout::set_side(settings, &id, side); + self.debug_start = Some("train".to_owned()); + return; + } + self.start(SessionKind::Daily, settings); + } + } + "train" => self.start(SessionKind::Daily, settings), + "main" => self.main_action(&ctx, settings), + "review" => self.start(SessionKind::ReviewAll, settings), + "lines" => { + let path = std::env::var("CP_REPERTOIRE_LINE") + .ok() + .map(|path| path.split_whitespace().map(str::to_owned).collect()); + self.open_lines(settings, path); + } + "branch" => { + let through: Vec = std::env::var("CP_REPERTOIRE_LINE") + .unwrap_or_default() + .split_whitespace() + .map(str::to_owned) + .collect(); + let label = through.join(" "); + self.start(SessionKind::Branch { through, label }, settings); + } + "menu" => self.debug_menu = true, + "new" => { + self.dialog = Some(Dialog::New { + name: std::env::var("CP_REPERTOIRE_NAME").unwrap_or_default(), + side: LearningSide::White, + error: None, + }); + if std::env::var_os("CP_REPERTOIRE_NAME").is_some() { + self.confirm_dialog(settings, &mut Vec::new()); + } + } + "rename" => self.menu_item(MenuItem::Rename, &ctx, settings), + "color" => self.open_color_dialog(settings), + "reset" => self.open_reset_dialog(settings), + "delete" => self.menu_item(MenuItem::Delete, &ctx, settings), + "message" => self.show_message( + trf( + "Could not save: {e}", + &[("e", &"Permission denied (os error 13)")], + ), + true, + ), _ => {} } } + pub fn debug_moves(&mut self, moves: &str) { - if let Some(t) = &mut self.training { - t.debug_moves(moves); + if let Screen::Session(session) = &mut self.screen { + session.debug_moves(moves); } else { self.debug_pending_moves = Some(moves.to_owned()); } } + pub fn debug_hint(&mut self) { - if let Some(t) = &mut self.training { - t.debug_hint(); + if let Screen::Session(session) = &mut self.screen { + session.debug_hint(); } } } impl Drop for RepertoireUi { fn drop(&mut self) { - if let Some(cancel) = &self.cancel { - cancel.store(true, Ordering::Relaxed); + if let Some(Dialog::Import(import)) = &self.dialog { + import.cancel.store(true, Ordering::Relaxed); } } } +fn next_job() -> u64 { + NEXT_JOB.fetch_add(1, Ordering::Relaxed) +} + +/// `CP_REPERTOIRE_SLOW=`: a session takes this long to prepare (to see «Preparing…»). +fn debug_slow() -> Option { + std::env::var("CP_REPERTOIRE_SLOW") + .ok()? + .parse() + .ok() + .map(Duration::from_millis) +} + +fn row_stats( + library: &Library, + learning: &LearningData, + id: &RepertoireId, + side: LearningSide, + today: i64, +) -> Result { + let scope = StatsScope::for_repertoire(id.clone(), side, today); + let scoped = aggregate_scope(library, learning, &scope, &SrsSettings::default()) + .map_err(|error| error.to_string())?; + let summary = &scoped.summary; + let next = summary.next_due_at.map(|at| { + let day_end = end_of_day(at); + let count = scoped + .items + .iter() + .filter(|item| { + item.introduced + && item + .next_review_at + .is_some_and(|next| next > today && next <= day_end) + }) + .count(); + (at, count) + }); + Ok(RowStats { + total: summary.total, + due: summary.due, + unseen: summary.unseen, + learning: summary.learning, + learnt: summary.learnt, + next, + }) +} + +fn end_of_day(at: i64) -> i64 { + use chrono::{Local, TimeZone}; + Local + .timestamp_opt(at, 0) + .single() + .and_then(|time| time.date_naive().succ_opt()) + .and_then(|day| day.and_hms_opt(0, 0, 0)) + .and_then(|midnight| Local.from_local_datetime(&midnight).earliest()) + .map_or(at, |midnight| midnight.timestamp() - 1) +} + +/// Lines 2 and 4 of the card. +fn card_texts(state: &CardState, side: LearningSide) -> (String, String) { + match state { + CardState::Review { due, new } => { + let today = if *new > 0 { + trf("Today: {n} to review · {m} new", &[("n", due), ("m", new)]) + } else { + trf("Today: {n} to review", &[("n", due)]) + }; + let seconds = (due + new) * SECONDS_PER_MOVE; + let note = if seconds >= 60 { + trf("About {t} min", &[("t", &seconds.div_ceil(60))]) + } else { + String::new() + }; + (today, note) + } + CardState::OnlyNew { new } => ( + trf("Today: {m} new moves", &[("m", new)]), + tr("Nothing to review today").to_owned(), + ), + CardState::Done { next } => ( + tr("Done for today").to_owned(), + next.map(|(at, count)| { + trf( + "Next review: {when} · {n} moves", + &[("when", &layout::when(at, layout::now())), ("n", &count)], + ) + }) + .unwrap_or_default(), + ), + CardState::Empty => ( + tr("No moves yet").to_owned(), + tr("Add a PGN, or use “Add to repertoire…” in any game").to_owned(), + ), + CardState::OtherColor => ( + match side { + LearningSide::White => tr("No moves for White here"), + LearningSide::Black => tr("No moves for Black here"), + } + .to_owned(), + tr("This PGN may be a repertoire for the other colour").to_owned(), + ), + CardState::Counting => (tr("Counting moves…").to_owned(), String::new()), + CardState::Failed(error) => (tr("Cannot read this repertoire").to_owned(), error.clone()), + } +} + +/// The card's main button: label, enabled, what it does. +fn main_button(state: &CardState, side: LearningSide) -> (String, bool, Option) { + match state { + CardState::Review { .. } => (tr("Train").to_owned(), true, Some(MenuItem::Train)), + CardState::OnlyNew { new } => ( + trf("Learn {m} new", &[("m", new)]), + true, + Some(MenuItem::Train), + ), + CardState::Done { .. } => ( + tr("Review all lines").to_owned(), + true, + Some(MenuItem::ReviewAll), + ), + CardState::Empty => (tr("Add PGN…").to_owned(), true, Some(MenuItem::AddPgn)), + CardState::OtherColor => ( + match side { + LearningSide::White => tr("Play as Black"), + LearningSide::Black => tr("Play as White"), + } + .to_owned(), + true, + Some(MenuItem::SwitchColor), + ), + CardState::Counting => (tr("Train").to_owned(), false, None), + CardState::Failed(_) => (tr("Try again").to_owned(), true, Some(MenuItem::Train)), + } +} + +/// Row 3 of the card: learnt, in progress, the rest. +fn progress(ui: &mut Ui, stats: Option<&RowStats>) { + let width = ui.available_width(); + let (bar, _) = ui.allocate_exact_size(vec2(width, 8.0), egui::Sense::hover()); + let painter = ui.painter(); + painter.rect_filled(bar, 2.0, ui.visuals().extreme_bg_color); + if let Some(stats) = stats.filter(|stats| stats.total > 0) { + let total = stats.total as f32; + let learnt = bar.width() * stats.learnt as f32 / total; + let learning = bar.width() * stats.learning as f32 / total; + let fill = ui.visuals().selection.bg_fill; + painter.rect_filled( + egui::Rect::from_min_size(bar.min, vec2(learnt, bar.height())), + 2.0, + fill, + ); + painter.rect_filled( + egui::Rect::from_min_size(bar.min + vec2(learnt, 0.0), vec2(learning, bar.height())), + 0.0, + fill.gamma_multiply(0.45), + ); + } + ui.add_space(-2.0); + ui.horizontal(|ui| { + ui.set_height(20.0); + let (learnt, total, learning) = stats.map_or((0, 0, 0), |stats| { + (stats.learnt, stats.total, stats.learning) + }); + if stats.is_some() { + layout::line( + ui, + trf("Learned {x} of {y} moves", &[("x", &learnt), ("y", &total)]), + ); + } + if learning > 0 { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(RichText::new(trf("{k} in progress", &[("k", &learning)])).weak()); + }); + } + }); +} + +fn menu_items( + ui: &mut Ui, + side: LearningSide, + stats: Option<&Result>, +) -> Option { + let has_moves = matches!(stats, Some(Ok(stats)) if stats.total > 0); + let mut chosen = None; + let mut item = |ui: &mut Ui, enabled: bool, label: &str, value: MenuItem| { + if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + chosen = Some(value); + ui.close(); + } + }; + item(ui, has_moves, tr("Train"), MenuItem::Train); + item(ui, has_moves, tr("Review all lines"), MenuItem::ReviewAll); + item(ui, true, tr("Lines…"), MenuItem::Lines); + ui.separator(); + item(ui, true, tr("Rename…"), MenuItem::Rename); + item( + ui, + true, + match side { + LearningSide::White => tr("Play as Black"), + LearningSide::Black => tr("Play as White"), + }, + MenuItem::SwitchColor, + ); + item( + ui, + true, + tr("Add PGN to this repertoire…"), + MenuItem::AddPgn, + ); + item(ui, true, tr("Export PGN…"), MenuItem::Export); + ui.separator(); + item(ui, has_moves, tr("Reset progress…"), MenuItem::Reset); + item(ui, true, tr("Delete…"), MenuItem::Delete); + chosen +} + +/// The dialog's buttons on the right: «Cancel», then the main one. `danger`: both are +/// plain and Enter means «Cancel». Returns `Some(true)` to confirm, `Some(false)` to +/// cancel. +fn dialog_buttons( + ui: &mut Ui, + label: &str, + enabled: bool, + danger: Option<()>, + enter: bool, +) -> Option { + let mut result = None; + ui.add_space(12.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let main = if danger.is_some() { + ui.add_enabled(enabled, egui::Button::new(label).min_size(vec2(0.0, 30.0))) + } else { + ui.add_enabled_ui(enabled, |ui| crate::widgets::primary(ui, label)) + .inner + }; + if main.clicked() { + result = Some(true); + } + let cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(0.0, 30.0))); + if danger.is_some() && !ui.ctx().memory(|m| m.focused().is_some()) { + cancel.request_focus(); + } + if cancel.clicked() { + result = Some(false); + } + }); + if result.is_none() && enter { + if danger.is_some() { + result = Some(false); + } else if enabled { + result = Some(true); + } + } + result +} + +fn name_field(ui: &mut Ui, name: &mut String, error: &mut Option, select_all: bool) { + ui.label(RichText::new(tr("Name")).strong().size(15.0)); + let output = egui::TextEdit::singleline(name) + .char_limit(120) + .desired_width(f32::INFINITY) + .show(ui); + if select_all { + let mut state = output.state.clone(); + state + .cursor + .set_char_range(Some(egui::text::CCursorRange::two( + egui::text::CCursor::new(0), + egui::text::CCursor::new(name.chars().count()), + ))); + state.store(ui.ctx(), output.response.id); + output.response.request_focus(); + } + if output.response.changed() { + *error = None; + } + // The place of the error is kept: the dialog does not grow when it appears. + ui.allocate_ui(vec2(ui.available_width(), 18.0), |ui| { + if let Some(error) = error.as_deref() { + ui.label(RichText::new(error).color(ui.visuals().warn_fg_color)); + } + }); +} + +fn side_choice(ui: &mut Ui, side: &mut LearningSide) { + ui.add_space(4.0); + ui.label(RichText::new(tr("You play")).strong().size(15.0)); + ui.add_space(2.0); + ui.horizontal(|ui| { + for (value, label) in [ + (LearningSide::White, tr("♔ White")), + (LearningSide::Black, tr("♚ Black")), + ] { + if ui + .add_sized( + [222.0, 34.0], + egui::Button::selectable(*side == value, RichText::new(label).size(14.0)) + .frame_when_inactive(true), + ) + .clicked() + { + *side = value; + } + } + }); +} + +fn import_dialog( + ui: &mut Ui, + dialog: &mut ImportDialog, + name_of: impl Fn(&RepertoireId) -> String, + enter: bool, +) -> Option { + let adding = dialog.target.is_some(); + ui.heading(match &dialog.target { + Some(id) => trf("Add PGN to “{name}”", &[("name", &name_of(id))]), + None => tr("Import PGN").to_owned(), + }); + ui.add_space(8.0); + if !adding { + name_field(ui, &mut dialog.name, &mut dialog.error, false); + side_choice(ui, &mut dialog.side); + ui.label(RichText::new(tr("Chosen from the PGN — check it")).weak()); + ui.add_space(6.0); + } + let mut enabled = false; + let mut hover = None; + match &dialog.preview { + None => { + ui.label(RichText::new(tr("Reading the file…")).weak()); + ui.ctx().request_repaint_after(Duration::from_millis(50)); + } + Some(preview) => { + if adding { + let lines = preview.lines.saturating_sub(preview.lines_before); + if preview.report.added_nodes == 0 { + ui.label(RichText::new(tr("Nothing new in this file")).weak()); + } else { + ui.label( + RichText::new(trf( + "{m} new moves · {v} new lines", + &[("m", &preview.report.added_nodes), ("v", &lines)], + )) + .weak(), + ); + enabled = true; + } + } else { + let own = preview.own(dialog.side); + ui.label( + RichText::new(trf( + "{g} games · {v} lines · {y} your moves", + &[("g", &preview.games), ("v", &preview.lines), ("y", &own)], + )) + .weak(), + ); + enabled = own > 0 && !dialog.name.trim().is_empty(); + if own == 0 { + hover = Some(tr("No moves for this colour")); + } + } + for warning in preview.warnings.iter().take(WARNING_ROWS) { + layout::line(ui, RichText::new(warning).color(ui.visuals().warn_fg_color)); + } + if preview.warnings.len() > WARNING_ROWS { + ui.label( + RichText::new(trf( + "and {k} more", + &[("k", &(preview.warnings.len() - WARNING_ROWS))], + )) + .color(ui.visuals().warn_fg_color), + ); + } + if adding && let Some(error) = &dialog.error { + ui.label(RichText::new(error).color(ui.visuals().warn_fg_color)); + } + } + } + let label = if adding { tr("Add") } else { tr("Import") }; + let result = dialog_buttons(ui, label, enabled, None, enter); + if let Some(hover) = hover { + ui.label(RichText::new(hover).weak()); + } + result +} + +fn text_width(ui: &Ui, text: &str, size: f32) -> f32 { + ui.painter() + .layout_no_wrap( + text.to_owned(), + egui::FontId::proportional(size), + egui::Color32::WHITE, + ) + .size() + .x +} + +/// The colour whose moves a PGN repertoire gives: the side with fewer positions where +/// the PGN has several moves (one answer to many replies). White on a tie. +fn suggested_side(game: &Game) -> LearningSide { + let mut branching = [0usize; 2]; + let mut stack = vec![NodeId::ROOT]; + while let Some(node) = stack.pop() { + let children = game.children(node); + if children.len() > 1 + && let Some(position) = game.position(node) + { + branching[usize::from(position.turn() == Color::Black)] += 1; + } + stack.extend(children.iter().copied()); + } + if branching[1] < branching[0] { + LearningSide::Black + } else { + LearningSide::White + } +} + fn read_import( path: &Path, target: Option, @@ -2148,185 +2691,115 @@ fn read_import( if db.is_empty() { return Err(tr("No games").to_owned()); } + let base_revision = library.revision; let stem = path .file_stem() .map(|s| s.to_string_lossy().into_owned()) .unwrap_or_else(|| tr("New repertoire").to_owned()); - let mut name = stem.clone(); - let mut suffix = 2; - while library - .repertoires - .iter() - .any(|r| r.name.to_lowercase() == name.to_lowercase()) - { - name = format!("{stem} ({suffix})"); - suffix += 1; - } + let mut warnings = Vec::new(); let mut id = target.clone(); let mut report = MergeReport::default(); + let mut event = None; + let lines_before = target + .as_ref() + .and_then(|id| library.repertoire(id)) + .map_or(0, |r| layout::lines(&r.game(), |_| false).len()); for index in 0..db.len() { if cancel.load(Ordering::Relaxed) { - return Err(tr("Cancelled").to_owned()); + return Err(String::new()); } - let parsed = db - .load_game(index) - .ok_or_else(|| tr("No games").to_owned())?; + let Some(parsed) = db.load_game(index) else { + warnings.push(trf("Game {n}: could not be read", &[("n", &(index + 1))])); + continue; + }; if let Some(d) = parsed .diagnostics .iter() .find(|d| d.severity == Severity::Error) { - return Err(format!("PGN #{}: {}", index + 1, d.message)); + warnings.push(trf( + "Game {n}: {message}", + &[("n", &(index + 1)), ("message", &d.message)], + )); + } + if event.is_none() { + event = parsed + .game + .tag("Event") + .map(|value| value.trim().to_owned()) + .filter(|value| !value.is_empty() && value != "?"); + } + if parsed.game.children(NodeId::ROOT).is_empty() { + warnings.push(trf("Game {n} has no moves", &[("n", &(index + 1))])); + continue; } let current = match &id { Some(id) => id.clone(), None => { let new_id = library - .create(name.clone(), &Game::from_start(parsed.game.start().clone())) + .create(stem.clone(), &Game::from_start(parsed.game.start().clone())) .map_err(|e| e.to_string())?; id = Some(new_id.clone()); new_id } }; - let added = library - .add_game(¤t, &parsed.game) - .map_err(|e| format!("PGN #{}: {e}", index + 1))?; - report.added_nodes += added.added_nodes; - report.merged_nodes += added.merged_nodes; - report.annotation_changes += added.annotation_changes; + match library.add_game(¤t, &parsed.game) { + Ok(added) => { + report.added_nodes += added.added_nodes; + report.merged_nodes += added.merged_nodes; + report.annotation_changes += added.annotation_changes; + } + Err(error) => warnings.push(trf( + "Game {n}: {message}", + &[("n", &(index + 1)), ("message", &error.to_string())], + )), + } + } + let id = id.ok_or_else(|| tr("No games with moves in this file").to_owned())?; + let game = library + .repertoire(&id) + .map(|r| r.game()) + .ok_or_else(|| tr("No games").to_owned())?; + let own = [LearningSide::White, LearningSide::Black].map(|side| { + active_learning_keys(&library, &StatsScope::for_repertoire(id.clone(), side, 0)) + .map_or(0, |keys| keys.len()) + }); + let mut name = event.unwrap_or(stem); + let base = name.clone(); + let mut suffix = 2; + while library + .repertoires + .iter() + .any(|r| r.id != id && r.name.to_lowercase() == name.to_lowercase()) + { + name = format!("{base} ({suffix})"); + suffix += 1; } - let id = id.ok_or_else(|| tr("No games").to_owned())?; Ok(ImportPreview { + lines: layout::lines(&game, |_| false).len(), + lines_before, + suggested: suggested_side(&game), library, id, - records: db.len(), + base_revision, + games: db.len(), + own, + default_name: name, + warnings, report, - name, - target, }) } -fn pgn_route_count(tree: &RepertoireTree) -> usize { - let mut count = 0usize; - let _ = tree.visit_source_paths(&TrainingScope::whole(), |_| { - count = count.saturating_add(1); - std::ops::ControlFlow::Continue(()) - }); - count -} -fn start_kind(summary: &LearningAggregate) -> StartKind { - if summary.total == 0 { - StartKind::Unavailable - } else if summary.due > 0 { - StartKind::Review - } else if summary.unseen > 0 { - StartKind::IntroduceNew - } else { - StartKind::Unavailable - } -} -fn mode_start_kind(queue: QueueMode, summary: &LearningAggregate) -> StartKind { - match queue { - QueueMode::SpacedRepetition => start_kind(summary), - QueueMode::ReviewInOrder | QueueMode::LeastRecent if summary.total > 0 => StartKind::Review, - QueueMode::Practice | QueueMode::ReviewInOrder | QueueMode::LeastRecent => { - StartKind::Unavailable - } - } -} -fn queue_mode_label(queue: QueueMode) -> &'static str { - tr(match queue { - QueueMode::Practice | QueueMode::SpacedRepetition => "On schedule", - QueueMode::ReviewInOrder => "Review in order", - QueueMode::LeastRecent => "Least recent and unseen first", - }) -} -fn learning_priority_label(priority: LearningPriority) -> &'static str { - tr(match priority { - LearningPriority::DepthFirst => "Depth first", - LearningPriority::BreadthOverDepth => "Breadth over depth", - LearningPriority::MainLinesFirst => "Main lines first", - LearningPriority::CommonPositionsFirst => "Common positions first", - }) -} -fn training_mode(side: LearningSide) -> TrainingMode { - match side { - LearningSide::White => TrainingMode::White, - LearningSide::Black => TrainingMode::Black, - } -} -fn learning_side_label(side: LearningSide) -> &'static str { - tr(match side { - LearningSide::White => "White", - LearningSide::Black => "Black", - }) -} -fn opening_labels(tree: &RepertoireTree) -> Vec { - let mut labels = BTreeSet::new(); - let start = tree.game().start().position(); - let _ = tree.visit_source_paths(&TrainingScope::whole(), |moves| { - let mut position = start.clone(); - let mut keys = Vec::with_capacity(moves.len() + 1); - keys.push(chess_openings::key(&position)); - for uci in moves { - let Some(mv) = uci - .parse::() - .ok() - .and_then(|uci| uci.to_move(&position).ok()) - else { - return std::ops::ControlFlow::Continue(()); - }; - position.play_unchecked(mv); - keys.push(chess_openings::key(&position)); - } - if let Some((_, id)) = chess_openings::deepest(&keys) { - let opening = chess_openings::get(id); - labels.insert(OpeningLabel { - eco: opening.eco.clone(), - name: opening.name.clone(), - }); - } - std::ops::ControlFlow::Continue(()) - }); - labels.into_iter().collect() -} -fn table_text_line(ui: &mut Ui, text: RichText, height: f32) -> egui::Response { - ui.allocate_ui_with_layout( - egui::vec2(ui.available_width(), height), - egui::Layout::left_to_right(egui::Align::Center), - |ui| { - ui.add( - egui::Label::new(text) - .selectable(false) - .truncate() - .halign(egui::Align::Min), - ) - }, - ) - .inner +fn load_library(store: &LibraryStore) -> Result { + let mut library = store.load().map_err(|error| error.to_string())?; + // The depth limit of 2.2 is not a user's choice: trained lines go to their ends. + // The PGN does not change. + for repertoire in &mut library.repertoires { + repertoire.set_max_plies(u32::MAX); + } + Ok(library) } -fn count_cell(ui: &mut Ui, count: Option) { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if let Some(count) = count { - ui.label(count.to_string()); - } else { - ui.spinner(); - ui.ctx() - .request_repaint_after(std::time::Duration::from_millis(100)); - } - }); -} -fn now() -> i64 { - web_time::SystemTime::now() - .duration_since(web_time::UNIX_EPOCH) - .map_or(0, |d| d.as_secs() as i64) -} -fn load_library(store: &LibraryStore) -> Result { - store.load().map_err(|error| LibraryLoadError { - message: error.to_string(), - }) -} fn prefix_label(game: &Game, at: NodeId) -> String { game.path(at) .into_iter() @@ -2336,6 +2809,7 @@ fn prefix_label(game: &Game, at: NodeId) -> String { .collect::>() .join(" ") } + fn stores() -> (LibraryStore, LearningStore) { let legacy = std::env::var_os("CP_TRAINING_FILE") .map(PathBuf::from) diff --git a/apps/desktop/src/repertoire_ui_tests.rs b/apps/desktop/src/repertoire_ui_tests.rs index 3c1a32a..3e0542a 100644 --- a/apps/desktop/src/repertoire_ui_tests.rs +++ b/apps/desktop/src/repertoire_ui_tests.rs @@ -1,1727 +1,525 @@ -use super::*; use std::sync::atomic::AtomicU64; -use std::time::Duration; -static NEXT_TEST: AtomicU64 = AtomicU64::new(0); +use super::*; +use trainer::repertoire::{QueueMode, TrainingMode, active_learning_memberships}; -struct Fixture { - ui: RepertoireUi, - settings: Settings, - dir: PathBuf, - id: RepertoireId, -} +static NEXT_DIR: AtomicU64 = AtomicU64::new(1); +const DAY: i64 = 24 * 60 * 60; -impl Fixture { - fn new() -> Self { - let dir = std::env::temp_dir().join(format!( - "cp-repertoire-ui-{}-{}", +struct TestDir(PathBuf); + +impl TestDir { + fn new(name: &str) -> Self { + let path = std::env::temp_dir().join(format!( + "cp-repertoire-ui-{}-{}-{name}", std::process::id(), - NEXT_TEST.fetch_add(1, Ordering::Relaxed) + NEXT_DIR.fetch_add(1, Ordering::Relaxed) )); - let library_store = LibraryStore::new(dir.join("library.json")); - let mut library = Library::default(); - let id = library - .create("Async opening", &chess_core::parse_str("1. e4 e5 *").game) - .unwrap(); - library_store.save(&mut library).unwrap(); - let mut ui = - RepertoireUi::with_stores(library_store, LearningStore::new(dir.join("learning.json"))); - let event = ui.rx.recv_timeout(Duration::from_secs(5)).unwrap(); - ui.tx.send(event).unwrap(); - let mut settings = Settings::default(); - ui.poll(&mut settings); - assert!(!ui.indexing); - ui.select(id.clone(), &settings); - Self { - ui, - settings, - dir, - id, - } + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Self(path) } - fn completed_job(&self) -> Event { - self.ui.rx.recv_timeout(Duration::from_secs(5)).unwrap() + fn stores(&self) -> (LibraryStore, LearningStore) { + ( + LibraryStore::new(self.0.join("repertoires.json")), + LearningStore::new(self.0.join("repertoire-training.json")), + ) } - fn deliver(&mut self, event: Event) { - self.ui.tx.send(event).unwrap(); - self.ui.poll(&mut self.settings); - } - - fn aggregate(&mut self) -> ScopedLearningAggregate { - for _ in 0..4 { - if self.ui.selected_aggregate().is_some() { - break; - } - let event = self.completed_job(); - self.deliver(event); - } - self.ui.selected_aggregate().cloned().expect("aggregate") - } - - fn start(&mut self) { - self.ui.side = LearningSide::White; - self.aggregate(); - self.ui.start(&mut self.settings); - assert!(self.ui.preparing); + fn ui(&self) -> RepertoireUi { + let (library, learning) = self.stores(); + RepertoireUi::with_stores(library, learning) } } -impl Drop for Fixture { +impl Drop for TestDir { fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.dir); + let _ = std::fs::remove_dir_all(&self.0); } } -fn render_library(f: &mut Fixture, ctx: &egui::Context, width: f32, time: f64) { +fn save_library(dir: &TestDir, repertoires: &[(&str, &str)]) -> Vec { + let mut library = Library::default(); + let ids = repertoires + .iter() + .map(|(name, pgn)| { + library + .create(*name, &chess_core::parse_str(pgn).game) + .unwrap() + }) + .collect(); + dir.stores().0.save(&mut library).unwrap(); + ids +} + +/// Frames until the background index and counts are in. +fn settle(ui: &mut RepertoireUi, ctx: &egui::Context, settings: &mut Settings, size: egui::Vec2) { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + frame(ui, ctx, settings, size, Vec::new()); + let ready = ui.preparing.is_none() + && ui.lines_job.is_none() + && !ui.learning_loading + && ui + .library + .repertoires + .iter() + .all(|r| ui.index.contains_key(&r.id) && ui.stats.contains_key(&r.id)) + && ui.stats_key.as_ref().is_some_and(|key| { + key.library_revision == ui.library.revision + && key.learning_revision == ui.learning.revision + }); + if ready || Instant::now() > deadline { + frame(ui, ctx, settings, size, Vec::new()); + return; + } + std::thread::sleep(Duration::from_millis(2)); + } +} + +fn frame( + ui: &mut RepertoireUi, + ctx: &egui::Context, + settings: &mut Settings, + size: egui::Vec2, + events: Vec, +) -> Vec { + let mut actions = Vec::new(); ctx.run_ui( egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, 900.0), - )), - time: Some(time), - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - f.ui.show_library(ui, &f.settings); - }); - }, - ) - .drop_without_applying_deltas(); -} - -fn render_repertoire( - f: &mut Fixture, - ctx: &egui::Context, - width: f32, - time: f64, - events: Vec, -) -> Vec { - render_repertoire_frame(f, ctx, width, 700.0, time, events).1 -} - -fn render_repertoire_frame( - f: &mut Fixture, - ctx: &egui::Context, - width: f32, - height: f32, - time: f64, - events: Vec, -) -> (Vec, Vec) { - let mut actions = Vec::new(); - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - actions = f.ui.show(ui, &mut f.settings); - }); - }, - ); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - (actions, shapes) + |root| actions = ui.show(root, settings), + ) + .drop_without_applying_deltas(); + actions } -fn click_events(position: egui::Pos2) -> Vec { - vec![ - egui::Event::PointerMoved(position), - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }, - ] +fn panel_rect(ctx: &egui::Context) -> egui::Rect { + egui::containers::panel::PanelState::load(ctx, egui::Id::new("opening_side")) + .map(|state| state.outer_rect) + .unwrap_or(egui::Rect::NOTHING) +} + +fn key(key: Key) -> egui::Event { + egui::Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers: Modifiers::NONE, + } } #[test] -fn first_entry_restores_selected_preferences_and_starts_without_reselecting() { - let mut f = Fixture::new(); - f.settings.repertoire_modes.insert( - f.id.to_string(), +fn the_card_says_what_to_do_in_every_state() { + let stats = |due, unseen, total| RowStats { + total, + due, + unseen, + learning: 0, + learnt: total - unseen, + next: None, + }; + assert_eq!(card_state(Some(true), None), CardState::Counting); + assert_eq!( + card_state(Some(true), Some(&Err("broken".into()))), + CardState::Failed("broken".into()) + ); + assert_eq!( + card_state(Some(false), Some(&Ok(stats(0, 0, 0)))), + CardState::Empty + ); + assert_eq!( + card_state(Some(true), Some(&Ok(stats(0, 0, 0)))), + CardState::OtherColor + ); + assert_eq!( + card_state(Some(true), Some(&Ok(stats(3, 40, 50)))), + CardState::Review { due: 3, new: 10 } + ); + assert_eq!( + card_state(Some(true), Some(&Ok(stats(0, 4, 50)))), + CardState::OnlyNew { new: 4 } + ); + assert_eq!( + card_state(Some(true), Some(&Ok(stats(0, 0, 50)))), + CardState::Done { next: None } + ); + // Every state has a main button that does something, but «Counting». + for (state, side) in [ + (CardState::Review { due: 3, new: 10 }, LearningSide::White), + (CardState::OnlyNew { new: 4 }, LearningSide::White), + ( + CardState::Done { + next: Some((1_800_000_000, 2)), + }, + LearningSide::White, + ), + (CardState::Empty, LearningSide::White), + (CardState::OtherColor, LearningSide::White), + (CardState::Failed("x".into()), LearningSide::Black), + ] { + let (label, enabled, item) = main_button(&state, side); + assert!(enabled && item.is_some() && !label.is_empty(), "{state:?}"); + let (today, _) = card_texts(&state, side); + assert!(!today.is_empty(), "{state:?}"); + } + assert!(!main_button(&CardState::Counting, LearningSide::White).1); + assert_eq!( + main_button(&CardState::OtherColor, LearningSide::White).0, + tr("Play as Black") + ); + assert_eq!( + card_texts(&CardState::Review { due: 3, new: 10 }, LearningSide::White), + ( + trf("Today: {n} to review · {m} new", &[("n", &3), ("m", &10)]), + trf("About {t} min", &[("t", &5)]) + ) + ); + // Under a minute the time is not shown; a part with zero is left out. + assert_eq!( + card_texts(&CardState::Review { due: 2, new: 0 }, LearningSide::White), + (trf("Today: {n} to review", &[("n", &2)]), String::new()) + ); +} + +#[test] +fn today_counts_until_the_end_of_the_day_and_at_most_ten_new() { + let mut library = Library::default(); + let pgn = "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 \ + 8. c3 O-O 9. h3 Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 *"; + let id = library + .create("Ruy", &chess_core::parse_str(pgn).game) + .unwrap(); + let today = layout::end_of_today(); + let scope = StatsScope::for_repertoire(id.clone(), LearningSide::White, today); + let keys: Vec<_> = active_learning_memberships(&library, &scope) + .unwrap() + .into_iter() + .map(|membership| membership.key) + .collect(); + assert_eq!(keys.len(), 12); + let mut learning = LearningData::default(); + let now = layout::now(); + for (index, key) in keys.iter().take(3).enumerate() { + let item = learning.ensure_item(key.clone()); + item.introduced = true; + item.correct_streak = 3; + // Due later today, due long ago, due in two days. + item.next_review_at = Some(match index { + 0 => today - 1, + 1 => now - 10 * DAY, + _ => now + 2 * DAY, + }); + } + let stats = row_stats(&library, &learning, &id, LearningSide::White, today).unwrap(); + assert_eq!( + (stats.total, stats.due, stats.unseen, stats.learnt), + (12, 2, 9, 3) + ); + assert_eq!(stats.new_today(), 9); + assert_eq!(stats.today(), 11); + assert_eq!( + card_state(Some(true), Some(&Ok(stats.clone()))), + CardState::Review { due: 2, new: 9 } + ); + let black = row_stats(&library, &learning, &id, LearningSide::Black, today).unwrap(); + assert_eq!(black.total, 11); + assert_eq!(black.new_today(), NEW_PER_SESSION); +} + +#[test] +fn loading_lifts_the_old_depth_limit_without_touching_the_pgn() { + let dir = TestDir::new("depth"); + let ids = save_library(&dir, &[("Limited", "1. e4 e5 2. Nf3 *")]); + let (store, _) = dir.stores(); + let stored = store.load().unwrap(); + assert_eq!( + stored.repertoires[0].max_plies, + trainer::repertoire::DEFAULT_MAX_PLIES + ); + let ui = dir.ui(); + let repertoire = ui.library.repertoire(&ids[0]).unwrap(); + assert_eq!(repertoire.max_plies, u32::MAX); + assert_eq!(repertoire.pgn, stored.repertoires[0].pgn); + // Nothing is written until the user changes something. + assert_eq!( + store.load().unwrap().repertoires[0].max_plies, + stored.repertoires[0].max_plies + ); +} + +#[test] +fn an_import_reads_name_colour_counts_and_warnings() { + let dir = TestDir::new("import"); + let path = dir.0.join("caro.pgn"); + std::fs::write( + &path, + "[Event \"Caro-Kann for Black\"]\n\n1. e4 c6 2. d4 (2. Nc3 d5) (2. c4 d5) d5 *\n\n\ + [Event \"Empty\"]\n\n*\n", + ) + .unwrap(); + let preview = read_import(&path, None, Library::default(), &AtomicBool::new(false)).unwrap(); + assert_eq!(preview.default_name, "Caro-Kann for Black"); + assert_eq!(preview.suggested, LearningSide::Black); + assert_eq!(preview.games, 2); + assert_eq!(preview.lines, 3); + assert_eq!(preview.own(LearningSide::Black), 4); + assert_eq!(preview.own(LearningSide::White), 4); + assert_eq!( + preview.warnings, + [trf("Game {n} has no moves", &[("n", &2)])] + ); + // The source file is only read. + assert!( + std::fs::read_to_string(&path) + .unwrap() + .starts_with("[Event \"Caro-Kann") + ); + + let mut ui = dir.ui(); + let mut settings = Settings::default(); + ui.dialog = Some(Dialog::Import(ImportDialog { + job: 1, + target: None, + name: preview.default_name.clone(), + side: preview.suggested, + preview: Some(preview), + error: None, + cancel: Arc::new(AtomicBool::new(false)), + })); + assert!(ui.confirm_import(&mut settings)); + let id = ui.selected.clone().unwrap(); + assert_eq!( + ui.library.repertoire(&id).unwrap().name, + "Caro-Kann for Black" + ); + assert_eq!(layout::side_of(&settings, &id), LearningSide::Black); + assert_eq!( + settings.repertoire_modes.get(id.as_str()), + Some(&(TrainingMode::Black, QueueMode::SpacedRepetition)) + ); + assert_eq!(dir.stores().0.load().unwrap().repertoires.len(), 1); +} + +#[test] +fn a_white_repertoire_is_suggested_for_white() { + let game = chess_core::parse_str("1. e4 e5 (1... c5 2. Nf3) (1... e6 2. d4) 2. Nf3 *").game; + assert_eq!(suggested_side(&game), LearningSide::White); + let even = chess_core::parse_str("1. e4 e5 *").game; + assert_eq!(suggested_side(&even), LearningSide::White); +} + +#[test] +fn old_colours_open_as_before_and_both_opens_as_white() { + let mut settings = Settings::default(); + let id = Library::default().create_empty("Any").unwrap(); + assert_eq!(layout::side_of(&settings, &id), LearningSide::White); + settings.repertoire_modes.insert( + id.to_string(), (TrainingMode::Black, QueueMode::ReviewInOrder), ); - f.settings - .repertoire_priorities - .insert(f.id.to_string(), LearningPriority::BreadthOverDepth); - f.ui = RepertoireUi::with_stores(f.ui.library_store.clone(), f.ui.learning_store.clone()); - assert_eq!(f.ui.selected.as_ref(), Some(&f.id)); - let ctx = egui::Context::default(); - // Production entry: show(), without the debug_open/select hooks. - render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.0, Vec::new()); - assert_eq!(f.ui.side, LearningSide::Black); - assert_eq!(f.ui.queue, QueueMode::ReviewInOrder); - assert_eq!(f.ui.priority, LearningPriority::BreadthOverDepth); - f.aggregate(); - render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 1.0, Vec::new()); - let train = f.ui.debug_layout.action_buttons[0].unwrap().center(); - render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 2.0, click_events(train)); - assert!( - f.ui.preparing, - "the selected repertoire starts on the first click" - ); - while f.ui.preparing { - f.deliver(f.completed_job()); - } - assert!(f.ui.training_visible); -} - -fn text_click_position(shapes: &[egui::epaint::ClippedShape], text: &str) -> egui::Pos2 { - shapes - .iter() - .find_map(|clipped| match &clipped.shape { - egui::Shape::Text(shape) if shape.galley.text() == text => { - Some(shape.pos + egui::vec2(8.0, 6.0)) - } - _ => None, - }) - .unwrap_or_else(|| panic!("missing text {text:?}")) -} - -fn assert_rect_inside(outer: egui::Rect, inner: egui::Rect) { - assert!(inner.min.x >= outer.min.x, "{inner:?} outside {outer:?}"); - assert!(inner.min.y >= outer.min.y, "{inner:?} outside {outer:?}"); - assert!(inner.max.x <= outer.max.x, "{inner:?} outside {outer:?}"); - assert!(inner.max.y <= outer.max.y, "{inner:?} outside {outer:?}"); - assert!(inner.width() > 0.0, "empty rect: {inner:?}"); - assert!(inner.height() > 0.0, "empty rect: {inner:?}"); -} - -#[test] -fn dashboard_close_reloads_learning_and_preserves_repertoire_selection() { - let mut f = Fixture::new(); - f.ui.side = LearningSide::Black; - let ctx = egui::Context::default(); - let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 0.0, Vec::new()); - let details = text_click_position(&shapes, "Statistics"); - - let (actions, _) = - render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 1.0, click_events(details)); - - assert!(actions.is_empty()); - assert_eq!( - f.ui.dashboard - .as_ref() - .and_then(LearningDashboardUi::selected_repertoire), - Some(&f.id) - ); - assert_eq!( - f.ui.dashboard - .as_ref() - .map(LearningDashboardUi::selected_side), - Some(LearningSide::Black) - ); - f.ui.dashboard.as_mut().unwrap().wait_until_idle_for_test(); - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::Black, now()); - let key = active_learning_keys(&f.ui.library, &scope) - .unwrap() - .into_iter() - .next() - .unwrap(); - let mut data = f.ui.learning_store.load().unwrap(); - assert_eq!(data.snapshots.len(), 1); - data.revision = 23; - data.learning.ensure_item(key.clone()).introduced = true; - std::fs::write( - f.ui.learning_store.path(), - serde_json::to_vec_pretty(&data).unwrap(), - ) - .unwrap(); - let (actions, shapes) = render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 2.0, Vec::new()); - assert!(actions.is_empty()); - let close = text_click_position(&shapes, "← Back to repertoire"); - f.ui.scroll_to_selected = false; - - let (actions, _) = - render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 3.0, click_events(close)); - - assert!(actions.is_empty()); - assert!(f.ui.dashboard.is_none()); - assert_eq!(f.ui.selected.as_ref(), Some(&f.id)); - assert_eq!(f.ui.learning.revision, 23); - assert!(f.ui.learning.learning.item(&key).unwrap().introduced); - assert!(!f.ui.scroll_to_selected); - - data.revision = 24; - std::fs::write( - f.ui.learning_store.path(), - serde_json::to_vec_pretty(&data).unwrap(), - ) - .unwrap(); - let before_reopen = std::fs::read(f.ui.learning_store.path()).unwrap(); - f.ui.open_dashboard(); - assert!(f.ui.dashboard.is_some()); - f.ui.dashboard.as_mut().unwrap().wait_until_idle_for_test(); - assert_eq!( - std::fs::read(f.ui.learning_store.path()).unwrap(), - before_reopen - ); - f.ui.scroll_to_selected = false; - let (actions, _) = render_repertoire_frame( - &mut f, - &ctx, - 1400.0, - 900.0, - 4.0, - vec![egui::Event::Key { - key: Key::Escape, - physical_key: None, - pressed: true, - repeat: false, - modifiers: Modifiers::NONE, - }], - ); - - assert!(actions.is_empty()); - assert!(f.ui.dashboard.is_none()); - assert_eq!(f.ui.selected.as_ref(), Some(&f.id)); - assert_eq!(f.ui.learning.revision, 24); - assert!(!f.ui.scroll_to_selected); -} - -#[test] -fn compact_statistics_shows_actionable_counts() { - let mut f = Fixture::new(); - f.aggregate(); - let ctx = egui::Context::default(); - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(640.0, 480.0), - )), - ..Default::default() - }, - |ui| f.ui.statistics_panel(ui), - ); - let has_text = |expected: &str| { - output.shapes.iter().any(|clipped| { - matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text().replace('\n', " ") == expected) - }) - }; - assert!(has_text("Learnt 0 of 1 moves")); - assert!(has_text("Unseen: 1 · Due now: 0")); - output.drop_without_applying_deltas(); -} - -#[test] -fn dashboard_does_not_open_over_editor_or_preparing_training() { - let mut f = Fixture::new(); - f.ui.open_editor(); - - f.ui.open_dashboard(); - assert!(f.ui.dashboard.is_none()); - - f.ui.close_editor(); - f.ui.preparing = true; - f.ui.open_dashboard(); - assert!(f.ui.dashboard.is_none()); -} - -#[test] -fn dashboard_uses_the_full_workspace_at_both_window_sizes() { - for (width, height) in [(1400.0, 900.0), (640.0, 480.0)] { - let mut f = Fixture::new(); - f.ui.open_dashboard(); - let ctx = egui::Context::default(); - let mut bounds = None; - let mut actions = Vec::new(); - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - let available = ui.available_rect_before_wrap(); - actions = f.ui.show(ui, &mut f.settings); - bounds = Some((available, ui.min_rect())); - }); - }, - ); - let dashboard_visible = output.shapes.iter().any(|clipped| { - matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text() == "Training statistics") - }); - let repertoire_header_visible = output.shapes.iter().any(|clipped| { - matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text() == "Opening training (α version)") - }); - output.drop_without_applying_deltas(); - - assert!(actions.is_empty()); - assert!(dashboard_visible); - assert!(!repertoire_header_visible); - let (available, content) = bounds.unwrap(); - assert_rect_inside(available, content); - assert!(f.ui.dashboard.is_some()); - assert_eq!(f.ui.selected.as_ref(), Some(&f.id)); - f.ui.dashboard.as_mut().unwrap().wait_until_idle_for_test(); - } -} - -#[test] -fn early_paths_paint_opaque_window_background_without_allocating() { - for visuals in [egui::Visuals::light(), egui::Visuals::dark()] { - for (width, height) in [(1400.0, 900.0), (960.0, 600.0), (640.0, 480.0)] { - for editor in [false, true] { - let mut f = Fixture::new(); - if editor { - f.ui.open_editor(); - } else { - f.ui.open_dashboard(); - } - let ctx = egui::Context::default(); - ctx.set_visuals(visuals.clone()); - let mut available = None; - let mut content = None; - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - available = Some(ui.available_rect_before_wrap()); - let actions = f.ui.show(ui, &mut f.settings); - assert!(actions.is_empty()); - content = Some(ui.min_rect()); - }); - }, - ); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - let available = available.unwrap(); - assert_rect_inside(available, content.unwrap()); - assert!(shapes.iter().any(|clipped| { - matches!(&clipped.shape, egui::Shape::Rect(shape) if shape.rect == available && shape.fill == visuals.window_fill() && shape.fill.a() == 255) - })); - if editor { - assert!(f.ui.debug_layout.editor.is_some()); - } else { - f.ui.dashboard.as_mut().unwrap().wait_until_idle_for_test(); - } - } - } - } -} - -#[test] -fn creating_an_empty_repertoire_selects_it_in_the_workspace() { - let mut f = Fixture::new(); - f.ui.open_library(); - f.ui.edit_name = Some((None, "Empty opening".to_owned())); - - f.ui.save_name(None, "Empty opening", &f.settings); - - let created = - f.ui.library - .repertoires - .iter() - .find(|r| r.name == "Empty opening") - .expect("the repertoire is saved"); - assert!(!f.ui.training_visible); - assert_eq!(f.ui.selected.as_ref(), Some(&created.id)); - assert!(f.ui.edit_name.is_none()); - assert!(f.ui.error.is_none()); -} - -#[test] -fn editor_opens_in_the_full_workspace() { - let mut f = Fixture::new(); - f.ui.open_editor(); - let ctx = egui::Context::default(); - - render_repertoire(&mut f, &ctx, 1000.0, 0.0, Vec::new()); - - let editor_rect = f.ui.debug_layout.editor.unwrap(); - assert!(editor_rect.width() > 900.0, "{editor_rect:?}"); - assert!(f.ui.editor.is_some()); - assert_eq!(f.ui.editor_id.as_ref(), Some(&f.id)); -} - -#[test] -fn applied_editor_library_is_adopted_without_a_second_save() { - let mut f = Fixture::new(); - f.ui.open_editor(); - let mut applied = f.ui.library.clone(); - applied.repertoire_mut(&f.id).unwrap().set_max_plies(7); - f.ui.library_store.save(&mut applied).unwrap(); - let before = std::fs::read(f.ui.library_store.path()).unwrap(); - let expected = applied.clone(); - let generation = f.ui.index_generation; - - let _ = f.ui.handle_editor_action(RepertoireEditorAction::Applied { - repertoire_id: f.id.clone(), - library: applied, - }); - - assert_eq!( - serde_json::to_value(&f.ui.library).unwrap(), - serde_json::to_value(&expected).unwrap() - ); - assert_eq!(std::fs::read(f.ui.library_store.path()).unwrap(), before); - assert!(f.ui.index_generation > generation); - assert!(f.ui.editor.is_none()); - assert!(f.ui.editor_id.is_none()); -} - -#[test] -fn cancelling_editor_does_not_change_library_bytes() { - let mut f = Fixture::new(); - f.ui.open_editor(); - let before = std::fs::read(f.ui.library_store.path()).unwrap(); - let library = f.ui.library.clone(); - - let _ = f.ui.handle_editor_action(RepertoireEditorAction::Cancel); - - assert!(f.ui.editor.is_none()); - assert_eq!( - serde_json::to_value(&f.ui.library).unwrap(), - serde_json::to_value(&library).unwrap() - ); - assert_eq!(std::fs::read(f.ui.library_store.path()).unwrap(), before); -} - -#[test] -fn editor_draft_blocks_selection_start_and_unresolved_exit() { - let mut f = Fixture::new(); - let mut library = f.ui.library.clone(); - let second = library - .create("Other opening", &chess_core::parse_str("1. d4 d5 *").game) - .unwrap(); - assert!(f.ui.persist(library)); - f.deliver(f.completed_job()); - f.ui.select(f.id.clone(), &f.settings); - f.ui.open_editor(); - let ctx = egui::Context::default(); - let shapes = render_repertoire(&mut f, &ctx, 1000.0, 0.0, Vec::new()); - let start = shapes - .iter() - .find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) if text.galley.text() == "20" => { - Some(text.pos + egui::vec2(8.0, 6.0)) - } - _ => None, - }) - .expect("depth DragValue text"); - render_repertoire( - &mut f, - &ctx, - 1000.0, - 1.0, - vec![ - egui::Event::PointerMoved(start), - egui::Event::PointerButton { - pos: start, - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: start, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: start, - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: start, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }, - ], - ); - render_repertoire( - &mut f, - &ctx, - 1000.0, - 2.0, - vec![ - egui::Event::Text("7".to_owned()), - egui::Event::Key { - key: egui::Key::Enter, - physical_key: None, - pressed: true, - repeat: false, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::Key { - key: egui::Key::Enter, - physical_key: None, - pressed: false, - repeat: false, - modifiers: egui::Modifiers::NONE, - }, - ], - ); - assert!(f.ui.has_unsaved(), "edit did not change the editor depth"); - let before = std::fs::read(f.ui.library_store.path()).unwrap(); - - f.ui.select(second, &f.settings); - assert_eq!(f.ui.selected.as_ref(), Some(&f.id)); - assert!(f.ui.editor.is_some()); - f.ui.start(&mut f.settings); - assert!(!f.ui.preparing); - assert!(f.ui.editor.is_some()); - f.ui.resolve_unsaved(); - assert!(f.ui.editor.is_some()); - assert!(!f.ui.training_visible); - assert_eq!(std::fs::read(f.ui.library_store.path()).unwrap(), before); -} - -#[test] -fn stale_applied_is_ignored_after_changing_repertoire() { - let mut f = Fixture::new(); - let mut library = f.ui.library.clone(); - let second = library - .create("Other opening", &chess_core::parse_str("1. d4 d5 *").game) - .unwrap(); - assert!(f.ui.persist(library)); - f.deliver(f.completed_job()); - f.ui.select(f.id.clone(), &f.settings); - f.ui.open_editor(); - let current = f.ui.library.clone(); - let before = std::fs::read(f.ui.library_store.path()).unwrap(); - let mut stale = current.clone(); - stale.revision = current.revision.saturating_add(1); - stale.repertoire_mut(&f.id).unwrap().set_max_plies(3); - f.ui.select(second.clone(), &f.settings); - - let _ = f.ui.handle_editor_action(RepertoireEditorAction::Applied { - repertoire_id: f.id.clone(), - library: stale, - }); - - assert_eq!(f.ui.selected.as_ref(), Some(&second)); - assert_eq!( - serde_json::to_value(&f.ui.library).unwrap(), - serde_json::to_value(¤t).unwrap() - ); - assert_eq!(std::fs::read(f.ui.library_store.path()).unwrap(), before); - assert!(f.ui.editor.is_none()); -} - -#[test] -fn clicking_a_row_selects_it_without_leaving_the_workspace() { - let mut f = Fixture::new(); - f.ui.open_library(); - f.ui.selected = None; - let ctx = egui::Context::default(); - let mut frame = |time: f64, events: Vec| { - ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(1000.0, 700.0), - )), - time: Some(time), - events, - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - f.ui.show_library(ui, &f.settings); - }); - }, - ) - .drop_without_applying_deltas(); - (f.ui.selected.clone(), f.ui.training_visible) - }; - let click = || { - let position = egui::pos2(200.0, 120.0); - vec![ - egui::Event::PointerMoved(position), - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }, - ] - }; - - frame(0.0, Vec::new()); - let (selected, training) = frame(1.0, click()); - assert_eq!(selected.as_ref(), Some(&f.id)); - assert!(!training); - assert!(f.ui.tree.is_some()); -} - -#[test] -fn long_save_error_and_import_cancel_stay_inside_the_fixed_status_row() { - for width in [640.0_f32, 1400.0] { - let mut f = Fixture::new(); - f.ui.side = LearningSide::White; - let ctx = egui::Context::default(); - render_library(&mut f, &ctx, width, 0.0); - let baseline = f.ui.debug_layout; - let baseline_status = baseline.status.unwrap(); - let baseline_table = baseline.table.unwrap(); - assert_eq!(baseline_status.height(), 24.0); - assert!(baseline_table.height() > 0.0); - - let path = f - .dir - .join("a-very-long-save-error-parent-directory-for-layout-regression") - .join("another-long-directory-component-that-makes-the-error-wrap") - .join("learning.json"); - let file_name = path.file_name().unwrap().to_string_lossy().into_owned(); - let lock = path.with_file_name(format!("{file_name}.lock")); - std::fs::create_dir_all(&lock).unwrap(); - let attempt = trainer::repertoire::TrainingAttempt { - user_id: trainer::repertoire::LOCAL_PROFILE_ID.to_owned(), - position_fen4: fen4(&chess_core::shakmaty::Chess::default()), - client_attempt_id: "status-layout-error".to_owned(), - session_id: "status-layout-session".to_owned(), - event_type: trainer::repertoire::TrainingEventType::CorrectIndependent, - expected_uci: "e2e4".to_owned(), - actual_uci: Some("e2e4".to_owned()), - response_time_ms: Some(1), - happened_at: now(), - }; - let error = LearningStore::new(&path) - .apply_attempt(attempt, &SrsSettings::default()) - .unwrap_err() - .to_string(); - assert!(error.len() > 160, "short fixture error: {error}"); - assert!(error.contains("learning.json.lock"), "{error}"); - f.ui.error = Some(error); - f.ui.cancel = Some(Arc::new(AtomicBool::new(false))); - - render_library(&mut f, &ctx, width, 1.0); - - let with_error = f.ui.debug_layout; - let status = with_error.status.unwrap(); - let message = with_error.message.unwrap(); - let retry = with_error.retry.unwrap(); - let cancel = with_error.cancel.unwrap(); - assert_eq!(status, baseline_status); - assert_eq!(with_error.table, baseline.table); - assert_rect_inside(status, message); - assert_rect_inside(status, retry); - assert_rect_inside(status, cancel); - assert!(message.max.x <= cancel.min.x, "{message:?} {cancel:?}"); - assert!(cancel.max.x <= retry.min.x, "{cancel:?} {retry:?}"); - assert!(status.bottom() <= with_error.table.unwrap().top()); - assert_eq!(f.ui.side, LearningSide::White); - assert!(f.ui.error.is_some()); - } -} - -#[test] -fn opening_index_has_the_deepest_eco_and_variation_name() { - let game = chess_core::parse_str("1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 4. O-O *").game; - let mut library = Library::default(); - let id = library.create("Rossolimo", &game).unwrap(); - let tree = RepertoireTree::new(library.repertoire(&id).unwrap()); - - let labels = opening_labels(&tree); - - assert_eq!(labels.len(), 1); - assert_eq!(labels[0].eco, "B31"); - assert!( - labels[0] - .name - .starts_with("Sicilian Defense: Nyezhmetdinov-Rossolimo Attack"), - "{}", - labels[0].name - ); -} - -#[test] -fn rows_have_one_height_and_show_at_most_five_opening_names() { - let f = Fixture::new(); - let row = |count: usize| LibraryRow { - id: f.id.clone(), - name: "Opening".to_owned(), - openings: (0..count) - .map(|index| OpeningLabel { - eco: format!("B{index:02}"), - name: format!("Opening {index}"), - }) - .collect(), - }; - - assert_eq!(LibraryRow::height(), 156.0); - assert_eq!(row(0).visible_openings().len(), 0); - assert_eq!(row(3).visible_openings().len(), 3); - assert_eq!(row(8).visible_openings().len(), OPENING_LINES); -} - -#[test] -fn load_preserves_scope_and_main_answer_overrides() { - let f = Fixture::new(); - let store = LibraryStore::new(f.dir.join("scoped-library.json")); - let mut library = Library::default(); - let id = library - .create("Scoped opening", &chess_core::parse_str("1. e4 e5 *").game) - .unwrap(); - let repertoire = library.repertoire_mut(&id).unwrap(); - repertoire.max_plies = 1; - repertoire - .set_prefix_disabled(&["e2e4".to_owned()], true) - .unwrap(); - let start = fen4(repertoire.game().start().position()); - repertoire - .set_main_answer_override(&start, "e2e4", LearningSide::White) - .unwrap(); - let pgn = repertoire.pgn.clone(); - let overrides = repertoire.main_answer_overrides.clone(); - store.save(&mut library).unwrap(); - - let ui = RepertoireUi::with_stores( - store.clone(), - LearningStore::new(f.dir.join("scoped-learning.json")), - ); - - assert!(ui.library_error.is_none(), "{:?}", ui.library_error); - let saved = store.load().unwrap(); - for library in [&ui.library, &saved] { - let repertoire = library.repertoire(&id).unwrap(); - assert_eq!(repertoire.max_plies, 1); - assert_eq!(repertoire.disabled_prefixes, [vec!["e2e4".to_owned()]]); - assert_eq!(repertoire.main_answer_overrides, overrides); - assert_eq!(repertoire.pgn, pgn); - } -} - -#[test] -fn persist_does_not_wipe_scope_or_main_answer_overrides() { - let mut f = Fixture::new(); - let mut library = f.ui.library.clone(); - let repertoire = library.repertoire_mut(&f.id).unwrap(); - repertoire.max_plies = 1; - repertoire - .set_prefix_disabled(&["e2e4".to_owned()], true) - .unwrap(); - let start = fen4(repertoire.game().start().position()); - repertoire - .set_main_answer_override(&start, "e2e4", LearningSide::White) - .unwrap(); - let pgn = repertoire.pgn.clone(); - let overrides = repertoire.main_answer_overrides.clone(); - - assert!(f.ui.persist(library)); - - let saved = f.ui.library_store.load().unwrap(); - for library in [&f.ui.library, &saved] { - let repertoire = library.repertoire(&f.id).unwrap(); - assert_eq!(repertoire.max_plies, 1); - assert_eq!(repertoire.disabled_prefixes, [vec!["e2e4".to_owned()]]); - assert_eq!(repertoire.main_answer_overrides, overrides); - assert_eq!(repertoire.pgn, pgn); - } - f.deliver(f.completed_job()); - assert_eq!(f.ui.variant_counts[&f.id], 1); -} - -#[test] -fn aggregate_reports_mixed_learning_and_unseen_items() { - let mut f = Fixture::new(); - let mut library = f.ui.library.clone(); - library.repertoire_mut(&f.id).unwrap().pgn = - chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 3. Bb5 *") - .game - .to_pgn(); - assert!(f.ui.persist(library)); - f.deliver(f.completed_job()); - - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()); - let keys = trainer::repertoire::active_learning_keys(&f.ui.library, &scope).unwrap(); - assert_eq!(keys.len(), 3); - let at = now(); - let mut learning = trainer::repertoire::LearningData::default(); - for key in keys { - match key.expected_uci.as_str() { - "e2e4" => { - let item = learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 1; - item.next_review_at = Some(at - 1); - } - "g1f3" => { - let item = learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 3; - item.next_review_at = Some(at + 86_400); - item.previous_interval_seconds = Some(86_400); - } - _ => {} - } - } - f.ui.learning.learning = learning; - f.ui.learning.revision += 1; - - let scoped = f.aggregate(); - let summary = &scoped.summary; - assert_eq!(scoped.scope.side, LearningSide::White); - assert_eq!(scoped.scope.repertoire_ids.len(), 1); - assert!(scoped.scope.repertoire_ids.contains(&f.id)); - assert_eq!(summary.total, 3); - assert_eq!(summary.unseen, 1); - assert_eq!(summary.learning, 1); - assert_eq!(summary.learnt, 1); - assert_eq!(summary.uncertain, 0); - assert_eq!(summary.due, 1); - assert_eq!(summary.next_due_at, None); - assert_eq!(summary.learnt_percent, Some(100.0 / 3.0)); - assert_eq!(summary.confident_percent, Some(100.0 / 3.0)); -} - -#[test] -fn migration_v2_is_read_only_and_old_runs_do_not_become_learning_kpis() { - let mut f = Fixture::new(); - let path = f.dir.join("v2-learning.json"); - let mut legacy = trainer::repertoire::StatsData::default(); - legacy.runs.push(trainer::repertoire::RunStats { - repertoire_id: f.id.clone(), - mode: TrainingMode::White, - completions: 42, - last: Some(now()), - recent: Vec::new(), - }); - legacy.legacy_lines.insert( - "legacy-line".to_owned(), - serde_json::json!({"runs": 7, "unknown": [1, 2, 3]}), - ); - trainer::repertoire::StatsStore::new(&path) - .save(&mut legacy) - .unwrap(); - let before = std::fs::read(&path).unwrap(); - - f.ui = RepertoireUi::with_stores(f.ui.library_store.clone(), LearningStore::new(&path)); - - assert!(f.ui.learning_error.is_none()); - let legacy = f.ui.learning.legacy_practice.as_ref().unwrap(); - assert_eq!(legacy["runs"][0]["completions"], 42); - assert_eq!(legacy["legacy_lines"]["legacy-line"]["runs"], 7); - assert!(f.ui.learning.learning.items.is_empty()); - let scoped = f.aggregate(); - assert_eq!(scoped.summary.total, 1); - assert_eq!(scoped.summary.unseen, 1); - assert_eq!(scoped.summary.learning, 0); - assert_eq!(scoped.summary.accuracy_attempts, 0); - assert_eq!(std::fs::read(&path).unwrap(), before); -} - -#[test] -fn stale_index_cannot_replace_a_newer_rebuild() { - let mut f = Fixture::new(); - f.ui.rebuild_tree(); - let old = f.completed_job(); - f.ui.rebuild_tree(); - let current = f.completed_job(); - f.deliver(old); - assert!(f.ui.indexing); - assert!(f.ui.tree.is_none()); - assert!(f.ui.trees.is_empty()); - f.deliver(current); - assert!(!f.ui.indexing); - assert!(f.ui.tree.is_some()); - assert!(f.ui.trees.contains_key(&f.id)); -} - -#[test] -fn completed_training_start_is_ignored_after_leaving_the_workspace() { - let mut f = Fixture::new(); - f.start(); - let ready = f.completed_job(); - f.ui.open_library(); - f.deliver(ready); - assert!(!f.ui.preparing); - assert!(!f.ui.training_visible); - assert!(f.ui.training.is_none()); - assert!(f.ui.error.is_none()); -} - -#[test] -fn stale_training_start_cannot_cancel_or_replace_a_new_generation() { - let mut f = Fixture::new(); - f.start(); - let old = f.completed_job(); - let old_generation = f.ui.training_generation; - f.ui.open_library(); - f.ui.select(f.id.clone(), &f.settings); - f.start(); - let current = f.completed_job(); - assert!(f.ui.training_generation > old_generation); - f.deliver(old); - f.deliver(Event::TrainingReady( - old_generation, - Err("stale failure".into()), - )); - assert!(f.ui.preparing); - assert!(f.ui.training.is_none()); - assert!(f.ui.error.is_none()); - f.deliver(current); - assert!(!f.ui.preparing); - assert!(f.ui.training_visible); - assert!(f.ui.training.is_some()); -} - -#[test] -fn async_start_can_finish_a_real_opening_and_persist_learning() { - let mut f = Fixture::new(); - f.start(); - let ready = f.completed_job(); - f.deliver(ready); - assert!(f.ui.training_visible); - - f.ui.debug_moves("e2e4 settle"); - - let training = f.ui.training.as_ref().unwrap(); - assert!(training.is_finished()); - assert!(!training.target_available()); - assert!(!training.has_unsaved()); - let saved = f.ui.learning_store.load().unwrap(); - assert_eq!(saved.learning.attempts.len(), 1); - assert!(saved.learning.attempts[0].event_type.is_independent()); - assert_eq!( - saved - .learning - .items - .iter() - .map(|item| item.correct_count) - .sum::(), - 1 - ); - assert!(f.ui.error.is_none()); -} - -#[test] -fn unsaved_learning_blocks_start_and_resolve_restores_the_session() { - let mut f = Fixture::new(); - f.start(); - let ready = f.completed_job(); - f.deliver(ready); - let lock = f.dir.join("learning.json.lock"); - std::fs::remove_file(&lock).unwrap(); - std::fs::create_dir(&lock).unwrap(); - f.ui.debug_moves("e2e4"); - assert!(f.ui.has_unsaved()); - - let generation = f.ui.training_generation; - f.ui.start(&mut f.settings); - assert!(!f.ui.preparing); - assert_eq!(f.ui.training_generation, generation); - f.ui.open_library(); - assert!(!f.ui.training_visible); - f.ui.resolve_unsaved(); - assert!(f.ui.training_visible); -} - -#[test] -fn start_uses_the_srs_queue_instead_of_legacy_practice() { - let mut f = Fixture::new(); - f.settings + assert_eq!(layout::side_of(&settings, &id), LearningSide::Black); + settings .repertoire_modes - .insert(f.id.to_string(), (TrainingMode::White, QueueMode::Practice)); - f.ui.select(f.id.clone(), &f.settings); - assert_eq!(f.ui.side, LearningSide::White); - let summary = f.aggregate().summary.clone(); - assert_eq!(summary.due, 0); - assert_eq!(summary.unseen, 1); - - f.start(); - + .insert(id.to_string(), (TrainingMode::Both, QueueMode::LeastRecent)); + assert_eq!(layout::side_of(&settings, &id), LearningSide::White); + layout::set_side(&mut settings, &id, LearningSide::Black); assert_eq!( - f.settings.repertoire_modes.get(f.id.as_str()), - Some(&(TrainingMode::White, QueueMode::SpacedRepetition)) + settings.repertoire_modes[id.as_str()], + (TrainingMode::Black, QueueMode::SpacedRepetition) ); - f.deliver(f.completed_job()); - assert!(f.ui.training_visible); - let saved = f.ui.learning_store.load().unwrap(); - let session = saved.session_snapshots.last().unwrap(); - assert_eq!(session.session.mode, QueueMode::SpacedRepetition); - assert_eq!(session.queue.len(), 1); - assert_eq!(session.queue[0].key.expected_uci, "e2e4"); } #[test] -fn review_mode_and_priority_are_saved_and_start_without_due_items() { - let mut f = Fixture::new(); - f.settings.repertoire_modes.insert( - f.id.to_string(), - (TrainingMode::White, QueueMode::LeastRecent), +fn the_three_screens_keep_the_board_and_the_panel_in_one_place() { + let dir = TestDir::new("geometry"); + save_library( + &dir, + &[ + ("Italian", "1. e4 e5 2. Nf3 Nc6 3. Bc4 *"), + ("London", "1. d4 d5 2. Bf4 *"), + ], ); - f.settings - .repertoire_priorities - .insert(f.id.to_string(), LearningPriority::CommonPositionsFirst); - f.ui.select(f.id.clone(), &f.settings); - assert_eq!(f.ui.queue, QueueMode::LeastRecent); - assert_eq!(f.ui.priority, LearningPriority::CommonPositionsFirst); - - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()); - let keys = trainer::repertoire::active_learning_keys(&f.ui.library, &scope).unwrap(); - let mut data = LearningStoreData::default(); - for key in keys { - let item = data.learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 3; - item.next_review_at = Some(now() + 86_400); - item.previous_interval_seconds = Some(86_400); - } - std::fs::write( - f.ui.learning_store.path(), - serde_json::to_vec_pretty(&data).unwrap(), - ) - .unwrap(); - f.ui.learning = f.ui.learning_store.load().unwrap(); - let summary = f.aggregate().summary.clone(); - assert_eq!(summary.due, 0); - assert_eq!(summary.unseen, 0); - - f.start(); - - assert_eq!( - f.settings.repertoire_modes.get(f.id.as_str()), - Some(&(TrainingMode::White, QueueMode::LeastRecent)) - ); - assert_eq!( - f.settings.repertoire_priorities.get(f.id.as_str()), - Some(&LearningPriority::CommonPositionsFirst) - ); - f.deliver(f.completed_job()); - assert!(f.ui.training_visible); - let saved = f.ui.learning_store.load().unwrap(); - let session = saved.session_snapshots.last().unwrap(); - assert_eq!(session.session.mode, QueueMode::LeastRecent); - assert_eq!( - session.stats_scope.learning_priority, - LearningPriority::CommonPositionsFirst - ); - assert_eq!(session.queue.len(), 1); -} - -#[test] -fn shared_reset_previews_impact_and_cancel_is_a_no_op_before_confirm() { - let mut f = Fixture::new(); - let mut library = f.ui.library.clone(); - library.repertoire_mut(&f.id).unwrap().pgn = - chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 *").game.to_pgn(); - let second = library - .create("Second shared", &chess_core::parse_str("1. e4 c5 *").game) - .unwrap(); - assert!(f.ui.persist(library)); - f.deliver(f.completed_job()); - let pgn_before = - f.ui.library - .repertoires - .iter() - .map(|repertoire| repertoire.pgn.clone()) - .collect::>(); - - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()); - let keys = trainer::repertoire::active_learning_keys(&f.ui.library, &scope).unwrap(); - assert_eq!(keys.len(), 2); - let mut data = LearningStoreData::default(); - for key in keys { - let item = data.learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 3; - item.next_review_at = Some(now() + 86_400); - } - std::fs::write( - f.ui.learning_store.path(), - serde_json::to_vec_pretty(&data).unwrap(), - ) - .unwrap(); - f.ui.learning = f.ui.learning_store.load().unwrap(); - let before = std::fs::read(f.ui.learning_store.path()).unwrap(); - - f.ui.begin_shared_reset(scope.clone()); - f.deliver(f.completed_job()); - let state = f.ui.shared_reset.as_ref().unwrap(); - let impact = state.impact.as_ref().unwrap(); - assert_eq!(impact.reset_count, 2); - assert_eq!(impact.shared_count, 1); - assert_eq!( - impact - .affected_repertoires - .iter() - .map(|repertoire| repertoire.name.as_str()) - .collect::>(), - BTreeSet::from(["Async opening", "Second shared"]) - ); - f.ui.cancel_shared_reset(); - assert!(f.ui.shared_reset.is_none()); - assert_eq!(std::fs::read(f.ui.learning_store.path()).unwrap(), before); - assert!(matches!(f.ui.rx.try_recv(), Err(mpsc::TryRecvError::Empty))); - - f.ui.begin_shared_reset(scope.clone()); - f.deliver(f.completed_job()); - f.ui.confirm_shared_reset(); - assert!(!f.ui.shared_reset.as_ref().unwrap().busy); - assert_eq!(std::fs::read(f.ui.learning_store.path()).unwrap(), before); - assert!(matches!(f.ui.rx.try_recv(), Err(mpsc::TryRecvError::Empty))); - - f.ui.shared_reset.as_mut().unwrap().confirmed = true; - f.ui.confirm_shared_reset(); - assert!(f.ui.shared_reset.as_ref().unwrap().busy); - f.deliver(f.completed_job()); - assert!(f.ui.shared_reset.is_none()); - assert!( - f.ui.learning - .learning - .items - .iter() - .all(|item| item.is_unseen()) - ); - let second_scope = StatsScope::for_repertoire(second, LearningSide::White, now()); - let second_summary = aggregate_scope( - &f.ui.library, - &f.ui.learning.learning, - &second_scope, - &SrsSettings::default(), - ) - .unwrap(); - assert_eq!(second_summary.summary.unseen, 1); - assert_eq!(f.aggregate().summary.unseen, 2); - assert_eq!( - f.ui.library - .repertoires - .iter() - .map(|repertoire| repertoire.pgn.clone()) - .collect::>(), - pgn_before - ); - - f.ui.begin_shared_reset(scope); - let stale = f.completed_job(); - f.ui.select(f.id.clone(), &f.settings); - f.deliver(stale); - assert!(f.ui.shared_reset.is_none()); - assert!(f.ui.error.is_none()); -} - -#[test] -fn review_order_reset_changes_only_the_cycle_cursor() { - let mut f = Fixture::new(); - f.ui.library.repertoire_mut(&f.id).unwrap().pgn = - chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 *").game.to_pgn(); - f.ui.queue = QueueMode::ReviewInOrder; - f.ui.priority = LearningPriority::DepthFirst; - f.start(); - f.deliver(f.completed_job()); - f.ui.debug_moves("e2e4 settle"); - f.ui.open_library(); - let before = f.ui.learning.learning.clone(); - let cursor = f.ui.review_snapshot().unwrap(); - assert_eq!(cursor.current_index, 1); - assert_eq!(cursor.completed_keys.len(), 1); - - f.ui.reset_review_cursor(); - assert!(f.ui.review_reset_pending); - f.deliver(f.completed_job()); - - assert!(!f.ui.review_reset_pending); - assert_eq!(f.ui.learning.learning, before); - let cursor = f.ui.review_snapshot().unwrap(); - assert_eq!(cursor.current_index, 0); - assert_eq!(cursor.cycle, 0); - assert!(cursor.completed_keys.is_empty()); -} - -#[test] -fn review_reset_controls_keep_statistics_and_library_visible() { - let mut f = Fixture::new(); - for queue in [QueueMode::ReviewInOrder, QueueMode::LeastRecent] { - f.ui.queue = queue; - f.ui.parameters_open = false; - f.ui.debug_layout.reset_review = None; + for (size, left) in [(vec2(1400.0, 900.0), 940.0), (vec2(960.0, 600.0), 576.0)] { + let mut ui = dir.ui(); + let mut settings = Settings::default(); let ctx = egui::Context::default(); - let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.0, Vec::new()); - let parameters = text_click_position(&shapes, "Parameters"); - render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.1, click_events(parameters)); - render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.2, Vec::new()); - let table = f.ui.debug_layout.table.expect("library table"); + crate::assets::install(&ctx); + settle(&mut ui, &ctx, &mut settings, size); + let repertoires = panel_rect(&ctx); assert!( - table.top() < 600.0, - "table is outside the viewport: {table:?}" + (repertoires.left() - left).abs() <= 1.0, + "{repertoires:?} in {size:?}" ); - assert!(table.height() > 0.0); - assert_eq!( - f.ui.debug_layout.reset_review.is_some(), - queue == QueueMode::ReviewInOrder + // Selecting another row moves nothing. + frame( + &mut ui, + &ctx, + &mut settings, + size, + vec![key(Key::ArrowDown)], ); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + assert_eq!(panel_rect(&ctx), repertoires); + // Lines. + ui.open_lines(&settings, None); + settle(&mut ui, &ctx, &mut settings, size); + assert!(matches!(ui.screen, Screen::Lines(_))); + assert_eq!(panel_rect(&ctx), repertoires); + // A session started from Lines, and back to Lines. + ui.start(SessionKind::ReviewAll, &settings); + settle(&mut ui, &ctx, &mut settings, size); + assert!(matches!(ui.screen, Screen::Session(_))); + assert_eq!(panel_rect(&ctx), repertoires); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + assert!(matches!(ui.screen, Screen::Lines(_))); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + assert!(matches!(ui.screen, Screen::Repertoires)); + assert_eq!(panel_rect(&ctx), repertoires); } } #[test] -fn due_start_has_priority_and_there_is_no_hidden_early_or_empty_start() { - let mixed = LearningAggregate { - total: 2, - unseen: 1, - due: 1, - ..LearningAggregate::default() - }; - assert_eq!(start_kind(&mixed), StartKind::Review); - let introduce = LearningAggregate { - total: 2, - unseen: 1, - learning: 1, - ..LearningAggregate::default() - }; - assert_eq!(start_kind(&introduce), StartKind::IntroduceNew); - let future = LearningAggregate { - total: 1, - learnt: 1, - learnt_percent: Some(100.0), - confident_percent: Some(100.0), - next_due_at: Some(now() + 86_400), - ..LearningAggregate::default() - }; - assert_eq!(start_kind(&future), StartKind::Unavailable); - assert_eq!( - start_kind(&LearningAggregate::default()), - StartKind::Unavailable - ); -} - -#[test] -fn partial_srs_continue_has_priority_over_introduce_and_keeps_snapshot() { - let mut f = Fixture::new(); - f.ui.library.repertoire_mut(&f.id).unwrap().pgn = - chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *") - .game - .to_pgn(); - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()) - .with_max_depth(Some(20)); - let keys = trainer::repertoire::active_learning_keys(&f.ui.library, &scope).unwrap(); - let key_for = |expected: &str| { - keys.iter() - .find(|key| key.expected_uci == expected) - .unwrap() - .clone() - }; - let mut learning = trainer::repertoire::LearningData::default(); - for expected in ["e2e4", "g1f3"] { - let item = learning.ensure_item(key_for(expected)); - item.introduced = true; - item.next_review_at = Some(now()); - } - let mut snapshot = LearningSessionSnapshot::new( - "partial-srs-continue", - &f.ui.library, - &learning, - scope, - SrsSettings::default(), - ) - .unwrap(); - let attempt = snapshot - .play_uci(&f.ui.library, "e2e4", "partial-e4", now(), Some(100)) - .unwrap(); - let _ = learning - .apply_attempt(attempt, &SrsSettings::default()) - .unwrap(); - let attempt = snapshot - .advance_context(&f.ui.library, "partial-context", now()) - .unwrap(); - let _ = learning - .apply_attempt(attempt, &SrsSettings::default()) - .unwrap(); - assert_eq!(snapshot.context_index, 1); - assert_ne!(snapshot.phase, LearningSessionPhase::Finished); - for item in &mut learning.items { - item.next_review_at = Some(now() + 86_400); - } - std::fs::write( - f.ui.learning_store.path(), - serde_json::to_vec_pretty(&LearningStoreData { - sessions: vec![snapshot.session.clone()], - session_snapshots: vec![snapshot.clone()], - learning, - ..LearningStoreData::default() - }) - .unwrap(), - ) - .unwrap(); - f.ui.reload_learning(); - f.ui.aggregates.clear(); - - let summary = f.aggregate().summary.clone(); - assert_eq!(summary.due, 0); - assert!(summary.unseen > 0); - assert_eq!(f.ui.selected_start_kind(&summary), StartKind::Review); - let unfinished = f.ui.learning.session_snapshots[0].clone(); - f.ui.learning.session_snapshots[0].phase = LearningSessionPhase::Finished; - assert_eq!(f.ui.selected_start_kind(&summary), StartKind::IntroduceNew); - f.ui.learning.session_snapshots[0] = unfinished; - - let snapshot_count = f.ui.learning.session_snapshots.len(); - f.ui.start(&mut f.settings); - assert!(f.ui.preparing); - f.deliver(f.completed_job()); - - let training = f.ui.training.as_ref().unwrap(); - assert_eq!(training.session_id(), "partial-srs-continue"); - let saved = f.ui.learning_store.load().unwrap(); - assert_eq!(saved.session_snapshots.len(), snapshot_count); - assert_eq!( - saved - .session_snapshot("partial-srs-continue") - .unwrap() - .context_index, - 1 - ); -} - -#[test] -fn aggregate_reuses_pending_work_across_minutes_and_ignores_evicted_results() { - let mut f = Fixture::new(); - let mut key = f.ui.current_aggregate_key().unwrap(); - key.minute -= 2; - f.ui.aggregates.insert(key.clone(), None); - - f.ui.request_aggregate(f.ui.current_aggregate_key().unwrap()); - - assert_eq!(f.ui.aggregates.len(), 1); - assert_eq!(f.ui.aggregates.get(&key), Some(&None)); - assert!(matches!(f.ui.rx.try_recv(), Err(mpsc::TryRecvError::Empty))); - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()); - let scoped = aggregate_scope( - &f.ui.library, - &f.ui.learning.learning, - &scope, - &SrsSettings::default(), - ) - .unwrap(); - f.deliver(Event::Aggregated(key.clone(), Box::new(Ok(scoped)))); - assert!(matches!( - f.ui.aggregates.get(&key), - Some(Some(Ok(scoped))) if scoped.summary.total == 1 - )); - f.ui.aggregates.clear(); - f.deliver(Event::Aggregated( - key, - Box::new(Err("stale failure".to_owned())), - )); - assert!(f.ui.aggregates.is_empty()); - assert!(f.ui.error.is_none()); -} - -#[test] -fn variant_count_is_pgn_routes_not_learning_total() { - let mut f = Fixture::new(); - f.ui.library.repertoire_mut(&f.id).unwrap().pgn = - chess_core::parse_str("1. e4 e5 (1... c5) *").game.to_pgn(); - let library = f.ui.library.clone(); - assert!(f.ui.persist(library)); - f.deliver(f.completed_job()); - assert_eq!(f.ui.variant_counts[&f.id], 2); - assert_eq!(f.aggregate().summary.total, 1); - - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()); - let keys = trainer::repertoire::active_learning_keys(&f.ui.library, &scope).unwrap(); - let mut learning = trainer::repertoire::LearningData::default(); - for key in keys { - let item = learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 3; - item.next_review_at = Some(now() + 86_400); - } - f.ui.learning.learning = learning; - f.ui.learning.revision += 1; - - assert_eq!(f.aggregate().summary.learnt, 1); - assert_eq!(f.ui.variant_counts[&f.id], 2); - assert!(matches!(f.ui.rx.try_recv(), Err(mpsc::TryRecvError::Empty))); -} - -#[test] -fn deleting_a_repertoire_preserves_global_learning() { - let mut f = Fixture::new(); - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()); - let key = trainer::repertoire::active_learning_keys(&f.ui.library, &scope) - .unwrap() - .into_iter() - .next() - .unwrap(); - let mut data = LearningStoreData { - revision: 7, - ..LearningStoreData::default() - }; - let item = data.learning.ensure_item(key.clone()); - item.introduced = true; - item.correct_streak = 2; - std::fs::write( - f.ui.learning_store.path(), - serde_json::to_vec_pretty(&data).unwrap(), - ) - .unwrap(); - f.ui.learning = f.ui.learning_store.load().unwrap(); - let before = std::fs::read(f.ui.learning_store.path()).unwrap(); - - assert!(f.ui.debug_delete(&f.settings)); - - assert!(f.ui.library.repertoire(&f.id).is_none()); - assert_eq!(std::fs::read(f.ui.learning_store.path()).unwrap(), before); - let saved = f.ui.learning_store.load().unwrap(); - assert!(saved.learning.item(&key).is_some()); - assert_eq!(saved.learning.items.len(), 1); -} - -#[test] -fn importing_and_saving_a_repertoire_does_not_change_source_pgn() { - let mut f = Fixture::new(); - let path = f.dir.join("source.pgn"); - let source = b"[Event \"Source\"]\n\n1. e4 e5 (1... c5) 2. Nf3 {keep} *\n"; - std::fs::write(&path, source).unwrap(); - let cancel = AtomicBool::new(false); - - let preview = read_import(&path, None, f.ui.library.clone(), &cancel).unwrap(); - assert!(f.ui.persist(preview.library)); - - assert_eq!(std::fs::read(&path).unwrap(), source); -} - -#[test] -#[ignore = "manual corpus import and indexing measurement"] -fn corpus_import_preserves_source_and_reports_real_outcome() { - for filename in ["The Ruy Lopez - Move by Move.pgn", "Alekhin.pgn"] { - println!("File: {filename}"); - let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../pgnFilesforExample") - .join(filename); - let before = std::fs::read(&path).unwrap(); - let cancelled = AtomicBool::new(false); - let started = std::time::Instant::now(); - let imported = read_import(&path, None, Library::default(), &cancelled); - let import_elapsed = started.elapsed(); - assert_eq!( - std::fs::read(&path).unwrap(), - before, - "import changed source bytes" - ); - - // Count the source independently, including records after any rejected one. - let db = PgnDatabase::from_bytes(before.clone(), None, &mut |_| {}, &cancelled).unwrap(); - let source_nodes: usize = (0..db.len()) - .map(|index| { - db.load_game(index) - .unwrap() - .game - .attached_nodes() - .len() - .saturating_sub(1) - }) - .sum(); - println!( - "Corpus: {} bytes; {} records; {} parsed source move nodes", - before.len(), - db.len(), - source_nodes - ); - match imported { - Ok(preview) => { - let repertoire = preview.library.repertoire(&preview.id).unwrap(); - let started = std::time::Instant::now(); - let tree = RepertoireTree::new(repertoire); - let index_elapsed = started.elapsed(); - let nodes = tree.game().attached_nodes().len().saturating_sub(1); - assert_eq!(preview.records, db.len()); - assert!(nodes > 0); - println!( - "IMPORTED: {} records; {} merged move nodes; import {:?}; index {:?}; combined {:?}", - preview.records, - nodes, - import_elapsed, - index_elapsed, - import_elapsed + index_elapsed - ); - } - Err(reason) => { - assert!(!reason.is_empty()); - println!( - "REJECTED (no repertoire imported, indexing not run): {reason}; read_import elapsed {import_elapsed:?}" - ); - } - } - if filename == "Alekhin.pgn" { - let fixture = Fixture::new(); - let subset_path = fixture.dir.join("Alekhin-first-200.pgn"); - let subset = (0..200) - .map(|index| db.raw_text(index).expect("source record exists")) - .collect::>() - .join("\n\n"); - std::fs::write(&subset_path, subset.as_bytes()).unwrap(); - let started = std::time::Instant::now(); - let mut preview = read_import(&subset_path, None, Library::default(), &cancelled) - .expect("the first 200 complete source records must import successfully"); - let subset_import_elapsed = started.elapsed(); - assert_eq!(preview.records, 200); - let repertoire = preview.library.repertoire(&preview.id).unwrap(); - let started = std::time::Instant::now(); - let tree = RepertoireTree::new(repertoire); - let index_elapsed = started.elapsed(); - let nodes = tree.game().attached_nodes().len().saturating_sub(1); - let canonical = tree.game().canonical_tree(); - let started = std::time::Instant::now(); - let store = LibraryStore::new(fixture.dir.join("corpus-library.json")); - store.save(&mut preview.library).unwrap(); - let loaded = store.load().unwrap(); - assert_eq!( - loaded - .repertoire(&preview.id) - .unwrap() - .game() - .canonical_tree(), - canonical - ); - let roundtrip_elapsed = started.elapsed(); - assert_eq!(std::fs::read(&subset_path).unwrap(), subset.as_bytes()); - assert!(nodes > 0); - println!( - "IMPORTED TEMP FIRST 200: {} bytes; {} merged move nodes; import {:?}; index {:?}; import+index {:?}; save/reload+canonical verification {:?}", - subset.len(), - nodes, - subset_import_elapsed, - index_elapsed, - subset_import_elapsed + index_elapsed, - roundtrip_elapsed - ); - } - assert_eq!( - std::fs::read(&path).unwrap(), - before, - "corpus check changed source bytes" - ); - } -} - -#[test] -fn training_scope_uses_repertoire_depth_and_custom_context_policy() { - let mut f = Fixture::new(); - let repertoire = f.ui.library.repertoire_mut(&f.id).unwrap(); - repertoire.pgn = chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 *").game.to_pgn(); - repertoire.set_max_plies(2); - let policy = trainer::repertoire::LearningContextPolicy { - use_fixed_piece_speed: false, - move_speed_adjustment: 0.25, - consider_leadup_moves: true, - ..Default::default() - }; - f.settings - .repertoire_context_policies - .insert(f.id.to_string(), policy); - - let scoped = f.aggregate(); - assert_eq!(scoped.scope.max_depth, Some(2)); - assert_eq!(scoped.summary.total, 1); - +fn keys_of_the_screen_do_nothing_under_a_dialog() { + let dir = TestDir::new("dialog-keys"); + save_library(&dir, &[("A", "1. e4 *"), ("B", "1. d4 *")]); + let mut ui = dir.ui(); + let mut settings = Settings::default(); let ctx = egui::Context::default(); - let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 0.0, Vec::new()); - assert!(shapes.iter().any(|clipped| { - matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text() == "Learnt 0 of 1 moves") - })); - assert!(!shapes.iter().any(|clipped| { - matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text().contains("Depth") || shape.galley.text().contains("4294967295")) - })); - assert!(!shapes.iter().any(|clipped| { - matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text().contains("Scope: whole repertoire")) - })); - - f.start(); - f.deliver(f.completed_job()); - - let saved = f.ui.learning_store.load().unwrap(); - let session = saved.session_snapshots.last().unwrap(); - assert_eq!(session.stats_scope.max_depth, Some(2)); - assert_eq!(session.queue.len(), 1); - assert_eq!(session.queue[0].key.expected_uci, "e2e4"); - assert_eq!(session.context_policy, policy); - assert!(f.ui.matches_review_snapshot(session)); -} - -#[test] -fn context_control_changes_are_saved_from_the_workspace() { - let mut f = Fixture::new(); - let ctx = egui::Context::default(); - let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 0.0, Vec::new()); - let settings = text_click_position(&shapes, "Parameters"); - render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 0.1, click_events(settings)); - let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 0.2, Vec::new()); - let fixed = text_click_position(&shapes, "Speed up familiar moves"); - - let (actions, _) = - render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 2.0, click_events(fixed)); - + crate::assets::install(&ctx); + let size = vec2(1400.0, 900.0); + settle(&mut ui, &ctx, &mut settings, size); + let selected = ui.selected.clone(); + ui.dialog = Some(Dialog::New { + name: String::new(), + side: LearningSide::White, + error: None, + }); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + let actions = frame( + &mut ui, + &ctx, + &mut settings, + size, + vec![key(Key::ArrowDown)], + ); + assert!(actions.is_empty()); + assert_eq!(ui.selected, selected); + let actions = frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); assert!( actions .iter() - .any(|action| matches!(action, RepertoireAction::SettingsChanged)) + .all(|action| !matches!(action, RepertoireAction::Close)), + "Esc closes the dialog, not the screen" ); - let policy = f - .settings - .repertoire_context_policies - .get(f.id.as_str()) - .unwrap(); - assert!(!policy.use_fixed_piece_speed); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + assert!(ui.dialog.is_none()); + let actions = frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); + assert!(matches!(actions.as_slice(), [RepertoireAction::Close])); } #[test] -fn preparation_actions_share_one_size_and_row() { - let mut f = Fixture::new(); - f.aggregate(); - for (width, height) in [(960.0, 600.0), (1400.0, 900.0)] { - let ctx = egui::Context::default(); - render_repertoire_frame(&mut f, &ctx, width, height, 0.0, Vec::new()); - let buttons = f.ui.debug_layout.action_buttons.map(Option::unwrap); - for button in buttons { - assert_eq!(button.size(), buttons[0].size()); - assert_eq!(button.top(), buttons[0].top()); - assert_eq!(button.height(), 30.0); - assert!(button.right() <= width); - } - assert!(buttons[0].right() < buttons[1].left()); - assert!(buttons[1].right() < buttons[2].left()); +fn names_are_checked_and_a_new_repertoire_keeps_its_colour() { + let dir = TestDir::new("names"); + save_library(&dir, &[("Najdorf", "1. e4 c5 *")]); + let mut ui = dir.ui(); + let mut settings = Settings::default(); + let mut actions = Vec::new(); + for (name, error) in [ + (" ", tr("The repertoire name must not be empty")), + ("najdorf", tr("A repertoire with this name already exists")), + ] { + ui.dialog = Some(Dialog::New { + name: name.into(), + side: LearningSide::Black, + error: None, + }); + ui.confirm_dialog(&mut settings, &mut actions); + assert!( + matches!(&ui.dialog, Some(Dialog::New { error: Some(e), .. }) if e == error), + "{name:?}" + ); } + ui.dialog = Some(Dialog::New { + name: "Sveshnikov".into(), + side: LearningSide::Black, + error: None, + }); + ui.confirm_dialog(&mut settings, &mut actions); + assert!(ui.dialog.is_none()); + let id = ui.selected.clone().unwrap(); + assert_eq!(ui.library.repertoire(&id).unwrap().name, "Sveshnikov"); + assert_eq!(layout::side_of(&settings, &id), LearningSide::Black); + assert!(matches!( + actions.as_slice(), + [RepertoireAction::SettingsChanged] + )); } #[test] -fn repertoire_row_menu_opens_editor() { - let mut f = Fixture::new(); - let ctx = egui::Context::default(); - let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.0, Vec::new()); - let menu = text_click_position(&shapes, "⋯"); - render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.1, click_events(menu)); - let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.2, Vec::new()); - let edit = text_click_position(&shapes, "Edit"); - render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.3, click_events(edit)); - assert_eq!(f.ui.editor_id.as_ref(), Some(&f.id)); - assert!(f.ui.editor.is_some()); +fn delete_keeps_the_answers_and_selects_the_neighbour() { + let dir = TestDir::new("delete"); + let ids = save_library( + &dir, + &[("A", "1. e4 *"), ("B", "1. d4 *"), ("C", "1. c4 *")], + ); + let mut learning = LearningData::default(); + let library = dir.stores().0.load().unwrap(); + let scope = StatsScope::for_repertoire(ids[1].clone(), LearningSide::White, 0); + let key = active_learning_keys(&library, &scope) + .unwrap() + .into_iter() + .next() + .unwrap(); + learning.ensure_item(key.clone()).introduced = true; + let data = LearningStoreData { + learning, + ..LearningStoreData::default() + }; + std::fs::write( + dir.0.join("repertoire-training.json"), + serde_json::to_vec(&data).unwrap(), + ) + .unwrap(); + let mut ui = dir.ui(); + ui.select(ids[1].clone()); + ui.dialog = Some(Dialog::Delete { id: ids[1].clone() }); + ui.delete_selected(); + assert!(ui.dialog.is_none()); + assert_eq!(ui.selected, Some(ids[2].clone())); + assert!(ui.library.repertoire(&ids[1]).is_none()); + let kept = dir.stores().1.load().unwrap(); + assert!(kept.learning.item(&key).is_some_and(|item| item.introduced)); +} + +#[test] +fn a_session_needs_no_question_to_go_back_and_counts_refresh_after_it() { + let dir = TestDir::new("session-back"); + save_library(&dir, &[("Scotch", "1. e4 e5 2. Nf3 Nc6 3. d4 *")]); + let mut ui = dir.ui(); + let mut settings = Settings::default(); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let size = vec2(1400.0, 900.0); + settle(&mut ui, &ctx, &mut settings, size); + let id = ui.selected.clone().unwrap(); + assert_eq!(ui.selected_card(), CardState::OnlyNew { new: 3 }); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Enter)]); + settle(&mut ui, &ctx, &mut settings, size); + assert!(matches!(ui.screen, Screen::Session(_))); + ui.debug_moves("settle answer settle"); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Enter)]); + settle(&mut ui, &ctx, &mut settings, size); + assert!(matches!(ui.screen, Screen::Repertoires)); + // One new move was shown and played: it is due again today, two are left new. + let stats = ui.stats.get(&id).unwrap().as_ref().unwrap(); + assert_eq!((stats.unseen, stats.due), (2, 1)); } diff --git a/apps/desktop/src/widgets.rs b/apps/desktop/src/widgets.rs index 748ebcb..461b66f 100644 --- a/apps/desktop/src/widgets.rs +++ b/apps/desktop/src/widgets.rs @@ -11,6 +11,7 @@ pub fn settings_button(ui: &mut Ui, compact: bool) -> egui::Response { /// A section header: reserve global actions before laying out a long title. /// Returns (back, settings). +#[allow(dead_code)] pub fn section_header(ui: &mut Ui, back: &str, title: &str) -> (bool, bool) { let mut clicked = (false, false); let compact = ui.available_width() < 600.0; @@ -29,6 +30,37 @@ pub fn section_header(ui: &mut Ui, back: &str, title: &str) -> (bool, bool) { clicked } +/// A two-line section header in the places of the game's (title and a quiet line under +/// it; an empty subtitle keeps its line, so the header never changes height). +/// Returns (back, settings). +pub fn section_header_sub(ui: &mut Ui, back: &str, title: &str, subtitle: &str) -> (bool, bool) { + let mut clicked = (false, false); + let compact = ui.available_width() < 600.0; + ui.add_space(4.0); + ui.horizontal(|ui| { + clicked.0 = ui.button(back).clicked(); + ui.separator(); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + clicked.1 = settings_button(ui, compact).clicked(); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + ui.add(egui::Label::new(egui::RichText::new(title).strong().size(16.0)).truncate()) + .on_hover_text(title); + let sub = ui.add( + egui::Label::new( + egui::RichText::new(if subtitle.is_empty() { " " } else { subtitle }) + .weak(), + ) + .truncate(), + ); + if !subtitle.is_empty() { + sub.on_hover_text(subtitle); + } + }); + }); + }); + clicked +} + /// A dev check (`CP_PANEL_CHECK=1`): a panel whose content is wider than the panel. egui /// then moves a right panel out (its left part under the central panel, its right part /// off the window); the content of every panel must fit its least width diff --git a/docs/dev/opening-trainer-v2-handoff.md b/docs/dev/opening-trainer-v2-handoff.md new file mode 100644 index 0000000..0874c5b --- /dev/null +++ b/docs/dev/opening-trainer-v2-handoff.md @@ -0,0 +1,37 @@ +# Тренировка дебюта v2 — точка продолжения (2026-11-26) + +Как продолжить в новой сессии оркестратора: прочитать этот файл, затем +`docs/qa/opening-trainer-v2-devhooks.md` (раздел «Состояние работы» — пишет разработчик). + +## Где что + +- Рабочая копия: `/home/vrubel/projects/chessbaseLinux-opening-v2`, ветка `feature/opening-trainer-v2` + (от `main` = выпуск 2.3.0). Сборка: `CARGO_TARGET_DIR=/tmp/opencode/v2-target`. +- Основная папка `/home/vrubel/projects/chessbaseLinux` (ветка `feature/opening-repertoire-training`, 2.2.0) + содержит НЕзакоммиченные временные стрелки/круги (board.rs, game_view.rs, …). Не удалять; + при интеграции перенести в v2 (по одной строке `temporary_shapes` в экране задания). +- Документы (в v2): концепция `docs/design/opening-trainer-concept-2026-11-26.md`, + спецификация `docs/design/opening-trainer-v2-spec.md` (+ «Решения оркестратора» в конце), + аудиты `docs/design/opening-trainer-ui-audit-2026-11-26.md`, `docs/research/opening-trainer-*-2026-11-26.md`. +- Снимки аудита: `/home/vrubel/projects/chessbaseLinux/target/qa-opening-rethink/shots/`; + корпус форума/FAQ/блога ChessTempo: там же `chesstempo-corpus/` (читать поиском по вопросу, не целиком). + +## Договорённости с владельцем + +- Менять только раздел «Тренировка дебюта»; другие разделы — ни функционально, ни визуально. +- На UI/UX не экономить; экономить на служебных проходах. Бюджет ограничен (~$30 на реализацию). +- Агенты запускаются строго последовательно (параллельные запросы упираются в лимит провайдера). +- Решения по составу раздела делегированы оркестратору; итог записать в `docs/decisions.md`. +- Строка «Путь» (ходы линии) в занятии — не делать; предложено владельцу как опция, ответа нет. + +## План + +1. ✅ Исследование, аудиты, концепция, спецификация (коммит `bd72aea`). +2. ✅ Ядро: дневная очередь (к повторению + N новых), возврат ошибки, проход/ветка (`3db35e4`). +3. ⏳ Разработчик (сессия `ses_de7ebabe0ffeYd1iH2ZOmQggaQ`): UI — репертуары, карточка, диалоги, + занятие S0–S9, итог, «Повторить всё подряд», ветка, «Варианты», удаление старого UI, i18n, проверки. + Если сессия агента потеряна — запустить нового developer: «продолжи по handoff и devhooks.md». +4. Дизайн-ревью designer (не автор кода) на реальных снимках 1400×900 и 960×600 по §9 спецификации, + сравнение с экраном партии/игры, отсутствие скачков. +5. Исправления → обновить `docs/dev/tasks.md` (задача 37/новая), `docs/decisions.md`, CHANGELOG. +6. Интеграция: перенести временные стрелки; слияние в main — только с разрешения владельца. diff --git a/docs/qa/opening-trainer-v2-devhooks.md b/docs/qa/opening-trainer-v2-devhooks.md new file mode 100644 index 0000000..c9ed544 --- /dev/null +++ b/docs/qa/opening-trainer-v2-devhooks.md @@ -0,0 +1,46 @@ +# Тренировка дебюта v2: dev-хуки для снимков + +Изолированный профиль: `XDG_CONFIG_HOME`, `XDG_DATA_HOME` во временный каталог и +`CP_REPERTOIRE_DIR=<каталог>` (там `repertoires.json`, `repertoire-training.json`). +Снимок: `CP_SCREENSHOT=file.png CP_SCREENSHOT_DELAY=<сек>`. + +| Переменная | Что делает | +| --- | --- | +| `CP_REPERTOIRE=library` | открыть экран «Репертуары» | +| `CP_REPERTOIRE_SELECT=<часть имени>` | выбрать репертуар перед действием | +| `CP_REPERTOIRE=train` / `main` / `review` | занятие «Тренироваться» / главная кнопка карточки / «Повторить всё подряд» | +| `CP_REPERTOIRE=white` / `black` | задать цвет выбранному и начать занятие | +| `CP_REPERTOIRE=lines` (+ `CP_REPERTOIRE_LINE="e2e4 e7e5"`) | экран «Варианты», выбран ход по пути UCI | +| `CP_REPERTOIRE=branch` + `CP_REPERTOIRE_LINE=…` | «Тренировать эту ветку» | +| `CP_REPERTOIRE=menu` | открыть меню `⋯` выбранной строки | +| `CP_REPERTOIRE=new` (+ `CP_REPERTOIRE_NAME=…` — сразу создать) | диалог «Новый репертуар» | +| `CP_REPERTOIRE=rename` / `color` / `reset` / `delete` | диалоги §7.3–7.5 | +| `CP_REPERTOIRE=message` | полоса сообщения с ошибкой | +| `CP_REPERTOIRE_IMPORT_FILE=` (+ `CP_REPERTOIRE_IMPORT_INTO=1` — в выбранный) | диалог импорта с этим файлом | +| `CP_REPERTOIRE_CONFIRM_IMPORT=1` | подтвердить импорт, когда файл прочитан | +| `CP_REPERTOIRE_SLOW=<мс>` | задержать подготовку занятия (виден S0 «Готовим занятие…») | +| `CP_REPERTOIRE_MOVES="…"` | действия в занятии: UCI-ходы, `answer`, `wrong`, `hint`, `skip`, `settle`, `stop` (= Esc) | +| `CP_REPERTOIRE_HINT=1` | подсказка в текущем вопросе | +| `CP_REPERTOIRE_EXPORT=1` (+ `CP_REPERTOIRE_EXPORT_FILE=…`) | экспорт PGN | + +## Состояние работы (2026-11-26, wip) + +Сделано: +- Ядро (`crates/trainer`, коммит 3db35e4): `new_daily` (к повторению + ≤10 новых), `introduce_more`, + возврат ошибки/подсказки в конец очереди, `preview_new`, `new_single_pass_review`, + `new_branch_review`; необязательные флаги снимка; тесты `daily_tests.rs` (7), все 200 тестов trainer зелёные. +- Desktop: новые модули `opening_layout.rs`, `opening_session.rs` (бывший `learning_training.rs`, + движок записи/перетаскивания/подвода сохранён), `opening_lines.rs`; `repertoire_ui.rs` переписан + (таблица, карточка, меню `⋯`, диалоги §7, «Добавить в репертуар» с цветом); `widgets::section_header_sub`. + Удалены `learning_dashboard/branches/charts/context_controls`, `repertoire_editor`, `repertoire_training`. + i18n: 120 новых строк на 9 языках. Тесты opening_* (41) зелёные; repertoire_ui — 10 из 11. + +Следующее: +- Починить тест `a_session_needs_no_question_to_go_back_and_counts_refresh_after_it`: хук `debug_moves` + «answer» после «settle» играет ход до подготовки показа (в журнале лишние AutoContext/Previewed) — + разобраться с порядком `settle`/показа нового хода при асинхронной записи. +- Удалить из `i18n.rs` неиспользуемые строки старого раздела; clippy `-D warnings`; wasm-проверка `apps/web`; + mobile-api; снимки в `target/qa-opening-v2/dev-shots/` (репертуары, новый ход, итог). +- Обрезка пути слева в блоке «Выбранный ход» (сейчас обрезка справа). + +Известные поломки/отклонения: см. выше; визуально не проверено (снимков ещё нет).