diff --git a/assets/locales/pending/review-markups.json b/assets/locales/pending/review-markups.json new file mode 100644 index 00000000000..da384d7e5fd --- /dev/null +++ b/assets/locales/pending/review-markups.json @@ -0,0 +1,79 @@ +{ + "en": { + "cmd.markup_add": "Add Markup", + "cmd.markup_delete": "Delete Markup", + "cmd.markup_edit": "Edit Markup", + "cmd.markup_image": "Markup Picture", + "cmd.markup_list": "List Markups", + "cmd.markup_reject": "Reject Markup", + "cmd.markup_reopen": "Reopen Markup", + "cmd.markup_reply": "Reply to Markup", + "cmd.markup_resolve": "Resolve Markup" + }, + "ar": { + "cmd.markup_add": "إضافة ملاحظة مراجعة", + "cmd.markup_delete": "حذف ملاحظة المراجعة", + "cmd.markup_edit": "تعديل ملاحظة المراجعة", + "cmd.markup_image": "صورة ملاحظة المراجعة", + "cmd.markup_list": "عرض ملاحظات المراجعة", + "cmd.markup_reject": "رفض ملاحظة المراجعة", + "cmd.markup_reopen": "إعادة فتح ملاحظة المراجعة", + "cmd.markup_reply": "الرد على ملاحظة المراجعة", + "cmd.markup_resolve": "إنهاء ملاحظة المراجعة" + }, + "de": { + "cmd.markup_add": "Markierung hinzufügen", + "cmd.markup_delete": "Markierung löschen", + "cmd.markup_edit": "Markierung bearbeiten", + "cmd.markup_image": "Bild zur Markierung", + "cmd.markup_list": "Markierungen auflisten", + "cmd.markup_reject": "Markierung ablehnen", + "cmd.markup_reopen": "Markierung wieder öffnen", + "cmd.markup_reply": "Auf Markierung antworten", + "cmd.markup_resolve": "Markierung erledigen" + }, + "he": { + "cmd.markup_add": "הוספת הערת סקירה", + "cmd.markup_delete": "מחיקת הערת סקירה", + "cmd.markup_edit": "עריכת הערת סקירה", + "cmd.markup_image": "תמונה להערת סקירה", + "cmd.markup_list": "רשימת הערות סקירה", + "cmd.markup_reject": "דחיית הערת סקירה", + "cmd.markup_reopen": "פתיחה מחדש של הערת סקירה", + "cmd.markup_reply": "תגובה להערת סקירה", + "cmd.markup_resolve": "סגירת הערת סקירה כטופלה" + }, + "ja": { + "cmd.markup_add": "マークアップを追加", + "cmd.markup_delete": "マークアップを削除", + "cmd.markup_edit": "マークアップを編集", + "cmd.markup_image": "マークアップの画像", + "cmd.markup_list": "マークアップ一覧", + "cmd.markup_reject": "マークアップを却下", + "cmd.markup_reopen": "マークアップを再オープン", + "cmd.markup_reply": "マークアップに返信", + "cmd.markup_resolve": "マークアップを解決" + }, + "vi": { + "cmd.markup_add": "Thêm ghi chú duyệt", + "cmd.markup_delete": "Xóa ghi chú duyệt", + "cmd.markup_edit": "Sửa ghi chú duyệt", + "cmd.markup_image": "Ảnh của ghi chú duyệt", + "cmd.markup_list": "Danh sách ghi chú duyệt", + "cmd.markup_reject": "Từ chối ghi chú duyệt", + "cmd.markup_reopen": "Mở lại ghi chú duyệt", + "cmd.markup_reply": "Trả lời ghi chú duyệt", + "cmd.markup_resolve": "Hoàn tất ghi chú duyệt" + }, + "zh": { + "cmd.markup_add": "添加批注", + "cmd.markup_delete": "删除批注", + "cmd.markup_edit": "编辑批注", + "cmd.markup_image": "批注图片", + "cmd.markup_list": "批注列表", + "cmd.markup_reject": "拒绝批注", + "cmd.markup_reopen": "重新打开批注", + "cmd.markup_reply": "回复批注", + "cmd.markup_resolve": "解决批注" + } +} diff --git a/assets/locales/pending/review-pins.json b/assets/locales/pending/review-pins.json new file mode 100644 index 00000000000..bfc71b8c60d --- /dev/null +++ b/assets/locales/pending/review-pins.json @@ -0,0 +1,562 @@ +{ + "en": { + "cmd.view_review": "Review", + "help.view.review": "Shows or hides the Review list and the review pins on the model. Use it to mark what needs changing with a note and pictures, and to work through the markups an agent or a colleague left beside the design.", + "review.add": "Add", + "review.ago_days": "{n} d ago", + "review.ago_hours": "{n} h ago", + "review.ago_minutes": "{n} min ago", + "review.ago_now": "just now", + "review.attach": "Attach image…", + "review.cancel": "Cancel", + "review.close": "Close Review", + "review.delete": "Delete", + "review.delete_ask": "Delete this markup and its pictures?", + "review.done_by": "Done by {by}: {reason}", + "review.edit_feature": "Edit {name}", + "review.empty": "No markups here. Press Mark this, or M, to pin a note on the model.", + "review.filter_all": "All {count}", + "review.filter_done": "Done {count}", + "review.filter_open": "Open {count}", + "review.filter_rejected": "Rejected {count}", + "review.go_there": "Go there", + "review.gone_line": "What it was on is no longer in this design", + "review.hidden_line": "Hidden here: not in the model at this point of the history or in this configuration", + "review.hide_pins": "Hide the pins", + "review.hint": "Newest first · pins follow the filter", + "review.in_browser": "kept in this browser", + "review.mark": "Mark this", + "review.mark_tip": "Pin a note on the model: click where it goes. M pins it on what the pointer is on.", + "review.marked": "Marked by {by} · {ago}", + "review.moved_line": "What it is on has moved since it was marked", + "review.new": "New", + "review.no_file": "save the design to mark it", + "review.not_read": "the markups could not be read", + "review.note_hint": "What needs changing?", + "review.on_component": "Component {name}", + "review.on_edge": "Edge on {body}", + "review.on_face": "Face on {body}", + "review.on_face_by": "{feature} on {body}", + "review.on_feature": "Feature {name}", + "review.on_point": "A point in space", + "review.on_view": "The view", + "review.one_picture": "1 picture", + "review.one_reply": "1 reply", + "review.pictures": "{count} pictures", + "review.pictures_label": "Pictures (PNG or JPEG)", + "review.placing": "Click where the markup goes; Esc stops.", + "review.reject": "Reject…", + "review.reject_go": "Reject", + "review.reject_hint": "Why is it not done?", + "review.rejected_why": "Rejected: {reason}", + "review.reopen": "Reopen", + "review.replies": "{count} replies", + "review.reply_hint": "Reply…", + "review.resolve": "Resolve…", + "review.resolve_go": "Resolve", + "review.resolve_hint": "What was done?", + "review.saved": "beside the design · saved", + "review.screenshot": "Screenshot", + "review.screenshot_tip": "Attach a picture of the view as it is now", + "review.select": "Select", + "review.send": "Send", + "review.show_pins": "Show the pins", + "review.status_done": "Done", + "review.status_gone": "Gone", + "review.status_hidden": "Hidden here", + "review.status_open": "Open", + "review.status_rejected": "Rejected", + "review.title": "Review", + "review.unsaved": "Save the design first: its markups are kept in a file beside it." + }, + "ar": { + "cmd.view_review": "المراجعة", + "help.view.review": "يُظهر قائمة المراجعة ودبابيس المراجعة على النموذج أو يخفيها. استخدمه لتحديد ما يحتاج إلى تغيير بملاحظة وصور، ولمعالجة الملاحظات التي تركها وكيل أو زميل بجانب التصميم.", + "review.add": "إضافة", + "review.ago_days": "منذ {n} يوم", + "review.ago_hours": "منذ {n} ساعة", + "review.ago_minutes": "منذ {n} دقيقة", + "review.ago_now": "الآن", + "review.attach": "إرفاق صورة…", + "review.cancel": "إلغاء", + "review.close": "إغلاق المراجعة", + "review.delete": "حذف", + "review.delete_ask": "حذف هذه الملاحظة وصورها؟", + "review.done_by": "أنجزها {by}: {reason}", + "review.edit_feature": "تحرير {name}", + "review.empty": "لا توجد ملاحظات هنا. اضغط «حدّد هنا» أو M لتثبيت ملاحظة على النموذج.", + "review.filter_all": "الكل {count}", + "review.filter_done": "منجزة {count}", + "review.filter_open": "مفتوحة {count}", + "review.filter_rejected": "مرفوضة {count}", + "review.go_there": "انتقل إليها", + "review.gone_line": "ما كانت عليه لم يعد في هذا التصميم", + "review.hidden_line": "مخفية هنا: ليست في النموذج عند هذه النقطة من السجل أو في هذا التكوين", + "review.hide_pins": "إخفاء الدبابيس", + "review.hint": "الأحدث أولاً · الدبابيس تتبع عامل التصفية", + "review.in_browser": "محفوظة في هذا المتصفح", + "review.mark": "حدّد هنا", + "review.mark_tip": "ثبّت ملاحظة على النموذج: انقر حيث تريدها. يثبّتها M على ما تحت المؤشر.", + "review.marked": "حدّدها {by} · {ago}", + "review.moved_line": "ما هي عليه تحرّك منذ تحديدها", + "review.new": "جديدة", + "review.no_file": "احفظ التصميم لتحديده", + "review.not_read": "تعذّرت قراءة الملاحظات", + "review.note_hint": "ما الذي يحتاج إلى تغيير؟", + "review.on_component": "المكوّن {name}", + "review.on_edge": "حافة على {body}", + "review.on_face": "وجه على {body}", + "review.on_face_by": "{feature} على {body}", + "review.on_feature": "الميزة {name}", + "review.on_point": "نقطة في الفراغ", + "review.on_view": "العرض", + "review.one_picture": "صورة واحدة", + "review.one_reply": "رد واحد", + "review.pictures": "{count} صور", + "review.pictures_label": "صور (PNG أو JPEG)", + "review.placing": "انقر حيث تريد الملاحظة؛ Esc للإيقاف.", + "review.reject": "رفض…", + "review.reject_go": "رفض", + "review.reject_hint": "لماذا لن تُنجز؟", + "review.rejected_why": "مرفوضة: {reason}", + "review.reopen": "إعادة فتح", + "review.replies": "{count} ردود", + "review.reply_hint": "رد…", + "review.resolve": "إنجاز…", + "review.resolve_go": "إنجاز", + "review.resolve_hint": "ما الذي أُنجز؟", + "review.saved": "بجانب التصميم · محفوظة", + "review.screenshot": "لقطة شاشة", + "review.screenshot_tip": "إرفاق صورة للعرض كما هو الآن", + "review.select": "تحديد", + "review.send": "إرسال", + "review.show_pins": "إظهار الدبابيس", + "review.status_done": "منجزة", + "review.status_gone": "زالت", + "review.status_hidden": "مخفية هنا", + "review.status_open": "مفتوحة", + "review.status_rejected": "مرفوضة", + "review.title": "المراجعة", + "review.unsaved": "احفظ التصميم أولاً: تُحفظ ملاحظاته في ملف بجانبه." + }, + "de": { + "cmd.view_review": "Prüfung", + "help.view.review": "Zeigt oder verbirgt die Prüfliste und die Prüfnadeln auf dem Modell. Damit markieren Sie mit Notiz und Bildern, was sich ändern soll, und arbeiten die Markierungen ab, die ein Agent oder eine Kollegin neben dem Entwurf hinterlassen hat.", + "review.add": "Hinzufügen", + "review.ago_days": "vor {n} T", + "review.ago_hours": "vor {n} h", + "review.ago_minutes": "vor {n} min", + "review.ago_now": "gerade eben", + "review.attach": "Bild anhängen…", + "review.cancel": "Abbrechen", + "review.close": "Prüfung schließen", + "review.delete": "Löschen", + "review.delete_ask": "Diese Markierung und ihre Bilder löschen?", + "review.done_by": "Erledigt von {by}: {reason}", + "review.edit_feature": "{name} bearbeiten", + "review.empty": "Hier gibt es keine Markierungen. Drücken Sie „Hier markieren“ oder M, um eine Notiz an das Modell zu heften.", + "review.filter_all": "Alle {count}", + "review.filter_done": "Erledigt {count}", + "review.filter_open": "Offen {count}", + "review.filter_rejected": "Abgelehnt {count}", + "review.go_there": "Hingehen", + "review.gone_line": "Worauf sie stand, ist nicht mehr in diesem Entwurf", + "review.hidden_line": "Hier verborgen: an dieser Stelle des Verlaufs oder in dieser Konfiguration nicht im Modell", + "review.hide_pins": "Nadeln ausblenden", + "review.hint": "Neueste zuerst · die Nadeln folgen dem Filter", + "review.in_browser": "in diesem Browser gespeichert", + "review.mark": "Hier markieren", + "review.mark_tip": "Eine Notiz an das Modell heften: klicken Sie, wohin sie gehört. M heftet sie an das, worauf der Zeiger steht.", + "review.marked": "Markiert von {by} · {ago}", + "review.moved_line": "Worauf sie steht, hat sich seit dem Markieren bewegt", + "review.new": "Neu", + "review.no_file": "Entwurf speichern, um ihn zu markieren", + "review.not_read": "die Markierungen konnten nicht gelesen werden", + "review.note_hint": "Was soll sich ändern?", + "review.on_component": "Komponente {name}", + "review.on_edge": "Kante an {body}", + "review.on_face": "Fläche an {body}", + "review.on_face_by": "{feature} an {body}", + "review.on_feature": "Feature {name}", + "review.on_point": "Ein Punkt im Raum", + "review.on_view": "Die Ansicht", + "review.one_picture": "1 Bild", + "review.one_reply": "1 Antwort", + "review.pictures": "{count} Bilder", + "review.pictures_label": "Bilder (PNG oder JPEG)", + "review.placing": "Klicken Sie, wohin die Markierung gehört; Esc beendet.", + "review.reject": "Ablehnen…", + "review.reject_go": "Ablehnen", + "review.reject_hint": "Warum wird es nicht gemacht?", + "review.rejected_why": "Abgelehnt: {reason}", + "review.reopen": "Wieder öffnen", + "review.replies": "{count} Antworten", + "review.reply_hint": "Antworten…", + "review.resolve": "Erledigen…", + "review.resolve_go": "Erledigen", + "review.resolve_hint": "Was wurde gemacht?", + "review.saved": "neben dem Entwurf · gespeichert", + "review.screenshot": "Bildschirmfoto", + "review.screenshot_tip": "Ein Bild der Ansicht, wie sie jetzt ist, anhängen", + "review.select": "Auswählen", + "review.send": "Senden", + "review.show_pins": "Nadeln einblenden", + "review.status_done": "Erledigt", + "review.status_gone": "Weg", + "review.status_hidden": "Hier verborgen", + "review.status_open": "Offen", + "review.status_rejected": "Abgelehnt", + "review.title": "Prüfung", + "review.unsaved": "Speichern Sie den Entwurf zuerst: seine Markierungen liegen in einer Datei daneben." + }, + "he": { + "cmd.view_review": "סקירה", + "help.view.review": "מציג או מסתיר את רשימת הסקירה ואת סיכות הסקירה על המודל. השתמשו בו כדי לסמן מה צריך לשנות בהערה ובתמונות, וכדי לעבור על הסימונים שסוכן או עמית השאירו ליד התכנון.", + "review.add": "הוספה", + "review.ago_days": "לפני {n} ימים", + "review.ago_hours": "לפני {n} שעות", + "review.ago_minutes": "לפני {n} דקות", + "review.ago_now": "עכשיו", + "review.attach": "צירוף תמונה…", + "review.cancel": "ביטול", + "review.close": "סגירת הסקירה", + "review.delete": "מחיקה", + "review.delete_ask": "למחוק את הסימון הזה ואת התמונות שלו?", + "review.done_by": "בוצע על ידי {by}: {reason}", + "review.edit_feature": "עריכת {name}", + "review.empty": "אין כאן סימונים. לחצו על „סמן כאן” או M כדי להצמיד הערה למודל.", + "review.filter_all": "הכול {count}", + "review.filter_done": "בוצעו {count}", + "review.filter_open": "פתוחים {count}", + "review.filter_rejected": "נדחו {count}", + "review.go_there": "מעבר לשם", + "review.gone_line": "מה שעליו עמד כבר אינו בתכנון הזה", + "review.hidden_line": "מוסתר כאן: אינו במודל בנקודה זו של ההיסטוריה או בתצורה זו", + "review.hide_pins": "הסתרת הסיכות", + "review.hint": "החדשים קודם · הסיכות לפי המסנן", + "review.in_browser": "נשמר בדפדפן הזה", + "review.mark": "סמן כאן", + "review.mark_tip": "הצמדת הערה למודל: לחצו במקום הרצוי. M מצמיד אותה למה שמתחת לסמן.", + "review.marked": "סומן על ידי {by} · {ago}", + "review.moved_line": "מה שעליו הוא עומד זז מאז הסימון", + "review.new": "חדש", + "review.no_file": "שמרו את התכנון כדי לסמן אותו", + "review.not_read": "לא ניתן לקרוא את הסימונים", + "review.note_hint": "מה צריך לשנות?", + "review.on_component": "רכיב {name}", + "review.on_edge": "קצה על {body}", + "review.on_face": "פאה על {body}", + "review.on_face_by": "{feature} על {body}", + "review.on_feature": "תכונה {name}", + "review.on_point": "נקודה במרחב", + "review.on_view": "התצוגה", + "review.one_picture": "תמונה אחת", + "review.one_reply": "תגובה אחת", + "review.pictures": "{count} תמונות", + "review.pictures_label": "תמונות (PNG או JPEG)", + "review.placing": "לחצו במקום שבו יעמוד הסימון; Esc עוצר.", + "review.reject": "דחייה…", + "review.reject_go": "דחייה", + "review.reject_hint": "למה זה לא ייעשה?", + "review.rejected_why": "נדחה: {reason}", + "review.reopen": "פתיחה מחדש", + "review.replies": "{count} תגובות", + "review.reply_hint": "תגובה…", + "review.resolve": "סיום…", + "review.resolve_go": "סיום", + "review.resolve_hint": "מה נעשה?", + "review.saved": "ליד התכנון · נשמר", + "review.screenshot": "צילום מסך", + "review.screenshot_tip": "צירוף תמונה של התצוגה כפי שהיא עכשיו", + "review.select": "בחירה", + "review.send": "שליחה", + "review.show_pins": "הצגת הסיכות", + "review.status_done": "בוצע", + "review.status_gone": "נעלם", + "review.status_hidden": "מוסתר כאן", + "review.status_open": "פתוח", + "review.status_rejected": "נדחה", + "review.title": "סקירה", + "review.unsaved": "שמרו קודם את התכנון: הסימונים שלו נשמרים בקובץ לידו." + }, + "ja": { + "cmd.view_review": "レビュー", + "help.view.review": "レビュー一覧とモデル上のレビューピンを表示または非表示にします。変更点をメモと画像で記録し、エージェントや同僚が設計の横に残したマークアップを順に処理するときに使います。", + "review.add": "追加", + "review.ago_days": "{n} 日前", + "review.ago_hours": "{n} 時間前", + "review.ago_minutes": "{n} 分前", + "review.ago_now": "たった今", + "review.attach": "画像を添付…", + "review.cancel": "キャンセル", + "review.close": "レビューを閉じる", + "review.delete": "削除", + "review.delete_ask": "このマークアップと画像を削除しますか?", + "review.done_by": "{by} が完了: {reason}", + "review.edit_feature": "{name} を編集", + "review.empty": "マークアップはまだありません。「ここをマーク」または M でモデルにメモを留めます。", + "review.filter_all": "すべて {count}", + "review.filter_done": "完了 {count}", + "review.filter_open": "未処理 {count}", + "review.filter_rejected": "却下 {count}", + "review.go_there": "そこへ移動", + "review.gone_line": "対象はこの設計にもうありません", + "review.hidden_line": "ここでは非表示: 履歴のこの時点またはこの構成ではモデルにありません", + "review.hide_pins": "ピンを隠す", + "review.hint": "新しい順 · ピンはフィルターに従います", + "review.in_browser": "このブラウザーに保存", + "review.mark": "ここをマーク", + "review.mark_tip": "モデルにメモを留めます: 置く場所をクリック。M はポインターの下に留めます。", + "review.marked": "{by} がマーク · {ago}", + "review.moved_line": "対象はマーク後に移動しました", + "review.new": "新規", + "review.no_file": "マークするには設計を保存", + "review.not_read": "マークアップを読み込めませんでした", + "review.note_hint": "何を変更しますか?", + "review.on_component": "コンポーネント {name}", + "review.on_edge": "{body} のエッジ", + "review.on_face": "{body} の面", + "review.on_face_by": "{body} の {feature}", + "review.on_feature": "フィーチャー {name}", + "review.on_point": "空間の点", + "review.on_view": "ビュー", + "review.one_picture": "画像 1 枚", + "review.one_reply": "返信 1 件", + "review.pictures": "画像 {count} 枚", + "review.pictures_label": "画像 (PNG または JPEG)", + "review.placing": "マークアップを置く場所をクリック。Esc で終了。", + "review.reject": "却下…", + "review.reject_go": "却下", + "review.reject_hint": "行わない理由は?", + "review.rejected_why": "却下: {reason}", + "review.reopen": "再オープン", + "review.replies": "返信 {count} 件", + "review.reply_hint": "返信…", + "review.resolve": "完了…", + "review.resolve_go": "完了", + "review.resolve_hint": "何を行いましたか?", + "review.saved": "設計の横 · 保存済み", + "review.screenshot": "スクリーンショット", + "review.screenshot_tip": "現在のビューの画像を添付", + "review.select": "選択", + "review.send": "送信", + "review.show_pins": "ピンを表示", + "review.status_done": "完了", + "review.status_gone": "消失", + "review.status_hidden": "ここでは非表示", + "review.status_open": "未処理", + "review.status_rejected": "却下", + "review.title": "レビュー", + "review.unsaved": "先に設計を保存してください: マークアップは横のファイルに保存されます。" + }, + "ko": { + "cmd.view_review": "검토", + "help.view.review": "검토 목록과 모델 위의 검토 핀을 표시하거나 숨깁니다. 바꿀 부분을 메모와 그림으로 표시하고, 에이전트나 동료가 설계 옆에 남긴 마크업을 하나씩 처리할 때 사용합니다.", + "review.add": "추가", + "review.ago_days": "{n}일 전", + "review.ago_hours": "{n}시간 전", + "review.ago_minutes": "{n}분 전", + "review.ago_now": "방금", + "review.attach": "이미지 첨부…", + "review.cancel": "취소", + "review.close": "검토 닫기", + "review.delete": "삭제", + "review.delete_ask": "이 마크업과 그림을 삭제할까요?", + "review.done_by": "{by} 완료: {reason}", + "review.edit_feature": "{name} 편집", + "review.empty": "아직 마크업이 없습니다. '여기 표시' 또는 M을 눌러 모델에 메모를 고정하세요.", + "review.filter_all": "전체 {count}", + "review.filter_done": "완료 {count}", + "review.filter_open": "열림 {count}", + "review.filter_rejected": "거부 {count}", + "review.go_there": "이동", + "review.gone_line": "대상이 더 이상 이 설계에 없습니다", + "review.hidden_line": "여기서 숨김: 기록의 이 지점이나 이 구성에서는 모델에 없습니다", + "review.hide_pins": "핀 숨기기", + "review.hint": "최신순 · 핀은 필터를 따릅니다", + "review.in_browser": "이 브라우저에 보관", + "review.mark": "여기 표시", + "review.mark_tip": "모델에 메모를 고정합니다: 놓을 곳을 클릭하세요. M은 포인터 아래에 고정합니다.", + "review.marked": "{by} 표시 · {ago}", + "review.moved_line": "표시한 뒤 대상이 이동했습니다", + "review.new": "새로 만들기", + "review.no_file": "표시하려면 설계를 저장하세요", + "review.not_read": "마크업을 읽을 수 없습니다", + "review.note_hint": "무엇을 바꿔야 하나요?", + "review.on_component": "구성 요소 {name}", + "review.on_edge": "{body}의 모서리", + "review.on_face": "{body}의 면", + "review.on_face_by": "{body}의 {feature}", + "review.on_feature": "피처 {name}", + "review.on_point": "공간의 한 점", + "review.on_view": "뷰", + "review.one_picture": "그림 1개", + "review.one_reply": "답글 1개", + "review.pictures": "그림 {count}개", + "review.pictures_label": "그림 (PNG 또는 JPEG)", + "review.placing": "마크업을 놓을 곳을 클릭하세요. Esc로 중지합니다.", + "review.reject": "거부…", + "review.reject_go": "거부", + "review.reject_hint": "하지 않는 이유는?", + "review.rejected_why": "거부: {reason}", + "review.reopen": "다시 열기", + "review.replies": "답글 {count}개", + "review.reply_hint": "답글…", + "review.resolve": "완료…", + "review.resolve_go": "완료", + "review.resolve_hint": "무엇을 했나요?", + "review.saved": "설계 옆 · 저장됨", + "review.screenshot": "스크린샷", + "review.screenshot_tip": "현재 뷰의 그림을 첨부", + "review.select": "선택", + "review.send": "보내기", + "review.show_pins": "핀 표시", + "review.status_done": "완료", + "review.status_gone": "사라짐", + "review.status_hidden": "여기서 숨김", + "review.status_open": "열림", + "review.status_rejected": "거부", + "review.title": "검토", + "review.unsaved": "먼저 설계를 저장하세요: 마크업은 옆의 파일에 보관됩니다." + }, + "vi": { + "cmd.view_review": "Duyệt", + "help.view.review": "Hiện hoặc ẩn danh sách Duyệt và các ghim duyệt trên mô hình. Dùng nó để đánh dấu chỗ cần sửa bằng ghi chú và hình, và để xử lý từng đánh dấu mà một tác tử hay đồng nghiệp để lại bên cạnh thiết kế.", + "review.add": "Thêm", + "review.ago_days": "{n} ngày trước", + "review.ago_hours": "{n} giờ trước", + "review.ago_minutes": "{n} phút trước", + "review.ago_now": "vừa xong", + "review.attach": "Đính kèm hình…", + "review.cancel": "Hủy", + "review.close": "Đóng Duyệt", + "review.delete": "Xóa", + "review.delete_ask": "Xóa đánh dấu này và các hình của nó?", + "review.done_by": "{by} đã làm: {reason}", + "review.edit_feature": "Sửa {name}", + "review.empty": "Chưa có đánh dấu nào. Nhấn Đánh dấu chỗ này, hoặc M, để ghim một ghi chú lên mô hình.", + "review.filter_all": "Tất cả {count}", + "review.filter_done": "Đã xong {count}", + "review.filter_open": "Đang mở {count}", + "review.filter_rejected": "Từ chối {count}", + "review.go_there": "Đến đó", + "review.gone_line": "Thứ nó nằm trên không còn trong thiết kế này", + "review.hidden_line": "Ẩn ở đây: không có trong mô hình tại điểm này của lịch sử hoặc trong cấu hình này", + "review.hide_pins": "Ẩn các ghim", + "review.hint": "Mới nhất trước · ghim theo bộ lọc", + "review.in_browser": "lưu trong trình duyệt này", + "review.mark": "Đánh dấu chỗ này", + "review.mark_tip": "Ghim một ghi chú lên mô hình: bấm vào chỗ đặt. M ghim vào thứ dưới con trỏ.", + "review.marked": "{by} đánh dấu · {ago}", + "review.moved_line": "Thứ nó nằm trên đã dịch chuyển từ khi đánh dấu", + "review.new": "Mới", + "review.no_file": "lưu thiết kế để đánh dấu", + "review.not_read": "không đọc được các đánh dấu", + "review.note_hint": "Cần sửa gì?", + "review.on_component": "Thành phần {name}", + "review.on_edge": "Cạnh trên {body}", + "review.on_face": "Mặt trên {body}", + "review.on_face_by": "{feature} trên {body}", + "review.on_feature": "Tính năng {name}", + "review.on_point": "Một điểm trong không gian", + "review.on_view": "Khung nhìn", + "review.one_picture": "1 hình", + "review.one_reply": "1 trả lời", + "review.pictures": "{count} hình", + "review.pictures_label": "Hình (PNG hoặc JPEG)", + "review.placing": "Bấm vào chỗ đặt đánh dấu; Esc để dừng.", + "review.reject": "Từ chối…", + "review.reject_go": "Từ chối", + "review.reject_hint": "Vì sao không làm?", + "review.rejected_why": "Từ chối: {reason}", + "review.reopen": "Mở lại", + "review.replies": "{count} trả lời", + "review.reply_hint": "Trả lời…", + "review.resolve": "Hoàn tất…", + "review.resolve_go": "Hoàn tất", + "review.resolve_hint": "Đã làm gì?", + "review.saved": "bên cạnh thiết kế · đã lưu", + "review.screenshot": "Chụp màn hình", + "review.screenshot_tip": "Đính kèm hình của khung nhìn hiện tại", + "review.select": "Chọn", + "review.send": "Gửi", + "review.show_pins": "Hiện các ghim", + "review.status_done": "Đã xong", + "review.status_gone": "Đã mất", + "review.status_hidden": "Ẩn ở đây", + "review.status_open": "Đang mở", + "review.status_rejected": "Từ chối", + "review.title": "Duyệt", + "review.unsaved": "Hãy lưu thiết kế trước: các đánh dấu được giữ trong một tệp bên cạnh nó." + }, + "zh": { + "cmd.view_review": "审阅", + "help.view.review": "显示或隐藏审阅列表和模型上的审阅图钉。用它以备注和图片标出需要修改之处,并逐条处理代理或同事留在设计旁的标记。", + "review.add": "添加", + "review.ago_days": "{n} 天前", + "review.ago_hours": "{n} 小时前", + "review.ago_minutes": "{n} 分钟前", + "review.ago_now": "刚刚", + "review.attach": "附加图片…", + "review.cancel": "取消", + "review.close": "关闭审阅", + "review.delete": "删除", + "review.delete_ask": "删除此标记及其图片?", + "review.done_by": "{by} 已完成:{reason}", + "review.edit_feature": "编辑 {name}", + "review.empty": "这里还没有标记。按“标记此处”或 M,在模型上钉一条备注。", + "review.filter_all": "全部 {count}", + "review.filter_done": "已完成 {count}", + "review.filter_open": "未处理 {count}", + "review.filter_rejected": "已拒绝 {count}", + "review.go_there": "前往", + "review.gone_line": "它所在的对象已不在此设计中", + "review.hidden_line": "此处隐藏:在历史的这一位置或此配置中不在模型里", + "review.hide_pins": "隐藏图钉", + "review.hint": "最新在前 · 图钉跟随筛选", + "review.in_browser": "保存在此浏览器中", + "review.mark": "标记此处", + "review.mark_tip": "在模型上钉一条备注:点击放置位置。M 钉在指针所指之处。", + "review.marked": "由 {by} 标记 · {ago}", + "review.moved_line": "它所在的对象在标记后已移动", + "review.new": "新建", + "review.no_file": "保存设计后才能标记", + "review.not_read": "无法读取标记", + "review.note_hint": "需要修改什么?", + "review.on_component": "组件 {name}", + "review.on_edge": "{body} 上的边", + "review.on_face": "{body} 上的面", + "review.on_face_by": "{body} 上的 {feature}", + "review.on_feature": "特征 {name}", + "review.on_point": "空间中的一点", + "review.on_view": "视图", + "review.one_picture": "1 张图片", + "review.one_reply": "1 条回复", + "review.pictures": "{count} 张图片", + "review.pictures_label": "图片(PNG 或 JPEG)", + "review.placing": "点击标记要放的位置;按 Esc 停止。", + "review.reject": "拒绝…", + "review.reject_go": "拒绝", + "review.reject_hint": "为什么不做?", + "review.rejected_why": "已拒绝:{reason}", + "review.reopen": "重新打开", + "review.replies": "{count} 条回复", + "review.reply_hint": "回复…", + "review.resolve": "完成…", + "review.resolve_go": "完成", + "review.resolve_hint": "做了什么?", + "review.saved": "在设计旁 · 已保存", + "review.screenshot": "截图", + "review.screenshot_tip": "附加当前视图的图片", + "review.select": "选择", + "review.send": "发送", + "review.show_pins": "显示图钉", + "review.status_done": "已完成", + "review.status_gone": "已消失", + "review.status_hidden": "此处隐藏", + "review.status_open": "未处理", + "review.status_rejected": "已拒绝", + "review.title": "审阅", + "review.unsaved": "请先保存设计:标记保存在它旁边的文件中。" + } +} diff --git a/attribution/pending/review-pins.md b/attribution/pending/review-pins.md new file mode 100644 index 00000000000..65b1ab3345c --- /dev/null +++ b/attribution/pending/review-pins.md @@ -0,0 +1 @@ +| crates/look/icons/design/svg/flat/review_mark.svg | SolidCraft contributors | Original analytic pin-with-plus icon for marking a place for review | SolidCraft Brand and Interface Licence (LICENSE-BRAND) | diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index f7f8cf8ea24..b419d39eb7f 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -4429,6 +4429,12 @@ pub struct Document { /// copies the design does not copy a plugin's large files. #[serde(default, skip_serializing, deserialize_with = "crate::plugin_data::deserialize")] pub plugin_data: std::collections::BTreeMap, + /// Review markup pictures, by entry name (`.png` or `.jpg`), as bytes + /// ([`crate::markup_image`]). A container keeps each under `markups/`, as a canvas keeps its + /// image; a plain JSON design can't hold them ([`Document::binary_data`]). Shared, so an edit + /// that copies the design does not copy the pictures. + #[serde(default, skip_serializing, deserialize_with = "crate::markup_image::deserialize")] + pub markup_images: std::collections::BTreeMap, } /// The browser's view of a design: items and folders hidden or shown, sketch profiles and @@ -4733,6 +4739,7 @@ impl Document { visibility: Visibility::default(), drawings: Vec::new(), plugin_data: Default::default(), + markup_images: Default::default(), } } @@ -5247,6 +5254,9 @@ impl Document { if !self.plugin_data.is_empty() { kinds.push("plugin files"); } + if !self.markup_images.is_empty() { + kinds.push("review pictures"); + } kinds } diff --git a/crates/doc/src/format/pending/review-markup-pictures.rs b/crates/doc/src/format/pending/review-markup-pictures.rs new file mode 100644 index 00000000000..550742feda2 --- /dev/null +++ b/crates/doc/src/format/pending/review-markup-pictures.rs @@ -0,0 +1,5 @@ +//! A design may carry review markup pictures: the bytes of each picture attached to a markup +//! (`markup.image`), a part of its own at `markups/.png` or `.jpg` in the container +//! (`markup_images`, never written as text). The markup set beside the design names each one by +//! that entry. An older design has none. The last release warns about the newer format number, +//! opens the design, and keeps those parts as they are when it saves. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 30c44f6f0db..ae96116266e 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -63,6 +63,7 @@ pub use inline_params::Defined; pub mod joints; pub mod json_layout; mod lineage; +pub mod markup_image; pub mod metadata; pub use metadata::Metadata; pub mod motion; diff --git a/crates/doc/src/markup_image.rs b/crates/doc/src/markup_image.rs new file mode 100644 index 00000000000..86a61d66ef3 --- /dev/null +++ b/crates/doc/src/markup_image.rs @@ -0,0 +1,59 @@ +//! Review markup pictures (`markup.image`): each picture's bytes in the design, a part of the +//! container of its own under `markups/`, the way a canvas keeps its image. The markup set beside +//! the design (`solidcraft_io::markups`) keeps the threads and anchors and names each picture by +//! its entry here; the design holds the bytes, never text. +use std::collections::BTreeMap; + +use serde::{Deserialize, Deserializer}; + +use crate::blob::Blob; + +/// The container folder the pictures live in. +pub const PREFIX: &str = "markups/"; +/// The largest picture, in bytes. +pub const MAX_BYTES: usize = 16 << 20; +/// At most this many pictures in one design; past it the rest is left out as it opens. +pub const MAX_FILES: usize = 4096; +/// The most the pictures of one design take together, in bytes. +pub const MAX_TOTAL_BYTES: u64 = 1 << 30; + +/// Whether `name` is a picture's entry name: 32 hexadecimal digits and `.png` or `.jpg`, so it can +/// never name a part outside its folder. +pub fn valid_name(name: &str) -> bool { + name.strip_suffix(".png").or_else(|| name.strip_suffix(".jpg")).is_some_and(|g| g.len() == 32 && g.bytes().all(|b| b.is_ascii_hexdigit())) +} + +/// The kind of picture `bytes` hold by their first bytes: `png` or `jpg` (`None`: neither). +pub fn kind(bytes: &[u8]) -> Option<&'static str> { + if bytes.starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]) { + Some("png") + } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + Some("jpg") + } else { + None + } +} + +/// A design's JSON never holds the pictures: whatever a hand-edited file has there is left out. +pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + serde::de::IgnoredAny::deserialize(deserializer)?; + Ok(BTreeMap::new()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_and_kinds() { + let guid = "0123456789abcdef0123456789ABCDEF"; + assert!(valid_name(&format!("{guid}.png"))); + assert!(valid_name(&format!("{guid}.jpg"))); + for bad in ["x.png", "../x.png", &format!("{guid}.gif"), &format!("a/{guid}.png"), ""] { + assert!(!valid_name(bad), "{bad}"); + } + assert_eq!(kind(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0]), Some("png")); + assert_eq!(kind(&[0xFF, 0xD8, 0xFF, 0xE0]), Some("jpg")); + assert_eq!(kind(b"GIF89a"), None); + } +} diff --git a/crates/doc/src/placement_reuse.rs b/crates/doc/src/placement_reuse.rs index bba39651d9f..262173f094a 100644 --- a/crates/doc/src/placement_reuse.rs +++ b/crates/doc/src/placement_reuse.rs @@ -177,6 +177,8 @@ fn same_geometry_inputs(a: &Document, b: &Document) -> bool { notes: _, // Plugin data is kept beside the design; no feature reads it. plugin_data: _, + // Review pictures: no feature reads them. + markup_images: _, } = a; (Arc::ptr_eq(render, &b.render) || *render == b.render) && *format == b.format diff --git a/crates/engine/src/cmd/markups.rs b/crates/engine/src/cmd/markups.rs new file mode 100644 index 00000000000..0875bb9960b --- /dev/null +++ b/crates/engine/src/cmd/markups.rs @@ -0,0 +1,941 @@ +//! Review markup commands: mark a face, an edge, a body, a feature, a component, a point or a +//! view of a design with a note, reply to it, attach pictures, and close it as done or not done, +//! with a reason ([review markups](../../../../docs/review-markups.md)). +//! +//! The markups are a set of their own beside the design (`solidcraft_io::markups`): every write +//! is one step on the set as it stands on the disk, under its lock. Only a markup's pictures are +//! the design's: `markup.image` puts each picture's bytes in the design as an entry of its own +//! (`Document::markup_images`, saved as a part of the container the way a canvas's image is), one +//! undo step, and the set names the entry. They need no window and open no dialog. +//! +//! A markup on a face keeps the face's lasting name (the name `model.faces` lists) and the point +//! that was marked. `markup.list` finds each face again by that name with exact geometry, never +//! the display mesh: the B-rep's own faces, `Body::nearest_face` and `Body::point_lies_on_face`. +//! So a rebuild that moves the face keeps the markup on it (`moved`), a face the history marker +//! or the active configuration leaves out is `hidden`, not gone, and only a face no feature makes +//! any more is `gone`. + +use serde_json::{Value, json}; + +use solidcore_record::Vec3; +use solidcraft_doc::{ModelBody, ModelState, persistent_name}; +use solidcraft_geom::prelude::*; +use solidcraft_io::markups::{self as set, Anchor, Image, Markup, Message, Outcome, Set, Status, View}; + +use super::CommandSpec; +use crate::params::{bad, str_, vec3}; +use crate::schema::markups::{ + MarkupAddParams, MarkupChanged, MarkupCloseParams, MarkupDeleteParams, MarkupDeleted, MarkupEditParams, MarkupImageParams, MarkupList, + MarkupListParams, MarkupMade, MarkupReopenParams, MarkupReplyParams, +}; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{Result, Session}; + +const LIST: TypedContract = TypedContract::new(); +const ADD: TypedContract = TypedContract::new(); +const EDIT: TypedContract = TypedContract::new(); +const REPLY: TypedContract = TypedContract::new(); +const IMAGE: TypedContract = TypedContract::new(); +const CLOSE: TypedContract = TypedContract::new(); +const REOPEN: TypedContract = TypedContract::new(); +const DELETE: TypedContract = TypedContract::new(); + +/// Who wrote something when a call does not say: an agent or a script. +pub const AGENT: &str = "agent"; + +/// The keys that say what a markup is on. +const ANCHOR_KEYS: &[&str] = &["face", "edge", "body", "at", "feature", "occurrence"]; + +pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("markup.list", "List Markups", crate::checked!("markup.list", markup_list)) + .icon("list") + .contract(&LIST) + .output(output_schema_for::) + .noundo() + .read_only() + .params("set?: path (default: beside the design); status?: open|resolved|rejected → set, counts, markups: [{id, guid, status, note, thread, anchor, found: {state: anchored|moved|gone|hidden|unchecked, at?, was?, moved_by?, why?}, view?, images, by, made, changed, outcome?}]"), + CommandSpec::new("markup.add", "Add Markup", crate::checked!("markup.add", markup_add)) + .icon("text") + .contract(&ADD) + .output(output_schema_for::) + .noundo() + .params("text; face?: name (+ body?); edge?: name (+ body?); body?; at?: [x,y,z] (a point on a face, or in space); feature?; occurrence?: [ids]; view?: {target, yaw, pitch, distance, fov}; by?; set? → markup, guid, anchor, found"), + CommandSpec::new("markup.edit", "Edit Markup", crate::checked!("markup.edit", markup_edit)) + .icon("edit") + .contract(&EDIT) + .output(output_schema_for::) + .noundo() + .params("markup: id or guid; text? (the note, its maker only); face?/edge?/body?/at?/feature?/occurrence? (pin it again); view?; by?; set? → markup, status"), + CommandSpec::new("markup.reply", "Reply to Markup", crate::checked!("markup.reply", markup_reply)) + .icon("text") + .contract(&REPLY) + .output(output_schema_for::) + .noundo() + .doc_only() + .params("markup: id or guid; text (at most 280 characters from anyone but its maker); by?; set? → markup, status"), + CommandSpec::new("markup.image", "Markup Picture", crate::checked!("markup.image", markup_image)) + .icon("render_image") + .contract(&IMAGE) + .output(output_schema_for::) + .doc_only() + .params("markup: id or guid; file?: a PNG or JPEG path (+ name?) | remove?: a picture's entry; by?; set? → markup, status, image?"), + CommandSpec::new("markup.resolve", "Resolve Markup", crate::checked!("markup.resolve", markup_resolve)) + .icon("finish") + .contract(&CLOSE) + .output(output_schema_for::) + .noundo() + .doc_only() + .params("markup: id or guid; reason: what was done; by?; set? → markup, status"), + CommandSpec::new("markup.reject", "Reject Markup", crate::checked!("markup.reject", markup_reject)) + .icon("close") + .contract(&CLOSE) + .output(output_schema_for::) + .noundo() + .doc_only() + .params("markup: id or guid; reason: why it was not done; by?; set? → markup, status"), + CommandSpec::new("markup.reopen", "Reopen Markup", crate::checked!("markup.reopen", markup_reopen)) + .icon("undo") + .contract(&REOPEN) + .output(output_schema_for::) + .noundo() + .doc_only() + .params("markup: id or guid; reason?; by?; set? → markup, status"), + CommandSpec::new("markup.delete", "Delete Markup", crate::checked!("markup.delete", markup_delete)) + .icon("delete") + .contract(&DELETE) + .output(output_schema_for::) + .doc_only() + .params("markup: id or guid; set? → deleted: id (its pictures leave the design too)"), +]; + +/// The set a call works on: `set`, or the one beside the design's file. +fn set_path(s: &Session, p: &Value, cmd: &str) -> Result { + if let Some(v) = p.get("set").filter(|v| !v.is_null()) { + let path = v.as_str().filter(|t| !t.trim().is_empty()).ok_or_else(|| bad(cmd, "`set` must be a path"))?; + set::folder(path).map_err(|e| bad(cmd, e))?; + if path.chars().count() > set::MAX_NAME || path.contains('\0') { + return Err(bad(cmd, "`set` is too long a path")); + } + return Ok(path.to_string()); + } + match s.path.as_deref() { + Some(design) if !design.is_empty() => Ok(set::beside(design)), + _ => Err(bad(cmd, "the design has no file yet: save it first, or give `set`")), + } +} + +/// Who a call writes as: `by`, or [`AGENT`]. +fn who(p: &Value, cmd: &str) -> Result { + match p.get("by").filter(|v| !v.is_null()) { + None => Ok(AGENT.to_string()), + Some(v) => { + let by = v.as_str().ok_or_else(|| bad(cmd, "`by` must be a name"))?; + set::check_person(by).map_err(|e| bad(cmd, format!("`by`: {e}")))?; + Ok(by.to_string()) + } + } +} + +/// Unix seconds now. +fn now() -> u64 { + web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map_or(0, |d| d.as_secs()) +} + +/// A new guid: 32 hexadecimal digits from the clock, a counter and this process's random keys. +fn new_guid() -> String { + use std::hash::{BuildHasher, RandomState}; + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(1); + let nanos = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let a = RandomState::new().hash_one((nanos, n, 1u8)); + let b = RandomState::new().hash_one((n, nanos, 2u8)); + format!("{a:016x}{b:016x}") +} + +/// The markup `markup` names in `set`: its number, or its guid. +fn which(s: &Set, p: &Value) -> std::result::Result { + match p.get("markup") { + Some(Value::Number(n)) => { + let id = n.as_u64().ok_or("`markup` must be a markup's number or guid")?; + s.get(id).map(|m| m.id).ok_or_else(|| format!("no markup {id}")) + } + Some(Value::String(g)) if set::is_guid(g) => s.by_guid(g).ok_or_else(|| "no markup has that guid".to_string()), + Some(Value::String(t)) if t.parse::().is_ok() => { + let id = t.parse::().unwrap_or(0); + s.get(id).map(|m| m.id).ok_or_else(|| format!("no markup {id}")) + } + _ => Err("`markup` must be a markup's number or guid".into()), + } +} + +fn point(v: Vec3) -> [f64; 3] { + [v.x, v.y, v.z] +} + +fn vec(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} + +/// How far a picked point may lie from a body's exact face and still be on it. +fn reach(b: &ModelBody) -> f64 { + (b.body.size() * 2e-3).max(1e-3) +} + +/// The body called `name`, else the one body the feature `maker` made (a body renamed since). +fn find_body<'a>(st: &'a ModelState, name: &str, maker: u64) -> Option<&'a ModelBody> { + st.body(name).filter(|b| !b.body.is_mesh()).or_else(|| { + let mut made = st.bodies.iter().filter(|b| b.feature == maker && maker != 0 && !b.body.is_mesh()); + match (made.next(), made.next()) { + (Some(b), None) => Some(b), + _ => None, + } + }) +} + +/// The faces of `b` with the lasting name `name`, by B-rep face index. +fn faces_named(b: &ModelBody, name: &str) -> Vec { + solidcraft_doc::naming::face_names(b) + .iter() + .enumerate() + .filter(|(_, n)| !n.is_empty() && persistent_name::same_face(n, name)) + .map(|(i, _)| i) + .collect() +} + +/// The name of each B-rep edge of `b`: its faces' lasting names, sorted, joined by `|` (as +/// `model.edges` lists them, without the number that tells repeated ones apart). +fn edge_face_names(b: &ModelBody) -> Vec { + let faces = solidcraft_doc::naming::face_names(b); + b.body + .record() + .edges + .iter() + .map(|e| { + let mut n: Vec<&str> = e.uses.iter().filter_map(|u| faces.get(u.face as usize).map(String::as_str)).collect(); + n.sort_unstable(); + n.dedup(); + n.join("|") + }) + .collect() +} + +/// An edge name without the number that tells repeated edges between the same faces apart. +fn edge_stem(name: &str) -> &str { + name.rsplit_once('~').filter(|(_, k)| !k.is_empty() && k.bytes().all(|c| c.is_ascii_digit())).map_or(name, |(stem, _)| stem) +} + +/// Whether two edge names are the same pair of faces, in either text form. +fn same_edge_faces(a: &str, b: &str) -> bool { + let (a, b) = (edge_stem(a), edge_stem(b)); + if a == b { + return true; + } + let mut x: Vec<&str> = a.split('|').collect(); + let mut y: Vec<&str> = b.split('|').collect(); + x.sort_unstable(); + y.sort_unstable(); + x.len() == y.len() && x.iter().zip(&y).all(|(p, q)| persistent_name::same_face(p, q)) +} + +/// The point of face `face` nearest `p`, exactly, and how far `p` is from it. +fn nearest_on_face(b: &ModelBody, face: usize, p: Vec3) -> Option<(Vec3, f64)> { + let far = b.body.size().max(1.0) * 10.0 + p.dist(Vec3::ZERO); + let q = b.body.point_lies_on_face(face, p, far).ok()??; + Some((q, q.dist(p))) +} + +/// A point on edge `edge` of `b` near `p`, exactly: `p` taken onto the edge's two faces in turn +/// until it lies on both (an edge is where they meet). +fn near_edge(b: &ModelBody, edge: usize, p: Vec3) -> Option { + let faces: Vec = b.body.record().edges.get(edge)?.uses.iter().map(|u| u.face as usize).collect(); + let (first, second) = (*faces.first()?, *faces.get(1).or(faces.first())?); + let mut q = p; + for _ in 0..8 { + q = nearest_on_face(b, first, q)?.0; + q = nearest_on_face(b, second, q)?.0; + if solidcraft_kernel::edge_distance(&b.body, edge, q).ok().flatten().is_some_and(|d| d <= reach(b)) { + return Some(q); + } + } + Some(q) +} + +/// A point on face `face` of `b`: the one nearest the middle of the body. +fn point_on(b: &ModelBody, face: usize) -> Option { + let middle = b.body.exact_bounds().ok()?.center(); + nearest_on_face(b, face, middle).map(|(q, _)| q) +} + +/// The face of a body nearest `p` within a pick's reach, exactly: body, face, the point on it. +fn face_at<'a>(st: &'a ModelState, body: Option<&'a ModelBody>, p: Vec3) -> Option<(&'a ModelBody, usize, Vec3)> { + let bodies: Vec<&ModelBody> = match body { + Some(b) => vec![b], + None => st.bodies.iter().filter(|b| !b.body.is_mesh()).collect(), + }; + let mut best: Option<(f64, &ModelBody, usize)> = None; + for b in bodies { + let r = reach(b); + if body.is_none() && !b.body.exact_bounds().is_ok_and(|bb| bb.inflated(r).contains(p)) { + continue; + } + if let Some((d, f)) = b.body.nearest_face(p) + && d <= r + && best.is_none_or(|(bd, ..)| d < bd) + { + best = Some((d, b, f)); + } + } + let (_, b, f) = best?; + let q = b.body.point_lies_on_face(f, p, reach(b)).ok().flatten().unwrap_or(p); + Some((b, f, q)) +} + +/// The anchor a call names (`None`: it names none). +fn capture(s: &Session, p: &Value, cmd: &str) -> Result> { + if !ANCHOR_KEYS.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + return Ok(None); + } + let at = match p.get("at").filter(|v| !v.is_null()) { + Some(v) => Some( + vec3(v) + .filter(|v| v.is_finite() && [v.x, v.y, v.z].iter().all(|c| c.abs() <= set::MAX_COORD)) + .ok_or_else(|| bad(cmd, "`at` must be a point [x, y, z] of finite numbers"))?, + ), + None => None, + }; + let text = |k: &str| -> Result> { + match p.get(k).filter(|v| !v.is_null()) { + None => Ok(None), + Some(v) => { + let t = v.as_str().filter(|t| !t.trim().is_empty() && t.chars().count() <= set::MAX_NAME && !t.chars().any(char::is_control)); + t.map(|t| Some(t.to_string())).ok_or_else(|| bad(cmd, format!("`{k}` must be a name"))) + } + } + }; + let (face, edge, body) = (text("face")?, text("edge")?, text("body")?); + let config = s.doc.configs.active.clone(); + let st = s.world_state()?; + let body_ref = match &body { + Some(n) => Some(st.body(n).filter(|b| !b.body.is_mesh()).ok_or_else(|| bad(cmd, format!("no solid body `{n}`")))?), + None => None, + }; + if let Some(face) = face { + let candidates: Vec<(&ModelBody, Vec)> = match body_ref { + Some(b) => vec![(b, faces_named(b, &face))], + None => st.bodies.iter().filter(|b| !b.body.is_mesh()).map(|b| (b, faces_named(b, &face))).collect(), + }; + let found: Vec<(&ModelBody, Vec)> = candidates.into_iter().filter(|(_, f)| !f.is_empty()).collect(); + let (b, faces) = match found.as_slice() { + [] => return Err(bad(cmd, format!("no face is named `{face}` (`model.faces` lists the names)"))), + [one] => one.clone(), + _ => return Err(bad(cmd, format!("`{face}` names faces of several bodies: give `body`"))), + }; + let on = match at { + Some(a) => faces + .iter() + .find_map(|f| b.body.point_lies_on_face(*f, a, reach(b)).ok().flatten()) + .ok_or_else(|| bad(cmd, format!("`at` does not lie on face `{face}` of `{}`", b.name)))?, + None => faces.iter().find_map(|f| point_on(b, *f)).ok_or_else(|| bad(cmd, format!("face `{face}` has no point to mark")))?, + }; + return Ok(Some(Anchor::Face { body: b.name.clone(), maker: b.feature, face, at: point(on), config })); + } + if let Some(edge) = edge { + let bodies: Vec<&ModelBody> = match body_ref { + Some(b) => vec![b], + None => st.bodies.iter().filter(|b| !b.body.is_mesh()).collect(), + }; + let mut found: Vec<(&ModelBody, usize)> = Vec::new(); + for b in bodies { + for (i, n) in edge_face_names(b).iter().enumerate() { + if !n.is_empty() && same_edge_faces(n, &edge) { + found.push((b, i)); + } + } + } + let mut names: Vec<&str> = found.iter().map(|(b, _)| b.name.as_str()).collect(); + names.dedup(); + if names.len() > 1 { + return Err(bad(cmd, format!("`{edge}` names edges of several bodies: give `body`"))); + } + // Of several edges between the same faces, the one the point lies on. + let pick = match at { + Some(a) => { + found.iter().copied().find(|(b, i)| solidcraft_kernel::edge_distance(&b.body, *i, a).ok().flatten().is_some_and(|d| d <= reach(b))) + } + None if found.len() == 1 => found.first().copied(), + None => return Err(bad(cmd, format!("`{edge}` names {} edges: give `at`, a point on the one you mean", found.len()))), + }; + let Some((b, index)) = pick else { + return Err(bad( + cmd, + format!("no edge is named `{edge}`{} (`model.edges` lists the names)", if at.is_some() { " through `at`" } else { "" }), + )); + }; + // No point given: the edge's own point nearest the body's middle, so the markup is found + // where it was made. + let at = match at { + Some(a) => a, + None => { + let middle = b.body.exact_bounds().map(|bb| bb.center()).map_err(|e| bad(cmd, e.to_string()))?; + solidcraft_kernel::edge_closest_point(&b.body, index, middle) + .map_err(|e| bad(cmd, e.to_string()))? + .ok_or_else(|| bad(cmd, format!("`{edge}` could not be measured: give `at`, a point on it")))? + } + }; + return Ok(Some(Anchor::Edge { body: b.name.clone(), maker: b.feature, edge, at: point(at), config })); + } + if let Some(feature) = p.get("feature").filter(|v| !v.is_null()) { + let f = match feature { + Value::Number(n) => n.as_u64().and_then(|id| s.doc.features.iter().find(|f| f.id == id)), + Value::String(t) => s.doc.features.iter().find(|f| f.name == *t), + _ => None, + } + .ok_or_else(|| bad(cmd, "`feature` must name a feature of the timeline, by id or name"))?; + return Ok(Some(Anchor::Feature { feature: f.id, name: f.name.clone(), at: at.map(point) })); + } + if let Some(occ) = p.get("occurrence").filter(|v| !v.is_null()) { + let path: Vec = occ + .as_array() + .filter(|a| !a.is_empty() && a.len() <= set::MAX_PATH) + .and_then(|a| a.iter().map(Value::as_u64).collect::>>()) + .ok_or_else(|| bad(cmd, format!("`occurrence` must be a path of 1 to {} occurrence ids", set::MAX_PATH)))?; + let name = occurrence_name(s, &path).ok_or_else(|| bad(cmd, "`occurrence` names no placed component"))?; + return Ok(Some(Anchor::Occurrence { path, name, at: at.map(point) })); + } + if let Some(b) = body_ref { + // A point on the body marks the face it lies on; a body alone, the body. + if let Some(a) = at { + let (b, f, q) = face_at(&st, Some(b), a).ok_or_else(|| bad(cmd, format!("`at` does not lie on `{}`", b.name)))?; + if let Some(face) = solidcraft_doc::naming::face_names(b).get(f).filter(|n| !n.is_empty()) { + return Ok(Some(Anchor::Face { body: b.name.clone(), maker: b.feature, face: face.clone(), at: point(q), config })); + } + return Ok(Some(Anchor::Body { body: b.name.clone(), maker: b.feature, at: Some(point(q)), config })); + } + return Ok(Some(Anchor::Body { body: b.name.clone(), maker: b.feature, at: None, config })); + } + // A point alone: the face it lies on, or the point in space. + if let Some(a) = at { + if let Some((b, f, q)) = face_at(&st, None, a) + && let Some(face) = solidcraft_doc::naming::face_names(b).get(f).filter(|n| !n.is_empty()) + { + return Ok(Some(Anchor::Face { body: b.name.clone(), maker: b.feature, face: face.clone(), at: point(q), config })); + } + return Ok(Some(Anchor::Point { at: point(a) })); + } + Ok(None) +} + +/// The anchor of the one thing selected, as `markup.add` takes it when it is given no anchor and no view. +fn from_selection(s: &Session) -> Option { + let [one] = s.selection.as_slice() else { return None }; + let st = s.world_state().ok()?; + let config = s.doc.configs.active.clone(); + match one { + crate::Sel::Face { body, index, point: at } => { + let b = st.body(body).filter(|b| !b.body.is_mesh())?; + let face = solidcraft_doc::naming::face_names(b).get(*index).filter(|n| !n.is_empty())?.clone(); + let q = b.body.point_lies_on_face(*index, *at, reach(b)).ok().flatten().unwrap_or(*at); + Some(Anchor::Face { body: b.name.clone(), maker: b.feature, face, at: point(q), config }) + } + crate::Sel::Edge { body, index, point: at } => { + let b = st.body(body).filter(|b| !b.body.is_mesh())?; + let edge = edge_face_names(b).get(*index).filter(|n| !n.is_empty())?.clone(); + Some(Anchor::Edge { body: b.name.clone(), maker: b.feature, edge, at: point(*at), config }) + } + crate::Sel::Body { name } => { + let b = st.body(name)?; + Some(Anchor::Body { body: b.name.clone(), maker: b.feature, at: None, config }) + } + crate::Sel::Feature { id } => { + s.doc.features.iter().find(|f| f.id == *id).map(|f| Anchor::Feature { feature: f.id, name: f.name.clone(), at: None }) + } + crate::Sel::Occurrence { path } => occurrence_name(s, path).map(|name| Anchor::Occurrence { path: path.clone(), name, at: None }), + _ => None, + } +} + +/// The name of the placed component at `path`, when each step is a child of the one before. +fn occurrence_name(s: &Session, path: &[u64]) -> Option { + let mut parent = 0; + let mut name = None; + for id in path { + let o = s.doc.occurrences.iter().find(|o| o.id == *id && o.parent == parent)?; + parent = o.id; + name = Some(o.name.clone()); + } + name +} + +/// The camera a call gives (`None`: none). +fn view_of(p: &Value, cmd: &str) -> Result> { + match p.get("view").filter(|v| !v.is_null()) { + None => Ok(None), + Some(v) => { + let view: View = serde_json::from_value(v.clone()).map_err(|_| bad(cmd, "`view` is {target: [x, y, z], yaw, pitch, distance, fov?}"))?; + set::check_view(&view).map_err(|e| bad(cmd, format!("`view`: {e}")))?; + Ok(Some(view)) + } + } +} + +/// Where an anchor stands now. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Found { + /// There, at `at` (the point it was marked at, or none). + Anchored { at: Option<[f64; 3]> }, + /// There, but no longer where it was marked: now at `at`, `moved_by` mm from `was`. + Moved { at: [f64; 3], was: [f64; 3], moved_by: f64 }, + /// Not in the model now, but still in the design: the history marker or the active + /// configuration leaves it out. + Hidden { why: String, was: Option<[f64; 3]> }, + /// Gone from the design, or never given. + Gone { why: String, was: Option<[f64; 3]> }, + /// Could not be checked. + Unchecked { why: String }, +} + +impl Found { + fn word(&self) -> &'static str { + match self { + Found::Anchored { .. } => "anchored", + Found::Moved { .. } => "moved", + Found::Hidden { .. } => "hidden", + Found::Gone { .. } => "gone", + Found::Unchecked { .. } => "unchecked", + } + } + + pub(crate) fn to_value(&self) -> Value { + let mut v = json!({ "state": self.word() }); + match self { + Found::Anchored { at } => { + if let Some(a) = at { + v["at"] = json!(a); + } + } + Found::Moved { at, was, moved_by } => { + v["at"] = json!(at); + v["was"] = json!(was); + v["moved_by"] = json!(moved_by); + } + Found::Hidden { why, was } | Found::Gone { why, was } => { + v["why"] = json!(why); + if let Some(w) = was { + v["was"] = json!(w); + } + } + Found::Unchecked { why } => v["why"] = json!(why), + } + v + } +} + +/// Why a face, edge or body that is not in the model is hidden rather than gone: the features +/// that make it are all still in the design, and the history marker, a suppression or another +/// configuration leaves one of them out. `None`: it is gone. +fn hidden_why(s: &Session, features: &[u64], config: Option<&str>, what: &str) -> Option { + let doc = &s.doc; + let mut out = None; + for id in features.iter().filter(|id| **id != 0) { + let i = doc.feature_index(*id)?; + let f = doc.features.get(i)?; + if out.is_none() { + if doc.marker.is_some_and(|m| i >= m) { + out = Some(format!("{what} is past the history marker (made by `{}`)", f.name)); + } else if f.suppressed { + out = Some(format!("{what} is made by `{}`, which is suppressed", f.name)); + } + } + } + if out.is_none() && config != doc.configs.active.as_deref() { + let marked = config.map_or_else(|| "with no configuration".to_string(), |c| format!("in configuration `{c}`")); + let now = doc.configs.active.as_deref().map_or_else(|| "none is active now".to_string(), |c| format!("`{c}` is active now")); + out = Some(format!("{what} was marked {marked}; {now}")); + } + out +} + +/// The features a face name says made the face. +fn face_features(name: &str) -> Vec { + persistent_name::FaceName::parse(name).map(|f| f.features().into_iter().map(|id| id.0).collect()).unwrap_or_default() +} + +/// Where `anchor` stands in the session's model now. +pub(crate) fn found(s: &Session, st: &ModelState, anchor: &Anchor) -> Found { + match anchor { + Anchor::Face { body, maker, face, at, config } => { + let gone_or_hidden = |what: &str| { + let mut features = face_features(face); + features.push(*maker); + let was = Some(*at); + match hidden_why(s, &features, config.as_deref(), what) { + Some(why) => Found::Hidden { why, was }, + None => Found::Gone { why: format!("{what} was deleted or replaced"), was }, + } + }; + let Some(b) = find_body(st, body, *maker) else { return gone_or_hidden(&format!("the body `{body}` this face was on")) }; + let faces = faces_named(b, face); + if faces.is_empty() { + return gone_or_hidden(&format!("the face of `{}` it was on", b.name)); + } + let p = vec(*at); + let r = reach(b); + let mut best: Option<(Vec3, f64)> = None; + for f in &faces { + if let Some((q, d)) = nearest_on_face(b, *f, p) + && best.is_none_or(|(_, bd)| d < bd) + { + best = Some((q, d)); + } + } + match best { + Some((_, d)) if d <= r => Found::Anchored { at: Some(*at) }, + Some((q, d)) => Found::Moved { at: point(q), was: *at, moved_by: d }, + None => Found::Unchecked { why: format!("the face of `{}` could not be measured", b.name) }, + } + } + Anchor::Edge { body, maker, edge, at, config } => { + let gone_or_hidden = |what: &str| { + let mut features: Vec = edge_stem(edge).split('|').flat_map(face_features).collect(); + features.push(*maker); + let was = Some(*at); + match hidden_why(s, &features, config.as_deref(), what) { + Some(why) => Found::Hidden { why, was }, + None => Found::Gone { why: format!("{what} was deleted or replaced"), was }, + } + }; + let Some(b) = find_body(st, body, *maker) else { return gone_or_hidden(&format!("the body `{body}` this edge was on")) }; + let p = vec(*at); + let edges: Vec = + edge_face_names(b).iter().enumerate().filter(|(_, n)| !n.is_empty() && same_edge_faces(n, edge)).map(|(i, _)| i).collect(); + if edges.is_empty() { + return gone_or_hidden(&format!("the edge of `{}` it was on", b.name)); + } + let nearest = edges + .iter() + .filter_map(|i| solidcraft_kernel::edge_distance(&b.body, *i, p).ok().flatten().map(|d| (d, *i))) + .min_by(|x, y| x.0.total_cmp(&y.0)); + match nearest { + Some((d, _)) if d <= reach(b) => Found::Anchored { at: Some(*at) }, + Some((_, i)) => match near_edge(b, i, p) { + Some(q) => Found::Moved { at: point(q), was: *at, moved_by: q.dist(p) }, + None => Found::Unchecked { why: format!("the edge of `{}` could not be measured", b.name) }, + }, + None => Found::Unchecked { why: format!("the edge of `{}` could not be measured", b.name) }, + } + } + Anchor::Body { body, maker, at, config } => match find_body(st, body, *maker) { + Some(_) => Found::Anchored { at: *at }, + None => { + let what = format!("the body `{body}`"); + match hidden_why(s, &[*maker], config.as_deref(), &what) { + Some(why) => Found::Hidden { why, was: *at }, + None => Found::Gone { why: format!("{what} was deleted or replaced"), was: *at }, + } + } + }, + Anchor::Feature { feature, name, at } => match s.doc.features.iter().find(|f| f.id == *feature) { + Some(_) => Found::Anchored { at: *at }, + None => Found::Gone { why: format!("the feature `{name}` was deleted"), was: *at }, + }, + Anchor::Occurrence { path, name, at } => match occurrence_name(s, path) { + Some(_) => Found::Anchored { at: *at }, + None => Found::Gone { why: format!("the component `{name}` was removed from the assembly"), was: *at }, + }, + Anchor::Point { at } => Found::Anchored { at: Some(*at) }, + Anchor::View {} => Found::Anchored { at: None }, + Anchor::Unanchored { why, .. } => Found::Gone { why: why.clone(), was: None }, + } +} + +/// One markup as `markup.list` gives it. +fn row(s: &Session, st: &ModelState, m: &Markup) -> Value { + let thread: Vec = m.thread.iter().map(|t| json!({"by": t.by, "at": t.at, "text": t.text, "reviewer": t.by == m.by})).collect(); + let images: Vec = m + .images + .iter() + .map(|i| json!({"file": i.file, "name": i.name, "by": i.by, "at": i.at, "bytes": i.bytes, "in_design": s.doc.markup_images.contains_key(&i.file)})) + .collect(); + let mut v = json!({ + "id": m.id, + "guid": m.guid, + "status": m.status.word(), + "note": m.note(), + "thread": thread, + "anchor": serde_json::to_value(&m.anchor).unwrap_or(Value::Null), + "found": found(s, st, &m.anchor).to_value(), + "images": images, + "by": m.by, + "made": m.made, + "changed": m.changed, + }); + if let Some(view) = &m.view { + v["view"] = serde_json::to_value(view).unwrap_or(Value::Null); + } + if let Some(o) = &m.outcome { + v["outcome"] = json!({"by": o.by, "reason": o.reason, "at": o.at}); + } + v +} + +fn markup_list(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "markup.list"; + let path = set_path(s, p, CMD)?; + let status = match str_(p, "status") { + Some(w) => Some(Status::from_word(w).ok_or_else(|| bad(CMD, "`status` is open, resolved or rejected"))?), + None => None, + }; + let the_set = set::read(&path).map_err(|e| bad(CMD, e))?; + let st = s.world_state()?; + let count = |w: Status| the_set.markups.iter().filter(|m| m.status == w).count(); + let counts = json!({"open": count(Status::Open), "resolved": count(Status::Resolved), "rejected": count(Status::Rejected)}); + let markups: Vec = the_set.markups.iter().filter(|m| status.is_none_or(|w| m.status == w)).map(|m| row(s, &st, m)).collect(); + Ok(json!({ "set": path, "format": the_set.format, "counts": counts, "markups": markups })) +} + +fn markup_add(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "markup.add"; + let path = set_path(s, p, CMD)?; + let by = who(p, CMD)?; + let text = str_(p, "text").ok_or_else(|| bad(CMD, "`text` is required: the note"))?.to_string(); + set::check_text(&text, set::MAX_NOTE).map_err(|e| bad(CMD, e))?; + let view = view_of(p, CMD)?; + // A view given with nothing else named is the markup's place: Mark this on empty space means + // the view, whatever happens to be selected. + let anchor = match capture(s, p, CMD)? { + Some(a) => a, + None if view.is_some() => Anchor::View {}, + None => match from_selection(s) { + Some(a) => a, + None => { + return Err(bad( + CMD, + "say what the markup is on: `face`, `edge`, `body`, `at`, `feature`, `occurrence` or `view` (or select one thing)", + )); + } + }, + }; + let guid = new_guid(); + let at = now(); + let made = Markup { + id: 0, + guid: guid.clone(), + status: Status::Open, + thread: vec![Message { by: by.clone(), at, text }], + anchor: anchor.clone(), + view, + images: Vec::new(), + by, + made: at, + changed: at, + outcome: None, + }; + let id = set::update(&path, move |the_set| { + if the_set.markups.len() >= set::MAX_MARKUPS { + return Err(format!("a set holds at most {} markups", set::MAX_MARKUPS)); + } + let id = the_set.next_id; + the_set.next_id = id.checked_add(1).ok_or("the set has no numbers left")?; + the_set.markups.push(Markup { id, ..made }); + Ok(id) + }) + .map_err(|e| bad(CMD, e))?; + let st = s.world_state()?; + Ok(json!({ + "markup": id, + "guid": guid, + "set": path, + "anchor": serde_json::to_value(&anchor).unwrap_or(Value::Null), + "found": found(s, &st, &anchor).to_value(), + })) +} + +/// One change to markup `markup`, under the set's lock: `step` gets it and the time. +fn change(s: &Session, p: &Value, cmd: &str, step: impl FnOnce(&mut Markup, u64) -> std::result::Result) -> Result { + let path = set_path(s, p, cmd)?; + let at = now(); + let (id, status, extra) = set::update(&path, |the_set| { + let id = which(the_set, p)?; + let m = the_set.get_mut(id).ok_or_else(|| format!("no markup {id}"))?; + let extra = step(m, at)?; + m.changed = at; + Ok((id, m.status, extra)) + }) + .map_err(|e| bad(cmd, e))?; + let mut v = json!({ "markup": id, "status": status.word() }); + if let Value::Object(more) = extra { + for (k, x) in more { + v[k] = x; + } + } + Ok(v) +} + +/// Add a message to a markup's thread, under the limit for who wrote it. +fn say(m: &mut Markup, by: &str, text: &str, at: u64) -> std::result::Result<(), String> { + set::check_text(text, m.limit_for(by))?; + if m.thread.len() >= set::MAX_MESSAGES { + return Err(format!("a thread holds at most {} messages", set::MAX_MESSAGES)); + } + m.thread.push(Message { by: by.to_string(), at, text: text.to_string() }); + Ok(()) +} + +fn markup_edit(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "markup.edit"; + let by = who(p, CMD)?; + let text = str_(p, "text").map(str::to_string); + if let Some(t) = &text { + set::check_text(t, set::MAX_NOTE).map_err(|e| bad(CMD, e))?; + } + let anchor = capture(s, p, CMD)?; + let view = view_of(p, CMD)?; + if text.is_none() && anchor.is_none() && view.is_none() { + return Err(bad(CMD, "give the note's new `text`, what it is on now, or its `view`")); + } + change(s, p, CMD, |m, _| { + if let Some(t) = text { + if by != m.by { + return Err(format!("only the markup's maker ({}) changes its note: reply instead", m.by)); + } + if let Some(first) = m.thread.first_mut() { + first.text = t; + } + } + if let Some(a) = anchor { + m.anchor = a; + } + if let Some(v) = view { + m.view = Some(v); + } + Ok(Value::Null) + }) +} + +fn markup_reply(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "markup.reply"; + let by = who(p, CMD)?; + let text = str_(p, "text").ok_or_else(|| bad(CMD, "`text` is required: the reply"))?.to_string(); + change(s, p, CMD, |m, at| { + say(m, &by, &text, at)?; + Ok(Value::Null) + }) +} + +fn close(s: &mut Session, p: &Value, cmd: &str, to: Status) -> Result { + let by = who(p, cmd)?; + let reason = str_(p, "reason").ok_or_else(|| bad(cmd, "`reason` is required: what was done, or why not"))?.to_string(); + change(s, p, cmd, |m, at| { + if m.status != Status::Open { + return Err(format!("markup {} is {} already: reopen it first", m.id, m.status.word())); + } + say(m, &by, &reason, at)?; + m.status = to; + m.outcome = Some(Outcome { by: by.clone(), reason: reason.clone(), at }); + Ok(Value::Null) + }) +} + +fn markup_resolve(s: &mut Session, p: &Value) -> Result { + close(s, p, "markup.resolve", Status::Resolved) +} + +fn markup_reject(s: &mut Session, p: &Value) -> Result { + close(s, p, "markup.reject", Status::Rejected) +} + +fn markup_reopen(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "markup.reopen"; + let by = who(p, CMD)?; + let reason = str_(p, "reason").map(str::to_string); + change(s, p, CMD, |m, at| { + if m.status == Status::Open { + return Err(format!("markup {} is open already", m.id)); + } + if let Some(r) = &reason { + say(m, &by, r, at)?; + } + m.status = Status::Open; + m.outcome = None; + Ok(Value::Null) + }) +} + +fn markup_image(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "markup.image"; + set_path(s, p, CMD)?; + let by = who(p, CMD)?; + let given = ["file", "remove"].iter().filter(|k| p.get(**k).is_some_and(|v| !v.is_null())).count(); + if given != 1 { + return Err(bad(CMD, "give one of `file` (a PNG or JPEG) or `remove` (a picture's entry)")); + } + if let Some(file) = str_(p, "remove") { + let f = file.to_string(); + let out = change(s, p, CMD, move |m, _| { + let i = m.images.iter().position(|i| i.file == f).ok_or_else(|| format!("markup {} has no picture `{f}`", m.id))?; + m.images.remove(i); + Ok(json!({ "removed": f })) + })?; + // Out of the design once the set no longer names it. + if s.doc.markup_images.contains_key(file) { + s.doc_mut().markup_images.remove(file); + } + return Ok(out); + } + let file = str_(p, "file").filter(|f| !f.trim().is_empty()).ok_or_else(|| bad(CMD, "`file` must be a path"))?; + let bytes = solidcraft_io::vfs::read(file, set::MAX_IMAGE + 1).map_err(|e| bad(CMD, format!("{file}: {e}")))?; + if bytes.len() > set::MAX_IMAGE { + return Err(bad(CMD, format!("a picture is at most {} bytes", set::MAX_IMAGE))); + } + let kind = set::image_kind(&bytes).ok_or_else(|| bad(CMD, "a picture must be a PNG or a JPEG"))?; + let came = std::path::Path::new(file).file_name().map_or_else(|| "picture".to_string(), |n| n.to_string_lossy().to_string()); + let name = match str_(p, "name") { + Some(n) if !n.trim().is_empty() && n.chars().count() <= 200 && !n.chars().any(char::is_control) => n.to_string(), + Some(_) => return Err(bad(CMD, "`name` is 1 to 200 characters, with no control characters")), + None => came.chars().filter(|c| !c.is_control()).take(200).collect(), + }; + let images = &s.doc.markup_images; + if images.len() >= solidcraft_doc::markup_image::MAX_FILES { + return Err(bad(CMD, format!("a design holds at most {} review pictures", solidcraft_doc::markup_image::MAX_FILES))); + } + let total: u64 = images.values().map(|b| b.len() as u64).sum(); + if total.saturating_add(bytes.len() as u64) > solidcraft_doc::markup_image::MAX_TOTAL_BYTES { + return Err(bad(CMD, format!("a design's review pictures take at most {} bytes together", solidcraft_doc::markup_image::MAX_TOTAL_BYTES))); + } + let entry = format!("{}.{kind}", new_guid()); + let image = Image { file: entry.clone(), name, by, at: now(), bytes: bytes.len() as u64 }; + // The set names it first: a set that refuses leaves the design as it was. + let added = change(s, p, CMD, move |m, _| { + if m.images.len() >= set::MAX_IMAGES { + return Err(format!("a markup holds at most {} pictures", set::MAX_IMAGES)); + } + let f = image.file.clone(); + m.images.push(image); + Ok(json!({ "image": f })) + })?; + s.doc_mut().markup_images.insert(entry, bytes.into()); + Ok(added) +} + +fn markup_delete(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "markup.delete"; + let path = set_path(s, p, CMD)?; + let (id, files) = set::update(&path, |the_set| { + let id = which(the_set, p)?; + let i = the_set.markups.iter().position(|m| m.id == id).ok_or_else(|| format!("no markup {id}"))?; + let m = the_set.markups.remove(i); + Ok((id, m.images.into_iter().map(|i| i.file).collect::>())) + }) + .map_err(|e| bad(CMD, e))?; + for f in files { + if s.doc.markup_images.contains_key(&f) { + s.doc_mut().markup_images.remove(&f); + } + } + Ok(json!({ "deleted": id })) +} + +#[cfg(test)] +#[path = "markups_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/markups_tests.rs b/crates/engine/src/cmd/markups_tests.rs new file mode 100644 index 00000000000..8a1a7f99ef8 --- /dev/null +++ b/crates/engine/src/cmd/markups_tests.rs @@ -0,0 +1,419 @@ +//! Review markups (`markup.*`): marking faces, following them through rebuilds, the history +//! marker and configurations, threads and closing, pictures, writers that meet, and hostile input. + +use serde_json::{Value, json}; + +use crate::{EngineError, Session}; + +fn run(s: &mut Session, id: &str, params: Value) -> Value { + s.execute(id, ¶ms).unwrap_or_else(|e| panic!("{id} {params}: {e}")) +} + +fn refusal(s: &mut Session, id: &str, params: Value) -> String { + match s.execute(id, ¶ms) { + Ok(v) => panic!("{id} {params} should be refused: {v}"), + Err(e) => e.to_string(), + } +} + +/// A fresh folder for one test, and a session whose design is saved there as `part.sc` (the file +/// itself need not exist: the set goes beside it). +fn session(tag: &str) -> (Session, std::path::PathBuf) { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); + let dir = solidcraft_io::vfs::temp_dir().join(format!("solidcraft-markup-{tag}-{}-{nanos}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let s = Session { path: Some(dir.join("part.sc").to_string_lossy().to_string()), ..Default::default() }; + (s, dir) +} + +fn listed(s: &mut Session) -> Vec { + run(s, "markup.list", json!({}))["markups"].as_array().cloned().unwrap_or_default() +} + +fn close(a: &Value, b: [f64; 3]) -> bool { + a.as_array().is_some_and(|a| a.len() == 3 && a.iter().zip(b).all(|(x, y)| x.as_f64().is_some_and(|x| (x - y).abs() < 1e-6))) +} + +#[test] +fn a_markup_is_added_replied_to_closed_reopened_and_deleted_without_touching_the_design() { + let (mut s, dir) = session("round-trip"); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Box", "name": "Base"})); + let doc = s.doc.clone(); + let undo = s.undo.len(); + let added = run(&mut s, "markup.add", json!({"body": "Box", "at": [5.0, 10.0, 30.0], "text": "Round this top.", "by": "Reviewer"})); + let id = added["markup"].as_u64().unwrap(); + assert_eq!(added["anchor"]["kind"], "face", "{added}"); + assert_eq!(added["anchor"]["body"], "Box"); + assert_eq!(added["found"]["state"], "anchored", "{added}"); + assert!(dir.join("part.sc.markups.json").is_file()); + + run(&mut s, "markup.reply", json!({"markup": id, "text": "Which radius?"})); + run(&mut s, "markup.reply", json!({"markup": id, "text": "Two millimetres.", "by": "Reviewer"})); + let closed = run(&mut s, "markup.resolve", json!({"markup": id, "reason": "Top edges rounded 2 mm."})); + assert_eq!(closed, json!({"markup": id, "status": "resolved"})); + // Closed once: closing again is refused until it is reopened. + assert!(refusal(&mut s, "markup.reject", json!({"markup": id, "reason": "no"})).contains("reopen it first")); + + let rows = listed(&mut s); + assert_eq!(rows.len(), 1); + let m = &rows[0]; + assert_eq!(m["status"], "resolved"); + assert_eq!(m["note"], "Round this top."); + let thread: Vec<(&str, bool)> = + m["thread"].as_array().unwrap().iter().map(|t| (t["text"].as_str().unwrap(), t["reviewer"].as_bool().unwrap())).collect(); + assert_eq!(thread, [("Round this top.", true), ("Which radius?", false), ("Two millimetres.", true), ("Top edges rounded 2 mm.", false)]); + assert_eq!(m["outcome"]["by"], "agent"); + assert_eq!(m["outcome"]["reason"], "Top edges rounded 2 mm."); + + // By its guid too. + let guid = m["guid"].as_str().unwrap().to_string(); + assert_eq!(run(&mut s, "markup.reopen", json!({"markup": guid, "reason": "Still sharp at one corner."}))["status"], "open"); + assert_eq!(run(&mut s, "markup.list", json!({"status": "open"}))["markups"].as_array().unwrap().len(), 1); + assert_eq!(run(&mut s, "markup.list", json!({"status": "resolved"}))["counts"], json!({"open": 1, "resolved": 0, "rejected": 0})); + run(&mut s, "markup.reject", json!({"markup": id, "reason": "The corner is a sharp by design."})); + assert_eq!(listed(&mut s)[0]["status"], "rejected"); + + assert_eq!(run(&mut s, "markup.delete", json!({"markup": id})), json!({"deleted": id})); + assert!(listed(&mut s).is_empty()); + // Numbers are never used again. + let next = run(&mut s, "markup.add", json!({"at": [100.0, 100.0, 100.0], "text": "Out here."}))["markup"].as_u64().unwrap(); + assert!(next > id); + + // Not one write changed the design or made an undo step. + assert!(std::sync::Arc::ptr_eq(&doc, &s.doc)); + assert_eq!(s.undo.len(), undo); +} + +#[test] +fn what_a_markup_is_on_comes_from_the_call_the_selection_or_the_view() { + let (mut s, _dir) = session("anchors"); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Box", "name": "Base"})); + // A point in space, away from every body. + let a = run(&mut s, "markup.add", json!({"at": [50.0, 50.0, 50.0], "text": "Room for a bracket here."})); + assert_eq!(a["anchor"]["kind"], "point"); + // A point on a face, with no body named: the face it lies on, found exactly. + let a = run(&mut s, "markup.add", json!({"at": [10.0, 5.0, 15.0], "text": "This side."})); + assert_eq!(a["anchor"]["kind"], "face", "{a}"); + let side = a["anchor"]["face"].as_str().unwrap().to_string(); + // The same face by name, with no point: a point on it is chosen. + let a = run(&mut s, "markup.add", json!({"face": side, "text": "By name."})); + assert_eq!(a["anchor"]["face"], side); + assert!(a["anchor"]["at"][0].as_f64().is_some_and(|x| (x - 10.0).abs() < 1e-6), "{a}"); + // A point that is not on the named face is refused. + assert!(refusal(&mut s, "markup.add", json!({"face": side, "at": [0.0, 5.0, 15.0], "text": "x"})).contains("does not lie on")); + // A body alone, a feature by name. + assert_eq!(run(&mut s, "markup.add", json!({"body": "Box", "text": "Lighter."}))["anchor"]["kind"], "body"); + let f = run(&mut s, "markup.add", json!({"feature": "Base", "text": "Taller."})); + assert_eq!(f["anchor"]["kind"], "feature"); + assert_eq!(f["anchor"]["name"], "Base"); + // The selection, when the call names nothing. + run(&mut s, "select.set", json!({"items": [{"type": "face", "body": "Box", "point": [5.0, 10.0, 30.0]}]})); + let a = run(&mut s, "markup.add", json!({"text": "The selected face."})); + assert_eq!(a["anchor"]["kind"], "face", "{a}"); + assert!(close(&a["anchor"]["at"], [5.0, 10.0, 30.0]), "{a}"); + // The view alone, even with something selected: the view is what the call names. + let view = json!({"target": [0.0, 0.0, 0.0], "yaw": 30.0, "pitch": 20.0, "distance": 200.0, "fov": 45.0}); + let a = run(&mut s, "markup.add", json!({"view": view, "text": "The view, not the selected face."})); + assert_eq!(a["anchor"]["kind"], "view", "{a}"); + run(&mut s, "select.clear", json!({})); + let a = run(&mut s, "markup.add", json!({"view": view, "text": "This whole view."})); + assert_eq!(a["anchor"]["kind"], "view"); + assert_eq!(listed(&mut s).last().unwrap()["view"], view); + // Nothing at all. + assert!(refusal(&mut s, "markup.add", json!({"text": "On what?"})).contains("say what the markup is on")); +} + +#[test] +fn an_edge_named_without_a_point_is_marked_at_a_point_on_it() { + let (mut s, _dir) = session("edge-point"); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Box", "name": "Base"})); + let edges = run(&mut s, "model.edges", json!({"body": "Box"}))["edges"].as_array().cloned().unwrap(); + let named = |e: &Value| e["name"].as_str().map(str::to_string); + let one = edges.iter().find(|e| named(e).is_some_and(|n| edges.iter().filter(|o| named(o).as_deref() == Some(n.as_str())).count() == 1)).unwrap(); + let a = run(&mut s, "markup.add", json!({"edge": named(one), "body": "Box", "text": "Break this edge."})); + assert_eq!(a["anchor"]["kind"], "edge", "{a}"); + // The point kept lies on that straight edge, so the markup is found where it was made. + let at: Vec = a["anchor"]["at"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + let (p, q): (Vec, Vec) = ( + one["start"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(), + one["end"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(), + ); + let d: Vec = (0..3).map(|i| q[i] - p[i]).collect(); + let len2: f64 = d.iter().map(|x| x * x).sum(); + let k = ((0..3).map(|i| (at[i] - p[i]) * d[i]).sum::() / len2).clamp(0.0, 1.0); + let off: f64 = (0..3).map(|i| (at[i] - (p[i] + k * d[i])).powi(2)).sum::().sqrt(); + assert!(off < 1e-6, "{at:?} is {off} mm off the edge {p:?}..{q:?}"); + assert_eq!(listed(&mut s).last().unwrap()["found"]["state"], "anchored"); +} + +#[test] +fn a_rebuild_keeps_the_face_anchor_and_says_where_it_moved() { + let (mut s, _dir) = session("rebuild"); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Box", "name": "Base"})); + let top = run(&mut s, "markup.add", json!({"body": "Box", "at": [5.0, 10.0, 30.0], "text": "Top."})); + let side = run(&mut s, "markup.add", json!({"body": "Box", "at": [5.0, 0.0, 10.0], "text": "Front, low down."})); + let top_face = top["anchor"]["face"].as_str().unwrap().to_string(); + let side_face = side["anchor"]["face"].as_str().unwrap().to_string(); + assert_ne!(top_face, side_face); + + run(&mut s, "timeline.edit", json!({"feature": "Base", "set": {"height": "40"}})); + let rows = listed(&mut s); + // The top went up 10 mm: the markup is still on it, moved. + assert_eq!(rows[0]["anchor"]["face"], top_face, "the set keeps the face's lasting name"); + assert_eq!(rows[0]["found"]["state"], "moved", "{}", rows[0]); + assert!(close(&rows[0]["found"]["at"], [5.0, 10.0, 40.0]), "{}", rows[0]); + assert!(close(&rows[0]["found"]["was"], [5.0, 10.0, 30.0])); + assert!((rows[0]["found"]["moved_by"].as_f64().unwrap() - 10.0).abs() < 1e-6); + // The marked point still lies on the taller front face. + assert_eq!(rows[1]["found"]["state"], "anchored", "{}", rows[1]); + + // The body renamed: found again by the feature that made it. + run(&mut s, "body.rename", json!({"body": "Box", "name": "Block"})); + assert_eq!(listed(&mut s)[1]["found"]["state"], "anchored"); +} + +#[test] +fn a_face_left_out_by_the_marker_or_a_configuration_is_hidden_and_a_deleted_one_gone() { + let (mut s, _dir) = session("hidden"); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Base", "name": "Base"})); + run(&mut s, "solid.box", json!({"corner": [20, 0, 0], "length": 5, "width": 5, "height": 5, "body_name": "Peg", "name": "Peg"})); + let peg = run(&mut s, "markup.add", json!({"body": "Peg", "at": [22.0, 2.0, 5.0], "text": "Chamfer the peg."}))["markup"].as_u64().unwrap(); + let state = |s: &mut Session| { + let rows = listed(s); + let row = rows.iter().find(|m| m["id"] == json!(peg)).cloned().unwrap(); + (row["found"]["state"].as_str().unwrap().to_string(), row["found"]["why"].as_str().unwrap_or("").to_string()) + }; + assert_eq!(state(&mut s).0, "anchored"); + + // Rolled back before the peg: hidden, not gone. + run(&mut s, "timeline.rollback", json!({"position": 1})); + let (st, why) = state(&mut s); + assert_eq!(st, "hidden", "{why}"); + assert!(why.contains("history marker") && why.contains("Peg"), "{why}"); + run(&mut s, "timeline.rollback", json!({"position": "end"})); + assert_eq!(state(&mut s).0, "anchored"); + + // Suppressed: hidden. + run(&mut s, "timeline.suppress", json!({"features": ["Peg"], "suppressed": true})); + let (st, why) = state(&mut s); + assert_eq!(st, "hidden", "{why}"); + assert!(why.contains("suppressed"), "{why}"); + run(&mut s, "timeline.suppress", json!({"features": ["Peg"], "suppressed": false})); + assert_eq!(state(&mut s).0, "anchored"); + + // Left out by another configuration: hidden. + run(&mut s, "config.configure", json!({"features": ["Peg"]})); + run(&mut s, "config.row", json!({"name": "No peg", "values": {"suppress:Peg": true}})); + run(&mut s, "config.activate", json!({"row": "No peg"})); + let (st, why) = state(&mut s); + assert_eq!(st, "hidden", "{why}"); + let first = s.doc.configs.rows.first().map(|r| r.name.clone()).unwrap(); + run(&mut s, "config.activate", json!({"row": first})); + assert_eq!(state(&mut s).0, "anchored"); + + // Deleted: gone, in words that name no id. + run(&mut s, "timeline.delete", json!({"features": ["Peg"]})); + let (st, why) = state(&mut s); + assert_eq!(st, "gone", "{why}"); + assert!(why.contains("deleted or replaced") && !why.chars().any(|c| c.is_ascii_digit()), "{why}"); +} + +#[test] +fn an_agent_says_it_in_280_characters_and_only_the_maker_changes_the_note() { + let (mut s, _dir) = session("limits"); + let id = run(&mut s, "markup.add", json!({"at": [0.0, 0.0, 0.0], "text": "Here.", "by": "Reviewer"}))["markup"].as_u64().unwrap(); + let e = refusal(&mut s, "markup.reply", json!({"markup": id, "text": "x".repeat(658)})); + assert!(e.contains("280") && e.contains("658") && e.contains("378 over"), "{e}"); + // The maker may write a long reply. + run(&mut s, "markup.reply", json!({"markup": id, "text": "y".repeat(1000), "by": "Reviewer"})); + // A closing reason is under the same rule. + assert!(refusal(&mut s, "markup.resolve", json!({"markup": id, "reason": "z".repeat(300)})).contains("280")); + assert!(refusal(&mut s, "markup.edit", json!({"markup": id, "text": "Changed."})).contains("only the markup's maker")); + run(&mut s, "markup.edit", json!({"markup": id, "text": "Changed.", "by": "Reviewer"})); + assert_eq!(listed(&mut s)[0]["note"], "Changed."); + // An agent may pin it again. + run(&mut s, "markup.edit", json!({"markup": id, "at": [1.0, 2.0, 3.0]})); + assert!(close(&listed(&mut s)[0]["anchor"]["at"], [1.0, 2.0, 3.0])); +} + +#[test] +fn a_picture_is_attached_listed_and_taken_off() { + let (mut s, dir) = session("pictures"); + let id = run(&mut s, "markup.add", json!({"at": [0.0, 0.0, 0.0], "text": "See the picture."}))["markup"].as_u64().unwrap(); + let png = [0x89u8, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0]; + let shot = dir.join("view.png"); + std::fs::write(&shot, png).unwrap(); + let r = run(&mut s, "markup.image", json!({"markup": id, "file": shot.to_string_lossy(), "name": "screenshot"})); + let file = r["image"].as_str().unwrap().to_string(); + // The bytes are the design's own entry, never a file beside it, never text. + assert_eq!(s.doc.markup_images[&file].as_bytes(), png); + assert!(!dir.join("part.sc.markups").join(&file).exists()); + let jpg = dir.join("photo.jpg"); + std::fs::write(&jpg, [0xFF, 0xD8, 0xFF, 0xE0, 1, 2]).unwrap(); + run(&mut s, "markup.image", json!({"markup": id, "file": jpg.to_string_lossy()})); + let images = listed(&mut s)[0]["images"].as_array().cloned().unwrap(); + assert_eq!(images.len(), 2); + assert_eq!(images[0]["name"], "screenshot"); + assert_eq!(images[1]["name"], "photo.jpg"); + assert_eq!(images[0]["in_design"], true); + // A container saves them as parts, and they open again. + let saved = solidcraft_io::write_design_container(&s.doc).unwrap(); + assert_eq!(solidcraft_io::read_design(&saved).unwrap().markup_images, s.doc.markup_images); + // Not a picture, Base64 text, two sources, or nothing. + let gif = dir.join("x.gif"); + std::fs::write(&gif, b"GIF89a").unwrap(); + assert!(refusal(&mut s, "markup.image", json!({"markup": id, "file": gif.to_string_lossy()})).contains("PNG or a JPEG")); + // Base64 text is no way in: `data` is not a parameter. + refusal(&mut s, "markup.image", json!({"markup": id, "data": solidcraft_doc::canvas::base64_encode(&png)})); + assert!(refusal(&mut s, "markup.image", json!({"markup": id, "file": shot.to_string_lossy(), "remove": file})).contains("one of")); + assert!(refusal(&mut s, "markup.image", json!({"markup": id})).contains("one of")); + run(&mut s, "markup.image", json!({"markup": id, "remove": file})); + assert!(!s.doc.markup_images.contains_key(&file)); + assert_eq!(listed(&mut s)[0]["images"].as_array().unwrap().len(), 1); + // Deleting the markup takes its pictures out of the design. + let left = listed(&mut s)[0]["images"][0]["file"].as_str().unwrap().to_string(); + assert!(s.doc.markup_images.contains_key(&left)); + run(&mut s, "markup.delete", json!({"markup": id})); + assert!(s.doc.markup_images.is_empty()); +} + +/// Attaching a picture is one undo step on the design, as inserting a canvas is: undo takes its +/// bytes out again, and the set's record then says the design does not hold it. +#[test] +fn attaching_a_picture_is_an_undo_step() { + let (mut s, dir) = session("picture-undo"); + let id = run(&mut s, "markup.add", json!({"at": [0.0, 0.0, 0.0], "text": "Undo me."}))["markup"].as_u64().unwrap(); + let shot = dir.join("view.png"); + std::fs::write(&shot, [0x89u8, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 1]).unwrap(); + run(&mut s, "markup.image", json!({"markup": id, "file": shot.to_string_lossy()})); + assert_eq!(s.doc.markup_images.len(), 1); + run(&mut s, "edit.undo", json!({})); + assert!(s.doc.markup_images.is_empty()); + assert_eq!(listed(&mut s)[0]["images"][0]["in_design"], false); + run(&mut s, "edit.redo", json!({})); + assert_eq!(listed(&mut s)[0]["images"][0]["in_design"], true); +} + +/// The window and an agent, each with its own session on the design, add at once. +#[test] +fn two_writers_at_once_lose_nothing() { + let (s, _dir) = session("writers"); + let path = s.path.clone().unwrap(); + const EACH: usize = 20; + let writer = |who: &'static str| { + let path = path.clone(); + std::thread::spawn(move || { + let mut s = Session { path: Some(path), ..Default::default() }; + for i in 0..EACH { + run(&mut s, "markup.add", json!({"at": [i as f64, 0.0, 0.0], "text": format!("{who} {i}"), "by": who})); + } + }) + }; + let (a, b) = (writer("window"), writer("agent")); + a.join().unwrap(); + b.join().unwrap(); + let mut s = s; + let rows = listed(&mut s); + assert_eq!(rows.len(), 2 * EACH); + let mut ids: Vec = rows.iter().map(|m| m["id"].as_u64().unwrap()).collect(); + ids.dedup(); + assert_eq!(ids.len(), 2 * EACH); + for who in ["window", "agent"] { + assert_eq!(rows.iter().filter(|m| m["by"] == who).count(), EACH); + } +} + +#[test] +fn a_set_from_a_newer_solidcraft_is_refused_and_kept() { + let (mut s, dir) = session("newer"); + let set = dir.join("part.sc.markups.json"); + let newer = r#"{"format":2,"next_id":1,"markups":[],"areas":[]}"#; + std::fs::write(&set, newer).unwrap(); + assert!(refusal(&mut s, "markup.list", json!({})).contains("newer SolidCraft")); + assert!(refusal(&mut s, "markup.add", json!({"at": [0.0, 0.0, 0.0], "text": "x"})).contains("newer SolidCraft")); + assert_eq!(std::fs::read_to_string(&set).unwrap(), newer); +} + +#[test] +fn a_design_with_no_file_needs_a_set_and_a_set_is_a_markups_file() { + let mut s = Session::default(); + assert!(refusal(&mut s, "markup.list", json!({})).contains("save it first")); + assert!(refusal(&mut s, "markup.list", json!({"set": "/tmp/notes.json"})).contains(".markups.json")); + let (_, dir) = session("explicit"); + let set = dir.join("review.markups.json").to_string_lossy().to_string(); + run(&mut s, "markup.add", json!({"set": set, "at": [0.0, 0.0, 0.0], "text": "In a named set."})); + assert_eq!(run(&mut s, "markup.list", json!({"set": set}))["markups"].as_array().unwrap().len(), 1); +} + +/// Every markup command, with each hostile value in each key it reads and as the whole call, on a +/// design with a set: refused or done, never a crash. +#[test] +fn hostile_markup_params_never_panic() { + let (mut start, _dir) = session("hostile"); + run(&mut start, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})); + let id = run(&mut start, "markup.add", json!({"body": "Box", "at": [5.0, 5.0, 10.0], "text": "Seed."}))["markup"].as_u64().unwrap(); + // Each call starts from the seed set, so the calls that write leave the next one a set its size. + let set_file = format!("{}.markups.json", start.path.clone().unwrap()); + let seed = std::fs::read(&set_file).unwrap(); + let fresh = |start: &Session| { + std::fs::write(&set_file, &seed).unwrap(); + let mut s = start.scratch(); + s.path = start.path.clone(); + s + }; + let keys = + ["set", "markup", "text", "by", "reason", "status", "face", "edge", "body", "at", "feature", "occurrence", "view", "file", "name", "remove"]; + let commands = [ + "markup.list", + "markup.add", + "markup.edit", + "markup.reply", + "markup.image", + "markup.resolve", + "markup.reject", + "markup.reopen", + "markup.delete", + ]; + let mut values = crate::tests::hostile_values(); + values.extend([ + json!("../../../etc/passwd"), + json!("x.markups.json"), + json!("/"), + json!("\u{0}"), + json!([0, 0]), + json!([1, 2, 3, 4]), + json!(u64::MAX), + json!("ffffffffffffffffffffffffffffffff"), + json!({"target": [0, 0, 0], "yaw": 1e308, "pitch": 0, "distance": -1}), + json!("x".repeat(10_000)), + ]); + let mut internal = Vec::new(); + for cmd in commands { + for k in keys { + for v in &values { + // Each value alone, and beside a call that is otherwise good. + for p in [json!({ k: v.clone() }), { + let mut p = json!({"markup": id, "text": "ok", "reason": "ok", "at": [5.0, 5.0, 10.0]}); + p[k] = v.clone(); + p + }] { + // Never write outside the test's folder. + if k == "set" && v.as_str().is_some_and(|t| t.ends_with(".markups.json")) { + continue; + } + let mut s = fresh(&start); + if let Err(EngineError::Internal(id, msg)) = s.execute(cmd, &p) { + internal.push(format!("{id} {p}: {msg}")); + } + } + } + } + for v in &values { + let mut s = fresh(&start); + if let Err(EngineError::Internal(id, msg)) = s.execute(cmd, v) { + internal.push(format!("{id} {v}: {msg}")); + } + } + } + assert!(internal.is_empty(), "{internal:#?}"); +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 39065ae8aa4..e614035a47c 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -182,6 +182,7 @@ pub(crate) mod inspect; mod interference; pub(crate) mod joints; mod libraries; +mod markups; pub mod mass_properties; mod material_properties; mod materials; @@ -670,6 +671,7 @@ fn gather_command_specs() -> Vec<&'static CommandSpec> { v.extend(browser::COMMANDS.iter()); v.extend(remove_history::COMMANDS.iter()); v.extend(notes::COMMANDS.iter()); + v.extend(markups::COMMANDS.iter()); v.extend(delete::COMMANDS.iter()); v.extend(edit::COMMANDS.iter()); v.extend(selection::COMMANDS.iter()); diff --git a/crates/engine/src/cmd/view_navigation.rs b/crates/engine/src/cmd/view_navigation.rs index fae6e7d1bd9..46dfa787506 100644 --- a/crates/engine/src/cmd/view_navigation.rs +++ b/crates/engine/src/cmd/view_navigation.rs @@ -126,6 +126,10 @@ CommandSpec::new("view.navigation_bar", "Navigation Bar", crate::checked!("view. .icon("pan").noundo().doc_only() .contract(&NAVIGATION_BAR_CONTRACT).output(output_schema_for::) .params("visible?: bool (omitted: toggle) → visible?; show the navigation bar (window setting)"), +CommandSpec::new("view.review", "Review", crate::checked!("view.review", review)) + .at("SOLID", "INSPECT").icon("review_mark").noundo().doc_only() + .contract(&NAVIGATION_BAR_CONTRACT).output(output_schema_for::) + .params("visible?: bool (omitted: toggle) → visible?; show the Review list and the review pins on the model, and let M mark (window setting; the markups themselves are markup.*)"), CommandSpec::new("view.navigator", "Custom View Navigator", crate::checked!("view.navigator", navigator)) .icon("nav_settings").noundo().doc_only() .contract(&NAVIGATOR_CONTRACT).output(output_schema_for::) @@ -430,6 +434,9 @@ fn ground_shadow(_s: &mut Session, p: &Value) -> Result { fn navigation_bar(_s: &mut Session, p: &Value) -> Result { view_toggle(p, "view.navigation_bar", "visible") } +fn review(_s: &mut Session, p: &Value) -> Result { + view_toggle(p, "view.review", "visible") +} fn parts_library(_s: &mut Session, p: &Value) -> Result { view_toggle(p, "view.parts_library", "visible") } @@ -807,6 +814,7 @@ mod tests { ("view.ground_shadow", "on"), ("view.navigation_bar", "visible"), ("view.parts_library", "visible"), + ("view.review", "visible"), ] { assert_eq!(s.execute(id, &json!({})).unwrap(), json!({})); assert_eq!(s.execute(id, &Value::Null).unwrap(), json!({})); @@ -831,6 +839,7 @@ mod tests { "view.ground_shadow", "view.navigation_bar", "view.parts_library", + "view.review", ] { for params in [json!(true), json!(1), json!("orbit"), json!([]), json!({"unexpected":true})] { assert!(s.execute(id, ¶ms).is_err(), "{id}: {params}"); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4a2282b4a01..ce2571105cc 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -4486,9 +4486,11 @@ fn same_but_features(a: &Document, b: &Document) -> bool { drawings, next_component_color_index, plugin_data, + markup_images, linked_bodies_left_out, } = a; *plugin_data == b.plugin_data + && *markup_images == b.markup_images && *linked_bodies_left_out == b.linked_bodies_left_out && *render == b.render && *format == b.format diff --git a/crates/engine/src/plugin.rs b/crates/engine/src/plugin.rs index bd54cdc974e..a3132833127 100644 --- a/crates/engine/src/plugin.rs +++ b/crates/engine/src/plugin.rs @@ -317,7 +317,8 @@ pub fn command_group(id: &str) -> Option<&'static str> { match family { "plugin" => Some("plugin"), "doc" => Some("doc"), - "file" | "library" => Some("file"), + // Markups are a file beside the design, with their pictures. + "file" | "library" | "markup" => Some("file"), "settings" | "ui" | "diagnostics" => Some("app"), _ if FILE_COMMANDS.contains(&id) || id.starts_with("sketch.insert_") => Some("file"), _ => None, diff --git a/crates/engine/src/schema/markups.rs b/crates/engine/src/schema/markups.rs new file mode 100644 index 00000000000..23e757a0fe0 --- /dev/null +++ b/crates/engine/src/schema/markups.rs @@ -0,0 +1,384 @@ +//! Contracts and result types for the review markup commands in `cmd/markups.rs`. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::types::{Point3, present}; + +/// A markup: its number in the set, or its guid (32 hexadecimal digits). +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(untagged)] +pub enum MarkupRef { + Id(u64), + Guid(String), +} + +/// The camera a markup is seen from: the orbit camera's target (mm), yaw and pitch (degrees), +/// distance (mm, above 0) and field of view (degrees, 0 for orthographic, below 180). +#[derive(Debug, Serialize, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MarkupView { + pub target: [f64; 3], + pub yaw: f64, + pub pitch: f64, + pub distance: f64, + /// Default: 0 (orthographic). + #[serde(default)] + pub fov: f64, +} + +/// A component path: occurrence ids from the top of the assembly down, 1 to 64 of them. +#[derive(Debug, Deserialize, JsonSchema)] +pub struct OccurrencePath(pub Vec); + +/// A feature of the timeline: its id, or its name. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(untagged)] +pub enum FeatureRef { + Id(u64), + Name(String), +} + +/// List a design's review markups, with where each one's face, edge, body, feature or +/// component stands in the model now. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MarkupListParams { + /// The set's file (`…markups.json`). Default: the one beside the design's file. + #[serde(default)] + pub set: Option, + /// Only the markups with this status: `open`, `resolved` or `rejected`. Default: all. + #[serde(default)] + pub status: Option, +} + +/// Mark a place in the design with a note. Say what it is on with one of `face`, `edge`, +/// `feature`, `occurrence`, `body` or `at`; with none, the `view`, else the one thing selected. +/// Writes only the set beside the design: the design and its undo history stay as they are. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MarkupAddParams { + /// The note (1 to 4,000 characters). + pub text: String, + /// A face by its lasting name, as `model.faces` lists it. With `at`, the point marked on it, + /// which must lie on the face. Without `body`, the one body with a face of that name. + #[serde(default)] + pub face: Option, + /// An edge by its name, as `model.edges` lists it. With several edges between the same faces, + /// `at` says which. + #[serde(default)] + pub edge: Option, + /// The body a `face` or `edge` is on; alone, the body itself; with `at`, the face of it the + /// point lies on. + #[serde(default)] + pub body: Option, + /// A point (mm). Alone: the face of a body it lies on, found exactly, else the point in space. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "Point3")] + pub at: Option, + /// A feature of the timeline, by id or name. + #[serde(default)] + pub feature: Option, + /// A placed component, by its occurrence path. + #[serde(default)] + pub occurrence: Option, + /// The camera it was marked from, for Go there. + #[serde(default)] + pub view: Option, + /// Who marks it: the reviewer. Default: `agent`. + #[serde(default)] + pub by: Option, + /// The set's file (`…markups.json`). Default: the one beside the design's file. + #[serde(default)] + pub set: Option, +} + +/// Change a markup's note (its maker only), pin it again, or change its view. The thread, +/// pictures and status stay as they are. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MarkupEditParams { + /// The markup. + pub markup: MarkupRef, + /// The note's new text (1 to 4,000 characters). Only the markup's maker (`by`) changes it. + #[serde(default)] + pub text: Option, + /// Pin it again on this face, as in `markup.add`. + #[serde(default)] + pub face: Option, + /// Pin it again on this edge, as in `markup.add`. + #[serde(default)] + pub edge: Option, + /// Pin it again on this body, as in `markup.add`. + #[serde(default)] + pub body: Option, + /// Pin it again at this point, as in `markup.add`. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "Point3")] + pub at: Option, + /// Pin it again on this feature. + #[serde(default)] + pub feature: Option, + /// Pin it again on this placed component. + #[serde(default)] + pub occurrence: Option, + /// The new camera. + #[serde(default)] + pub view: Option, + /// Who changes it. Default: `agent`. + #[serde(default)] + pub by: Option, + /// The set's file. Default: the one beside the design's file. + #[serde(default)] + pub set: Option, +} + +/// Add a message to a markup's thread without closing it. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MarkupReplyParams { + /// The markup. + pub markup: MarkupRef, + /// The message: at most 280 characters from anyone but the markup's maker (a longer one is + /// refused whole), 4,000 from its maker. + pub text: String, + /// Who says it. Default: `agent`. + #[serde(default)] + pub by: Option, + /// The set's file. Default: the one beside the design's file. + #[serde(default)] + pub set: Option, +} + +/// Attach a picture to a markup, or take one off. Give exactly one of `file` and `remove`. A +/// picture is a PNG or a JPEG (by its first bytes), at most 16 MiB, at most 8 a markup. Its bytes +/// go in the design, an entry of their own; the set names the entry. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MarkupImageParams { + /// The markup. + pub markup: MarkupRef, + /// A picture file to attach. + #[serde(default)] + pub file: Option, + /// The name the picture is shown with. Default: the file's name. + #[serde(default)] + pub name: Option, + /// A picture's entry (`.png` or `.jpg`, as `markup.list` gives it) to take off. + #[serde(default)] + pub remove: Option, + /// Who attaches it. Default: `agent`. + #[serde(default)] + pub by: Option, + /// The set's file. Default: the one beside the design's file. + #[serde(default)] + pub set: Option, +} + +/// Close an open markup as done (`markup.resolve`) or not done (`markup.reject`), with a reason. +/// The reason goes in the thread too, under the same length rule as a reply. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MarkupCloseParams { + /// The markup. + pub markup: MarkupRef, + /// What was done, or why it was not. + pub reason: String, + /// Who closes it. Default: `agent`. + #[serde(default)] + pub by: Option, + /// The set's file. Default: the one beside the design's file. + #[serde(default)] + pub set: Option, +} + +/// Open a resolved or rejected markup again. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MarkupReopenParams { + /// The markup. + pub markup: MarkupRef, + /// Why, added to the thread. Default: nothing added. + #[serde(default)] + pub reason: Option, + /// Who opens it. Default: `agent`. + #[serde(default)] + pub by: Option, + /// The set's file. Default: the one beside the design's file. + #[serde(default)] + pub set: Option, +} + +/// Delete a markup and its pictures. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MarkupDeleteParams { + /// The markup. + pub markup: MarkupRef, + /// The set's file. Default: the one beside the design's file. + #[serde(default)] + pub set: Option, +} + +/// What a markup is on, as the set keeps it. `kind` says which: `face` (`body`, `maker`: the +/// feature that made the body, `face`: its lasting name, `at`, `config`?), `edge` (`body`, +/// `maker`, `edge`, `at`, `config`?), `body` (`body`, `maker`, `at`?, `config`?), `feature` +/// (`feature`: its id, `name`, `at`?), `occurrence` (`path`, `name`, `at`?), `point` (`at`), +/// `view` (nothing: the markup's view) or `unanchored` (`why`, `given`?). +#[derive(Debug, Serialize, JsonSchema)] +pub struct MarkupAnchor { + pub kind: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub body: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub maker: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub face: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub edge: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub feature: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + /// The point marked (mm), where it was then. + #[serde(skip_serializing_if = "Option::is_none")] + pub at: Option<[f64; 3]>, + /// The configuration active when it was marked. + #[serde(skip_serializing_if = "Option::is_none")] + pub config: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub why: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub given: Option, +} + +/// Where a markup's anchor stands in the model now. `state`: `anchored` (there, at `at`), +/// `moved` (there, now at `at`, `moved_by` mm from `was`), `hidden` (the history marker, a +/// suppression or another configuration leaves it out of the model; still in the design), +/// `gone` (deleted or replaced: `why` says what it was, in words) or `unchecked` (it could not be +/// measured: `why`). +#[derive(Debug, Serialize, JsonSchema)] +pub struct MarkupFound { + pub state: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub at: Option<[f64; 3]>, + #[serde(skip_serializing_if = "Option::is_none")] + pub was: Option<[f64; 3]>, + #[serde(skip_serializing_if = "Option::is_none")] + pub moved_by: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub why: Option, +} + +/// One message of a markup's thread. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MarkupMessage { + pub by: String, + /// Unix seconds. + pub at: u64, + pub text: String, + /// Written by the markup's maker. + pub reviewer: bool, +} + +/// A picture on a markup. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MarkupImage { + /// `.png` or `.jpg`: the picture's entry in the design. + pub file: String, + pub name: String, + pub by: String, + pub at: u64, + pub bytes: u64, + /// Whether the design holds the picture's bytes (not after an undo past `markup.image`). + pub in_design: bool, +} + +/// Who closed a markup, why and when (Unix seconds). +#[derive(Debug, Serialize, JsonSchema)] +pub struct MarkupOutcome { + pub by: String, + pub reason: String, + pub at: u64, +} + +/// One markup as `markup.list` gives it. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MarkupRow { + pub id: u64, + pub guid: String, + /// `open`, `resolved` or `rejected`. + pub status: String, + /// The thread's first message. + pub note: String, + pub thread: Vec, + #[schemars(with = "MarkupAnchor")] + pub anchor: Value, + pub found: MarkupFound, + #[serde(skip_serializing_if = "Option::is_none")] + pub view: Option, + pub images: Vec, + /// Who made it: the reviewer. + pub by: String, + /// Unix seconds. + pub made: u64, + pub changed: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub outcome: Option, +} + +/// How many markups have each status. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MarkupCounts { + pub open: usize, + pub resolved: usize, + pub rejected: usize, +} + +/// The result of `markup.list`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MarkupList { + /// The set's file. + pub set: String, + pub format: u32, + /// Over the whole set, whatever `status` asked for. + pub counts: MarkupCounts, + /// In the set's order (oldest first), only those of `status` when it was given. + pub markups: Vec, +} + +/// The result of `markup.add`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MarkupMade { + /// The new markup's number. + pub markup: u64, + pub guid: String, + /// The set's file. + pub set: String, + #[schemars(with = "MarkupAnchor")] + pub anchor: Value, + pub found: MarkupFound, +} + +/// The result of a change to a markup. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MarkupChanged { + pub markup: u64, + /// Its status after the change. + pub status: String, + /// `markup.image`: the picture attached. + #[serde(skip_serializing_if = "Option::is_none")] + pub image: Option, + /// `markup.image`: the picture taken off. + #[serde(skip_serializing_if = "Option::is_none")] + pub removed: Option, +} + +/// The result of `markup.delete`: the number that was removed. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MarkupDeleted { + pub deleted: u64, +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 4db03ca5d60..cc80feec66c 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -107,6 +107,7 @@ pub mod interference; pub mod joint_sweep; pub mod joints; pub mod libraries; +pub mod markups; pub mod mass_properties; pub mod material_properties; pub mod materials; diff --git a/crates/io/src/design.rs b/crates/io/src/design.rs index 097d536243c..b40de358627 100644 --- a/crates/io/src/design.rs +++ b/crates/io/src/design.rs @@ -397,6 +397,7 @@ fn write_container( if let Some(object) = metadata.as_object_mut() { object.remove("drawings"); object.remove("plugin_data"); + object.remove("markup_images"); // The parts the drawings' images are, named where a release that can't read the drawings' // records (0.45.0) looks before it keeps a part, so its save keeps them. let mut parts: Vec = doc @@ -434,6 +435,9 @@ fn write_container( for (key, data) in &doc.plugin_data { writer.part(&format!("{}{key}", solidcraft_doc::plugin_data::PREFIX), data, true)?; } + for (name, data) in &doc.markup_images { + writer.part(&format!("{}{name}", solidcraft_doc::markup_image::PREFIX), data, false)?; + } // The signature binds every authoritative part written above (never the optional caches), and // is written before them so their budget sees its bytes. if let Some(save) = provenance { @@ -1312,6 +1316,25 @@ fn hydrate_plugin_data(doc: &mut Document, reader: &mut PackageR } } +/// Review markup pictures: each `markups/.png` or `.jpg` part, as its bytes. One that does +/// not read, or is not a picture, is left out; the design opens all the same. +fn hydrate_markup_images(doc: &mut Document, reader: &mut PackageReader) { + use solidcraft_doc::markup_image::{MAX_BYTES, MAX_FILES, MAX_TOTAL_BYTES, PREFIX, kind, valid_name}; + let mut total = 0u64; + for name in reader.part_names() { + let Some(file) = name.strip_prefix(PREFIX).filter(|f| valid_name(f)) else { continue }; + if doc.markup_images.len() >= MAX_FILES { + break; + } + let Ok(bytes) = reader.limited_part(&name, MAX_BYTES) else { continue }; + if kind(&bytes).is_none() || total.saturating_add(bytes.len() as u64) > MAX_TOTAL_BYTES { + continue; + } + total = total.saturating_add(bytes.len() as u64); + doc.markup_images.insert(file.to_string(), bytes.into()); + } +} + /// A `container.json` that says only a format this build writes or wrote. fn is_known_container(container: &Value) -> bool { *container == json!({"format": VERSION}) @@ -1411,6 +1434,7 @@ fn read_document_within(reader: &mut PackageReader, record_bo hydrate_newer(&mut doc, &metadata, container, reader, &mut records_parts)?; } hydrate_plugin_data(&mut doc, reader); + hydrate_markup_images(&mut doc, reader); for (index, feature) in doc.features.iter_mut().enumerate() { let value = metadata.get("features").and_then(|v| v.get(index)).ok_or_else(|| invalid("missing feature metadata"))?; match &mut feature.kind { @@ -3659,6 +3683,38 @@ mod tests { } } + /// Review markup pictures are parts of their own under `markups/`, as bytes, named by the + /// markup set; a design without any has none. A part that is not a picture's name, or not a + /// PNG or JPEG, is left out. The design's JSON never holds them, and a plain JSON design can't + /// carry them and refuses to save. + #[test] + fn markup_pictures_are_parts_of_the_container() { + let doc = document(); + let without = parts(&write_design_container(&doc).unwrap()); + assert!(without.keys().all(|name| !name.starts_with("markups/"))); + let png: Vec = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A].into_iter().chain(0..=255).collect(); + let jpg: Vec = [0xFF, 0xD8, 0xFF, 0xE0, 1, 2, 3].to_vec(); + let mut with = doc.clone(); + with.markup_images.insert("0123456789abcdef0123456789abcdef.png".into(), png.as_slice().into()); + with.markup_images.insert("fedcba9876543210fedcba9876543210.jpg".into(), jpg.as_slice().into()); + let mut entries = parts(&write_design_container(&with).unwrap()); + assert_eq!(entries["markups/0123456789abcdef0123456789abcdef.png"], png, "the bytes, not text"); + assert_eq!(entries["markups/fedcba9876543210fedcba9876543210.jpg"], jpg); + let metadata: Value = serde_json::from_slice(&entries["document.json"]).unwrap(); + assert!(metadata.get("markup_images").is_none(), "the parts stand beside the design's record"); + assert_eq!(crate::read_design(&package(&entries)).unwrap().markup_images, with.markup_images); + + entries.insert("markups/x.png".into(), png.clone()); + entries.insert("markups/00000000000000000000000000000000.png".into(), b"GIF89a".to_vec()); + let opened = crate::read_design(&package(&entries)).unwrap(); + assert_eq!(opened.markup_images, with.markup_images, "only pictures under their own names"); + assert_eq!(opened.features, doc.features); + + let refused = crate::write_design(&opened).unwrap_err().to_string(); + assert!(refused.contains("review pictures"), "{refused}"); + assert!(!opened.to_json().contains("markup_images"), "never written as text"); + } + /// Plugin data under `plugins//` opens and saves back byte for byte with no plugin /// installed; a design without any has no `plugins/` part, and a part that is not a plugin data /// name is not kept. The model holds the bytes, never text; a plain JSON design can't carry diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 7be72204253..e6a4614de99 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -83,6 +83,7 @@ mod legacy_dir; pub mod library; pub mod library_files; pub mod limits; +pub mod markups; #[cfg(test)] mod mutate; mod native_cad; diff --git a/crates/io/src/markups.rs b/crates/io/src/markups.rs new file mode 100644 index 00000000000..00dfcf74ac3 --- /dev/null +++ b/crates/io/src/markups.rs @@ -0,0 +1,556 @@ +//! Review markups: places in a design someone marked for change, each with a note, replies and +//! pictures, kept in a set of their own beside the design for a person or an agent to work through +//! ([review markups](../../../docs/review-markups.md)). +//! +//! A set is `.markups.json`, with its lock in `.markups/`. Its threads and anchors +//! are never part of the design: a markup names a face, an edge, a body, a feature or a component +//! and owns none of them, so writing them changes neither the design file nor its undo history, +//! and the file reads with no app running. A markup's pictures are the one part the design holds: +//! their bytes are entries of the design container ([`solidcraft_doc::markup_image`]), as a +//! canvas's image is, and the set names each by its entry. +//! +//! Every change is one step on the set as it stands: [`update`] takes the set's lock, reads the +//! file, makes the change, checks the whole set ([`Set::check`]) and puts the new file in place +//! whole ([`crate::safe_write`]). So two writers (the window and an agent) wait for each other and +//! neither loses the other's work, and a crash leaves the last whole file. In the browser there is +//! one writer and no disk: the file lives where the host keeps files ([`crate::vfs`]). +//! +//! This module holds the file and its rules only. Which face a markup is on, and where it is now, +//! is the engine's (`markup.*` commands in `solidcraft-engine`). + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::vfs; + +/// The set's format. A change an older version would misread takes a new number; a set with a +/// higher number is refused, never rewritten. +pub const FORMAT: u32 = 1; +/// What a set's file name ends with: the design's file name and this. +pub const SUFFIX: &str = ".markups.json"; +/// The most markups a set holds. +pub const MAX_MARKUPS: usize = 2000; +/// The longest note, reply or reason from the markup's maker, in characters. +pub const MAX_NOTE: usize = 4000; +/// The longest message from anyone but the markup's maker, in characters. A longer one is refused +/// whole, never cut. +pub const MAX_REPLY: usize = 280; +/// The most messages in a markup's thread, its note among them. +pub const MAX_MESSAGES: usize = 200; +/// The most pictures on a markup. +pub const MAX_IMAGES: usize = 8; +/// The largest picture, in bytes. +pub const MAX_IMAGE: usize = solidcraft_doc::markup_image::MAX_BYTES; +/// The most a set's pictures take together, in bytes. +pub const MAX_ALL_IMAGES: u64 = 1 << 30; +/// The longest name (of a person, a body, a face, an edge, a picture), in characters. +pub const MAX_NAME: usize = 4096; +/// The largest set file read. +pub const MAX_FILE: usize = 64 << 20; +/// The farthest a stored point or camera target may lie from the origin, in mm. +pub const MAX_COORD: f64 = 1e9; +/// The deepest component path an anchor names. +pub const MAX_PATH: usize = 64; + +/// Where a markup stands. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Status { + Open, + Resolved, + Rejected, +} + +impl Status { + /// The word a list and a command use for it. + pub fn word(self) -> &'static str { + match self { + Status::Open => "open", + Status::Resolved => "resolved", + Status::Rejected => "rejected", + } + } + + /// The status a word names (`None`: no status is called that). + pub fn from_word(word: &str) -> Option { + match word { + "open" => Some(Status::Open), + "resolved" => Some(Status::Resolved), + "rejected" => Some(Status::Rejected), + _ => None, + } + } +} + +/// One message in a markup's thread: the note first, then each reply and closing reason. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Message { + pub by: String, + /// Unix seconds. + pub at: u64, + pub text: String, +} + +/// The camera a markup was made from: the orbit camera's target (mm), yaw and pitch (degrees), +/// distance (mm) and field of view (degrees; 0 for orthographic). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct View { + pub target: [f64; 3], + pub yaw: f64, + pub pitch: f64, + pub distance: f64, + #[serde(default)] + pub fov: f64, +} + +/// What a markup is on. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum Anchor { + /// A face, by its body and its lasting name (the name `model.faces` lists), and the point on + /// it that was marked, where it was then (mm). + Face { + body: String, + /// The feature that made the body: finds it again after a rename. + maker: u64, + face: String, + at: [f64; 3], + /// The configuration that was active when it was marked (`None`: the design had none). + #[serde(default, skip_serializing_if = "Option::is_none")] + config: Option, + }, + /// An edge, by its body and its name (`|`, as `model.edges` lists it), and the + /// point on it that was marked. + Edge { + body: String, + maker: u64, + edge: String, + at: [f64; 3], + #[serde(default, skip_serializing_if = "Option::is_none")] + config: Option, + }, + /// A body as a whole, and the point marked on it, if any. + Body { + body: String, + maker: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + at: Option<[f64; 3]>, + #[serde(default, skip_serializing_if = "Option::is_none")] + config: Option, + }, + /// A feature of the timeline, by id, with its name then. + Feature { + feature: u64, + name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + at: Option<[f64; 3]>, + }, + /// A component placed in the assembly, by its occurrence path (ids from the top), with its + /// name then. + Occurrence { + path: Vec, + name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + at: Option<[f64; 3]>, + }, + /// A point in space (mm). + Point { at: [f64; 3] }, + /// The view itself: the markup's `view` is what it is about. + View {}, + /// Nothing: what it was on is gone or was never given. `why` says so in words that name no id. + Unanchored { + why: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + given: Option, + }, +} + +impl Anchor { + /// The point the anchor was marked at, if it has one. + pub fn at(&self) -> Option<[f64; 3]> { + match self { + Anchor::Face { at, .. } | Anchor::Edge { at, .. } | Anchor::Point { at } => Some(*at), + Anchor::Body { at, .. } | Anchor::Feature { at, .. } | Anchor::Occurrence { at, .. } => *at, + Anchor::View {} | Anchor::Unanchored { .. } => None, + } + } + + /// The word for its kind (`face`, `edge`…). + pub fn kind(&self) -> &'static str { + match self { + Anchor::Face { .. } => "face", + Anchor::Edge { .. } => "edge", + Anchor::Body { .. } => "body", + Anchor::Feature { .. } => "feature", + Anchor::Occurrence { .. } => "occurrence", + Anchor::Point { .. } => "point", + Anchor::View {} => "view", + Anchor::Unanchored { .. } => "unanchored", + } + } + + fn check(&self) -> Result<(), String> { + let names: Vec<&str> = match self { + Anchor::Face { body, face, config, .. } => [Some(body.as_str()), Some(face.as_str()), config.as_deref()].into_iter().flatten().collect(), + Anchor::Edge { body, edge, config, .. } => [Some(body.as_str()), Some(edge.as_str()), config.as_deref()].into_iter().flatten().collect(), + Anchor::Body { body, config, .. } => [Some(body.as_str()), config.as_deref()].into_iter().flatten().collect(), + Anchor::Feature { name, .. } | Anchor::Occurrence { name, .. } => vec![name.as_str()], + Anchor::Unanchored { why, given } => [Some(why.as_str()), given.as_deref()].into_iter().flatten().collect(), + Anchor::Point { .. } | Anchor::View {} => Vec::new(), + }; + for n in names { + check_name(n, "an anchor's name")?; + } + match self { + Anchor::Face { body, face, .. } if body.trim().is_empty() || face.trim().is_empty() => { + return Err("a face anchor needs its body and face".into()); + } + Anchor::Edge { body, edge, .. } if body.trim().is_empty() || edge.trim().is_empty() => { + return Err("an edge anchor needs its body and edge".into()); + } + Anchor::Body { body, .. } if body.trim().is_empty() => return Err("a body anchor needs its body".into()), + Anchor::Occurrence { path, .. } if path.is_empty() || path.len() > MAX_PATH || path.contains(&0) => { + return Err(format!("an occurrence path holds 1 to {MAX_PATH} component ids, none 0")); + } + _ => {} + } + if let Some(at) = self.at() { + check_point(&at)?; + } + Ok(()) + } +} + +/// A picture on a markup: its bytes are the design's entry `file` +/// ([`solidcraft_doc::Document::markup_images`]). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Image { + /// `.png` or `.jpg`: the entry's name in the design. + pub file: String, + /// The name it came with (a file's name, `screenshot`). + pub name: String, + pub by: String, + pub at: u64, + pub bytes: u64, +} + +/// Who closed a markup, why and when. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Outcome { + pub by: String, + pub reason: String, + pub at: u64, +} + +/// One markup. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Markup { + /// Its number in the set, never used again. + pub id: u64, + /// 32 hexadecimal digits, the same wherever the set is copied. + pub guid: String, + pub status: Status, + /// What was said, oldest first; the first message is the note. + pub thread: Vec, + pub anchor: Anchor, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub view: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub images: Vec, + /// Who made it: the reviewer. + pub by: String, + /// Unix seconds. + pub made: u64, + pub changed: u64, + /// Set while the markup is resolved or rejected. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outcome: Option, +} + +impl Markup { + /// The note: the thread's first message. + pub fn note(&self) -> &str { + self.thread.first().map_or("", |m| m.text.as_str()) + } + + /// The longest message `by` may write on this markup: [`MAX_NOTE`] for its maker, + /// [`MAX_REPLY`] for anyone else. + pub fn limit_for(&self, by: &str) -> usize { + if by == self.by { MAX_NOTE } else { MAX_REPLY } + } + + fn check(&self) -> Result<(), String> { + let id = self.id; + if !is_guid(&self.guid) { + return Err(format!("markup {id}: its guid must be 32 hexadecimal digits")); + } + check_person(&self.by).map_err(|e| format!("markup {id}: {e}"))?; + if self.thread.is_empty() || self.thread.len() > MAX_MESSAGES { + return Err(format!("markup {id}: a thread holds 1 to {MAX_MESSAGES} messages")); + } + for m in &self.thread { + check_person(&m.by).map_err(|e| format!("markup {id}: {e}"))?; + check_text(&m.text, self.limit_for(&m.by)).map_err(|e| format!("markup {id}: {e}"))?; + } + self.anchor.check().map_err(|e| format!("markup {id}: {e}"))?; + if let Some(v) = &self.view { + check_view(v).map_err(|e| format!("markup {id}: {e}"))?; + } + if self.images.len() > MAX_IMAGES { + return Err(format!("markup {id}: at most {MAX_IMAGES} pictures")); + } + for i in &self.images { + if !is_image_file(&i.file) { + return Err(format!("markup {id}: a picture's file must be `.png` or `.jpg`")); + } + check_name(&i.name, "a picture's name").map_err(|e| format!("markup {id}: {e}"))?; + check_person(&i.by).map_err(|e| format!("markup {id}: {e}"))?; + if i.bytes > MAX_IMAGE as u64 { + return Err(format!("markup {id}: a picture is at most {MAX_IMAGE} bytes")); + } + } + match (&self.status, &self.outcome) { + (Status::Open, Some(_)) => return Err(format!("markup {id}: an open markup has no outcome")), + (Status::Resolved | Status::Rejected, None) => return Err(format!("markup {id}: a closed markup says who closed it and why")), + (_, Some(o)) => { + check_person(&o.by).map_err(|e| format!("markup {id}: {e}"))?; + check_text(&o.reason, MAX_NOTE).map_err(|e| format!("markup {id}: {e}"))?; + } + (Status::Open, None) => {} + } + Ok(()) + } +} + +/// A set of markups, as its file holds it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Set { + pub format: u32, + /// The number the next markup gets. + pub next_id: u64, + pub markups: Vec, +} + +impl Default for Set { + fn default() -> Self { + Set { format: FORMAT, next_id: 1, markups: Vec::new() } + } +} + +impl Set { + /// The one validation: a set that fails it is refused, never repaired or written. + pub fn check(&self) -> Result<(), String> { + if self.format != FORMAT { + return Err(format!("a markup set of format {} (this SolidCraft reads format {FORMAT})", self.format)); + } + if self.markups.len() > MAX_MARKUPS { + return Err(format!("a set holds at most {MAX_MARKUPS} markups")); + } + let mut ids = std::collections::BTreeSet::new(); + let mut guids = std::collections::BTreeSet::new(); + let mut files = std::collections::BTreeSet::new(); + let mut all: u64 = 0; + for m in &self.markups { + if m.id == 0 || m.id >= self.next_id { + return Err(format!("markup {}: its number must be at least 1 and below the set's next number {}", m.id, self.next_id)); + } + if !ids.insert(m.id) { + return Err(format!("markup {} is in the set twice", m.id)); + } + if !guids.insert(m.guid.to_ascii_lowercase()) { + return Err(format!("markup {}: another markup has its guid", m.id)); + } + m.check()?; + for i in &m.images { + if !files.insert(i.file.to_ascii_lowercase()) { + return Err(format!("markup {}: a picture's file is named twice in the set", m.id)); + } + all = all.saturating_add(i.bytes); + } + } + if all > MAX_ALL_IMAGES { + return Err(format!("a set's pictures take at most {MAX_ALL_IMAGES} bytes together")); + } + Ok(()) + } + + /// The markup with this number. + pub fn get(&self, id: u64) -> Option<&Markup> { + self.markups.iter().find(|m| m.id == id) + } + + /// The markup with this number, to change. + pub fn get_mut(&mut self, id: u64) -> Option<&mut Markup> { + self.markups.iter_mut().find(|m| m.id == id) + } + + /// The number of the markup with this guid (any case). + pub fn by_guid(&self, guid: &str) -> Option { + self.markups.iter().find(|m| m.guid.eq_ignore_ascii_case(guid)).map(|m| m.id) + } +} + +/// Whether `s` is a markup's or a picture's guid: 32 hexadecimal digits. +pub fn is_guid(s: &str) -> bool { + s.len() == 32 && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// Whether `s` is a picture's entry name: a guid and `.png` or `.jpg`. +pub fn is_image_file(s: &str) -> bool { + solidcraft_doc::markup_image::valid_name(s) +} + +/// The kind of picture `bytes` hold by their first bytes: `png` or `jpg` (`None`: neither). +pub fn image_kind(bytes: &[u8]) -> Option<&'static str> { + solidcraft_doc::markup_image::kind(bytes) +} + +fn check_point(p: &[f64; 3]) -> Result<(), String> { + if p.iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD) { + Ok(()) + } else { + Err(format!("a point's coordinates must be finite and within {MAX_COORD} mm")) + } +} + +/// Whether a camera is one a list can give and the window can fly to. +pub fn check_view(v: &View) -> Result<(), String> { + check_point(&v.target)?; + let angles = v.yaw.is_finite() && v.pitch.is_finite() && v.yaw.abs() <= 1e6 && v.pitch.abs() <= 1e6; + if !angles || !(v.distance.is_finite() && v.distance > 0.0 && v.distance <= MAX_COORD) || !(v.fov.is_finite() && (0.0..180.0).contains(&v.fov)) { + return Err("a view needs finite angles, a distance above 0 and a field of view from 0 to under 180 degrees".into()); + } + Ok(()) +} + +fn check_name(s: &str, what: &str) -> Result<(), String> { + if s.chars().count() > MAX_NAME || s.chars().any(|c| c.is_control()) { + return Err(format!("{what} is at most {MAX_NAME} characters, with no control characters")); + } + Ok(()) +} + +/// Whether `by` can name who wrote something: 1 to 200 characters, no control characters. +pub fn check_person(by: &str) -> Result<(), String> { + let n = by.chars().count(); + if by.trim().is_empty() || n > 200 || by.chars().any(|c| c.is_control()) { + return Err("a name is 1 to 200 characters, with no control characters".into()); + } + Ok(()) +} + +/// Whether `text` can be a message of at most `limit` characters: not blank, no control characters +/// but line breaks and tabs. The error says the limit, the length and how far over it is. +pub fn check_text(text: &str, limit: usize) -> Result<(), String> { + if text.trim().is_empty() { + return Err("a message must not be empty".into()); + } + if text.chars().any(|c| c.is_control() && c != '\n' && c != '\t' && c != '\r') { + return Err("a message has no control characters but line breaks and tabs".into()); + } + let n = text.chars().count(); + if n > limit { + let whose = if limit == MAX_REPLY { "a message from anyone but the markup's maker" } else { "a message" }; + return Err(format!("{whose} is at most {limit} characters; this one is {n}, {} over: say it shorter", n - limit)); + } + Ok(()) +} + +/// The set beside the design at `design`: `.markups.json`. +pub fn beside(design: &str) -> String { + format!("{design}{SUFFIX}") +} + +/// The folder of the set at `set` (its lock): the set's path without `.json`. +/// `Err` for a path that is not a set's (`…markups.json`). +pub fn folder(set: &str) -> Result { + match set.strip_suffix(".json") { + Some(stem) if set.ends_with(SUFFIX) && !stem.ends_with('/') && !stem.ends_with('\\') => Ok(stem.to_string()), + _ => Err(format!("a markup set's file name ends with `{SUFFIX}`")), + } +} + +/// Read a set's text: a set of [`FORMAT`] as it is, checked. A newer format is refused with a +/// message; so is a file that is not a set, or one that fails [`Set::check`]. +pub fn parse(text: &str) -> Result { + let v: Value = serde_json::from_str(text).map_err(|e| format!("not a markup set: {e}"))?; + let format = v.get("format").and_then(Value::as_u64).ok_or("not a markup set: it has no `format`")?; + if format > u64::from(FORMAT) { + return Err(format!("this markup set was made by a newer SolidCraft (format {format}; this one reads format {FORMAT}): open it there")); + } + let set: Set = serde_json::from_value(v).map_err(|e| format!("not a markup set: {e}"))?; + set.check()?; + Ok(set) +} + +/// The text a set is written as: plain JSON without indents. +pub fn to_text(set: &Set) -> Result { + serde_json::to_string(set).map_err(|e| e.to_string()) +} + +/// The set at `set` as it stands (an empty set where there is no file yet). +pub fn read(set: &str) -> Result { + folder(set)?; + if !vfs::exists(set) { + return Ok(Set::default()); + } + let bytes = vfs::read(set, MAX_FILE).map_err(|e| format!("{set}: {e}"))?; + let text = String::from_utf8(bytes).map_err(|_| format!("{set}: not a markup set: it is not text"))?; + parse(&text).map_err(|e| format!("{set}: {e}")) +} + +/// The set's lock, held while it lives (nothing in the browser, which has one writer). +struct Held { + #[cfg(not(target_arch = "wasm32"))] + _file: std::fs::File, +} + +#[cfg(not(target_arch = "wasm32"))] +fn lock(folder: &str) -> Result { + let path = format!("{folder}/lock"); + vfs::check_new(&path).map_err(|e| format!("{path}: {e}"))?; + if std::fs::symlink_metadata(&path).is_ok_and(|m| !m.is_file()) { + return Err(format!("{path}: not a regular file")); + } + let file = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&path).map_err(|e| format!("{path}: {e}"))?; + file.lock().map_err(|e| format!("{path}: {e}"))?; + Ok(Held { _file: file }) +} + +#[cfg(target_arch = "wasm32")] +fn lock(_folder: &str) -> Result { + Ok(Held {}) +} + +/// Make the set's folder, inside what the caller may write. +fn make_folder(set: &str) -> Result { + let dir = folder(set)?; + vfs::check_new(&dir).map_err(|e| format!("{dir}: {e}"))?; + vfs::create_dir_all(&dir).map_err(|e| format!("{dir}: {e}"))?; + Ok(dir) +} + +/// One change to the set at `set`, under its lock: read it as it stands, run `step`, check the +/// result and write it whole. When `step` or the check refuses, the file stays as it was. +pub fn update(set: &str, step: impl FnOnce(&mut Set) -> Result) -> Result { + vfs::check_new(set).map_err(|e| format!("{set}: {e}"))?; + let dir = make_folder(set)?; + let _held = lock(&dir)?; + let mut s = read(set)?; + let out = step(&mut s)?; + s.check()?; + let text = to_text(&s)?; + crate::safe_write::write_atomic_no_follow(std::path::Path::new(set), text.as_bytes()).map_err(|e| format!("{set}: {e}"))?; + Ok(out) +} + +#[cfg(test)] +#[path = "markups_tests.rs"] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests; diff --git a/crates/io/src/markups_tests.rs b/crates/io/src/markups_tests.rs new file mode 100644 index 00000000000..4e686eb3935 --- /dev/null +++ b/crates/io/src/markups_tests.rs @@ -0,0 +1,177 @@ +//! The markup set file: its format, its one check, and writers that meet. + +use super::*; + +/// A fresh folder of the system's temporary folder for one test. +fn scratch(tag: &str) -> std::path::PathBuf { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); + let dir = std::env::temp_dir().join(format!("solidcraft-markups-{tag}-{}-{nanos}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn markup(id: u64, guid: &str, by: &str) -> Markup { + Markup { + id, + guid: guid.into(), + status: Status::Open, + thread: vec![Message { by: by.into(), at: 1, text: "Make this wall 2 mm thicker.".into() }], + anchor: Anchor::Point { at: [1.0, 2.0, 3.0] }, + view: None, + images: Vec::new(), + by: by.into(), + made: 1, + changed: 1, + outcome: None, + } +} + +const GUID_A: &str = "0123456789abcdef0123456789abcdef"; +const GUID_B: &str = "fedcba9876543210fedcba9876543210"; + +/// A set written by format 1, frozen here as text: every later build reads it as it is. +const FORMAT_1: &str = r#"{"format":1,"next_id":3,"markups":[{"id":1,"guid":"0123456789abcdef0123456789abcdef","status":"open","thread":[{"by":"Reviewer","at":1700000000,"text":"Round this edge."},{"by":"agent","at":1700000100,"text":"Which radius?"}],"anchor":{"kind":"face","body":"Body1","maker":2,"face":"F2:top","at":[5.0,10.0,30.0]},"view":{"target":[0.0,0.0,0.0],"yaw":30.0,"pitch":20.0,"distance":200.0,"fov":45.0},"by":"Reviewer","made":1700000000,"changed":1700000100},{"id":2,"guid":"fedcba9876543210fedcba9876543210","status":"resolved","thread":[{"by":"Reviewer","at":1700000000,"text":"Thicker base."},{"by":"agent","at":1700000200,"text":"Base now 6 mm."}],"anchor":{"kind":"edge","body":"Body1","maker":2,"edge":"F2:side:l1|F2:top","at":[5.0,0.0,30.0],"config":"Default"},"by":"Reviewer","made":1700000000,"changed":1700000200,"outcome":{"by":"agent","reason":"Base now 6 mm.","at":1700000200}}]}"#; + +#[test] +fn a_format_1_set_reads_as_it_is_and_writes_back_the_same() { + let set = parse(FORMAT_1).unwrap(); + assert_eq!(set.markups.len(), 2); + assert_eq!(set.markups[0].note(), "Round this edge."); + assert!(matches!(&set.markups[0].anchor, Anchor::Face { face, .. } if face == "F2:top")); + assert_eq!(set.markups[1].status, Status::Resolved); + assert_eq!(to_text(&set).unwrap(), FORMAT_1); +} + +#[test] +fn a_newer_set_is_refused_and_left_as_it_was() { + let dir = scratch("newer"); + let set = dir.join("part.sc.markups.json").to_string_lossy().to_string(); + let newer = FORMAT_1.replacen("\"format\":1", "\"format\":2", 1); + std::fs::write(&set, &newer).unwrap(); + let e = read(&set).unwrap_err(); + assert!(e.contains("newer SolidCraft"), "{e}"); + let e = update(&set, |s| { + s.next_id += 1; + Ok(()) + }) + .unwrap_err(); + assert!(e.contains("newer SolidCraft"), "{e}"); + assert_eq!(std::fs::read_to_string(&set).unwrap(), newer); +} + +#[test] +fn keys_this_format_does_not_know_are_refused_not_dropped() { + // A write puts the set back whole, so a key it would leave out is refused instead. + let extra = FORMAT_1.replacen("\"next_id\":3", "\"next_id\":3,\"owner\":\"x\"", 1); + assert!(parse(&extra).is_err()); + let extra = FORMAT_1.replacen("\"status\":\"open\"", "\"status\":\"open\",\"priority\":1", 1); + assert!(parse(&extra).is_err()); + assert!(parse("{}").is_err()); + assert!(parse("[]").is_err()); + assert!(parse("not json").is_err()); +} + +#[test] +fn the_check_refuses_what_a_set_must_not_hold() { + let ok = Set { format: FORMAT, next_id: 3, markups: vec![markup(1, GUID_A, "R"), markup(2, GUID_B, "R")] }; + assert!(ok.check().is_ok()); + let bad = |f: &dyn Fn(&mut Set)| { + let mut s = ok.clone(); + f(&mut s); + s.check().is_err() + }; + assert!(bad(&|s| s.markups[1].id = 1), "a number twice"); + assert!(bad(&|s| s.markups[1].id = 3), "a number not below next_id"); + assert!(bad(&|s| s.markups[1].guid = GUID_A.to_uppercase()), "a guid twice"); + assert!(bad(&|s| s.markups[0].guid = "../../etc/passwd".into()), "a guid that is not one"); + assert!(bad(&|s| s.markups[0].thread.clear()), "no note"); + assert!(bad(&|s| s.markups[0].status = Status::Resolved), "closed with no outcome"); + assert!(bad(&|s| s.markups[0].anchor = Anchor::Point { at: [f64::NAN, 0.0, 0.0] }), "a point that is not one"); + assert!(bad(&|s| s.markups[0].anchor = Anchor::Occurrence { path: vec![], name: "A".into(), at: None }), "an empty path"); + assert!( + bad(&|s| s.markups[0].images.push(Image { file: "../x.png".into(), name: "x".into(), by: "R".into(), at: 1, bytes: 1 })), + "a picture outside the folder" + ); + assert!(bad(&|s| s.markups[0].by = "a\u{0}b".into()), "a control character in a name"); + assert!(bad(&|s| s.markups[0].thread[0].text = "x".repeat(MAX_NOTE + 1)), "a note too long"); + // Anyone but the maker writes at most MAX_REPLY characters. + assert!(bad(&|s| s.markups[0].thread.push(Message { by: "agent".into(), at: 2, text: "x".repeat(MAX_REPLY + 1) }))); + assert!(!bad(&|s| s.markups[0].thread.push(Message { by: "R".into(), at: 2, text: "x".repeat(MAX_REPLY + 1) }))); +} + +#[test] +fn a_reply_too_long_says_the_limit_its_length_and_how_far_over() { + let e = check_text(&"x".repeat(658), MAX_REPLY).unwrap_err(); + assert!(e.contains("280") && e.contains("658") && e.contains("378 over"), "{e}"); +} + +#[test] +fn a_set_path_names_its_folder_and_pictures_are_entry_names() { + assert_eq!(beside("/d/part.sc"), "/d/part.sc.markups.json"); + assert_eq!(folder("/d/part.sc.markups.json").unwrap(), "/d/part.sc.markups"); + assert!(folder("/d/part.json").is_err()); + assert!(folder("/d/part.sc").is_err()); + assert!(is_image_file(&format!("{GUID_A}.png"))); + for bad in ["../a.png", "a.png", &format!("{GUID_A}.gif"), &format!("../{GUID_A}.png"), ""] { + assert!(!is_image_file(bad), "{bad}"); + } + assert_eq!(image_kind(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0]), Some("png")); + assert_eq!(image_kind(&[0xFF, 0xD8, 0xFF, 0xE0]), Some("jpg")); + assert_eq!(image_kind(b"GIF89a"), None); +} + +/// Two writers at once, each adding markups one change at a time: neither loses the other's. +#[test] +fn two_writers_at_once_lose_nothing() { + let dir = scratch("writers"); + let set = dir.join("part.sc.markups.json").to_string_lossy().to_string(); + const EACH: u64 = 40; + let writer = |who: &'static str, set: String| { + std::thread::spawn(move || { + for i in 0..EACH { + update(&set, |s| { + let id = s.next_id; + s.next_id += 1; + let guid = format!("{:016x}{:016x}", if who == "a" { 1u64 } else { 2 }, i); + s.markups.push(markup(id, &guid, who)); + Ok(()) + }) + .unwrap(); + } + }) + }; + let a = writer("a", set.clone()); + let b = writer("b", set.clone()); + a.join().unwrap(); + b.join().unwrap(); + let s = read(&set).unwrap(); + assert_eq!(s.markups.len() as u64, 2 * EACH); + assert_eq!(s.next_id, 2 * EACH + 1); + for who in ["a", "b"] { + assert_eq!(s.markups.iter().filter(|m| m.by == who).count() as u64, EACH); + } +} + +#[test] +fn a_refused_change_leaves_the_file_as_it_was() { + let dir = scratch("refused"); + let set = dir.join("part.sc.markups.json").to_string_lossy().to_string(); + update(&set, |s| { + s.markups.push(markup(1, GUID_A, "R")); + s.next_id = 2; + Ok(()) + }) + .unwrap(); + let before = std::fs::read(&set).unwrap(); + // The step refuses. + assert!(update(&set, |_| Err::<(), _>("no".into())).is_err()); + // The step makes a set the check refuses. + assert!( + update(&set, |s| { + s.markups[0].thread.clear(); + Ok(()) + }) + .is_err() + ); + assert_eq!(std::fs::read(&set).unwrap(), before); +} diff --git a/crates/kernel/src/curvature_comb.rs b/crates/kernel/src/curvature_comb.rs index c2a0faad7db..aaccbb6a916 100644 --- a/crates/kernel/src/curvature_comb.rs +++ b/crates/kernel/src/curvature_comb.rs @@ -83,6 +83,25 @@ pub fn comb_edge_near(body: &Body, at: Vec3) -> Result> { }) } +/// The point of edge `edge` of `body` closest to `at`, exactly; `None` when the body or the edge +/// cannot be measured. +pub fn edge_closest_point(body: &Body, edge: usize, at: Vec3) -> Result> { + body.require_brep("an edge point")?; + if !at.is_finite() { + return Err(KernelError::Invalid("the point must be finite".into())); + } + let Some(form) = body.ops_body() else { return Ok(None) }; + let (ops, order) = &*form; + if edge >= body.record().edges.len() { + return Ok(None); + } + match ops.edge_closest_point(order, edge, [at.x, at.y, at.z]) { + Ok(found) => Ok(found.map(|c| Vec3::new(c.point[0], c.point[1], c.point[2])).filter(|p| p.is_finite())), + Err(solidcore_ops::Error::Argument) => Ok(None), + Err(e) => Err(KernelError::Failed(format!("edge point: {e}"))), + } +} + /// The exact distance from `at` to edge `edge` of `body` (its index in the body's edge order): /// to the edge's own curve over its interval, ends included, not to a tessellation, as /// [`comb_edge_near`] measures it. `None` for an edge that is a periodic face's own seam or a diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 9a0bef0be5c..d586ccdfb3f 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -295,6 +295,7 @@ pub use curvature_comb::CombTooth; pub use curvature_comb::MAX_COMB_TEETH; pub use curvature_comb::MIN_COMB_TEETH; pub use curvature_comb::comb_edge_near; +pub use curvature_comb::edge_closest_point; pub use curvature_comb::edge_comb; pub use curvature_comb::edge_distance; pub use curvature_comb::edge_middle; diff --git a/crates/look/icons/design/requested_icons.txt b/crates/look/icons/design/requested_icons.txt index dd17dfd57d7..0f5f9fd270a 100644 --- a/crates/look/icons/design/requested_icons.txt +++ b/crates/look/icons/design/requested_icons.txt @@ -304,6 +304,7 @@ replace_face false rest false restore false revert false +review_mark false revolve false rib false rigid_group false diff --git a/crates/look/icons/design/svg/flat/review_mark.svg b/crates/look/icons/design/svg/flat/review_mark.svg new file mode 100644 index 00000000000..064a0013dc3 --- /dev/null +++ b/crates/look/icons/design/svg/flat/review_mark.svg @@ -0,0 +1,5 @@ + + Mark for review + + + diff --git a/crates/ui-egui/src/command_help.rs b/crates/ui-egui/src/command_help.rs index 4f3787c4a35..87a7ed443e9 100644 --- a/crates/ui-egui/src/command_help.rs +++ b/crates/ui-egui/src/command_help.rs @@ -344,6 +344,7 @@ pub const DOCUMENTED: &[&str] = &[ "view.navigation_bar", "view.parts_library", "view.rename", + "view.review", "view.ribbon_tabs_only", "view.save", "view.spin", diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index f69f452644d..13533a0149f 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -196,6 +196,7 @@ fn open_windows(app: &SolveApp) -> Vec<&'static str> { (app.crashes.open, "crashes"), (app.issue_report.draft.is_some(), "report"), (app.messages.open, "messages"), + (app.review.open, "view.review"), ] .into_iter() .filter_map(|(open, command)| open.then_some(command)) @@ -280,6 +281,7 @@ fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result | "view.navigation_bar" | "view.browser" | "view.parts_library" + | "view.review" | "view.ribbon_tabs_only" | "view.toolbar_reset_all" | "view.next_tab" diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 81d6a3553ad..9b2f7bf6e02 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -499,6 +499,10 @@ pub fn command_for(app: &SolveApp, key: &str) -> Option<&'static str> { /// Sketch (on the selected plane or planar face, else on the plane picked next) and the tool /// starts in the new sketch. pub fn press(app: &mut SolveApp, key: &str, repeat: bool) { + // While Review is on, M marks (the review's own key); off, M is Move/Copy's as ever. + if !repeat && crate::review_pins::take_key(app, key) { + return; + } if keeps_old_show_hide(app, key) { app.start("ui.toggle_visibility"); } else if let Some(id) = command_for(app, key) { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ccb14a6762b..fd21751ca9f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -312,6 +312,7 @@ pub(crate) mod refused_part; mod render_ui; pub mod render_workspace; pub mod resume_ui; +mod review_pins; #[cfg(test)] mod revolve_edit_tests; #[cfg(test)] @@ -796,6 +797,8 @@ pub struct SolveApp { pub messages: messages::Messages, /// An editable local issue draft and optional captured app frame. pub issue_report: issue_report::ReportState, + /// Review pins over the view (`view.review`); window state, never saved in the design. + pub(crate) review: review_pins::State, /// Problem reports on the ticket server: sign-in, sending, the offline queue. pub tickets: tickets::Tickets, /// The Crash Reports window. @@ -1199,6 +1202,7 @@ impl SolveApp { help: help::HelpState::default(), messages: messages::Messages::default(), issue_report: issue_report::ReportState::default(), + review: review_pins::State::default(), tickets: tickets::Tickets::new(), crashes: crash_ui::CrashUi::default(), updater: update::Updater::default(), @@ -2030,6 +2034,7 @@ impl SolveApp { browser::close_shared_panel(self, "browser"); } } + "view.review" => review_pins::set_open(self, v.get("visible").and_then(Value::as_bool)), "view.next_tab" | "view.previous_tab" => documents::cycle(self, id == "view.next_tab"), "view.toolbar_reset_all" => toolbar_custom::reset_all(self), "view.ribbon_tabs_only" => { @@ -2720,6 +2725,7 @@ impl SolveApp { | "view.navigation_bar" | "view.browser" | "view.parts_library" + | "view.review" | "view.next_tab" | "view.previous_tab" | "tab.view.open" @@ -5074,9 +5080,10 @@ impl SolveApp { } fn collect_screenshots(&mut self, ctx: &egui::Context) { - let report = issue_report::pending(self); + let report = issue_report::pending(self) || review_pins::pending(self); let shots = self.shots.collect(ctx, now_ms(), report, control::save_screenshot); for (token, image) in shots { + review_pins::receive(self, token, image.clone()); issue_report::receive(self, token, image); } } diff --git a/crates/ui-egui/src/panel_runtime/app.rs b/crates/ui-egui/src/panel_runtime/app.rs index 204b01ecf10..50ec0b14978 100644 --- a/crates/ui-egui/src/panel_runtime/app.rs +++ b/crates/ui-egui/src/panel_runtime/app.rs @@ -1773,6 +1773,7 @@ impl crate::SolveApp { self.shell.browser = None; self.shell.history = None; self.shell.workspace_panels.clear(); + crate::review_pins::register(self); self.publish_tab_accent(ui.ctx()); crate::browser::publish_row_prefs(self, ui.ctx()); let prepared = self.prepare_workspace_panels(ui, render_domain, true); diff --git a/crates/ui-egui/src/render_workspace_setups.rs b/crates/ui-egui/src/render_workspace_setups.rs index d876bf7e80e..bcada238602 100644 --- a/crates/ui-egui/src/render_workspace_setups.rs +++ b/crates/ui-egui/src/render_workspace_setups.rs @@ -462,7 +462,8 @@ fn load_values(view: &mut super::ViewState, setup: RenderSetup) { view.draft = setup; } -/// Compare the complete authoring source, excluding saved Render settings and drawings. +/// Compare the complete authoring source, excluding saved Render settings, drawings and review +/// pictures. /// Stable body labels alone do not prove that geometry or its material is unchanged. pub(super) fn same_model_source(app: &SolveApp, document: &std::sync::Weak) -> bool { if app.session.model.is_stale() { @@ -475,7 +476,7 @@ pub(super) fn same_model_source(app: &SolveApp, document: &std::sync::Weak {{ - let solidcraft_engine::doc::Document { render: _, drawings: _, $($field),* } = source.as_ref(); + let solidcraft_engine::doc::Document { render: _, drawings: _, markup_images: _, $($field),* } = source.as_ref(); true $(&& $field == &app.session.doc.$field)* }}; } diff --git a/crates/ui-egui/src/review_pins.rs b/crates/ui-egui/src/review_pins.rs new file mode 100644 index 00000000000..0e5c8454603 --- /dev/null +++ b/crates/ui-egui/src/review_pins.rs @@ -0,0 +1,1471 @@ +//! Review pins: the review markups kept beside a design ([review markups](../../../docs/review-markups.md)) +//! drawn on the model, with a card beside the chosen pin and the Review list along the right of the view. +//! +//! Review is a window setting, off until `view.review` turns it on (Inspect › Review). While it is on: +//! - a teardrop pin stands at each markup's place, its tip on the point marked: amber and numbered when +//! open, red when an open one's face is gone, green with a tick when done, grey with a cross when +//! rejected, faint grey when its face is hidden here (the history marker or another configuration +//! leaves it out); the chosen one is larger, in the accent colour, with a ring; +//! - **Mark this** beside the navigation bar, and M, pin a new markup: M on what the pointer is on (else +//! the middle of the view), the button on the next click. The card opens with the note box; nothing is +//! in the set until Add, and Cancel or Esc leaves nothing; +//! - the card reads a markup: its status, what it is on, who and when, the thread, a reply box, its +//! pictures, Screenshot, Attach image, Go there, Select, Edit , Delete, Resolve…, Reject… and +//! Reopen; +//! - the Review list holds the set, newest first, filtered by All, Open, Done and Rejected; the pins +//! follow the filter, and its eye hides every pin. +//! +//! The window only reads and writes the set through the `markup.*` commands. It lists the set again +//! when the set's file changes on the disk (an agent closed one), when the model changes (where each +//! face stands now), and after its own writes; in the browser, where there is no file to look at, every +//! two seconds. Which face a new pin means is decided by `markup.add` on the exact geometry: the window +//! sends the body and the point under the pointer, never a mesh triangle's face. + +use std::collections::HashMap; +use std::sync::Arc; + +use egui::{Align, Color32, ColorImage, Id, Layout, Pos2, Rect, RichText, Sense, Shape, Stroke, Vec2, pos2, vec2}; +use serde::Deserialize; +use serde_json::{Value, json}; +use solidcore_record::Vec3; +use solidcraft_theme::Tokens; + +use crate::SolveApp; +use crate::ui_kit::{self, BackingTooltipExt as _, Container, Surface}; + +/// How often the set is listed again where its file can't be looked at (the browser), in seconds. +const BROWSER_POLL: f64 = 2.0; +/// How often the set's file is looked at for a change, in seconds. +const STAMP_POLL: f64 = 0.5; +/// Pictures kept as textures at once. +const THUMBS: usize = 32; +/// A picture's small copy, at most this many points each way. +const THUMB: Vec2 = vec2(96.0, 66.0); +/// The card's width, in points. +const CARD_WIDTH: f32 = 360.0; +/// The Review list's width, in points. +const LIST_WIDTH: f32 = 326.0; + +/// Which markups the list and the pins show. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Filter { + All, + #[default] + Open, + Done, + Rejected, +} + +impl Filter { + fn keeps(self, row: &Row) -> bool { + match self { + Filter::All => true, + Filter::Open => row.status == "open", + Filter::Done => row.status == "resolved", + Filter::Rejected => row.status == "rejected", + } + } +} + +/// One message of a markup's thread, as `markup.list` gives it. +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default)] +pub(crate) struct Said { + pub by: String, + pub at: u64, + pub text: String, + pub reviewer: bool, +} + +/// Where a markup's anchor stands now, as `markup.list` gives it. +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default)] +pub(crate) struct Found { + pub state: String, + pub at: Option<[f64; 3]>, + pub was: Option<[f64; 3]>, + pub why: Option, +} + +/// The camera a markup was marked from. +#[derive(Clone, Copy, Debug, Default, Deserialize)] +#[serde(default)] +pub(crate) struct Seen { + pub target: [f64; 3], + pub yaw: f64, + pub pitch: f64, + pub distance: f64, + pub fov: f64, +} + +impl Seen { + /// A markup's view, kept with its angles in degrees, as the camera takes it (radians). + fn in_radians(self) -> Self { + Self { yaw: self.yaw.to_radians(), pitch: self.pitch.to_radians(), fov: self.fov.to_radians(), ..self } + } +} + +/// A picture of a markup. +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default)] +pub(crate) struct Picture { + /// Its entry in the design. + pub file: String, + pub name: String, + /// The design holds its bytes (not after an undo past attaching it). + pub in_design: bool, +} + +/// How a closed markup ended. +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default)] +pub(crate) struct Ended { + pub by: String, + pub reason: String, +} + +/// One markup, as `markup.list` gives it. +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default)] +pub(crate) struct Row { + pub id: u64, + pub status: String, + pub note: String, + pub thread: Vec, + pub anchor: Value, + pub found: Found, + pub view: Option, + pub images: Vec, + pub by: String, + pub made: u64, + pub outcome: Option, +} + +/// How a pin looks. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Look { + Open, + Gone, + Done, + Rejected, + Hidden, +} + +impl Row { + /// Where its pin stands: where its anchor is now, else where it was. + pub(crate) fn place(&self) -> Option { + let at = self.found.at.or(self.found.was).or_else(|| point(self.anchor.get("at")?))?; + let p = Vec3::new(at[0], at[1], at[2]); + p.is_finite().then_some(p) + } + + pub(crate) fn look(&self) -> Look { + match (self.status.as_str(), self.found.state.as_str()) { + (_, "hidden") => Look::Hidden, + ("resolved", _) => Look::Done, + ("rejected", _) => Look::Rejected, + (_, "gone") => Look::Gone, + _ => Look::Open, + } + } + + fn kind(&self) -> &str { + self.anchor.get("kind").and_then(Value::as_str).unwrap_or("") + } + + fn text_of(&self, key: &str) -> String { + self.anchor.get(key).and_then(Value::as_str).unwrap_or("").to_owned() + } + + /// The feature that made what it is on, by its id. + fn maker(&self) -> Option { + match self.kind() { + // A face names the feature that made it (`F:` in its name); the anchor's maker is the body's. + "face" => self + .anchor + .get("face") + .and_then(Value::as_str) + .and_then(|f| solidcraft_engine::doc::persistent_name::FaceName::parse(f).ok()) + .and_then(|f| f.made_by()) + .map(|f| f.0) + .or_else(|| self.anchor.get("maker").and_then(Value::as_u64)) + .filter(|id| *id != 0), + "edge" | "body" => self.anchor.get("maker").and_then(Value::as_u64).filter(|id| *id != 0), + "feature" => self.anchor.get("feature").and_then(Value::as_u64), + _ => None, + } + } +} + +fn point(v: &Value) -> Option<[f64; 3]> { + let a = v.as_array()?; + match a.as_slice() { + [x, y, z] => Some([x.as_f64()?, y.as_f64()?, z.as_f64()?]), + _ => None, + } +} + +/// The set as last listed. +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default)] +pub(crate) struct Listing { + pub set: String, + pub markups: Vec, +} + +/// What the list was made from: when any of it changes, the set is listed again. +#[derive(Clone, Debug, PartialEq)] +struct Key { + set: String, + stamp: Option<(u64, u128)>, + revision: u64, + marker: Option, + config: Option, +} + +/// A new markup, before Add puts it in the set. +#[derive(Clone, Debug)] +pub(crate) struct Draft { + /// The point marked, on `body` or in space; none for a markup on the view. + pub at: Option, + pub body: Option, + /// The edge of `body` marked, by its lasting name (as `model.edges` lists it). + pub edge: Option, + pub view: Value, + pub text: String, +} + +/// A question the card asks before it writes. +#[derive(Clone, Debug, PartialEq)] +enum Ask { + Resolve(String), + Reject(String), + Delete, +} + +/// A screenshot asked for a markup: the frame's token, the markup, and the view's place then. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Shot { + pub token: u64, + pub markup: u64, + view: Rect, + scale: f32, + /// When it is given up (ms): a frame that never comes (a hidden window, a dropped frame) + /// must not keep the list and the card hidden. + until: f64, +} + +/// How long a screenshot waits for its frame, ms. +const SHOT_WAIT_MS: f64 = 3000.0; + +/// Where the list, the card and the Mark this button were drawn last frame. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct Drawn { + pub list: Option, + pub card: Option, + pub mark: Option, +} + +/// The window's review state; never saved in the design. +#[derive(Default)] +pub(crate) struct State { + /// `view.review`: the list, the pins, Mark this and M. + pub open: bool, + /// The eye: every pin taken off the model (the list stays). + pub pins_hidden: bool, + pub filter: Filter, + pub chosen: Option, + pub listing: Option, + /// Why the set could not be listed. + pub error: Option, + pub draft: Option, + /// Mark this was pressed: the next click on the model places the pin. + pub placing: bool, + pub shot: Option, + pub drawn: Drawn, + /// A picture chosen to attach, waiting for the picker to close: the markup, the file. + attach: Option<(u64, String)>, + reply: String, + ask: Option, + key: Option, + /// List again on the next frame (after this window wrote). + stale: bool, + listed_at: f64, + stamped_at: f64, + stamp: Option<(u64, u128)>, + /// Where the pointer is now (the viewport's own hover stops while a card or panel covers it). + pointer: Option, + thumbs: HashMap>, +} + +impl State { + pub(crate) fn chosen_row(&self) -> Option<&Row> { + let id = self.chosen?; + self.listing.as_ref()?.markups.iter().find(|m| m.id == id) + } + + fn rows(&self) -> &[Row] { + self.listing.as_ref().map_or(&[], |l| l.markups.as_slice()) + } + + /// Open, done and rejected counts. + fn counts(&self) -> [usize; 3] { + let rows = self.rows(); + let n = |w: &str| rows.iter().filter(|r| r.status == w).count(); + [n("open"), n("resolved"), n("rejected")] + } +} + +/// `view.review` ran: `visible` or, without it, the other way. +pub(crate) fn set_open(app: &mut SolveApp, visible: Option) { + let open = visible.unwrap_or(!app.review.open); + app.review.open = open; + if open { + app.review.stale = true; + } else { + app.review.draft = None; + app.review.placing = false; + app.review.ask = None; + app.review.drawn = Drawn::default(); + } +} + +/// Who writes from this window: the system's user name, else "reviewer". +pub(crate) fn me() -> String { + ["USER", "USERNAME", "LOGNAME"] + .iter() + .find_map(|k| std::env::var(k).ok()) + .map(|n| n.trim().to_owned()) + .filter(|n| solidcraft_engine::io::markups::check_person(n).is_ok()) + .unwrap_or_else(|| "reviewer".to_owned()) +} + +/// The set's file, beside the design, while the design has one. +fn set_of(app: &SolveApp) -> Option { + app.session.path.as_deref().filter(|p| !p.trim().is_empty()).map(solidcraft_engine::io::markups::beside) +} + +/// The file's length and change time, where there is a file system to ask. +fn stamp(set: &str) -> Option<(u64, u128)> { + #[cfg(not(target_arch = "wasm32"))] + { + let m = std::fs::metadata(set).ok()?; + let at = m.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_nanos(); + Some((m.len(), at)) + } + #[cfg(target_arch = "wasm32")] + { + let _ = set; + None + } +} + +/// Before the view takes this frame's input: the list, the card and Mark this shield the model under +/// them, and their footprints keep the view's other controls clear. Last frame's places stand in. +pub(crate) fn register(app: &mut SolveApp) { + let drawn = if app.review.open { app.review.drawn } else { Drawn::default() }; + crate::shell::register_panel(app, "review:list", drawn.list); + crate::shell::register_panel(app, "review:card", drawn.card); + crate::shell::register_panel(app, "review:mark", drawn.mark); +} + +/// Each frame while Review is on: list the set again when it or the model changed. +pub(crate) fn poll(app: &mut SolveApp, ctx: &egui::Context) { + if !app.review.open { + return; + } + let now = ctx.input(|i| i.time); + app.review.pointer = ctx.input(|i| i.pointer.latest_pos()); + let Some(set) = set_of(app) else { + app.review.listing = None; + app.review.key = None; + app.review.error = None; + return; + }; + if now - app.review.stamped_at >= STAMP_POLL || app.review.stale { + app.review.stamp = stamp(&set); + app.review.stamped_at = now; + } + let key = Key { + set, + stamp: app.review.stamp, + revision: app.session.revision, + marker: app.session.doc.marker, + config: app.session.doc.configs.active.clone(), + }; + let browser = key.stamp.is_none() && now - app.review.listed_at >= BROWSER_POLL; + if app.review.stale || browser || app.review.key.as_ref() != Some(&key) { + list(app); + app.review.key = Some(key); + app.review.listed_at = now; + app.review.stale = false; + } + if let Some((markup, file)) = app.review.attach.take() { + if app.file_picker.is_some() { + app.review.attach = Some((markup, file)); + } else { + write(app, "markup.image", json!({"markup": markup, "file": file})); + } + } + ctx.request_repaint_after(std::time::Duration::from_secs_f64(STAMP_POLL * 2.0)); +} + +/// List the set. A read: it goes straight to the engine, so a refusal is said in the list, not as a +/// message each time it is asked. +fn list(app: &mut SolveApp) { + match app.session.execute("markup.list", &json!({})) { + Ok(v) => match serde_json::from_value::(v) { + Ok(mut l) => { + l.markups.sort_by_key(|m| std::cmp::Reverse(m.id)); + if app.review.chosen.is_some_and(|id| !l.markups.iter().any(|m| m.id == id)) { + app.review.chosen = None; + } + app.review.listing = Some(l); + app.review.error = None; + } + Err(e) => app.review.error = Some(e.to_string()), + }, + Err(e) => app.review.error = Some(e.to_string()), + } +} + +/// Run a `markup.*` write as this window's person; its refusal is said like any command's. +fn write(app: &mut SolveApp, id: &str, mut params: Value) -> Option { + if let Some(p) = params.as_object_mut() { + p.insert("by".into(), Value::String(me())); + } + let r = app.run(id, params).ok(); + app.review.stale = true; + r +} + +/// M while Review is on: mark what the pointer is on. Returns whether it took the key. +pub(crate) fn take_key(app: &mut SolveApp, key: &str) -> bool { + if key != "M" || !app.review.open || set_of(app).is_none() || crate::render_workspace::active(app) { + return false; + } + let Some(rect) = app.viewport.rect else { return false }; + match app.review.pointer.or(app.viewport.mouse).filter(|p| rect.contains(*p) && !crate::shell::covered(app, *p)) { + Some(at) => mark_at(app, rect, at), + // Over a card or a panel: M is Mark this, and the next click on the model places the pin. + None => start_placing(app), + } + true +} + +/// A new markup's draft on what is under `at` (a face or an edge of a solid; else the view). +pub(crate) fn mark_at(app: &mut SolveApp, rect: Rect, at: Pos2) { + let proj = crate::viewport::projection(app, rect); + let hit = crate::viewport::pick(app, &proj, at).into_iter().find_map(|h| match h { + crate::viewport::Hit::Face { body, point, .. } | crate::viewport::Hit::Vertex { body, point } => Some((body, None, point)), + crate::viewport::Hit::Edge { body, index, point, .. } => Some((body, Some(index), point)), + _ => None, + }); + let (body, edge, at) = match hit { + Some((b, e, p)) => { + let edge = e.and_then(|i| edge_name(app, &b, i)); + (Some(b), edge, Some(p)) + } + None => (None, None, None), + }; + app.review.draft = Some(Draft { at, body, edge, view: view_now(app), text: String::new() }); + app.review.chosen = None; + app.review.placing = false; + app.review.ask = None; +} + +/// The lasting name of edge `index` of the body `body`, as `markup.add` takes it. +fn edge_name(app: &SolveApp, body: &str, index: usize) -> Option { + let st = app.session.world_state().ok()?; + let b = st.body(body)?; + solidcraft_engine::doc::naming::edge_names(b).get(index).filter(|n| !n.is_empty()).cloned() +} + +/// The body a markup names, else the one body its feature made (renamed since), as +/// `markup.list` finds it. +fn body_of<'a>(st: &'a solidcraft_engine::doc::ModelState, row: &Row) -> Option<&'a solidcraft_engine::doc::ModelBody> { + let name = row.text_of("body"); + st.body(&name).filter(|b| !b.body.is_mesh()).or_else(|| { + let maker = row.anchor.get("maker").and_then(Value::as_u64).filter(|m| *m != 0)?; + let mut made = st.bodies.iter().filter(|b| b.feature == maker && !b.body.is_mesh()); + match (made.next(), made.next()) { + (Some(b), None) => Some(b), + _ => None, + } + }) +} + +/// The camera now, as a markup keeps it: angles in degrees. +fn view_now(app: &SolveApp) -> Value { + let c = app.cam; + json!({"target": [c.target.x, c.target.y, c.target.z], "yaw": c.yaw.to_degrees(), "pitch": c.pitch.to_degrees(), + "distance": c.distance, "fov": app.view_fov().to_degrees()}) +} + +/// Go there: the camera the markup was marked from, else the same view turned onto its place. +fn go_there(app: &mut SolveApp, row: &Row) { + go_to(app, row.view.map(Seen::in_radians), row.place()); +} + +/// The camera `view`, else the same view turned onto `place`. +fn go_to(app: &mut SolveApp, view: Option, place: Option) { + let mut to = app.cam; + if let Some(v) = view { + to.target = Vec3::new(v.target[0], v.target[1], v.target[2]); + to.yaw = v.yaw; + to.pitch = v.pitch; + to.roll = 0.0; + to.distance = v.distance; + } else if let Some(p) = place { + to.target = p; + } else { + return; + } + app.animate_to(to); +} + +/// Select what the markup is on: the body found as `markup.list` finds it, so a renamed body +/// still selects. +fn select(app: &mut SolveApp, row: &Row) { + let at = row.place().map_or(json!(null), |p| json!([p.x, p.y, p.z])); + let item = match row.kind() { + kind @ ("face" | "edge" | "body") => { + let Ok(st) = app.session.world_state() else { return }; + let Some(b) = body_of(&st, row) else { return }; + let body = b.name.clone(); + match kind { + "face" => { + let name = row.text_of("face"); + let names = solidcraft_engine::doc::naming::face_names(b); + let Some(index) = names.iter().position(|n| !n.is_empty() && solidcraft_engine::doc::persistent_name::same_face(n, &name)) else { + return; + }; + json!({"type": "face", "body": body, "index": index, "point": at}) + } + // The edge by its point on it: of several edges with one name, the one marked. + "edge" if !at.is_null() => json!({"type": "edge", "body": body, "point": at}), + _ => json!({"type": "body", "name": body}), + } + } + "feature" => json!({"type": "feature", "id": row.anchor.get("feature").cloned().unwrap_or(Value::Null)}), + _ => return, + }; + let _ = app.run("select.set", json!({"items": [item]})); +} + +/// Words for what a markup is on. +pub(crate) fn on_words(app: &SolveApp, row: &Row) -> String { + let feature = row.maker().and_then(|id| app.session.doc.feature(id)).map(|f| f.name.clone()); + let body = row.text_of("body"); + match (row.kind(), feature) { + ("face", Some(f)) => fmt("review.on_face_by", &[("feature", &f), ("body", &body)]), + ("face", None) => fmt("review.on_face", &[("body", &body)]), + ("edge", _) => fmt("review.on_edge", &[("body", &body)]), + ("body", _) => body, + ("feature", f) => fmt("review.on_feature", &[("name", &f.unwrap_or_else(|| row.text_of("name")))]), + ("occurrence", _) => fmt("review.on_component", &[("name", &row.text_of("name"))]), + ("point", _) => solidcraft_ui_text::tr("review.on_point").to_owned(), + _ => solidcraft_ui_text::tr("review.on_view").to_owned(), + } +} + +fn fmt(id: &str, args: &[(&str, &str)]) -> String { + solidcraft_ui_text::format(id, args) +} + +/// "5 min ago", from Unix seconds. +fn ago(at: u64) -> String { + let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map_or(at, |d| d.as_secs()); + let s = now.saturating_sub(at); + let n = |v: u64| v.to_string(); + if s < 60 { + solidcraft_ui_text::tr("review.ago_now").to_owned() + } else if s < 3600 { + fmt("review.ago_minutes", &[("n", &n(s / 60))]) + } else if s < 86_400 { + fmt("review.ago_hours", &[("n", &n(s / 3600))]) + } else { + fmt("review.ago_days", &[("n", &n(s / 86_400))]) + } +} + +/// A row's second line in the list. +fn row_line(app: &SolveApp, row: &Row) -> (String, bool) { + match (row.look(), &row.outcome) { + (Look::Done, Some(o)) => (fmt("review.done_by", &[("by", &o.by), ("reason", &o.reason)]), false), + (Look::Rejected, Some(o)) => (fmt("review.rejected_why", &[("reason", &o.reason)]), false), + (Look::Gone, _) => (solidcraft_ui_text::tr("review.gone_line").to_owned(), true), + (Look::Hidden, _) => (solidcraft_ui_text::tr("review.hidden_line").to_owned(), false), + _ => { + let mut words = vec![on_words(app, row)]; + let replies = row.thread.len().saturating_sub(1); + if replies == 1 { + words.push(solidcraft_ui_text::tr("review.one_reply").to_owned()); + } else if replies > 1 { + words.push(fmt("review.replies", &[("count", &replies.to_string())])); + } + match row.images.len() { + 0 => {} + 1 => words.push(solidcraft_ui_text::tr("review.one_picture").to_owned()), + n => words.push(fmt("review.pictures", &[("count", &n.to_string())])), + } + (words.join(" · "), false) + } + } +} + +/// A pin's colour: theme tokens only. +pub(crate) fn colour(look: Look, chosen: bool) -> Color32 { + let t = Tokens::get(); + if chosen { + return t.accent; + } + match look { + Look::Open => t.warning, + Look::Gone => t.error, + Look::Done => t.form_success, + Look::Rejected => t.text_dim, + Look::Hidden => t.text_dim.gamma_multiply(0.45), + } +} + +/// A teardrop with its tip at `tip`: a round head of radius `r` and two straight sides tangent to it, +/// as one convex outline. +pub(crate) fn teardrop(tip: Pos2, r: f32) -> Vec { + let d = r * 1.65; + let c = tip - vec2(0.0, d); + // The sides touch the head where the radius makes a right angle with the line from the tip. + let half = (r / d).clamp(-1.0, 1.0).acos(); + let down = std::f32::consts::FRAC_PI_2; + let (from, to) = (down + half, down - half + std::f32::consts::TAU); + let steps = 28; + let mut points = Vec::with_capacity(steps + 2); + points.push(tip); + for i in 0..=steps { + let a = from + (to - from) * i as f32 / steps as f32; + points.push(c + vec2(a.cos(), a.sin()) * r); + } + points +} + +/// The middle of a teardrop's head. +fn head(tip: Pos2, r: f32) -> Pos2 { + tip - vec2(0.0, r * 1.65) +} + +/// Paint one pin: its teardrop, then a number, a tick or a cross on its head. +pub(crate) fn paint_pin(painter: &egui::Painter, tip: Pos2, r: f32, fill: Color32, look: Look, number: Option, ring: bool) { + let t = Tokens::get(); + let ink = t.on_accent; + if ring { + painter.circle_stroke(tip, r * 0.7, Stroke::new(2.5, fill)); + } + painter.add(Shape::convex_polygon(teardrop(tip, r), fill, Stroke::new(2.0, ink))); + let c = head(tip, r); + let w = Stroke::new((r * 0.2).max(1.5), ink); + match look { + Look::Done => { + painter.line(vec![c + vec2(-0.42 * r, 0.0), c + vec2(-0.12 * r, 0.32 * r), c + vec2(0.45 * r, -0.36 * r)], w); + } + Look::Rejected => { + let k = 0.36 * r; + painter.line_segment([c + vec2(-k, -k), c + vec2(k, k)], w); + painter.line_segment([c + vec2(k, -k), c + vec2(-k, k)], w); + } + _ => { + if let Some(n) = number { + let size = if n >= 100 { r * 0.75 } else { r * 0.95 }; + painter.text(c, egui::Align2::CENTER_CENTER, n.to_string(), crate::ui_kit::type_face::bold(size), ink); + } + } + } +} + +/// Where the card stands: beside its pin (left of it when there is room, else right), inside the view +/// and clear of the list; with no pin on the screen, beside the list. +pub(crate) fn card_place(view: Rect, list: Option, size: Vec2, spot: Option) -> Pos2 { + let gap = 18.0; + let room = match list { + Some(l) if l.left() > view.left() => Rect::from_min_max(view.min, pos2(l.left() - gap / 2.0, view.bottom())), + _ => view, + }; + let (x, y) = match spot { + Some(p) => { + let left = p.x - gap - size.x; + let x = if left >= room.left() { left } else { p.x + gap }; + (x, p.y - size.y * 0.35) + } + None => match list { + Some(l) => (l.left() - gap - size.x, l.top()), + None => (room.left() + gap, room.top() + gap), + }, + }; + let x = x.clamp(room.left() + 4.0, (room.right() - size.x - 4.0).max(room.left() + 4.0)); + let y = y.clamp(room.top() + 4.0, (room.bottom() - size.y - 4.0).max(room.top() + 4.0)); + pos2(x, y) +} + +/// Draw the review over the view: pins, Mark this, the list and the card. Called with the view's rect, +/// after the view took its input. +pub(crate) fn show(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) { + if !app.review.open || crate::render_workspace::active(app) || !rect.is_positive() { + app.review.drawn = Drawn::default(); + return; + } + let ctx = ui.ctx().clone(); + if (app.review.draft.is_some() || app.review.placing) && ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + app.review.draft = None; + app.review.placing = false; + } + if app.review.shot.is_some_and(|s| crate::now_ms() > s.until) { + app.review.shot = None; + } + let shooting = app.review.shot.is_some(); + let proj = crate::viewport::projection(app, rect); + let spots = pins(app, ui, &proj, rect); + if app.review.placing { + let r = ui.interact(rect, Id::unique("sc_review_place"), Sense::click()); + if r.clicked() + && let Some(at) = r.interact_pointer_pos() + { + mark_at(app, rect, at); + } + ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); + } + let mut drawn = Drawn::default(); + if shooting { + app.review.drawn = drawn; + return; + } + drawn.mark = mark_button(app, ui, rect); + drawn.list = review_list(app, &ctx, rect); + let spot = match (&app.review.draft, app.review.chosen) { + (Some(d), _) => d.at.and_then(|p| proj.to_screen(p)).filter(|p| rect.contains(*p)), + (None, Some(id)) => spots.iter().find(|(m, _)| *m == id).map(|(_, p)| *p), + _ => None, + }; + if app.review.draft.is_some() || app.review.chosen_row().is_some() { + drawn.card = card(app, &ctx, rect, drawn.list, spot); + } + app.review.drawn = drawn; +} + +/// The pins on the model, and the one clicked chosen. Returns each drawn pin's tip on the screen. +fn pins(app: &mut SolveApp, ui: &mut egui::Ui, proj: &crate::viewport::Proj, rect: Rect) -> Vec<(u64, Pos2)> { + let painter = ui.painter_at(rect); + let r = 11.0; + let mut spots = Vec::new(); + let mut clicked = None; + if !app.review.pins_hidden { + let filter = app.review.filter; + let chosen = app.review.chosen; + let mut rows: Vec<&Row> = app.review.rows().iter().filter(|m| filter.keeps(m) || Some(m.id) == chosen).collect(); + // Oldest first, the chosen last: newer pins and the chosen one stand in front. + rows.sort_by_key(|m| (Some(m.id) == chosen, m.id)); + for m in rows { + let Some(tip) = m.place().and_then(|p| proj.to_screen(p)).filter(|p| rect.contains(*p)) else { continue }; + let on = Some(m.id) == chosen; + let size = if on { r * 1.25 } else { r }; + paint_pin(&painter, tip, size, colour(m.look(), on), m.look(), Some(m.id), on); + let hit = Rect::from_center_size(head(tip, size), Vec2::splat(size * 2.4)); + solidcraft_ui_registry::publish_handle(&format!("review:pin:{}", m.id), head(tip, size)); + let resp = ui.interact(hit, Id::unique(("sc_review_pin", m.id)), Sense::click()); + if resp.clicked() { + clicked = Some(m.id); + } + resp.backing_on_hover_text(m.note.lines().next().unwrap_or("")); + spots.push((m.id, tip)); + } + } + if let Some(d) = &app.review.draft + && let Some(tip) = d.at.and_then(|p| proj.to_screen(p)).filter(|p| rect.contains(*p)) + { + paint_pin(&painter, tip, r * 1.25, Tokens::get().accent, Look::Open, None, true); + } + if let Some(id) = clicked { + choose(app, id); + } + spots +} + +fn choose(app: &mut SolveApp, id: u64) { + if app.review.chosen != Some(id) { + app.review.reply.clear(); + app.review.ask = None; + } + app.review.chosen = Some(id); + app.review.draft = None; + app.review.placing = false; +} + +/// Mark this, just left of the navigation bar (or at the bottom middle of the view without it). +fn mark_button(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) -> Option { + let t = Tokens::get(); + let label = app.tr("review.mark").to_owned(); + let font = crate::ui_kit::type_face::semibold(t.font_body); + let text_w = ui.fonts_mut(|f| f.layout_no_wrap(label.clone(), font.clone(), t.on_accent).size().x); + let size = vec2(text_w + 76.0, 34.0); + let nav = app.viewport.layout.as_ref().map(|l| l.navigation).filter(|n| n.is_positive()); + let min = match nav { + Some(n) => pos2(n.left() - t.space_8 - size.x, n.center().y - size.y / 2.0), + None => pos2(rect.center().x - size.x / 2.0, rect.bottom() - size.y - t.space_12), + }; + let button = Rect::from_min_size(pos2(min.x.max(rect.left() + t.space_8), min.y), size); + if !rect.contains_rect(button) { + return None; + } + let can = set_of(app).is_some(); + let resp = ui.interact(button, Id::unique("sc_review_mark"), if can { Sense::click() } else { Sense::hover() }); + solidcraft_ui_registry::publish_handle("review:mark", button.center()); + let painter = ui.painter_at(rect); + let fill = if !can { + t.text_dim + } else if app.review.placing || resp.hovered() { + t.accent.gamma_multiply(0.85) + } else { + t.accent + }; + painter.rect_filled(button, f32::from(t.control_radius), fill); + let pin = button.left_center() + vec2(18.0, 8.0); + painter.add(Shape::convex_polygon(teardrop(pin, 6.5), t.on_accent, Stroke::NONE)); + painter.circle_filled(head(pin, 6.5), 2.2, fill); + painter.text(button.left_center() + vec2(32.0, 0.0), egui::Align2::LEFT_CENTER, &label, font, t.on_accent); + let chip = Rect::from_center_size(button.right_center() - vec2(20.0, 0.0), vec2(22.0, 20.0)); + painter.rect_stroke(chip, 4.0, Stroke::new(1.0, t.on_accent.gamma_multiply(0.8)), egui::StrokeKind::Inside); + painter.text(chip.center(), egui::Align2::CENTER_CENTER, "M", crate::ui_kit::type_face::medium(t.font_small), t.on_accent); + let tip = if can { app.tr("review.mark_tip") } else { app.tr("review.unsaved") }; + let resp = resp.backing_on_hover_text(tip); + if resp.clicked() { + if app.review.placing { + app.review.placing = false; + } else { + start_placing(app); + } + } + Some(button) +} + +/// Mark this: the next click on the model places the new markup's pin. +fn start_placing(app: &mut SolveApp) { + app.review.placing = true; + app.review.draft = None; + app.review.chosen = None; + let hint = app.tr("review.placing").to_owned(); + app.set_status(hint, false); +} + +/// The Review list along the right of the view, below the view navigator. +fn review_list(app: &mut SolveApp, ctx: &egui::Context, rect: Rect) -> Option { + let t = Tokens::get(); + let axis = crate::viewport::axis_rect(app, rect); + let top = + if axis.is_positive() && axis.right() > rect.right() - LIST_WIDTH - t.space_8 { axis.bottom() + t.space_8 } else { rect.top() + t.space_8 }; + let nav_top = app.viewport.layout.as_ref().map(|l| l.navigation).filter(|n| n.is_positive()).map_or(rect.bottom(), |n| n.top()); + let bottom = (nav_top - t.space_8).max(top + 120.0).min(rect.bottom() - t.space_8); + let bounds = Rect::from_min_max(pos2(rect.right() - LIST_WIDTH - t.space_8, top), pos2(rect.right() - t.space_8, bottom)); + if !bounds.is_positive() || bounds.width() < 200.0 { + return None; + } + let container = Container::floating_card(Surface::Panel); + let mut chose = None; + let mut close = false; + let shown = + container.area(Id::unique("sc_review_list")).movable(false).order(egui::Order::Middle).fixed_pos(bounds.min).constrain_to(bounds).show( + ctx, + |ui| { + let frame = container.frame(ctx, t.dialog_body, crate::frame::Side::Right).inner_margin(t.space_8); + container + .show_frame(ui, frame, bounds, |ui| { + ui_kit::scope(ui, |ui| { + ui.set_width(LIST_WIDTH - 2.0 * t.space_8 - 2.0); + ui.set_max_height(bounds.height() - 2.0 * t.space_8); + list_head(app, ui, &mut close); + list_filters(app, ui); + ui.add_space(t.space_4); + chose = list_rows(app, ui); + ui.add_space(t.space_4); + ui.add(egui::Label::new(RichText::new(app.tr("review.hint")).color(t.text_dim).size(t.font_small)).wrap()); + }) + }) + .response + .rect + }, + ); + if let Some(id) = chose { + if app.review.chosen == Some(id) { + app.review.chosen = None; + } else { + choose(app, id); + } + } + if close { + let _ = app.run("view.review", json!({"visible": false})); + } + solidcraft_ui_registry::publish_rect("review:list", shown.inner); + Some(shown.inner) +} + +fn list_head(app: &mut SolveApp, ui: &mut egui::Ui, close: &mut bool) { + let t = Tokens::get(); + ui.horizontal(|ui| { + ui.label(RichText::new(app.tr("review.title")).strong().size(t.font_subtitle).color(t.text)); + let (words, bad) = match (&app.review.error, set_of(app)) { + (Some(_), _) => (app.tr("review.not_read").to_owned(), true), + (None, None) => (app.tr("review.no_file").to_owned(), false), + (None, Some(_)) if cfg!(target_arch = "wasm32") => (app.tr("review.in_browser").to_owned(), false), + (None, Some(_)) => (app.tr("review.saved").to_owned(), false), + }; + let r = ui.label(RichText::new(words).size(t.font_small).color(if bad { t.error } else { t.text_dim })); + if let Some(e) = &app.review.error { + r.backing_on_hover_text(e); + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let x = small_icon(ui, "close", app.tr("review.close")); + solidcraft_ui_registry::publish_handle("review:close", x.rect.center()); + if x.clicked() { + *close = true; + } + let eye = if app.review.pins_hidden { "suppress" } else { "eye" }; + let tip = if app.review.pins_hidden { app.tr("review.show_pins") } else { app.tr("review.hide_pins") }; + let e = small_icon(ui, eye, tip); + solidcraft_ui_registry::publish_handle("review:eye", e.rect.center()); + if e.clicked() { + app.review.pins_hidden = !app.review.pins_hidden; + } + }); + }); +} + +fn list_filters(app: &mut SolveApp, ui: &mut egui::Ui) { + let [open, done, rejected] = app.review.counts(); + let all = open + done + rejected; + ui.horizontal_wrapped(|ui| { + for (f, key, n, handle) in [ + (Filter::All, "review.filter_all", all, "all"), + (Filter::Open, "review.filter_open", open, "open"), + (Filter::Done, "review.filter_done", done, "done"), + (Filter::Rejected, "review.filter_rejected", rejected, "rejected"), + ] { + let on = app.review.filter == f; + let label = fmt(key, &[("count", &n.to_string())]); + let b = ui_kit::button(ui, label, if on { ui_kit::Button::SmallSelected } else { ui_kit::Button::Small }); + solidcraft_ui_registry::publish_handle(&format!("review:filter:{handle}"), b.rect.center()); + if b.clicked() { + app.review.filter = f; + } + } + }); +} + +/// The rows, newest first; returns the one clicked. +fn list_rows(app: &mut SolveApp, ui: &mut egui::Ui) -> Option { + let t = Tokens::get(); + let filter = app.review.filter; + let rows: Vec = app.review.rows().iter().filter(|m| filter.keeps(m)).cloned().collect(); + if rows.is_empty() { + ui.add(egui::Label::new(RichText::new(app.tr("review.empty")).color(t.text_dim).size(t.font_small)).wrap()); + return None; + } + let mut clicked = None; + let max = (ui.max_rect().bottom() - ui.cursor().top() - 40.0).max(80.0); + egui::ScrollArea::vertical().max_height(max).auto_shrink([false, true]).show(ui, |ui| { + for m in &rows { + let on = app.review.chosen == Some(m.id); + let (line, bad) = row_line(app, m); + let width = ui.available_width(); + let height = 48.0; + let (row, resp) = ui.allocate_exact_size(vec2(width, height), Sense::click()); + solidcraft_ui_registry::publish_handle(&format!("review:row:{}", m.id), row.center()); + let p = ui.painter(); + if on { + p.rect(row, f32::from(t.control_radius), t.accent_soft, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + } else if resp.hovered() { + p.rect_filled(row, f32::from(t.control_radius), t.hover); + } + let look = m.look(); + paint_pin(p, row.left_center() + vec2(14.0, 12.0), 7.5, colour(look, on), look, None, false); + let first = m.note.lines().next().unwrap_or("").to_owned(); + let text_left = row.left() + 32.0; + let room = row.right() - 8.0 - text_left; + let head = one_line(p, format!("{} · {first}", m.id), crate::ui_kit::type_face::semibold(t.font_label), t.text, room); + p.galley(pos2(text_left, row.top() + 15.0 - head.size().y / 2.0), head, t.text); + let tone = if bad { t.error } else { t.text_dim }; + let sub = one_line(p, line, crate::ui_kit::type_face::medium(t.font_small), tone, room); + p.galley(pos2(text_left, row.top() + 33.0 - sub.size().y / 2.0), sub, tone); + if resp.clicked() { + clicked = Some(m.id); + } + } + }); + clicked +} + +/// The card beside the chosen pin, or the new markup's card. +fn card(app: &mut SolveApp, ctx: &egui::Context, view: Rect, list: Option, spot: Option) -> Option { + let t = Tokens::get(); + let size = app.review.drawn.card.map_or(vec2(CARD_WIDTH, 380.0), |r| r.size()); + let at = card_place(view, list, size, spot); + let container = Container::new(ctx, Surface::Canvas); + let bounds = view; + let mut out = None; + let shown = + container.area(Id::unique("sc_review_card")).movable(false).order(egui::Order::Middle).fixed_pos(at).constrain_to(bounds).show(ctx, |ui| { + let frame = container.frame(ctx, t.dialog_body, crate::frame::Side::Left).inner_margin(t.space_8); + container + .show_frame(ui, frame, bounds, |ui| { + ui_kit::scope(ui, |ui| { + ui.set_width(CARD_WIDTH - 2.0 * t.space_8); + ui.set_max_height((view.height() - 16.0).max(200.0)); + if app.review.draft.is_some() { + out = new_card(app, ui); + } else if let Some(row) = app.review.chosen_row().cloned() { + out = read_card(app, ui, &row); + } + }) + }) + .response + .rect + }); + match out { + Some(Do::Close) => { + app.review.chosen = None; + app.review.draft = None; + } + Some(Do::Add) => add(app), + Some(Do::Run(id, params)) => { + write(app, &id, params); + app.review.ask = None; + app.review.reply.clear(); + } + Some(Do::Delete(id)) => { + if write(app, "markup.delete", json!({"markup": id})).is_some() { + app.review.chosen = None; + } + app.review.ask = None; + } + Some(Do::GoThere(row)) => go_there(app, &row), + Some(Do::Select(row)) => select(app, &row), + Some(Do::Edit(id)) => app.edit_feature(id), + Some(Do::Shoot(id)) => shoot(app, ctx, view, id), + Some(Do::Attach(id)) => attach(app, id), + None => {} + } + solidcraft_ui_registry::publish_rect("review:card", shown.inner); + Some(shown.inner) +} + +/// What a card's press asks for, done after the card is drawn. +enum Do { + Close, + Add, + Run(String, Value), + Delete(u64), + GoThere(Box), + Select(Box), + Edit(u64), + Shoot(u64), + Attach(u64), +} + +/// A note box: the growing message field, or a plain area where that is not built (the browser). +fn note_box(ui: &mut egui::Ui, id: Id, text: &mut String, hint: &str) -> egui::Response { + #[cfg(not(target_arch = "wasm32"))] + { + ui_kit::message_field(ui, id, text, hint) + } + #[cfg(target_arch = "wasm32")] + { + ui_kit::text_area(ui, hint, id, text, 3, solidcraft_engine::io::markups::MAX_NOTE) + } +} + +/// The status as a pill: its words in the status colour on a faint wash of it. +fn pill(ui: &mut egui::Ui, words: &str, tone: Color32) { + let t = Tokens::get(); + let galley = ui.painter().layout_no_wrap(words.to_owned(), crate::ui_kit::type_face::semibold(t.font_small), tone); + let (rect, _) = ui.allocate_exact_size(galley.size() + vec2(14.0, 6.0), Sense::hover()); + ui.painter().rect_filled(rect, rect.height() / 2.0, tone.gamma_multiply(0.18)); + ui.painter().galley(rect.center() - galley.size() / 2.0, galley, tone); +} + +/// One line of text cut with … to `width`. +fn one_line(painter: &egui::Painter, text: String, font: egui::FontId, colour: Color32, width: f32) -> Arc { + let mut job = egui::text::LayoutJob::single_section(text, egui::TextFormat::simple(font, colour)); + job.wrap = egui::text::TextWrapping { max_width: width, max_rows: 1, break_anywhere: true, overflow_character: Some('…') }; + painter.layout_job(job) +} + +/// A quiet icon button the size of a line of text, with its hover words. +fn small_icon(ui: &mut egui::Ui, icon: &str, label: &str) -> egui::Response { + let side = ui.spacing().interact_size.y; + let (rect, _) = ui.allocate_exact_size(vec2(side, side), Sense::hover()); + ui_kit::quiet_icon_button_at(ui, rect, icon, label) +} + +fn card_head(ui: &mut egui::Ui, status: &str, tone: Color32, title: &str, out: &mut Option) { + let t = Tokens::get(); + ui.horizontal(|ui| { + pill(ui, status, tone); + ui.label(RichText::new(title).strong().size(t.font_body).color(t.text)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let x = small_icon(ui, "close", solidcraft_ui_text::tr("ui.close")); + solidcraft_ui_registry::publish_handle("review:card:close", x.rect.center()); + if x.clicked() { + *out = Some(Do::Close); + } + }); + }); +} + +fn new_card(app: &mut SolveApp, ui: &mut egui::Ui) -> Option { + let t = Tokens::get(); + let mut out = None; + let mut draft = app.review.draft.clone()?; + let on = match (&draft.body, draft.at) { + (Some(b), _) if draft.edge.is_some() => fmt("review.on_edge", &[("body", b)]), + (Some(b), _) => b.clone(), + (None, Some(_)) => app.tr("review.on_point").to_owned(), + (None, None) => app.tr("review.on_view").to_owned(), + }; + card_head(ui, app.tr("review.new"), t.accent, &on, &mut out); + ui.add_space(t.space_4); + let id = Id::unique("sc_review_note"); + let field = note_box(ui, id, &mut draft.text, app.tr("review.note_hint")); + solidcraft_ui_registry::publish_handle("review:note", field.rect.center()); + if !field.has_focus() && draft.text.is_empty() && !ui.memory(|m| m.has_focus(id)) { + field.request_focus(); + } + ui.add_space(t.space_4); + ui.horizontal(|ui| { + let can = !draft.text.trim().is_empty(); + let add = ui.add_enabled_ui(can, |ui| ui_kit::button(ui, app.tr("review.add"), ui_kit::Button::Primary)).inner; + solidcraft_ui_registry::publish_handle("review:add", add.rect.center()); + if add.clicked() { + out = Some(Do::Add); + } + let cancel = ui_kit::button(ui, app.tr("review.cancel"), ui_kit::Button::Normal); + solidcraft_ui_registry::publish_handle("review:cancel", cancel.rect.center()); + if cancel.clicked() { + out = Some(Do::Close); + } + }); + if let Some(d) = app.review.draft.as_mut() { + d.text = draft.text; + } + out +} + +fn add(app: &mut SolveApp) { + let Some(d) = app.review.draft.clone() else { return }; + let mut p = json!({"text": d.text.trim(), "view": d.view}); + if let Some(at) = d.at { + p["at"] = json!([at.x, at.y, at.z]); + } + if let Some(b) = &d.body { + p["body"] = json!(b); + } + if let Some(e) = &d.edge { + p["edge"] = json!(e); + } + let made = write(app, "markup.add", p.clone()).or_else(|| { + // What the pointer was on is not a solid body's face or edge (a mesh, a point in space): + // keep the place, else the view, rather than lose the note. + let mut p = p; + p.as_object_mut().map(|o| (o.remove("body"), o.remove("edge"))); + if d.body.is_some() { write(app, "markup.add", p) } else { None } + }); + if let Some(v) = made { + app.review.draft = None; + app.review.chosen = v.get("markup").and_then(Value::as_u64); + app.review.filter = if app.review.filter == Filter::All { Filter::All } else { Filter::Open }; + } +} + +fn read_card(app: &mut SolveApp, ui: &mut egui::Ui, row: &Row) -> Option { + let t = Tokens::get(); + let mut out = None; + let look = row.look(); + let (status, tone) = match look { + Look::Open => (app.tr("review.status_open"), t.warning), + Look::Gone => (app.tr("review.status_gone"), t.error), + Look::Done => (app.tr("review.status_done"), t.form_success), + Look::Rejected => (app.tr("review.status_rejected"), t.text_dim), + Look::Hidden => (app.tr("review.status_hidden"), t.text_dim), + }; + let title = format!("{} · {}", row.id, on_words(app, row)); + card_head(ui, status, tone, &title, &mut out); + ui.label(RichText::new(fmt("review.marked", &[("by", &row.by), ("ago", &ago(row.made))])).size(t.font_small).color(t.text_dim)); + match look { + Look::Gone => drop(ui.label(RichText::new(app.tr("review.gone_line")).size(t.font_small).color(t.error))), + Look::Hidden => drop(ui.label(RichText::new(app.tr("review.hidden_line")).size(t.font_small).color(t.text_dim))), + _ if row.found.state == "moved" => drop(ui.label(RichText::new(app.tr("review.moved_line")).size(t.font_small).color(t.text_dim))), + _ => {} + } + ui.add_space(t.space_4); + let thread_height = (ui.max_rect().height() * 0.45).max(90.0); + egui::ScrollArea::vertical().id_salt("sc_review_thread").max_height(thread_height).auto_shrink([false, true]).stick_to_bottom(true).show( + ui, + |ui| { + for said in &row.thread { + let fill = if said.reviewer { t.hover } else { t.accent_soft }; + let indent = if said.reviewer { 0.0 } else { t.space_12 }; + let width = ui.available_width() - indent - 12.0; + ui.horizontal_top(|ui| { + ui.add_space(indent); + let frame = + Container::new(ui.ctx(), Surface::Panel).edge_frame(fill).corner_radius(t.control_radius).inner_margin(egui::Margin::same(6)); + Container::show_backing(ui, frame, |ui| { + ui.vertical(|ui| { + ui.set_width(width); + let who = format!("{} · {}", said.by, ago(said.at)); + ui.label(RichText::new(who).size(t.font_small).strong().color(if said.reviewer { t.warning } else { t.accent })); + ui.add(egui::Label::new(RichText::new(&said.text).color(t.text)).wrap()); + }); + }); + }); + ui.add_space(t.space_2); + } + }, + ); + ui.add_space(t.space_4); + pictures(app, ui, row, &mut out); + ui.add_space(t.space_4); + let id = Id::unique(("sc_review_reply", row.id)); + let mut reply = std::mem::take(&mut app.review.reply); + let field = note_box(ui, id, &mut reply, app.tr("review.reply_hint")); + solidcraft_ui_registry::publish_handle("review:reply", field.rect.center()); + let send_key = field.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter) && !i.modifiers.shift); + if send_key { + // The Enter that sends is not part of the reply. + while reply.ends_with('\n') { + reply.pop(); + } + } + let send = ui.horizontal(|ui| { + let can = !reply.trim().is_empty(); + let b = ui.add_enabled_ui(can, |ui| ui_kit::button(ui, app.tr("review.send"), ui_kit::Button::Small)).inner; + solidcraft_ui_registry::publish_handle("review:send", b.rect.center()); + can && (b.clicked() || send_key) + }); + if send.inner { + out = Some(Do::Run("markup.reply".into(), json!({"markup": row.id, "text": reply.trim()}))); + } + app.review.reply = reply; + ui.add_space(t.space_4); + tools(app, ui, row, &mut out); + ui.add_space(t.space_4); + closing(app, ui, row, &mut out); + out +} + +/// Go there, Select, Edit and Delete. +fn tools(app: &mut SolveApp, ui: &mut egui::Ui, row: &Row, out: &mut Option) { + ui.horizontal_wrapped(|ui| { + let go = ui_kit::button(ui, app.tr("review.go_there"), ui_kit::Button::Small); + solidcraft_ui_registry::publish_handle("review:go_there", go.rect.center()); + if go.clicked() { + *out = Some(Do::GoThere(Box::new(row.clone()))); + } + if matches!(row.kind(), "face" | "edge" | "body" | "feature") && row.look() != Look::Gone && row.look() != Look::Hidden { + let s = ui_kit::button(ui, app.tr("review.select"), ui_kit::Button::Small); + solidcraft_ui_registry::publish_handle("review:select", s.rect.center()); + if s.clicked() { + *out = Some(Do::Select(Box::new(row.clone()))); + } + } + if let Some((id, name)) = row.maker().and_then(|id| app.session.doc.feature(id)).map(|f| (f.id, f.name.clone())) { + let e = ui_kit::button(ui, fmt("review.edit_feature", &[("name", &name)]), ui_kit::Button::Small); + solidcraft_ui_registry::publish_handle("review:edit", e.rect.center()); + if e.clicked() { + *out = Some(Do::Edit(id)); + } + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let d = ui_kit::button(ui, app.tr("review.delete"), ui_kit::Button::Ghost); + solidcraft_ui_registry::publish_handle("review:delete", d.rect.center()); + if d.clicked() { + app.review.ask = Some(Ask::Delete); + } + }); + }); +} + +/// Resolve… and Reject…, with their reason; Reopen for a closed one; and Delete's question. +fn closing(app: &mut SolveApp, ui: &mut egui::Ui, row: &Row, out: &mut Option) { + let t = Tokens::get(); + match app.review.ask.clone() { + Some(Ask::Delete) => { + ui.label(RichText::new(app.tr("review.delete_ask")).color(t.text)); + ui.horizontal(|ui| { + let yes = ui_kit::button(ui, app.tr("review.delete"), ui_kit::Button::DangerOutlined); + solidcraft_ui_registry::publish_handle("review:delete_yes", yes.rect.center()); + if yes.clicked() { + *out = Some(Do::Delete(row.id)); + } + if ui_kit::button(ui, app.tr("review.cancel"), ui_kit::Button::Normal).clicked() { + app.review.ask = None; + } + }); + } + Some(Ask::Resolve(mut why)) | Some(Ask::Reject(mut why)) => { + let resolving = matches!(app.review.ask, Some(Ask::Resolve(_))); + let hint = if resolving { app.tr("review.resolve_hint") } else { app.tr("review.reject_hint") }; + let field = note_box(ui, Id::unique(("sc_review_reason", row.id)), &mut why, hint); + solidcraft_ui_registry::publish_handle("review:reason", field.rect.center()); + ui.horizontal(|ui| { + let (label, command) = + if resolving { (app.tr("review.resolve_go"), "markup.resolve") } else { (app.tr("review.reject_go"), "markup.reject") }; + let can = !why.trim().is_empty(); + let go = ui.add_enabled_ui(can, |ui| ui_kit::button(ui, label, ui_kit::Button::Primary)).inner; + solidcraft_ui_registry::publish_handle("review:close_go", go.rect.center()); + if go.clicked() { + *out = Some(Do::Run(command.into(), json!({"markup": row.id, "reason": why.trim()}))); + } + if ui_kit::button(ui, app.tr("review.cancel"), ui_kit::Button::Normal).clicked() { + app.review.ask = None; + } + }); + if app.review.ask.is_some() { + app.review.ask = Some(if resolving { Ask::Resolve(why) } else { Ask::Reject(why) }); + } + } + None if row.status == "open" => { + ui.columns(2, |cols| { + let r = ui_kit::button(&mut cols[0], app.tr("review.resolve"), ui_kit::Button::Primary); + solidcraft_ui_registry::publish_handle("review:resolve", r.rect.center()); + if r.clicked() { + app.review.ask = Some(Ask::Resolve(String::new())); + } + let j = ui_kit::button(&mut cols[1], app.tr("review.reject"), ui_kit::Button::Normal); + solidcraft_ui_registry::publish_handle("review:reject", j.rect.center()); + if j.clicked() { + app.review.ask = Some(Ask::Reject(String::new())); + } + }); + } + None => { + let r = ui_kit::button(ui, app.tr("review.reopen"), ui_kit::Button::Normal); + solidcraft_ui_registry::publish_handle("review:reopen", r.rect.center()); + if r.clicked() { + *out = Some(Do::Run("markup.reopen".into(), json!({"markup": row.id}))); + } + } + } +} + +/// The pictures' small copies, with Screenshot and Attach image beside them. +fn pictures(app: &mut SolveApp, ui: &mut egui::Ui, row: &Row, out: &mut Option) { + let t = Tokens::get(); + ui.horizontal_wrapped(|ui| { + for (n, p) in row.images.iter().enumerate() { + let (rect, resp) = ui.allocate_exact_size(THUMB, Sense::click()); + match thumb(app, ui.ctx(), p) { + Some((tex, size)) => { + let fit = rect.center() - size / 2.0; + egui::Image::new(&tex).paint_at(ui, Rect::from_min_size(fit, size)); + } + None => { + ui.painter().rect_filled(rect, 6.0, t.panel); + } + } + ui.painter().rect_stroke(rect, 6.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + solidcraft_ui_registry::publish_handle(&format!("review:picture:{n}"), rect.center()); + resp.backing_on_hover_text(&p.name); + } + if row.images.len() < solidcraft_engine::io::markups::MAX_IMAGES { + let s = ui_kit::button(ui, app.tr("review.screenshot"), ui_kit::Button::Small).backing_on_hover_text(app.tr("review.screenshot_tip")); + solidcraft_ui_registry::publish_handle("review:screenshot", s.rect.center()); + if s.clicked() { + *out = Some(Do::Shoot(row.id)); + } + if cfg!(not(target_arch = "wasm32")) { + let a = ui_kit::button(ui, app.tr("review.attach"), ui_kit::Button::Small); + solidcraft_ui_registry::publish_handle("review:attach", a.rect.center()); + if a.clicked() { + *out = Some(Do::Attach(row.id)); + } + } + } + }); +} + +/// A picture's small copy as a texture, made once from the design's bytes (at most [`THUMBS`] +/// kept). +fn thumb(app: &mut SolveApp, ctx: &egui::Context, picture: &Picture) -> Option<(egui::TextureHandle, Vec2)> { + if !picture.in_design { + return None; + } + let path = picture.file.as_str(); + if let Some(kept) = app.review.thumbs.get(path) { + return kept.clone(); + } + if app.review.thumbs.len() >= THUMBS { + app.review.thumbs.clear(); + } + let made = app.session.doc.markup_images.get(path).and_then(|bytes| { + let img = image::load_from_memory(bytes).ok()?; + let small = img.thumbnail((THUMB.x * 2.0) as u32, (THUMB.y * 2.0) as u32).to_rgba8(); + let (w, h) = (small.width() as usize, small.height() as usize); + let pixels = ColorImage::from_rgba_unmultiplied([w, h], small.as_raw()); + let tex = ctx.load_texture(format!("review:{path}"), pixels, egui::TextureOptions::LINEAR); + let scale = (THUMB.x / w as f32).min(THUMB.y / h as f32); + Some((tex, vec2(w as f32, h as f32) * scale)) + }); + app.review.thumbs.insert(path.to_owned(), made.clone()); + made +} + +/// Screenshot: the view as it is, without the card and the list, a few frames on. +fn shoot(app: &mut SolveApp, ctx: &egui::Context, view: Rect, markup: u64) { + let Some(token) = app.shots.token.checked_add(1) else { return }; + app.shots.token = token; + app.shots.queued.push((token, crate::now_ms() + 150.0, 0)); + // The window's picture starts at its content's corner. + let view = view.translate(-ctx.content_rect().min.to_vec2()); + app.review.shot = Some(Shot { token, markup, view, scale: ctx.pixels_per_point(), until: crate::now_ms() + SHOT_WAIT_MS }); + ctx.request_repaint(); +} + +/// The window has a screenshot of its own waiting. +pub(crate) fn pending(app: &SolveApp) -> bool { + app.review.shot.is_some() +} + +/// A frame came: the one asked for is cut to the view and attached to its markup. +pub(crate) fn receive(app: &mut SolveApp, token: u64, image: Arc) { + let Some(shot) = app.review.shot.filter(|s| s.token == token) else { return }; + app.review.shot = None; + let cut = crate::issue_report::ticket::crop(&image, Some(shot.view), shot.scale); + let Some(png) = crate::issue_report::ticket::png(&cut) else { return }; + // The command takes a file: the picture goes through one in the temporary folder (in memory + // in the browser), and its bytes end up in the design. The name can't be guessed, and a link + // put there first is never followed. + let random = { + use std::hash::BuildHasher; + let seed = (crate::now_ms().to_bits(), token); + let a = std::collections::hash_map::RandomState::new().hash_one(seed); + let b = std::collections::hash_map::RandomState::new().hash_one((a, seed)); + format!("{a:016x}{b:016x}") + }; + let path = solidcraft_engine::io::vfs::temp_dir().join(format!("solidcraft-review-{random}-{token}.png")); + let file = path.to_string_lossy().to_string(); + if solidcraft_engine::io::safe_write::write_atomic_no_follow(&path, &png).is_ok() { + write(app, "markup.image", json!({"markup": shot.markup, "file": file, "name": "view.png"})); + let _ = solidcraft_engine::io::vfs::remove(&file); + } +} + +/// Attach image…: a PNG or JPEG from the disk. +fn attach(app: &mut SolveApp, markup: u64) { + let label = app.tr("review.pictures_label").to_owned(); + app.pick_file(&label, &["png", "jpg", "jpeg"], move |app, path| { + if let Some(path) = path { + app.review.attach = Some((markup, path)); + } + }); +} + +#[cfg(test)] +#[path = "review_pins_tests.rs"] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests; diff --git a/crates/ui-egui/src/review_pins_tests.rs b/crates/ui-egui/src/review_pins_tests.rs new file mode 100644 index 00000000000..c864b13eab1 --- /dev/null +++ b/crates/ui-egui/src/review_pins_tests.rs @@ -0,0 +1,362 @@ +//! Review pins in the running window: Mark this and M, the card, the list, a write by another +//! program, and the design and its undo history left alone. + +use super::*; +use crate::scenario::Harness; +use serde_json::json; + +/// A saved 40 × 30 × 10 box (so its markups have a file beside it), seen from Home, Review on. +fn reviewed_box() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 10})).unwrap(); + h.app.session.path = Some(h.dir.join("plate.sc").to_string_lossy().into_owned()); + h.app.run("view.home", json!({})).unwrap(); + h.frames(30); + h.app.run("view.review", json!({"visible": true})).unwrap(); + h.frames(3); + h +} + +/// The box's top face in the middle, on the screen. +fn top_middle(h: &Harness) -> Pos2 { + let st = h.app.session.world_state().unwrap(); + let b = st.bodies.first().unwrap().body.exact_bounds().unwrap(); + let c = b.center(); + let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + proj.to_screen(Vec3::new(c.x, c.y, b.max.z)).unwrap() +} + +fn listed(h: &Harness) -> Vec { + h.app.review.listing.as_ref().map(|l| l.markups.clone()).unwrap_or_default() +} + +/// Press M over `at`, write `note` and Add. +fn mark(h: &mut Harness, at: Pos2, note: &str) { + h.step(&json!({"move": [at.x, at.y]})).unwrap(); + h.step(&json!({"key": "M"})).unwrap(); + h.frames(3); + assert!(h.app.review.draft.is_some(), "M made no draft"); + h.app.review.draft.as_mut().unwrap().text = note.into(); + h.frames(2); + crate::test_support::click(h, "review:add"); + h.frames(3); +} + +#[test] +fn a_pin_is_convex_and_comes_to_a_point_at_its_tip() { + let tip = pos2(100.0, 200.0); + let pts = teardrop(tip, 12.0); + assert_eq!(pts[0], tip); + assert!(pts.iter().all(|p| p.y <= tip.y + 1e-3), "the tip is the lowest point"); + // Convex: every turn goes the same way. + let n = pts.len(); + let turns: Vec = (0..n) + .map(|i| { + let (a, b, c) = (pts[i], pts[(i + 1) % n], pts[(i + 2) % n]); + (b - a).x * (c - b).y - (b - a).y * (c - b).x + }) + .collect(); + assert!(turns.iter().all(|t| *t >= -1e-3) || turns.iter().all(|t| *t <= 1e-3), "{turns:?}"); + let top = pts.iter().map(|p| p.y).fold(f32::INFINITY, f32::min); + assert!((tip.y - top - 12.0 * 2.65).abs() < 0.5, "a head of radius 12 above a point 1.65 radii down"); +} + +#[test] +fn a_card_stands_beside_its_pin_inside_the_view_and_clear_of_the_list() { + let view = Rect::from_min_size(pos2(0.0, 0.0), vec2(1600.0, 900.0)); + let list = Some(Rect::from_min_max(pos2(1260.0, 120.0), pos2(1590.0, 700.0))); + let size = vec2(360.0, 400.0); + // Room on the left: the card is left of the pin. + let at = card_place(view, list, size, Some(pos2(800.0, 400.0))); + assert!(at.x + size.x <= 800.0 - 10.0, "{at:?}"); + // At the left edge it goes to the pin's right. + let at = card_place(view, list, size, Some(pos2(100.0, 400.0))); + assert!(at.x >= 100.0 + 10.0, "{at:?}"); + // It never covers the list. + let at = card_place(view, list, size, Some(pos2(1200.0, 400.0))); + assert!(at.x + size.x <= 1260.0, "{at:?}"); + // Near the bottom it keeps inside the view. + let at = card_place(view, list, size, Some(pos2(800.0, 880.0))); + assert!(at.y + size.y <= 900.0, "{at:?}"); + // No pin on the screen: beside the list, at its top. + let at = card_place(view, list, size, None); + assert!(at.x + size.x <= 1260.0 && (at.y - 120.0).abs() < 1.0, "{at:?}"); +} + +#[test] +fn m_marks_a_face_and_the_card_adds_it_without_touching_the_design() { + let mut h = reviewed_box(); + let (revision, undo, dirty) = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let selection = h.app.session.selection.clone(); + let at = top_middle(&h); + mark(&mut h, at, "Chamfer this edge 1 mm"); + let rows = listed(&h); + assert_eq!(rows.len(), 1, "{rows:?}"); + let m = &rows[0]; + assert_eq!(m.note, "Chamfer this edge 1 mm"); + assert_eq!(m.status, "open"); + assert_eq!(m.anchor["kind"], "face", "the face was found on the exact geometry: {}", m.anchor); + assert_eq!(m.found.state, "anchored"); + assert!(m.view.is_some(), "the view it was marked from is kept"); + assert_eq!(m.by, me()); + assert_eq!(h.app.review.chosen, Some(m.id), "its card stays open"); + assert!(crate::scenario::handle_at(&format!("review:pin:{}", m.id)).is_some(), "its pin is drawn"); + assert!(h.app.review.drawn.card.is_some() && h.app.review.drawn.list.is_some()); + assert_eq!(h.app.session.revision, revision, "the design did not change"); + assert_eq!(h.app.session.undo.len(), undo, "no undo step"); + assert_eq!(h.app.session.is_dirty(), dirty); + assert_eq!(h.app.session.selection, selection, "marking selects nothing"); + assert!(h.app.dialog.is_none() && h.app.tool.is_none(), "M did not start Move/Copy"); + // With the pointer over the open card, M is Mark this: no pin at a place the pointer is not + // over, and the next click on the model places it. + let card = h.app.review.drawn.card.unwrap(); + h.step(&json!({"move": [card.center().x, card.center().y]})).unwrap(); + h.step(&json!({"key": "M"})).unwrap(); + h.frames(2); + assert!(h.app.review.placing && h.app.review.draft.is_none(), "M over the card waits for a click on the model"); + let beside = at + vec2(30.0, 25.0); + h.step(&json!({"click": [beside.x, beside.y]})).unwrap(); + h.frames(3); + assert!(!h.app.review.placing && h.app.review.draft.as_ref().is_some_and(|d| d.at.is_some()), "the click placed the new pin"); +} + +/// A place on the screen where the first thing `pick` meets is wanted by `want`. +fn screen_where(h: &Harness, from: Vec3, to: Vec3, want: impl Fn(&crate::viewport::Hit) -> bool) -> Option { + let rect = h.app.viewport.rect.unwrap(); + let proj = crate::viewport::projection(&h.app, rect); + (1..20) + .filter_map(|i| proj.to_screen(from + (to - from) * (f64::from(i) / 20.0))) + .find(|p| rect.contains(*p) && !crate::shell::covered(&h.app, *p) && crate::viewport::pick(&h.app, &proj, *p).first().is_some_and(&want)) +} + +#[test] +fn an_edge_marks_an_edge_empty_space_marks_the_view_and_go_there_reads_degrees() { + let mut h = reviewed_box(); + h.app.preferences.look_at_anim = false; + let b = h.app.session.world_state().unwrap().bodies.first().unwrap().body.exact_bounds().unwrap(); + // The top front edge: an edge markup, and Select picks that edge, not its body. + let (front_left, front_right) = (Vec3::new(b.min.x, b.min.y, b.max.z), Vec3::new(b.max.x, b.min.y, b.max.z)); + let edge = + screen_where(&h, front_left, front_right, |hit| matches!(hit, crate::viewport::Hit::Edge { .. })).expect("the top front edge on the screen"); + mark(&mut h, edge, "Break this edge"); + let m = listed(&h).into_iter().max_by_key(|r| r.id).unwrap(); + assert_eq!(m.anchor["kind"], "edge", "{}", m.anchor); + assert_eq!(m.found.state, "anchored", "marked on the edge, found on it"); + select(&mut h.app, &m); + assert!(matches!(h.app.session.selection.as_slice(), [solidcraft_engine::Sel::Edge { .. }]), "{:?}", h.app.session.selection); + // Empty space with that edge still selected: the markup is on the view, as its card said. + let rect = h.app.viewport.rect.unwrap(); + let proj = crate::viewport::projection(&h.app, rect); + let empty = (1..10) + .flat_map(|i| (1..10).map(move |j| rect.min + vec2(rect.width() * i as f32 / 10.0, rect.height() * j as f32 / 10.0))) + .find(|p| !crate::shell::covered(&h.app, *p) && crate::viewport::pick(&h.app, &proj, *p).is_empty()) + .expect("empty space on the screen"); + mark(&mut h, empty, "This whole view"); + let v = listed(&h).into_iter().max_by_key(|r| r.id).unwrap(); + assert_eq!(v.anchor["kind"], "view", "{}", v.anchor); + // Its camera is kept in degrees, as the set's format says, and Go there turns back to it. + let was = h.app.cam; + let seen = v.view.unwrap(); + assert!((seen.yaw - was.yaw.to_degrees()).abs() < 1e-6 && (seen.pitch - was.pitch.to_degrees()).abs() < 1e-6, "{seen:?} {was:?}"); + h.app.cam.yaw += 1.0; + h.app.cam.pitch -= 0.3; + go_there(&mut h.app, &v); + assert!((h.app.cam.yaw - was.yaw).abs() < 1e-9 && (h.app.cam.pitch - was.pitch).abs() < 1e-9, "{:?} {was:?}", h.app.cam); +} + +#[test] +fn select_finds_a_renamed_body_and_a_lost_screenshot_frame_gives_the_list_back() { + let mut h = reviewed_box(); + let at = top_middle(&h); + mark(&mut h, at, "Thicker"); + let m = listed(&h).into_iter().max_by_key(|r| r.id).unwrap(); + let name = h.app.session.world_state().unwrap().bodies.first().unwrap().name.clone(); + h.app.run("body.rename", json!({"body": name, "name": "Lid"})).unwrap(); + h.frames(3); + h.app.run("select.clear", json!({})).unwrap(); + select(&mut h.app, &m); + assert!( + matches!(h.app.session.selection.as_slice(), [solidcraft_engine::Sel::Face { body, .. }] if body == "Lid"), + "{:?}", + h.app.session.selection + ); + // A screenshot whose frame never comes is given up, and the list and card come back. + let view = h.app.viewport.rect.unwrap(); + app_shoot(&mut h, view, m.id); + h.frames(1); + assert!(h.app.review.drawn.list.is_none(), "the list is hidden for the picture"); + h.app.shots.queued.clear(); + h.app.review.shot.as_mut().unwrap().until = crate::now_ms() - 1.0; + h.frames(2); + assert!(h.app.review.shot.is_none() && h.app.review.drawn.list.is_some(), "the list is back"); +} + +/// Ask the window for a Review screenshot, as Screenshot on the card does. +fn app_shoot(h: &mut Harness, view: Rect, markup: u64) { + let ctx = h.ctx.clone(); + shoot(&mut h.app, &ctx, view, markup); +} + +#[test] +fn cancel_and_esc_leave_nothing_in_the_set() { + let mut h = reviewed_box(); + let at = top_middle(&h); + h.step(&json!({"move": [at.x, at.y]})).unwrap(); + h.step(&json!({"key": "M"})).unwrap(); + h.frames(3); + crate::test_support::click(&mut h, "review:cancel"); + assert!(h.app.review.draft.is_none()); + h.step(&json!({"key": "M"})).unwrap(); + h.frames(2); + h.step(&json!({"key": "Escape"})).unwrap(); + h.frames(3); + assert!(h.app.review.draft.is_none()); + assert!(listed(&h).is_empty()); + let set = solidcraft_engine::io::markups::beside(h.app.session.path.as_deref().unwrap()); + assert!(!std::path::Path::new(&set).exists(), "no set file was made"); +} + +#[test] +fn a_pin_click_opens_its_card_and_selects_nothing_under_it() { + let mut h = reviewed_box(); + let at = top_middle(&h); + mark(&mut h, at, "Make it 12 mm thick"); + let id = listed(&h)[0].id; + crate::test_support::click(&mut h, "review:card:close"); + assert_eq!(h.app.review.chosen, None); + let selection = h.app.session.selection.clone(); + crate::test_support::click(&mut h, &format!("review:pin:{id}")); + assert_eq!(h.app.review.chosen, Some(id)); + assert_eq!(h.app.session.selection, selection, "the face under the pin was not picked"); +} + +#[test] +fn reply_resolve_and_reopen_from_the_card_and_an_agents_write_shows() { + let mut h = reviewed_box(); + let at = top_middle(&h); + mark(&mut h, at, "Round the outer corners R5"); + let id = listed(&h)[0].id; + h.app.review.reply = "Which corners?".into(); + h.frames(1); + crate::test_support::click(&mut h, "review:send"); + assert_eq!(listed(&h)[0].thread.len(), 2); + crate::test_support::click(&mut h, "review:resolve"); + match h.app.review.ask.as_mut() { + Some(Ask::Resolve(why)) => *why = "Fillet 2, 5 mm".into(), + other => panic!("{other:?}"), + } + h.frames(1); + crate::test_support::click(&mut h, "review:close_go"); + let m = &listed(&h)[0]; + assert_eq!(m.status, "resolved"); + assert_eq!(m.look(), Look::Done); + crate::test_support::click(&mut h, "review:reopen"); + assert_eq!(listed(&h)[0].status, "open"); + // Another program (an agent through the CLI) closes it on the disk: the window shows it. + let set = solidcraft_engine::io::markups::beside(h.app.session.path.as_deref().unwrap()); + let mut agent = solidcraft_engine::Session::default(); + agent.execute("markup.reject", &json!({"set": set, "markup": id, "reason": "It is a fillet already"})).unwrap(); + for _ in 0..90 { + h.frame(); + if listed(&h)[0].status == "rejected" { + break; + } + } + assert_eq!(listed(&h)[0].status, "rejected", "the window looked at the set again"); + assert_eq!(listed(&h)[0].outcome.as_ref().unwrap().by, "agent"); +} + +#[test] +fn the_filter_decides_the_pins_and_the_eye_hides_them() { + let mut h = reviewed_box(); + let at = top_middle(&h); + mark(&mut h, at, "First"); + let id = listed(&h)[0].id; + crate::test_support::click(&mut h, "review:card:close"); + let pin = format!("review:pin:{id}"); + assert!(crate::scenario::handle_at(&pin).is_some()); + crate::test_support::click(&mut h, "review:filter:done"); + assert!(crate::scenario::handle_at(&pin).is_none(), "an open pin is not drawn under Done"); + crate::test_support::click(&mut h, "review:filter:all"); + assert!(crate::scenario::handle_at(&pin).is_some()); + crate::test_support::click(&mut h, "review:eye"); + assert!(crate::scenario::handle_at(&pin).is_none(), "the eye hides every pin"); +} + +#[test] +fn a_pin_behind_the_history_marker_is_hidden_not_gone() { + let mut h = reviewed_box(); + let at = top_middle(&h); + mark(&mut h, at, "Thicker"); + h.app.run("timeline.rollback", json!({"position": 0})).unwrap(); + h.frames(5); + let m = &listed(&h)[0]; + assert_eq!(m.found.state, "hidden", "{:?}", m.found); + assert_eq!(m.look(), Look::Hidden); + assert!(m.place().is_some(), "a hidden pin stands where it was"); +} + +#[test] +fn with_review_off_m_is_move_and_with_no_file_it_marks_nothing() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 10})).unwrap(); + h.frames(5); + assert!(!take_key(&mut h.app, "M"), "Review is off: M stays Move/Copy's"); + h.app.run("view.review", json!({"visible": true})).unwrap(); + h.frames(3); + let status = h.app.status.clone(); + assert!(!take_key(&mut h.app, "M"), "an unsaved design has no set to mark in"); + h.frames(3); + assert!(h.app.review.draft.is_none()); + assert_eq!(h.app.status, status, "nothing is said each frame about the missing file"); + assert!(h.app.review.error.is_none()); + h.app.run("view.review", json!({})).unwrap(); + assert!(!h.app.review.open, "view.review with nothing toggles"); +} + +#[test] +fn a_screenshot_is_cut_to_the_view_and_attached() { + let mut h = reviewed_box(); + let at = top_middle(&h); + mark(&mut h, at, "Look here"); + let id = listed(&h)[0].id; + crate::test_support::click(&mut h, "review:screenshot"); + let shot = h.app.review.shot.expect("a frame was asked for"); + assert_eq!(shot.markup, id); + assert!(h.app.shots.queued.iter().any(|(t, ..)| *t == shot.token)); + h.frame(); + assert!(h.app.review.drawn.card.is_none() && h.app.review.drawn.list.is_none(), "the card and list are out of the picture"); + // The frame comes back (headless: one made here) and goes to its markup. + let image = Arc::new(ColorImage::filled([1600, 1000], Color32::from_rgb(40, 50, 60))); + receive(&mut h.app, shot.token, image); + h.frames(3); + assert!(h.app.review.shot.is_none()); + let m = &listed(&h)[0]; + assert_eq!(m.images.len(), 1, "{m:?}"); + assert!(m.images[0].in_design); + // The bytes are the design's entry, and the file they came through is gone. + let bytes = h.app.session.doc.markup_images[&m.images[0].file].as_bytes().to_vec(); + assert_eq!(solidcraft_engine::io::markups::image_kind(&bytes), Some("png")); + let temp = solidcraft_engine::io::vfs::temp_dir(); + let left = std::fs::read_dir(&temp).into_iter().flatten().flatten().any(|e| { + e.file_name().to_string_lossy().ends_with(&format!("-{}.png", shot.token)) + && e.file_name().to_string_lossy().starts_with("solidcraft-review-") + }); + assert!(!left, "the screenshot's passing file is removed"); + // Cut to the view: the window's own bar is left out. + let view = h.app.viewport.rect.unwrap(); + let picture = image::load_from_memory(&bytes).unwrap(); + assert!(picture.width().abs_diff((view.width() * shot.scale).round() as u32) <= 1, "{view:?} {}", picture.width()); + assert!(picture.height().abs_diff((view.height() * shot.scale).round() as u32) <= 1, "{view:?} {}", picture.height()); +} + +#[test] +fn the_list_is_not_asked_again_while_nothing_changed() { + let mut h = reviewed_box(); + let at = top_middle(&h); + mark(&mut h, at, "One"); + h.frames(2); + let listed_at = h.app.review.listed_at; + h.frames(20); + assert_eq!(h.app.review.listed_at, listed_at, "the set and the model did not change"); +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 33812b541c9..10e6b233660 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -10925,6 +10925,8 @@ pub(crate) fn show_host_controls(app: &mut SolveApp, ui: &mut egui::Ui, rect: Re crate::view_angles::show(app, ui, rect); } } + crate::review_pins::poll(app, ui.ctx()); + crate::review_pins::show(app, ui, rect); crate::navigation_bar_view::show(app, ui, rect); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2bb04a16a81..1bb64573ea5 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1108,7 +1108,7 @@ no box selection. | `ui.dialogInput` | `index` | what clicking an input's Select chip does: picks go to that input | | `ui.at` | `world: [x,y,z]` \| `sketch: [x,y]` \| `plane: "XY"` \| `axis: "Z"` \| `dimension: "d1"` (its value text) \| `handle: "arrow"` (a manipulator handle, see `scenario::publish_handle`) | the screen point (a scenario step's target; see `crates/ui-egui/src/scenario.rs`) | | `ui.pick` | `pixels?: [[x,y]…]`, `rays?: [{origin, dir}…]`, `frame?: "window"\|"model"`, `width?`, `height?`, `edges?` (default true), `edge_px?` (default 6), `all?`, `include_ghosted?` | read-only geometry under each pixel or ray (#6304): one entry per input, `null` where nothing is hit — body, face index, exact world `point` and outward `normal`, `depth`, `occurrence`/`component` for placed parts, `edge`/`vertex` within `edge_px` of a pixel, `section_cap: true` and the `section_plane` (its id in `inspect.section`) on a cut face. `window` pixels are physical pixels of a window screenshot; `model` pixels are pixels of a `ui.render` of `width`×`height` (default 960×600), without needing a window screenshot. Both pixel frames require the app's control channel; they are unavailable through `solidcraft-cli mcp --headless`. As `view.pick` through `engine.execute`/`engine.batch` when connected to the app. Without the app (`solidcraft-cli exec`, `run`, `mcp --headless`) the engine's `view.pick` answers `rays` (and `all`) with the same fields, decided on the bodies' exact faces, edges and vertices (`edge`/`vertex` name the one a ray passes through), and refuses `pixels`. See `crates/ui-egui/src/view_pick.rs` and `crates/engine/src/cmd/view_pick.rs` | -| `ui.handles` | `prefix?` | the handles drawn last frame, `[{name, x, y}]`: toolbar buttons and drop-down items `toolbar:` (the button alone: `button:`; a drop-down row: `dropdown:`, highlighted `dropdown_hot:`, its pin `dropdown_pin:`, its ⋯ menu button `dropdown_more:`; Customize Toolbar's check boxes `customize:`), ribbon tabs `tab:` (MODEL, SURFACE, ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW, SHEET METAL, WELDMENTS; contextual SKETCH; workspace RENDER), the toolbar menu button `ribbon:add_tab`, the hint when every tab is hidden `ribbon:tabs_hidden`, Preferences tab check boxes `prefs:toolbar_tab:`, panel labels `panel::` (also `ribbon:section::
`), document overflow list `tab:overflow`, workspace column `ribbon:workspace`, command-search launcher `ribbon:search`, browser rows `row: