A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
feat(gui): add local and remote session import workflow
RoversXe7635cde3ba9
diff --git a/NOTICE b/NOTICEindex ca377c4b..2dcbbcda 100644--- a/NOTICE+++ b/NOTICE@@ -141,6 +141,12 @@ license is:OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.+This product also embeds the Herdr logo from assets/logo.svg in the Herdr+project, licensed under the Apache License, Version 2.0. The unmodified+logo is included at third_party/herdr/logo.svg, and the full license at+third_party/herdr/LICENSE. See third_party/herdr/README for the upstream+commit.+Brand marks and logos appearing in this product are trademarks of theirrespective owners. They are used solely to identify the correspondingproduct or service (nominative use) and imply no affiliation with ordiff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftlindex 459dbc7a..a60cc0fa 100644--- a/thinkterm-i18n/i18n/de-DE.ftl+++ b/thinkterm-i18n/i18n/de-DE.ftl@@ -46,7 +46,7 @@ settings-archived-unarchived = „{ $name }“ in der Seitenleiste wiederhergestsettings-archived-deleted = „{ $name }“ endgültig gelöschtsettings-archived-remote-offline = Dieser Workspace liegt auf einem getrennten Server; verbinden Sie sich zuerst erneutsettings-section-keymap = Tastenbelegung-settings-section-compatibility = Aus WezTerm importieren+settings-section-import = Importierensettings-section-developer = Entwicklersettings-section-about = Übersettings-search-placeholder = Suchen@@ -192,7 +192,7 @@ settings-no-fields-loaded = Keine Felder geladensettings-fields-selected = { $selected } von { $total } ausgewähltsettings-detected-fields = Erkannte Feldersettings-load-source-description = Lesen Sie die erkannte WezTerm-Konfiguration, um die unterstützten Einstellungen zu prüfen.-settings-load-wezterm-source = Erkannte Einstellungen prüfen+settings-load-wezterm-source = Einstellungen prüfensettings-import-selected = Auswahl importierensettings-open-wezterm-source = WezTerm-Konfiguration öffnensettings-open-thinkterm-config = ThinkTerm-Konfiguration öffnen@@ -1027,3 +1027,76 @@ tab-icons-card-untitled = Neues Symboltab-icons-import-too-large = Diese SVG ist zu groß (höchstens 256 KB).tab-icons-import-not-svg = Diese Datei ist kein SVG-Symbol, das ThinkTerm zeichnen kann.tab-icons-import-failed = Die SVG konnte nicht importiert werden.++session-import-title = Aus { $source } importieren+session-import-description = Importieren Sie eine { $source }-Sitzung in einen neuen Space. Prüfen Sie vor dem Import die Struktur.+session-import-detect = Sitzungen suchen+session-import-detecting = { $source }-Sitzungen werden gelesen…+session-import-none = Keine { $source }-Sitzungen gefunden.+session-import-preview = Vorschau+session-import-destination = Neuer Space: { $name }+session-import-live = Laufende Sitzung: Terminals übertragen und bestehende Prozesse weiterlaufen lassen.+session-import-offline = Gespeichertes Layout: Neue Shells in den ursprünglichen Verzeichnissen öffnen. Gespeicherte Startbefehle und Befehle zum Fortsetzen von Agenten werden nicht ausgeführt.+session-import-project = { $name }: ein Projekt und ein Thread, { $tabs } Haupttabs, { $panes } Terminalbereiche+herdr-keep-state = Herdrs gespeicherte Dateien bleiben unverändert. Ein erneuter Start von Herdr kann das alte Layout wiederherstellen und gespeicherte Agenten fortsetzen.+herdr-live-limits = Der vollständige Scrollback und Bilder können nicht übertragen werden. Laufende Prozesse behalten ihre Umgebung; Vollbildprogramme müssen eventuell neu zeichnen.+session-import-back = Zurück+session-import-confirm-live = Laufende Sitzung übertragen+session-import-confirm-offline = Layout importieren+session-import-importing = Import läuft… Lassen Sie ThinkTerm geöffnet, bis die Übertragung abgeschlossen ist.+session-import-failed = Der Import konnte nicht abgeschlossen werden: { $error }+session-import-done-live = { $count } Terminals importiert. { $source } hat die Sitzung übergeben; die bestehenden Prozesse laufen in ThinkTerm weiter.+session-import-done-offline = Layout mit { $count } neuen Shells importiert.+session-import-open = Space öffnen+session-import-status-live = Laufende Sitzung+session-import-status-layout = Gespeichertes Layout+session-import-status-done = Import abgeschlossen+session-import-projects = Projekte+session-import-tabs = Haupttabs+session-import-terminals = Terminals+session-import-project-meta = { $threads } Thread · { $tabs } Haupttabs · { $panes } Terminals+session-import-terminal-untitled = Terminal { $number }+settings-import-description = Wähle eine Quelle, um die importierbaren Inhalte zu sehen.+settings-import-wezterm-description = Einstellungen und Tastenkürzel+settings-import-session-description = Sitzungen und Layouts+settings-import-wezterm-title = Aus WezTerm importieren+settings-import-open = Öffnen+session-import-select-session = Sitzung auswählen+session-import-preview-title = Import prüfen+settings-import-step-source = Quelle+settings-import-step-review = Vorschau+settings-import-step-result = Ergebnis+settings-import-choose-title = In ThinkTerm importieren+settings-import-continue = Weiter+settings-import-again = Weiteres importieren+settings-import-reload = Quelle neu laden++session-import-requirements-local = Erforderlich ist eine lokale Sitzung desselben Benutzers mit zugänglichem Sitzungsverzeichnis.+herdr-requirements-live = Die Live-Übertragung benötigt Herdrs live_handoff-Funktion und gemeinsamen Zugriff auf temporäre Dateien, Sockets und die ThinkTerm-Datei.+herdr-requirements-linux = Unter Linux muss /tmp die Skriptausführung erlauben; noexec wird nicht unterstützt.+session-import-requirements-layout = Gespeicherte Layouts beendeter Sitzungen benötigen keine Live-Übergabe. Arbeitsverzeichnisse müssen existieren und ThinkTerm muss das Layoutformat unterstützen.+session-import-requirements-refresh = Aktualisieren Sie die Vorschau, wenn sich Sitzungsstruktur oder Layout ändern.+session-import-refresh-preview = Vorschau aktualisieren+herdr-error-live-unsupported = Der laufende Herdr-Server unterstützt keine Live-Übergabe. Seine Prozesse können daher nicht übertragen werden. Verwenden Sie eine Herdr-Version mit dieser Funktion. Gespeicherte Layouts nicht laufender Sitzungen benötigen diese Funktion nicht.+session-import-error-empty = Diese Sitzung enthält keine importierbaren Terminals. Wählen Sie eine andere Sitzung oder öffnen Sie Terminals in { $source } und suchen Sie erneut nach Sitzungen.+session-import-error-session-missing = Das { $source }-Sitzungsverzeichnis ist nicht zugänglich. Prüfen Sie, ob es noch vorhanden und für den aktuellen Benutzer zugänglich ist, und suchen Sie erneut nach Sitzungen.+session-import-error-directory-missing = Mindestens ein gespeichertes Arbeitsverzeichnis fehlt oder ist nicht zugänglich. Stellen Sie die Verzeichnisse wieder her oder aktualisieren und speichern Sie das Layout in { $source }. Aktualisieren Sie danach die Vorschau.+session-import-error-layout-newer = Dieses Layoutformat ist neuer als von dieser ThinkTerm-Version unterstützt. Verwenden Sie eine ThinkTerm-Version mit Unterstützung für dieses Format und aktualisieren Sie die Vorschau.+session-import-error-handoff-version = Die Versionen des Live-Übergabeprotokolls sind nicht kompatibel. Verwenden Sie kompatible Versionen von ThinkTerm und { $source } und versuchen Sie es erneut.+session-import-error-changed = Die Sitzungsstruktur, der Ausführungsstatus oder das gespeicherte Layout hat sich seit der Vorschau geändert. Aktualisieren Sie die Vorschau, bevor Sie den Import bestätigen.+session-import-error-local-user = Verwenden Sie eine Sitzung desselben Kontos auf dem Zielrechner. Prüfen Sie die Berechtigungen des Sitzungsverzeichnisses und des Sockets.+session-import-error-terminal-missing = Einige Bereiche haben kein aktives Terminal für die Übergabe. Die Sitzung wurde nicht übertragen. Prüfen Sie diese Bereiche in { $source } und aktualisieren Sie die Vorschau.+session-import-error-receiver = Der Übergabeempfänger konnte nicht gestartet oder verbunden werden. Prüfen Sie, ob beide Programme auf dasselbe temporäre Verzeichnis, den Socket und die ThinkTerm-Datei zugreifen können. Unter Linux muss /tmp die Skriptausführung erlauben (kein noexec).+session-import-error-inspect = Die { $source }-Sitzung konnte nicht gelesen werden. Prüfen Sie den Zugriff auf { $source } und seine Sitzungsverzeichnisse auf dem Zielrechner und suchen Sie erneut nach Sitzungen.+session-import-error-import = Das Importergebnis konnte nicht bestätigt werden. Prüfen Sie die { $source }-Sitzung und den Ziel-Space, bevor Sie die Vorschau aktualisieren oder es erneut versuchen.+session-import-error-open = Die Sitzung wurde importiert, ihr Space konnte jedoch nicht geöffnet werden. Prüfen Sie die Verbindung zum Ziel-Sitzungsserver und versuchen Sie „Space öffnen“ erneut. Importieren Sie die Sitzung nicht noch einmal.+session-import-error-details = Technische Details: { $error }+session-import-notes-title = Hinweise zum Import+session-import-location-local = Importziel: dieser Computer+session-import-location-remote = Importziel: { $host } · die Prozesse bleiben auf diesem Server+session-import-requirements-remote = Verwenden Sie eine Sitzung des Kontos der Remoteverbindung. Terminals und Arbeitsverzeichnisse bleiben auf diesem Server.++session-import-check-result = Importergebnis prüfen+session-import-still-running = Der Import läuft noch auf dem Zielrechner. Prüfen Sie das Ergebnis später erneut.+session-import-result-interrupted = Der Dienst wurde unterbrochen oder die Anfrage ist abgelaufen. Das Ergebnis lässt sich nicht automatisch bestätigen. Prüfen Sie den Ziel-Space vor einem neuen Import.+session-import-result-unavailable = Die Verbindung wurde unterbrochen. Prüfen Sie das Importergebnis, um die Verbindung wiederherzustellen und diese Anfrage abzurufen. Starten Sie keinen zweiten Import.diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftlindex e591a02d..ce2cad5d 100644--- a/thinkterm-i18n/i18n/en-US.ftl+++ b/thinkterm-i18n/i18n/en-US.ftl@@ -46,7 +46,7 @@ settings-archived-unarchived = Restored "{ $name }" to the sidebarsettings-archived-deleted = Deleted "{ $name }" permanentlysettings-archived-remote-offline = That workspace lives on a disconnected server; reconnect firstsettings-section-keymap = Keymap-settings-section-compatibility = Import from WezTerm+settings-section-import = Importsettings-section-developer = Developersettings-section-about = Aboutsettings-search-placeholder = Search@@ -192,7 +192,7 @@ settings-no-fields-loaded = No fields loadedsettings-fields-selected = { $selected } of { $total } selectedsettings-detected-fields = Detected Fieldssettings-load-source-description = Read the detected WezTerm configuration to review supported settings.-settings-load-wezterm-source = Review Detected Settings+settings-load-wezterm-source = Review settingssettings-import-selected = Import Selectedsettings-open-wezterm-source = Open WezTerm Configurationsettings-open-thinkterm-config = Open ThinkTerm Configuration@@ -1027,3 +1027,76 @@ tab-icons-card-untitled = New icontab-icons-import-too-large = That SVG is too large (256 KB at most).tab-icons-import-not-svg = That file is not an SVG icon ThinkTerm can draw.tab-icons-import-failed = Could not import that SVG.++session-import-title = Import from { $source }+session-import-description = Import a { $source } session into a new Space. Preview its structure before importing.+session-import-detect = Detect sessions+session-import-detecting = Reading { $source } sessions…+session-import-none = No { $source } sessions were found.+session-import-preview = Preview+session-import-destination = New Space: { $name }+session-import-live = Running session: move its terminals and keep the existing processes running.+session-import-offline = Saved layout: open fresh shells in the saved directories. Saved launch and agent resume commands are not run.+session-import-project = { $name }: one Project and Thread, { $tabs } primary tabs, { $panes } terminal panes+herdr-keep-state = Herdr’s saved files are left unchanged. Starting Herdr again can restore its old layout and resume its saved agents.+herdr-live-limits = Full scrollback and images cannot be transferred. Running processes keep their existing environment; full-screen programs may need a redraw.+session-import-back = Back+session-import-confirm-live = Move running session+session-import-confirm-offline = Import layout+session-import-importing = Importing… Keep ThinkTerm open until the transfer finishes.+session-import-failed = Import could not be completed: { $error }+session-import-done-live = Imported { $count } terminals. { $source } has handed over the session; the existing processes continue in ThinkTerm.+session-import-done-offline = Imported the layout with { $count } new shells.+session-import-open = Open Space+session-import-status-live = Running session+session-import-status-layout = Saved layout+session-import-status-done = Import complete+session-import-projects = Projects+session-import-tabs = Primary tabs+session-import-terminals = Terminals+session-import-project-meta = { $threads } Thread · { $tabs } primary tabs · { $panes } terminals+session-import-terminal-untitled = Terminal { $number }+settings-import-description = Choose a source to see what you can import.+settings-import-wezterm-description = Settings and shortcuts+settings-import-session-description = Sessions and layouts+settings-import-wezterm-title = Import from WezTerm+settings-import-open = Open+session-import-select-session = Choose a session+session-import-preview-title = Review your import+settings-import-step-source = Source+settings-import-step-review = Review+settings-import-step-result = Complete+settings-import-choose-title = Import into ThinkTerm+settings-import-continue = Continue+settings-import-again = Import more+settings-import-reload = Reload source++session-import-requirements-local = Use a local session owned by the same user, with an accessible session directory.+herdr-requirements-live = Live migration requires Herdr’s live_handoff capability and shared access to temporary files, sockets, and the ThinkTerm executable.+herdr-requirements-linux = On Linux, /tmp must allow script execution; noexec mounts are unsupported.+session-import-requirements-layout = Saved layouts from stopped sessions need no live handoff. Working directories must exist and ThinkTerm must support the layout format.+session-import-requirements-refresh = Refresh the preview if the session structure or layout changes.+session-import-refresh-preview = Refresh preview+herdr-error-live-unsupported = The running Herdr server does not support live handoff, so its existing processes cannot be moved. Use a Herdr version that supports this capability. Saved layouts from sessions that are not running do not require it.+session-import-error-empty = This session has no terminals to import. Choose another session, or open terminals in { $source } and detect sessions again.+session-import-error-session-missing = The { $source } session directory cannot be accessed. Check that it still exists and is accessible to the current user, then detect sessions again.+session-import-error-directory-missing = One or more saved working directories are missing or inaccessible. Restore them, or update and save the layout in { $source }, then refresh the preview.+session-import-error-layout-newer = This layout format is newer than this version of ThinkTerm supports. Use a ThinkTerm version that supports the format, then refresh the preview.+session-import-error-handoff-version = The live handoff protocol versions are incompatible. Use compatible versions of ThinkTerm and { $source } before trying again.+session-import-error-changed = The session structure, running state, or saved layout changed after the preview. Refresh the preview before confirming the import.+session-import-error-local-user = Use a session owned by the same account on the destination machine. Check its directory and socket permissions.+session-import-error-terminal-missing = Some panes have no live terminal to hand over. The session was not moved. Check those panes in { $source }, then refresh the preview.+session-import-error-receiver = The handoff receiver could not start or connect. Check that both apps can access the same temporary directory, socket, and ThinkTerm executable. On Linux, /tmp must allow script execution (no noexec mount).+session-import-error-inspect = The { $source } session could not be read. Check access to { $source } and its session directories on the target machine, then detect sessions again.+session-import-error-import = The import result could not be confirmed. Check the { $source } session and the destination Space before refreshing the preview or trying again.+session-import-error-open = The session was imported, but its Space could not be opened. Check the target session server connection and retry Open Space. Do not import the session again.+session-import-error-details = Technical details: { $error }+session-import-notes-title = Import notes+session-import-location-local = Import location: this computer+session-import-location-remote = Import location: { $host } · remote processes stay on this server+session-import-requirements-remote = Use a session owned by the remote connection’s account. Terminals and working directories stay on that server.++session-import-check-result = Check import result+session-import-still-running = The import is still running on the target. Check again to retrieve its result.+session-import-result-interrupted = The service was interrupted or the request expired. Its result cannot be confirmed automatically. Check the target Space before starting another import.+session-import-result-unavailable = The connection was interrupted. Check the import result to reconnect and recover this request; do not start a second import.diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftlindex 0939993e..70ec3c34 100644--- a/thinkterm-i18n/i18n/fr-FR.ftl+++ b/thinkterm-i18n/i18n/fr-FR.ftl@@ -46,7 +46,7 @@ settings-archived-unarchived = « { $name } » restauré dans la barre latéralesettings-archived-deleted = « { $name } » supprimé définitivementsettings-archived-remote-offline = Ce projet vit sur un serveur déconnecté ; reconnectez-vous d'abordsettings-section-keymap = Raccourcis clavier-settings-section-compatibility = Importer depuis WezTerm+settings-section-import = Importersettings-section-developer = Développeursettings-section-about = À propossettings-search-placeholder = Rechercher@@ -192,7 +192,7 @@ settings-no-fields-loaded = Aucun champ chargésettings-fields-selected = { $selected } sur { $total } sélectionnéssettings-detected-fields = Champs détectéssettings-load-source-description = Lit la configuration WezTerm détectée pour afficher les réglages pris en charge.-settings-load-wezterm-source = Examiner les réglages détectés+settings-load-wezterm-source = Vérifier les réglagessettings-import-selected = Importer la sélectionsettings-open-wezterm-source = Ouvrir la configuration WezTermsettings-open-thinkterm-config = Ouvrir la configuration ThinkTerm@@ -1024,3 +1024,76 @@ tab-icons-card-untitled = Nouvelle icônetab-icons-import-too-large = Ce SVG est trop volumineux (256 Ko au maximum).tab-icons-import-not-svg = Ce fichier n’est pas une icône SVG que ThinkTerm peut dessiner.tab-icons-import-failed = Impossible d’importer ce SVG.++session-import-title = Importer depuis { $source }+session-import-description = Importez une session { $source } dans un nouvel espace. Vérifiez sa structure avant l’importation.+session-import-detect = Détecter les sessions+session-import-detecting = Lecture des sessions { $source }…+session-import-none = Aucune session { $source } trouvée.+session-import-preview = Aperçu+session-import-destination = Nouvel espace : { $name }+session-import-live = Session active : transférer les terminaux en conservant les processus en cours.+session-import-offline = Disposition enregistrée : ouvrir de nouveaux shells dans les répertoires d’origine, sans exécuter les commandes de lancement ou de reprise des agents.+session-import-project = { $name } : un projet et un fil, { $tabs } onglets principaux, { $panes } volets de terminal+herdr-keep-state = Les fichiers enregistrés par Herdr restent inchangés. Relancer Herdr peut restaurer l’ancienne disposition et reprendre les agents enregistrés.+herdr-live-limits = L’historique complet et les images ne peuvent pas être transférés. Les processus conservent leur environnement ; les programmes plein écran peuvent nécessiter un rafraîchissement.+session-import-back = Retour+session-import-confirm-live = Transférer la session active+session-import-confirm-offline = Importer la disposition+session-import-importing = Importation… Gardez ThinkTerm ouvert jusqu’à la fin du transfert.+session-import-failed = L’importation n’a pas pu aboutir : { $error }+session-import-done-live = { $count } terminaux importés. { $source } a transféré la session ; les processus continuent dans ThinkTerm.+session-import-done-offline = Disposition importée avec { $count } nouveaux shells.+session-import-open = Ouvrir l’espace+session-import-status-live = Session en cours+session-import-status-layout = Disposition enregistrée+session-import-status-done = Importation terminée+session-import-projects = Projets+session-import-tabs = Onglets principaux+session-import-terminals = Terminaux+session-import-project-meta = { $threads } fil · { $tabs } onglets principaux · { $panes } terminaux+session-import-terminal-untitled = Terminal { $number }+settings-import-description = Choisissez une source pour voir ce que vous pouvez importer.+settings-import-wezterm-description = Réglages et raccourcis+settings-import-session-description = Sessions et dispositions+settings-import-wezterm-title = Importer depuis WezTerm+settings-import-open = Ouvrir+session-import-select-session = Choisir une session+session-import-preview-title = Vérifier l’importation+settings-import-step-source = Source+settings-import-step-review = Aperçu+settings-import-step-result = Résultat+settings-import-choose-title = Importer dans ThinkTerm+settings-import-continue = Continuer+settings-import-again = Importer autre chose+settings-import-reload = Recharger la source++session-import-requirements-local = La session doit être locale, appartenir au même utilisateur et avoir un répertoire accessible.+herdr-requirements-live = Le transfert à chaud nécessite live_handoff dans Herdr et un accès partagé aux fichiers temporaires, aux sockets et à l’exécutable ThinkTerm.+herdr-requirements-linux = Sous Linux, /tmp doit autoriser les scripts ; les montages noexec ne sont pas pris en charge.+session-import-requirements-layout = Les dispositions de sessions arrêtées ne nécessitent pas de transfert à chaud. Les répertoires doivent exister et ThinkTerm doit prendre en charge le format.+session-import-requirements-refresh = Actualisez l’aperçu si la structure de la session ou la disposition change.+session-import-refresh-preview = Actualiser l’aperçu+herdr-error-live-unsupported = Le serveur Herdr en cours ne prend pas en charge le transfert à chaud ; ses processus ne peuvent donc pas être transférés. Utilisez une version de Herdr compatible avec cette fonction. Les dispositions enregistrées de sessions arrêtées n’en ont pas besoin.+session-import-error-empty = Cette session ne contient aucun terminal à importer. Choisissez une autre session ou ouvrez des terminaux dans { $source }, puis relancez la détection.+session-import-error-session-missing = Le répertoire de session { $source } est inaccessible. Vérifiez qu’il existe toujours et que l’utilisateur actuel peut y accéder, puis relancez la détection.+session-import-error-directory-missing = Un ou plusieurs répertoires de travail enregistrés sont absents ou inaccessibles. Restaurez-les, ou modifiez et enregistrez la disposition dans { $source }, puis actualisez l’aperçu.+session-import-error-layout-newer = Le format de cette disposition est plus récent que ceux pris en charge par cette version de ThinkTerm. Utilisez une version compatible avec ce format, puis actualisez l’aperçu.+session-import-error-handoff-version = Les versions du protocole de transfert à chaud sont incompatibles. Utilisez des versions compatibles de ThinkTerm et de { $source } avant de réessayer.+session-import-error-changed = La structure de la session, son état d’exécution ou la disposition enregistrée a changé depuis l’aperçu. Actualisez l’aperçu avant de confirmer l’importation.+session-import-error-local-user = Utilisez une session appartenant au même compte sur la machine de destination. Vérifiez les permissions du répertoire et du socket.+session-import-error-terminal-missing = Certains volets n’ont aucun terminal actif à transférer. La session n’a pas été déplacée. Vérifiez ces volets dans { $source }, puis actualisez l’aperçu.+session-import-error-receiver = Le récepteur du transfert n’a pas pu démarrer ou se connecter. Vérifiez que les deux applications accèdent au même répertoire temporaire, au socket et à l’exécutable ThinkTerm. Sous Linux, /tmp doit autoriser l’exécution des scripts (sans noexec).+session-import-error-inspect = Impossible de lire la session { $source }. Vérifiez l’accès à { $source } et à ses répertoires de session sur la machine cible, puis relancez la détection.+session-import-error-import = Le résultat de l’importation n’a pas pu être confirmé. Vérifiez la session { $source } et l’espace de destination avant d’actualiser l’aperçu ou de réessayer.+session-import-error-open = La session a été importée, mais son Space n’a pas pu être ouvert. Vérifiez la connexion au serveur de sessions cible et réessayez « Ouvrir le Space ». Ne réimportez pas la session.+session-import-error-details = Détails techniques : { $error }+session-import-notes-title = À savoir avant l’importation+session-import-location-local = Emplacement de l’importation : cet ordinateur+session-import-location-remote = Emplacement de l’importation : { $host } · les processus restent sur ce serveur+session-import-requirements-remote = Utilisez une session appartenant au compte de la connexion distante. Les terminaux et leurs répertoires de travail restent sur ce serveur.++session-import-check-result = Vérifier le résultat+session-import-still-running = L’importation est toujours en cours sur la machine cible. Vérifiez à nouveau son résultat dans un instant.+session-import-result-interrupted = Le service a été interrompu ou la demande a expiré. Le résultat ne peut pas être confirmé automatiquement. Vérifiez le Space cible avant de lancer une nouvelle importation.+session-import-result-unavailable = La connexion a été interrompue. Vérifiez le résultat pour vous reconnecter et récupérer cette demande, sans lancer une seconde importation.diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftlindex 1d593548..a94d4e78 100644--- a/thinkterm-i18n/i18n/ja-JP.ftl+++ b/thinkterm-i18n/i18n/ja-JP.ftl@@ -43,7 +43,7 @@ settings-archived-unarchived = 「{ $name }」をサイドバーに復元しまsettings-archived-deleted = 「{ $name }」を完全に削除しましたsettings-archived-remote-offline = このワークスペースは切断中のサーバー上にあります。先に再接続してくださいsettings-section-keymap = キーマップ-settings-section-compatibility = WezTerm からインポート+settings-section-import = インポートsettings-section-developer = 開発者settings-section-about = 情報settings-search-placeholder = 検索@@ -189,7 +189,7 @@ settings-no-fields-loaded = 項目が読み込まれていませんsettings-fields-selected = { $total } 件中 { $selected } 件を選択settings-detected-fields = 検出した項目settings-load-source-description = 検出された WezTerm 設定を読み取り、対応している項目を確認します。-settings-load-wezterm-source = 検出された設定を確認+settings-load-wezterm-source = 設定を確認settings-import-selected = 選択項目をインポートsettings-open-wezterm-source = WezTerm 設定を開くsettings-open-thinkterm-config = ThinkTerm 設定を開く@@ -1005,3 +1005,76 @@ tab-icons-card-untitled = 新しいアイコンtab-icons-import-too-large = この SVG は大きすぎます(最大 256 KB)。tab-icons-import-not-svg = このファイルは描画できる SVG アイコンではありません。tab-icons-import-failed = SVG を読み込めませんでした。++session-import-title = { $source } からインポート+session-import-description = { $source } セッションを新しい Space にインポートします。インポート前に構成を確認できます。+session-import-detect = セッションを検出+session-import-detecting = { $source } セッションを読み込み中…+session-import-none = { $source } セッションが見つかりません。+session-import-preview = プレビュー+session-import-destination = 新しい Space:{ $name }+session-import-live = 実行中のセッション:既存のプロセスを維持して端末を移します。+session-import-offline = 保存されたレイアウト:元のディレクトリで新しいシェルを開きます。保存された起動・エージェント再開コマンドは実行しません。+session-import-project = { $name }:Project と Thread 各 1 個、上位タブ { $tabs } 個、端末ペイン { $panes } 個+herdr-keep-state = Herdr の保存ファイルは変更しません。Herdr を再起動すると、以前のレイアウトや保存済みエージェントが復元される場合があります。+herdr-live-limits = スクロールバック全体と画像は移せません。実行中のプロセスは元の環境変数を保持し、全画面プログラムは再描画が必要な場合があります。+session-import-back = 戻る+session-import-confirm-live = 実行中のセッションを移す+session-import-confirm-offline = レイアウトをインポート+session-import-importing = インポート中… 完了するまで ThinkTerm を開いたままにしてください。+session-import-failed = インポートを完了できませんでした:{ $error }+session-import-done-live = 端末 { $count } 個をインポートしました。{ $source } からの引き継ぎが完了し、既存のプロセスは ThinkTerm で動作しています。+session-import-done-offline = レイアウトをインポートし、新しいシェルを { $count } 個作成しました。+session-import-open = Space を開く+session-import-status-live = 実行中のセッション+session-import-status-layout = 保存済みレイアウト+session-import-status-done = インポート完了+session-import-projects = プロジェクト+session-import-tabs = 第1階層タブ+session-import-terminals = ターミナル+session-import-project-meta = { $threads } スレッド · 第1階層タブ { $tabs } 個 · ターミナル { $panes } 個+session-import-terminal-untitled = ターミナル { $number }+settings-import-description = インポート元を選んで、取り込める内容を確認します。+settings-import-wezterm-description = 設定とショートカット+settings-import-session-description = セッションとレイアウト+settings-import-wezterm-title = WezTerm からインポート+settings-import-open = 開く+session-import-select-session = セッションを選択+session-import-preview-title = インポート内容の確認+settings-import-step-source = インポート元+settings-import-step-review = 内容の確認+settings-import-step-result = 完了+settings-import-choose-title = ThinkTerm にインポート+settings-import-continue = 続ける+settings-import-again = 続けてインポート+settings-import-reload = 読み直す++session-import-requirements-local = 同じユーザーのローカルセッションと、アクセス可能なセッションディレクトリが必要です。+herdr-requirements-live = ライブ移行には Herdr の live_handoff 対応と、一時ファイル、ソケット、ThinkTerm 実行ファイルへの双方からのアクセスが必要です。+herdr-requirements-linux = Linux の /tmp ではスクリプト実行が必要です(noexec は不可)。+session-import-requirements-layout = 停止中の保存済みレイアウトにはライブ引き継ぎは不要です。作業ディレクトリが存在し、ThinkTerm が形式に対応している必要があります。+session-import-requirements-refresh = セッション構造やレイアウトが変わったら、プレビューを更新してください。+session-import-refresh-preview = プレビューを更新+herdr-error-live-unsupported = 実行中の Herdr はライブ引き継ぎに対応していないため、既存のプロセスを移行できません。この機能に対応した Herdr を使用してください。停止中のセッションの保存済みレイアウトには、この機能は不要です。+session-import-error-empty = このセッションにはインポートできる端末がありません。別のセッションを選ぶか、{ $source } で端末を開いて再検出してください。+session-import-error-session-missing = { $source } のセッションディレクトリにアクセスできません。ディレクトリが存在し、現在のユーザーにアクセス権があることを確認して再検出してください。+session-import-error-directory-missing = 保存された作業ディレクトリの一部が存在しないか、アクセスできません。ディレクトリを復元するか、{ $source } でレイアウトを更新・保存してからプレビューを更新してください。+session-import-error-layout-newer = このレイアウトは現在の ThinkTerm が対応する形式より新しいものです。この形式に対応した ThinkTerm を使用してプレビューを更新してください。+session-import-error-handoff-version = ライブ引き継ぎプロトコルのバージョンに互換性がありません。互換性のある ThinkTerm と { $source } を使用して再試行してください。+session-import-error-changed = プレビュー後にセッション構造、実行状態、または保存済みレイアウトが変わりました。プレビューを更新してからインポートを確定してください。+session-import-error-local-user = インポート先のマシンで同じアカウントが所有するセッションを使用し、ディレクトリとソケットの権限を確認してください。+session-import-error-terminal-missing = 一部のペインに引き継げる端末がありません。セッションは移行されていません。{ $source } で該当するペインを確認してプレビューを更新してください。+session-import-error-receiver = 引き継ぎ受信プログラムを起動または接続できません。同じ一時ディレクトリ、ソケット、ThinkTerm 実行ファイルに双方からアクセスできることを確認してください。Linux では /tmp でのスクリプト実行が必要です(noexec は不可)。+session-import-error-inspect = { $source } セッションを読み取れません。{ $source } と対象マシン上のセッションディレクトリへのアクセスを確認して再検出してください。+session-import-error-import = インポート結果を確認できませんでした。プレビューの更新や再試行の前に、{ $source } のセッションとインポート先の Space を確認してください。+session-import-error-open = セッションはインポートされましたが、Space を開けませんでした。対象セッションサーバーの接続を確認して「Space を開く」を再試行してください。再インポートは不要です。+session-import-error-details = 技術的な詳細:{ $error }+session-import-notes-title = インポートの注意事項+session-import-location-local = インポート先:このコンピュータ+session-import-location-remote = インポート先:{ $host } · リモートプロセスはこのサーバーで実行を続けます+session-import-requirements-remote = リモート接続のアカウントが所有するセッションを使用してください。端末プロセスと作業ディレクトリはサーバーに残ります。++session-import-check-result = インポート結果を確認+session-import-still-running = 対象のマシンでインポートを実行中です。後でもう一度結果を確認してください。+session-import-result-interrupted = サービスが中断されたか、リクエストの有効期限が切れたため、結果を自動確認できません。新しいインポートを始める前に対象の Space を確認してください。+session-import-result-unavailable = 接続が中断されました。「インポート結果を確認」で再接続し、このリクエストの結果を取得してください。別のインポートを開始しないでください。diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftlindex e06618c7..288b8e2a 100644--- a/thinkterm-i18n/i18n/zh-CN.ftl+++ b/thinkterm-i18n/i18n/zh-CN.ftl@@ -43,7 +43,7 @@ settings-archived-unarchived = 已将「{ $name }」恢复到侧边栏settings-archived-deleted = 已永久删除「{ $name }」settings-archived-remote-offline = 该工作区在已断开的服务器上,请先重新连接settings-section-keymap = 快捷键-settings-section-compatibility = 从 WezTerm 导入+settings-section-import = 导入settings-section-developer = 开发者settings-section-about = 关于settings-search-placeholder = 搜索@@ -189,7 +189,7 @@ settings-no-fields-loaded = 未加载字段settings-fields-selected = 已选择 { $selected }/{ $total }settings-detected-fields = 检测到的字段settings-load-source-description = 读取检测到的 WezTerm 配置并查看支持的设置。-settings-load-wezterm-source = 查看检测到的设置+settings-load-wezterm-source = 查看设置settings-import-selected = 导入所选项settings-open-wezterm-source = 打开 WezTerm 配置settings-open-thinkterm-config = 打开 ThinkTerm 配置@@ -1005,3 +1005,76 @@ tab-icons-card-untitled = 新图标tab-icons-import-too-large = 这个 SVG 太大了(最多 256 KB)。tab-icons-import-not-svg = 这个文件不是能画出来的 SVG 图标。tab-icons-import-failed = 没能导入这个 SVG。++session-import-title = 从 { $source } 导入+session-import-description = 将 { $source } 会话导入到新 Space。导入前可预览结构。+session-import-detect = 检测会话+session-import-detecting = 正在读取 { $source } 会话…+session-import-none = 未找到 { $source } 会话。+session-import-preview = 预览+session-import-destination = 新 Space:{ $name }+session-import-live = 会话正在运行:迁移终端,让现有进程继续运行。+session-import-offline = 仅导入保存的布局,在原目录新建 shell;不执行保存的启动命令或代理恢复命令。+session-import-project = { $name }:一个 Project 和 Thread,{ $tabs } 个一级标签,{ $panes } 个终端窗格+herdr-keep-state = Herdr 保存的文件保持不变。再次启动 Herdr 时,它可能恢复旧布局并继续保存的代理会话。+herdr-live-limits = 无法转移完整回滚历史和图片。运行中的进程保留原环境变量;全屏程序可能需要重绘。+session-import-back = 返回+session-import-confirm-live = 迁移运行中的会话+session-import-confirm-offline = 导入布局+session-import-importing = 正在导入… 请保持 ThinkTerm 打开,直到迁移完成。+session-import-failed = 未能完成导入:{ $error }+session-import-done-live = 已导入 { $count } 个终端。{ $source } 已交出会话,现有进程继续在 ThinkTerm 中运行。+session-import-done-offline = 已导入布局,并新建 { $count } 个 shell。+session-import-open = 打开 Space+session-import-status-live = 正在运行+session-import-status-layout = 已保存的布局+session-import-status-done = 导入完成+session-import-projects = 项目+session-import-tabs = 一级标签+session-import-terminals = 终端+session-import-project-meta = { $threads } 个 Thread · { $tabs } 个一级标签 · { $panes } 个终端+session-import-terminal-untitled = 终端 { $number }+settings-import-description = 选择一个来源,查看可导入的内容。+settings-import-wezterm-description = 配置与快捷键+settings-import-session-description = 会话与布局+settings-import-wezterm-title = 从 WezTerm 导入+settings-import-open = 打开+session-import-select-session = 选择会话+session-import-preview-title = 导入预览+settings-import-step-source = 选择来源+settings-import-step-review = 预览内容+settings-import-step-result = 导入结果+settings-import-choose-title = 导入到 ThinkTerm+settings-import-continue = 继续+settings-import-again = 继续导入+settings-import-reload = 重新读取++session-import-requirements-local = 仅支持本机同一用户的会话,需能访问会话目录。+herdr-requirements-live = 实时迁移需 Herdr 支持 live_handoff,且两端能访问相同的临时目录、socket 和 ThinkTerm 程序。+herdr-requirements-linux = Linux 的 /tmp 必须允许执行脚本(不能以 noexec 挂载)。+session-import-requirements-layout = 未运行会话的布局导入无需实时交接能力;工作目录必须存在,布局格式须受当前 ThinkTerm 支持。+session-import-requirements-refresh = 预览后会话结构或布局有变动,请重新预览。+session-import-refresh-preview = 重新预览+herdr-error-live-unsupported = 当前运行的 Herdr 不支持实时交接,无法迁移现有进程。请使用支持该能力的 Herdr 版本。导入未运行会话的保存布局不需要此能力。+session-import-error-empty = 会话中没有可导入的终端。请选择其他会话,或在 { $source } 中打开终端后重新检测。+session-import-error-session-missing = 无法访问 { $source } 会话目录。请确认目录仍存在且当前用户有访问权限,然后重新检测。+session-import-error-directory-missing = 保存布局中的一个或多个工作目录已不存在或无法访问。请恢复这些目录,或在 { $source } 中更新并保存布局,然后重新预览。+session-import-error-layout-newer = 该布局格式比当前 ThinkTerm 支持的版本更新。请使用支持该格式的 ThinkTerm 版本后重新预览。+session-import-error-handoff-version = 两端的实时交接协议版本不兼容。请使用相互兼容的 ThinkTerm 和 { $source } 版本后重试。+session-import-error-changed = 会话结构、运行状态或保存布局已在预览后改变。请重新预览,再确认导入。+session-import-error-local-user = 请使用目标机器上同一账号拥有的会话,并检查会话目录和套接字的权限。+session-import-error-terminal-missing = 部分窗格没有可交接的活动终端,会话未迁移。请在 { $source } 中检查这些窗格,然后重新预览。+session-import-error-receiver = 无法启动或连接交接接收程序。请确认两边能访问同一临时目录、socket 和 ThinkTerm 程序;Linux 上还需允许在 /tmp 执行脚本(不能为 noexec)。+session-import-error-inspect = 无法读取 { $source } 会话。请检查 { $source } 和目标机器上会话目录的访问权限,然后重新检测。+session-import-error-import = 未能确认导入结果。请先检查 { $source } 会话和目标 Space,再刷新预览或决定是否重试。+session-import-error-open = 会话已导入,但无法打开 Space。请检查目标会话服务的连接,然后重试“打开 Space”;无需再次导入。+session-import-error-details = 技术详情:{ $error }+session-import-notes-title = 导入须知+session-import-location-local = 导入位置:本机+session-import-location-remote = 导入位置:{ $host } · 远程进程仍在这台服务器上运行+session-import-requirements-remote = 使用远程连接账号拥有的会话。终端进程和工作目录保留在该服务器上。++session-import-check-result = 检查导入结果+session-import-still-running = 目标机器仍在导入。稍后再次检查,即可取回本次结果。+session-import-result-interrupted = 服务曾中断或请求已过期,无法自动确认结果。请检查目标 Space 后再决定是否发起新的导入。+session-import-result-unavailable = 连接已中断。请使用“检查导入结果”重新连接并查询本次请求,不要另行发起导入。diff --git a/thinkterm-i18n/src/lib.rs b/thinkterm-i18n/src/lib.rsindex 09ff58e8..9793abbb 100644--- a/thinkterm-i18n/src/lib.rs+++ b/thinkterm-i18n/src/lib.rs@@ -247,6 +247,24 @@ pub fn native_name_for_locale(locale: &str) -> &'static str {#[cfg(test)]mod tests {+ #[test]+ fn session_import_strings_format_for_every_source_and_locale() {+ let mut args = FluentArgs::new();+ for (name, value) in [("source", "Example"), ("host", "server-a"), ("threads", "2"), ("tabs", "3"), ("panes", "4"), ("count", "4")] {+ args.set(name, value);+ }+ for &locale in SUPPORTED_LOCALES {+ for key in ["session-import-title", "session-import-done-live", "session-import-project-meta", "session-import-error-import", "session-import-location-local", "session-import-location-remote", "session-import-requirements-remote", "session-import-check-result", "session-import-still-running", "session-import-result-interrupted", "session-import-result-unavailable"] {+ let catalog = &catalogs().locales[locale.index()];+ let message = catalog.bundle.get_message(key).unwrap();+ let mut errors = vec![];+ let value = catalog.bundle.format_pattern(message.value().unwrap(), Some(&args), &mut errors);+ assert!(errors.is_empty(), "{}: {}: {:?}", locale.code, key, errors);+ assert!(!value.is_empty());+ }+ }+ }+use super::*;use std::collections::BTreeSet;diff --git a/third_party/herdr/LICENSE b/third_party/herdr/LICENSEnew file mode 100644index 00000000..261eeb9e--- /dev/null+++ b/third_party/herdr/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/third_party/herdr/README b/third_party/herdr/READMEnew file mode 100644index 00000000..6ecfe998--- /dev/null+++ b/third_party/herdr/README@@ -0,0 +1,4 @@+Herdr logo++The unmodified logo.svg comes from assets/logo.svg in the Herdr source,+commit e5443f077c2bdf329ef5dfe9830580e53f9b00e8. Distributed under Apache-2.0; see LICENSE.diff --git a/third_party/herdr/logo.svg b/third_party/herdr/logo.svgnew file mode 100644index 00000000..23057315--- /dev/null+++ b/third_party/herdr/logo.svg@@ -0,0 +1,6 @@+<svg role="img" aria-label="Herdr logo" xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512" preserveAspectRatio="xMidYMid meet">+ <rect width="512" height="512" fill="#d9dad8"/>+ <g fill="#303438" transform="translate(0 512) scale(.1 -.1)" stroke="none">+ <path d="M2794 3710 c-129 -33 -299 -135 -359 -214 -21 -28 -26 -42 -21 -63 9 -38 154 -178 199 -192 32 -11 41 -9 104 23 171 86 354 70 475 -43 150 -138 150 -379 0 -511 -107 -95 -278 -94 -386 2 l-46 40 -11 -29 c-16 -40 -14 -122 4 -164 60 -144 264 -222 452 -174 360 92 559 494 430 868 -36 103 -81 173 -175 267 -71 72 -100 93 -180 132 -52 26 -127 54 -167 62 -96 21 -230 20 -319 -4z M2183 3695 c-116 -32 -221 -108 -273 -199 -17 -28 -30 -54 -30 -58 0 -4 20 1 45 12 66 28 220 68 294 76 64 7 65 7 137 83 40 41 71 77 69 79 -2 2 -21 8 -42 13 -55 12 -140 10 -200 -6z M2212 3388 c-159 -22 -390 -122 -559 -241 -299 -210 -585 -600 -609 -828 -12 -118 40 -251 125 -318 96 -76 178 -98 426 -116 110 -8 224 -21 254 -29 125 -34 230 -115 272 -211 11 -24 24 -81 30 -127 20 -170 65 -271 166 -374 34 -35 63 -65 63 -67 0 -1 -10 -27 -22 -57 -29 -76 -37 -259 -14 -350 42 -170 158 -318 311 -397 44 -23 98 -46 120 -52 22 -6 45 -14 51 -18 5 -5 15 -48 22 -96 6 -48 14 -92 17 -97 4 -6 415 -10 1131 -10 l1124 0 0 1584 0 1585 -55 -19 c-84 -29 -143 -68 -232 -154 l-83 -78 -54 49 c-111 102 -233 151 -391 160 -113 6 -199 -10 -298 -54 l-60 -27 -26 34 c-37 51 -120 134 -127 128 -3 -4 0 -34 7 -67 17 -89 7 -268 -21 -356 -103 -328 -377 -545 -688 -545 -161 0 -273 41 -373 137 -37 35 -66 75 -85 116 -79 173 -8 407 124 407 44 0 68 -14 117 -66 74 -78 167 -82 238 -9 60 62 72 147 33 231 -42 90 -120 130 -238 122 -50 -4 -85 -14 -131 -37 -89 -45 -122 -52 -176 -40 -92 20 -262 163 -302 253 -11 25 -21 45 -22 45 -1 -1 -30 -6 -65 -11z m-256 -505 c115 -88 129 -102 132 -131 2 -18 -2 -40 -9 -49 -7 -8 -69 -55 -138 -105 -103 -73 -130 -88 -151 -83 -35 8 -51 34 -48 74 3 31 12 42 83 92 44 31 80 61 82 66 1 4 -30 31 -69 58 -39 28 -77 56 -85 63 -18 19 -16 72 4 94 32 35 63 23 199 -79z m528 -88 c23 -24 28 -52 14 -82 l-13 -28 -141 -3 c-130 -2 -142 -1 -158 17 -23 26 -24 66 -1 91 16 18 32 20 151 20 105 0 136 -3 148 -15z"/>+ </g>+</svg>diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex 894c78ba..dfa1e679 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -1543,6 +1543,13 @@ pub(crate) const RESTARTED_ENV: &str = "THINKTERM_RESTARTED";static RESTARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);fn main() {+ #[cfg(unix)]+ {+ thinkterm_import_herdr::register().expect("register built-in session importer");+ if let Some(result) = thinkterm_import::maybe_run_helper() {+ std::process::exit(if result.is_ok() { 0 } else { 1 });+ }+ }#[cfg(feature = "dhat-heap")]let _profiler = dhat::Profiler::new_heap();diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rsindex 64010ccd..ce9d8839 100644--- a/wezterm-gui/src/settings_window.rs+++ b/wezterm-gui/src/settings_window.rs@@ -47,6 +47,11 @@ use crate::native_settings::{};use fluent_bundle::FluentArgs;+#[cfg(unix)]+mod session_import;+mod import;+use import::{ImportButton, ImportSource, ImportStep};+// All chrome geometry below is authored in 2x macOS backing pixels.// settings_ui_scale_for_dpi maps it onto other platforms by treating the// design as a 192dpi surface, which halves everything at a 1x/96dpi@@ -273,6 +278,7 @@ thread_local! {/// in the terminal the user was looking at rather than in whichever/// window happens to sort first.static OPENED_FROM: Cell<Option<MuxWindowId>> = const { Cell::new(None) };+ static OPENED_FROM_SPACE: RefCell<Option<String>> = const { RefCell::new(None) };}enum SettingsWindowSlot {@@ -616,7 +622,7 @@ enum SettingsSection {Archived,Keymap,CommandPalette,- Compatibility,+ Import,Developer,UiKit,Memory,@@ -637,7 +643,7 @@ const BASE_SECTIONS: &[SettingsSection] = &[SettingsSection::Archived,SettingsSection::Keymap,SettingsSection::CommandPalette,- SettingsSection::Compatibility,+ SettingsSection::Import,SettingsSection::Developer,SettingsSection::Backup,SettingsSection::Update,@@ -715,13 +721,15 @@ fn initial_section() -> SettingsSection {"archived" => SettingsSection::Archived,"keymap" => SettingsSection::Keymap,"commandpalette" => SettingsSection::CommandPalette,- "compatibility" => SettingsSection::Compatibility,+ "import" | "compatibility" => SettingsSection::Import,"developer" => SettingsSection::Developer,"uikit" => SettingsSection::UiKit,"memory" => SettingsSection::Memory,"backup" => SettingsSection::Backup,"update" => SettingsSection::Update,"about" => SettingsSection::About,+ #[cfg(unix)]+ id if thinkterm_import::source(id).is_ok() => SettingsSection::Import,_ => SettingsSection::Appearance,};if section == SettingsSection::Agents {@@ -747,7 +755,7 @@ impl SettingsSection {Self::Archived => crate::i18n::tr("settings-section-archived"),Self::Keymap => crate::i18n::tr("settings-section-keymap"),Self::CommandPalette => crate::i18n::tr("settings-section-command-palette"),- Self::Compatibility => crate::i18n::tr("settings-section-compatibility"),+ Self::Import => crate::i18n::tr("settings-section-import"),Self::Developer => crate::i18n::tr("settings-section-developer"),Self::UiKit => "UI Kit".to_string(),Self::Memory => "Memory".to_string(),@@ -770,7 +778,7 @@ impl SettingsSection {Self::Archived => SettingsIcon::Archived,Self::Keymap => SettingsIcon::Keymap,Self::CommandPalette => SettingsIcon::CommandPalette,- Self::Compatibility => SettingsIcon::Sync,+ Self::Import => SettingsIcon::Import,Self::Developer => SettingsIcon::Developer,Self::UiKit => SettingsIcon::UiKit,Self::Memory => SettingsIcon::Memory,@@ -795,7 +803,7 @@ impl SettingsSection {Self::Archived => TileColor::Indigo,Self::Keymap => TileColor::Gray,Self::CommandPalette => TileColor::Blue,- Self::Compatibility => TileColor::Green,+ Self::Import => TileColor::Green,Self::Developer => TileColor::Gray,Self::UiKit => TileColor::Pink,Self::Memory => TileColor::Teal,@@ -924,7 +932,10 @@ impl SettingsSection {"Font Size","Theme Search",],- Self::Compatibility => &[+ Self::Import => &[+ "Herdr",+ "Import Session",+ "导入","ThinkTerm Config","WezTerm Source","Copy WezTerm Config",@@ -1366,6 +1377,22 @@ fn web_token_key(id: &str) -> u64 {#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum SettingsAction {+ SelectImportSource(ImportSource),+ ImportContinue,+ ImportBack,+ ImportStartOver,+ #[cfg(unix)]+ SessionImportDetect,+ #[cfg(unix)]+ SessionImportPreview(u64),+ #[cfg(unix)]+ SessionImportBack,+ #[cfg(unix)]+ SessionImportConfirm,+ #[cfg(unix)]+ SessionImportRecover,+ #[cfg(unix)]+ SessionImportOpen,WindowHide,WindowMaximize,WindowClose,@@ -2016,6 +2043,11 @@ impl ChromeFontArea {#[derive(Debug, Clone)]struct SettingsUiState {+ import_source: ImportSource,+ import_step: ImportStep,+ import_result: Option<String>,+ #[cfg(unix)]+ session_import: session_import::ImportUi,tokens: UiTokens,sidebar: ResizablePaneState,sidebar_scroll: ScrollState,@@ -2139,6 +2171,22 @@ impl SettingsUiState {fn new(dpi: usize) -> Self {let tokens = UiTokens::for_dpi(dpi);Self {+ #[cfg(unix)]+ session_import: session_import::ImportUi::default(),+ import_source: ImportSource::initial(),+ import_step: {+ #[cfg(unix)]+ if session_import::remembered_source().is_some() {+ ImportStep::Review+ } else {+ ImportStep::Source+ }+ #[cfg(not(unix))]+ {+ ImportStep::Source+ }+ },+ import_result: None,sidebar: ResizablePaneState::new(tokens.sidebar_default_width,tokens.sidebar_min_width,@@ -2859,8 +2907,25 @@ pub fn show_update_page() {}/// Open Settings, remembering which window asked. See `OPENED_FROM`.-pub fn show_from(mux_window_id: MuxWindowId) {+pub fn show_from(mux_window_id: MuxWindowId, space_id: &str) {OPENED_FROM.with(|slot| slot.set(Some(mux_window_id)));+ let changed = OPENED_FROM_SPACE+ .with(|slot| slot.replace(Some(space_id.to_string())).as_deref() != Some(space_id));+ #[cfg(unix)]+ if changed {+ SETTINGS_WINDOW.with(|slot| {+ if let SettingsWindowSlot::Open { settings, .. } = &*slot.borrow() {+ let mut settings = settings.borrow_mut();+ // A preview is bound to its owner until that import finishes.+ if !settings.ui.session_import.busy() {+ settings.ui.session_import = session_import::ImportUi::default();+ settings.ui.import_step = ImportStep::Source;+ }+ }+ });+ }+ #[cfg(not(unix))]+ let _ = changed;show();}@@ -2971,6 +3036,8 @@ struct SettingsWindow {/// weight for labels and explanations made the two read as equally/// important; macOS separates them by weight, not only by color.body_font: Rc<LoadedFont>,+ import_body_font: Rc<LoadedFont>,+ import_title_font: Rc<LoadedFont>,title_font: Rc<LoadedFont>,sidebar_title_font: Rc<LoadedFont>,logo_caption_font: Rc<LoadedFont>,@@ -3060,6 +3127,14 @@ impl SettingsWindow {settings_font_size,settings_body_font_weight(settings_font_weight),)?;+ let import_body_font = fonts.command_palette_font_with_size_and_weight(+ (settings_font_size - 1.0).max(10.0),+ (settings_font_weight as f32 * 0.67).round().max(350.0) as u16,+ )?;+ let import_title_font = fonts.title_font_with_size_and_weight(+ settings_font_size + 10.0,+ settings_font_weight,+ )?;let logo_caption_font = fonts.command_palette_font_with_size_and_weight(LOGO_CAPTION_FONT_SIZE,LOGO_CAPTION_FONT_WEIGHT,@@ -3131,6 +3206,8 @@ impl SettingsWindow {fonts: Rc::clone(&fonts),ui_font,body_font,+ import_body_font,+ import_title_font,title_font,sidebar_title_font,logo_caption_font,@@ -3255,6 +3332,18 @@ impl SettingsWindow {return Ok(());}+ #[cfg(debug_assertions)]+ if std::env::var("THINKTERM_SETTINGS_EXPAND")+ .is_ok_and(|value| value == "import-preview")+ {+ if let Some(settings) = settings_window_for_instance(instance_id) {+ let mut settings = settings.borrow_mut();+ if settings.selected == SettingsSection::Import {+ settings.perform_import_navigation(SettingsAction::ImportContinue, &window);+ }+ }+ }+window.show();window.invalidate();@@ -4557,6 +4646,14 @@ impl SettingsWindow {settings_font_size,settings_body_font_weight(settings_font_weight),)?;+ self.import_body_font = self.fonts.command_palette_font_with_size_and_weight(+ (settings_font_size - 1.0).max(10.0),+ (settings_font_weight as f32 * 0.67).round().max(350.0) as u16,+ )?;+ self.import_title_font = self.fonts.title_font_with_size_and_weight(+ settings_font_size + 10.0,+ settings_font_weight,+ )?;self.logo_caption_font = self.fonts.command_palette_font_with_size_and_weight(LOGO_CAPTION_FONT_SIZE,LOGO_CAPTION_FONT_WEIGHT,@@ -5131,6 +5228,26 @@ impl SettingsWindow {fn perform_action(&mut self, action: SettingsAction, window: &Window) {match action {+ SettingsAction::SelectImportSource(source) => {+ if self.import_busy() { return; }+ #[cfg(unix)]+ if self.ui.import_source != source {+ self.ui.session_import = session_import::ImportUi::default();+ }+ self.ui.import_source = source;+ self.ui.content_scroll.reset();+ self.ui.open_dropdown = None;+ }+ SettingsAction::ImportContinue+ | SettingsAction::ImportBack+ | SettingsAction::ImportStartOver => self.perform_import_navigation(action, window),+ #[cfg(unix)]+ SettingsAction::SessionImportDetect+ | SettingsAction::SessionImportPreview(_)+ | SettingsAction::SessionImportBack+ | SettingsAction::SessionImportRecover+ | SettingsAction::SessionImportConfirm+ | SettingsAction::SessionImportOpen => self.perform_session_import_action(action),SettingsAction::WindowHide => {self.ui.open_dropdown = None;window.hide();@@ -5188,6 +5305,7 @@ impl SettingsWindow {}SettingsAction::LoadWezTermSource => {self.ui.open_dropdown = None;+ self.compatibility_import = CompatibilityImportState::default();match self.load_compatibility_source() {Ok(()) => window.invalidate(),Err(err) => {@@ -5211,12 +5329,16 @@ impl SettingsWindow {},&[("count", count.to_string())],);+ self.ui.import_result = Some(self.status.clone());+ self.ui.import_step = ImportStep::Result;+ self.ui.content_scroll.reset();}Err(err) => {self.status = settings_tr("settings-status-import-error",&[("error", format!("{err:#}"))],);+ self.compatibility_import.error = Some(self.status.clone());}}}@@ -7260,20 +7382,22 @@ impl SettingsWindow {let scroll = self.ui.content_scroll.offset;let selected_label = self.selected.label();- self.draw_text(- layers,- &title_font,- x,- self.ui_px(CONTENT_TITLE_Y) - scroll,- &selected_label,- palette.title,- max_width,- )?;+ if self.selected != SettingsSection::Import {+ self.draw_text(+ layers,+ &title_font,+ x,+ self.ui_px(CONTENT_TITLE_Y) - scroll,+ &selected_label,+ palette.title,+ max_width,+ )?;+ }match self.selected {SettingsSection::Appearance => self.paint_appearance(layers, x, max_width)?,SettingsSection::TabIcons => self.paint_tab_icons(layers, x, max_width)?,- SettingsSection::Compatibility => self.paint_compatibility(layers, x, max_width)?,+ SettingsSection::Import => self.paint_import(layers, x, max_width)?,SettingsSection::General => self.paint_general(layers, x, max_width)?,SettingsSection::Terminal => self.paint_terminal(layers, x, max_width)?,SettingsSection::Workspaces => self.paint_workspaces(layers, x, max_width)?,@@ -12079,14 +12203,6 @@ impl SettingsWindow {let scroll = self.ui.content_scroll.offset;let row_step = self.settings_row_step();let section_y = self.ui_px(CONTENT_SECTION_Y) - scroll;- let (card_y, first_row_y) = self.settings_card_geometry(section_y, 4);- let card_height = self.settings_card_height(4);- let button_y = card_y + card_height + self.settings_section_card_gap();- self.ui.content_scroll.set_extents(- self.content_viewport_extent(),- self.settings_content_extent(button_y + scroll + self.ui_px(CONTROL_HEIGHT)),- );-self.draw_text(layers,&body_font,@@ -12097,6 +12213,10 @@ impl SettingsWindow {max_width,)?;+ let (card_y, first_row_y) = self.settings_card_geometry(section_y, 4);+ let card_height = self.settings_card_height(4);+ let button_y = card_y + card_height + self.settings_section_card_gap();+let card_padding = self.ui_px(36.0);let row_x = x + card_padding;let row_width = max_width - card_padding * 2.0;@@ -12158,6 +12278,16 @@ impl SettingsWindow {SettingsAction::ShowOnboardingNow,)?;+ self.ui.content_scroll.set_extents(+ self.content_viewport_extent(),+ self.settings_content_extent(button_y + scroll + self.ui_px(CONTROL_HEIGHT)),+ );+ if self.ui.content_scroll.offset != scroll {+ if let Some(window) = &self.window {+ window.invalidate();+ }+ }+Ok(())}@@ -13113,201 +13243,6 @@ impl SettingsWindow {Ok(())}- fn paint_compatibility(- &mut self,- layers: &mut TripleLayerQuadAllocator<'_>,- x: f32,- max_width: f32,- ) -> anyhow::Result<()> {- let palette = self.palette();- let body_font = Rc::clone(&self.body_font);- let scroll = self.ui.content_scroll.offset;- let row_step = self.settings_row_step();- let section_y = self.ui_px(CONTENT_SECTION_Y) - scroll;- let field_count = self.compatibility_import.fields.len();- let row_count = 3 + field_count;- let (card_y, first_row_y) = self.settings_card_geometry(section_y, row_count);- let card_height = self.settings_card_height(row_count);- let buttons_y = card_y + card_height + self.settings_section_card_gap();- self.ui.content_scroll.set_extents(- self.content_viewport_extent(),- self.settings_content_extent(- buttons_y + scroll + self.ui_px(CONTROL_HEIGHT) * 2.0 + 14.0,- ),- );- let thinkterm_path = Self::thinkterm_compatible_config_path();- let thinkterm_source = if thinkterm_path.exists() {- thinkterm_path.display().to_string()- } else {- let mut args = FluentArgs::new();- args.set("path", thinkterm_path.display().to_string());- crate::i18n::tr_args("settings-thinkterm-config-missing", &args)- };- let wezterm_source_path = self.selected_wezterm_source_path();- let wezterm_source = wezterm_source_path- .as_ref()- .map(|path| path.display().to_string())- .unwrap_or_else(|| crate::i18n::tr("settings-wezterm-source-missing"));- let thinkterm_status = if thinkterm_path.exists() {- crate::i18n::tr("settings-import-config-ready")- } else {- crate::i18n::tr("settings-import-config-will-create")- };- let wezterm_status = if wezterm_source_path.is_some() {- crate::i18n::tr("common-found")- } else {- crate::i18n::tr("common-missing")- };- let selected_count = self- .compatibility_import- .fields- .iter()- .filter(|field| field.lua_value.is_some() && self.import_field_selected(field.id))- .count();- let selection_status = if self.compatibility_import.error.is_some() {- crate::i18n::tr("common-error")- } else if field_count == 0 {- crate::i18n::tr("settings-not-loaded")- } else {- let mut args = FluentArgs::new();- args.set("selected", selected_count);- args.set("total", field_count);- crate::i18n::tr_args("settings-fields-selected", &args)- };- let selection_description = self- .compatibility_import- .error- .clone()- .unwrap_or_else(|| crate::i18n::tr("settings-import-selection-description"));-- self.draw_text(- layers,- &body_font,- x,- section_y,- &crate::i18n::tr("settings-compatibility-description"),- palette.secondary_text,- max_width,- )?;- let card_padding = self.ui_px(36.0);- let row_x = x + card_padding;- let row_width = max_width - card_padding * 2.0;- self.paint_group_card(layers, x, card_y, max_width, card_height)?;- self.paint_setting_row(- layers,- row_x,- first_row_y,- row_width,- &crate::i18n::tr("settings-thinkterm-config"),- &thinkterm_source,- &thinkterm_status,- false,- )?;- self.paint_setting_row(- layers,- row_x,- first_row_y + row_step,- row_width,- &crate::i18n::tr("settings-wezterm-source"),- &wezterm_source,- &wezterm_status,- true,- )?;- self.paint_setting_row(- layers,- row_x,- first_row_y + row_step * 2.0,- row_width,- &crate::i18n::tr("settings-import-selection"),- &selection_description,- &selection_status,- true,- )?;-- let mut row_y = first_row_y + row_step * 3.0;- if !self.compatibility_import.fields.is_empty() {- let fields = self.compatibility_import.fields.clone();- for field in fields {- self.paint_import_field_row(layers, row_x, row_y, row_width, &field, true)?;- row_y += row_step;- }- }- let load_label = crate::i18n::tr("settings-load-wezterm-source");- let select_all_label = crate::i18n::tr("common-select-all");- let clear_label = crate::i18n::tr("common-clear");- let import_label = crate::i18n::tr("settings-import-selected");- let open_wezterm_label = crate::i18n::tr("settings-open-wezterm-source");- let open_thinkterm_label = crate::i18n::tr("settings-open-thinkterm-config");- // Without a WezTerm configuration there is nothing to review, import- // or open, and until one is reviewed nothing to select: those buttons- // are greyed out instead of answering a click with an error.- let has_source = wezterm_source_path.is_some();- let has_fields = field_count > 0;- self.draw_button_enabled(- layers,- x,- buttons_y,- self.button_width_for_label(&load_label, 290.0),- &load_label,- SettingsAction::LoadWezTermSource,- has_source,- )?;- let second_x = x + self.button_width_for_label(&load_label, 290.0) + self.ui_px(16.0);- self.draw_button_enabled(- layers,- second_x,- buttons_y,- self.button_width_for_label(&select_all_label, 180.0),- &select_all_label,- SettingsAction::SelectAllImportFields,- has_fields,- )?;- let third_x =- second_x + self.button_width_for_label(&select_all_label, 180.0) + self.ui_px(16.0);- self.draw_button_enabled(- layers,- third_x,- buttons_y,- self.button_width_for_label(&clear_label, 150.0),- &clear_label,- SettingsAction::ClearImportFields,- has_fields,- )?;- let fourth_x =- third_x + self.button_width_for_label(&clear_label, 150.0) + self.ui_px(16.0);- self.draw_button_enabled(- layers,- fourth_x,- buttons_y,- self.button_width_for_label(&import_label, 260.0),- &import_label,- SettingsAction::ImportSelectedFields,- has_source,- )?;- let open_buttons_y = buttons_y + self.ui_px(CONTROL_HEIGHT) + 14.0;- self.draw_button_enabled(- layers,- x,- open_buttons_y,- self.button_width_for_label(&open_wezterm_label, 300.0),- &open_wezterm_label,- SettingsAction::OpenWezTermConfigFile,- has_source,- )?;- let fifth_x =- x + self.button_width_for_label(&open_wezterm_label, 300.0) + self.ui_px(16.0);- self.draw_button(- layers,- fifth_x,- open_buttons_y,- self.button_width_for_label(&open_thinkterm_label, 300.0),- &open_thinkterm_label,- SettingsAction::OpenThinkTermConfigFile,- )?;-- Ok(())- }-/// Row geometry for the two app-level pages. Unlike `settings_row_step`/// these rows carry no explanation line, so they are a single line tall/// -- the shape macOS System Settings uses for a list of plain facts.@@ -15860,7 +15795,7 @@ impl SettingsWindow {) -> anyhow::Result<()> {let palette = self.palette();let ui_font = Rc::clone(&self.ui_font);- let body_font = Rc::clone(&self.body_font);+ let body_font = Rc::clone(&self.import_body_font);let action = SettingsAction::ToggleImportField(field.id);let enabled = field.lua_value.is_some();let selected = enabled && self.import_field_selected(field.id);@@ -15880,11 +15815,9 @@ impl SettingsWindow {if enabled {self.ui_context.push(row_rect, WidgetKind::Button, action);}- if selected || hovered || pressed {+ if hovered || pressed {let bg = if pressed {palette.control_pressed_bg- } else if selected {- rgba(10, 132, 255, 0.14)} else {palette.control_hover_bg};@@ -15900,18 +15833,18 @@ impl SettingsWindow {)?;}- let checkbox_size = 30.0;+ let checkbox_size = self.ui_px(28.0);let checkbox_x = x;let checkbox_y = y + self.ui_px(6.0);let checkbox_fill = if selected {- palette.nav_selected_bg+ self.chrome_palette.accent} else if hovered {palette.control_hover_bg} else {palette.control_bg};let checkbox_border = if selected || hovered {- palette.nav_selected_bg+ self.chrome_palette.accent} else {palette.control_border};@@ -15927,15 +15860,13 @@ impl SettingsWindow {self.ui_px(8.0),)?;if selected {- self.draw_rounded_rect(+ self.draw_svg_icon(layers,- 1,- checkbox_x + self.ui_px(8.0),- checkbox_y + self.ui_px(8.0),- checkbox_size - self.ui_px(16.0),- checkbox_size - self.ui_px(16.0),- palette.selected_text,- self.ui_px(4.0),+ SvgIcon::Check,+ checkbox_x + self.ui_px(5.0),+ checkbox_y + self.ui_px(5.0),+ checkbox_size - self.ui_px(10.0),+ palette.on_accent,)?;}@@ -15947,13 +15878,13 @@ impl SettingsWindow {};let value_x = x + width - value_width;let text_width = (value_x - label_x - self.ui_px(28.0)).max(width * 0.42);- let title = format!("{} / {}", field.category, field.label);+ let title = &field.label;self.draw_text(layers,- &body_font,+ &ui_font,label_x,y,- &title,+ title,if enabled {palette.text} else {diff --git a/wezterm-gui/src/settings_window/import.rs b/wezterm-gui/src/settings_window/import.rsnew file mode 100644index 00000000..a461ad0a--- /dev/null+++ b/wezterm-gui/src/settings_window/import.rs@@ -0,0 +1,1330 @@+use super::*;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) enum ImportStep {+ Source,+ Review,+ Result,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) enum ImportSource {+ WezTerm,+ #[cfg(unix)]+ Session(&'static str),+}++impl ImportSource {+ pub(super) fn all() -> Vec<Self> {+ let mut sources = vec![Self::WezTerm];+ #[cfg(unix)]+ sources.extend(+ thinkterm_import::sources()+ .into_iter()+ .map(|source| Self::Session(source.id)),+ );+ sources+ }++ pub(super) fn initial() -> Self {+ #[cfg(unix)]+ if let Some(source) = session_import::remembered_source() {+ return source;+ }+ #[cfg(unix)]+ if let Ok(selected) = std::env::var("THINKTERM_SETTINGS_SECTION") {+ if let Some(source) = thinkterm_import::sources()+ .into_iter()+ .find(|s| s.id.eq_ignore_ascii_case(&selected))+ {+ return Self::Session(source.id);+ }+ }+ Self::WezTerm+ }++ pub(super) fn label(self) -> &'static str {+ match self {+ Self::WezTerm => "WezTerm",+ #[cfg(unix)]+ Self::Session(id) => thinkterm_import::source(id)+ .map(|s| s.info().name)+ .unwrap_or(id),+ }+ }++ fn description(self) -> String {+ crate::i18n::tr(match self {+ Self::WezTerm => "settings-import-wezterm-description",+ #[cfg(unix)]+ Self::Session(_) => "settings-import-session-description",+ })+ }++ fn icon(self) -> Option<BrandIcon> {+ match self {+ Self::WezTerm => Some(BrandIcon::WezTerm),+ #[cfg(unix)]+ Self::Session(id) => match thinkterm_import::source(id).ok()?.info().icon {+ "herdr" => Some(BrandIcon::Herdr),+ _ => None,+ },+ }+ }++ #[cfg(unix)]+ pub(super) fn provider(self) -> anyhow::Result<&'static dyn thinkterm_import::ImportSource> {+ match self {+ Self::Session(id) => thinkterm_import::source(id),+ Self::WezTerm => anyhow::bail!("The selected source imports settings, not sessions"),+ }+ }++ pub(super) fn text(self, key: &str) -> String {+ self.text_args(key, &[])+ }++ pub(super) fn text_args(self, key: &str, values: &[(&str, String)]) -> String {+ let mut args = FluentArgs::new();+ for (name, value) in values {+ args.set(*name, value.as_str());+ }+ args.set("source", self.label());+ crate::i18n::tr_args(key, &args)+ }+}++pub(super) struct ImportButton {+ pub(super) label: String,+ pub(super) action: SettingsAction,+ pub(super) primary: bool,+ pub(super) enabled: bool,+}++struct ImportSourceLayout {+ columns: usize,+ card_width: f32,+ card_height: f32,+ total_height: f32,+ descriptions: Vec<Vec<String>>,+}++impl SettingsWindow {+ pub(super) fn import_busy(&self) -> bool {+ #[cfg(unix)]+ if matches!(self.ui.import_source, ImportSource::Session(_)) {+ return self.ui.session_import.busy();+ }+ false+ }++ pub(super) fn perform_import_navigation(&mut self, action: SettingsAction, window: &Window) {+ if self.import_busy() {+ return;+ }+ self.ui.content_scroll.reset();+ self.ui.open_dropdown = None;+ match action {+ SettingsAction::ImportContinue => {+ self.ui.import_step = ImportStep::Review;+ self.ui.import_result = None;+ match self.ui.import_source {+ ImportSource::WezTerm => {+ self.perform_action(SettingsAction::LoadWezTermSource, window)+ }+ #[cfg(unix)]+ ImportSource::Session(_) => {+ self.perform_session_import_action(SettingsAction::SessionImportDetect)+ }+ }+ }+ SettingsAction::ImportBack => {+ #[cfg(unix)]+ if matches!(self.ui.import_source, ImportSource::Session(_))+ && self.ui.session_import.has_preview()+ {+ self.perform_session_import_action(SettingsAction::SessionImportBack);+ window.invalidate();+ return;+ }+ self.ui.import_step = ImportStep::Source;+ }+ SettingsAction::ImportStartOver => {+ self.ui.import_step = ImportStep::Source;+ self.ui.import_result = None;+ #[cfg(unix)]+ {+ self.ui.session_import = session_import::ImportUi::default();+ }+ }+ _ => {}+ }+ window.invalidate();+ }++ pub(super) fn paint_import(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ width: f32,+ ) -> anyhow::Result<()> {+ let measure = width.min(self.ui_px(1040.0));+ let x = x + (width - measure) / 2.0;+ let width = measure;+ let scroll = self.ui.content_scroll.offset;+ let step_bottom =+ self.paint_import_steps(layers, x, self.ui_px(CONTENT_TITLE_Y) - scroll, width)?;+ let top = step_bottom + self.ui_px(64.0);+ let bottom = match self.ui.import_step {+ ImportStep::Source => {+ let title = crate::i18n::tr("settings-import-choose-title");+ let description = crate::i18n::tr("settings-import-description");+ let layout = self.import_source_layout(width);+ let heading_height = self.import_heading_height(width, &title, &description);+ let body_height = heading_height + self.ui_px(40.0) + layout.total_height;+ let body_end = self.content_bottom() - scroll - self.ui_px(172.0);+ let centered_top = top + ((body_end - top - body_height) / 2.0).max(0.0);+ let heading = self.paint_import_heading(+ layers,+ x,+ centered_top,+ width,+ &title,+ &description,+ )?;+ let body = self.paint_import_sources(+ layers,+ x,+ heading + self.ui_px(40.0),+ width,+ &layout,+ )?;+ self.paint_import_footer(+ layers,+ x,+ body + self.ui_px(40.0),+ width,+ None,+ &[ImportButton {+ label: crate::i18n::tr("settings-import-continue"),+ action: SettingsAction::ImportContinue,+ primary: true,+ enabled: true,+ }],+ )?+ }+ ImportStep::Review => match self.ui.import_source {+ ImportSource::WezTerm => self.paint_wezterm_import(layers, x, top, width)?,+ #[cfg(unix)]+ ImportSource::Session(_) => self.paint_session_import(layers, x, top, width)?,+ },+ ImportStep::Result => match self.ui.import_source {+ ImportSource::WezTerm => {+ let message = self.ui.import_result.clone().unwrap_or_default();+ let bottom = self.paint_import_result(+ layers,+ x,+ top + self.ui_px(64.0),+ width,+ &message,+ )?;+ self.paint_import_footer(+ layers,+ x,+ bottom + self.ui_px(40.0),+ width,+ Some(SettingsAction::ImportStartOver),+ &[ImportButton {+ label: crate::i18n::tr("settings-open-thinkterm-config"),+ action: SettingsAction::OpenThinkTermConfigFile,+ primary: true,+ enabled: true,+ }],+ )?+ }+ #[cfg(unix)]+ ImportSource::Session(_) => self.paint_session_result(layers, x, top, width)?,+ },+ };+ self.ui.content_scroll.set_extents(+ self.content_viewport_extent(),+ self.settings_content_extent(bottom + scroll),+ );+ if self.ui.content_scroll.offset != scroll {+ if let Some(window) = &self.window {+ window.invalidate();+ }+ }+ Ok(())+ }++ fn paint_import_steps(+ &self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ ) -> anyhow::Result<f32> {+ let labels = [+ "settings-import-step-source",+ "settings-import-step-review",+ "settings-import-step-result",+ ]+ .map(crate::i18n::tr);+ let active = match self.ui.import_step {+ ImportStep::Source => 0,+ ImportStep::Review => 1,+ ImportStep::Result => 2,+ };+ let font = Rc::clone(&self.ui_font);+ let cell = RenderMetrics::with_font_metrics(&font.metrics())+ .cell_size+ .height as f32;+ let circle = self.ui_px(48.0);+ let gap = self.ui_px(16.0);+ let connector = self.ui_px(64.0);+ let widths: Vec<_> = labels+ .iter()+ .map(|label| circle + gap + self.measure_text_width(&font, label))+ .collect();+ let total = widths.iter().sum::<f32>() + connector * 2.0;+ if total > width {+ let label = format!("{} / 3 · {}", active + 1, labels[active]);+ self.draw_text(+ layers,+ &font,+ x,+ y,+ &label,+ self.palette().secondary_text,+ width,+ )?;+ return Ok(y + cell);+ }+ let mut left = x + (width - total) / 2.0;+ for (index, label) in labels.iter().enumerate() {+ let color = if index <= active {+ self.chrome_palette.accent+ } else {+ self.palette().separator+ };+ self.draw_rounded_frame(+ layers,+ 0,+ left,+ y,+ circle,+ circle,+ if index <= active {+ color+ } else {+ self.palette().control_bg+ },+ color,+ circle / 2.0,+ )?;+ if index < active {+ self.draw_svg_icon(+ layers,+ SvgIcon::Check,+ left + circle * 0.25,+ y + circle * 0.25,+ circle * 0.5,+ self.palette().on_accent,+ )?;+ } else {+ let number = (index + 1).to_string();+ self.draw_import_step_text(+ layers,+ &font,+ left,+ y,+ circle,+ circle,+ &number,+ if index == active {+ self.palette().on_accent+ } else {+ self.palette().secondary_text+ },+ )?;+ }+ self.draw_import_step_text(+ layers,+ &font,+ left + circle + gap,+ y,+ widths[index] - circle - gap,+ circle,+ label,+ if index == active {+ self.palette().title+ } else {+ self.palette().secondary_text+ },+ )?;+ left += widths[index];+ if index < 2 {+ self.draw_rect(+ layers,+ 0,+ left + self.ui_px(16.0),+ y + (circle - self.ui_px(1.0)) / 2.0,+ connector - self.ui_px(32.0),+ self.ui_px(1.0),+ self.palette().separator,+ )?;+ left += connector;+ }+ }+ Ok(y + circle)+ }++ fn draw_import_step_text(+ &self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ font: &Rc<LoadedFont>,+ x: f32,+ y: f32,+ width: f32,+ height: f32,+ text: &str,+ color: LinearRgba,+ ) -> anyhow::Result<()> {+ let Some((left, top, right, bottom)) = self.import_ink_bounds(font, text) else {+ return Ok(());+ };+ let baseline = self.metrics.cell_size.height as f32 + self.metrics.descender.get() as f32;+ self.draw_text(+ layers,+ font,+ x + (width - (right - left)) / 2.0 - left,+ y + (height - (bottom - top)) / 2.0 - top - baseline,+ text,+ color,+ width.max(self.measure_text_width(font, text)),+ )+ }++ fn import_ink_bounds(&self, font: &Rc<LoadedFont>, text: &str) -> Option<(f32, f32, f32, f32)> {+ let shaped = self.shaped_text(font, text)?;+ let mut bounds: Option<(f32, f32, f32, f32)> = None;+ let mut advance = 0.0;+ for glyph in &shaped.glyphs {+ if let Some(texture) = &glyph.texture {+ let left = advance + (glyph.x_offset + glyph.bearing_x).get() as f32;+ let top = -(glyph.y_offset + glyph.bearing_y).get() as f32;+ let right = left + texture.coords.size.width as f32 * glyph.scale as f32;+ let bottom = top + texture.coords.size.height as f32 * glyph.scale as f32;+ bounds = Some(match bounds {+ Some((l, t, r, b)) => (l.min(left), t.min(top), r.max(right), b.max(bottom)),+ None => (left, top, right, bottom),+ });+ }+ advance += glyph.x_advance.get() as f32;+ }+ bounds+ }++ pub(super) fn draw_import_line(+ &self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ font: &Rc<LoadedFont>,+ x: f32,+ y: f32,+ width: f32,+ height: f32,+ text: &str,+ color: LinearRgba,+ ) -> anyhow::Result<()> {+ let Some((left, top, _, bottom)) = self.import_ink_bounds(font, text) else {+ return Ok(());+ };+ let baseline = self.metrics.cell_size.height as f32 + self.metrics.descender.get() as f32;+ self.draw_text(+ layers,+ font,+ x - left,+ y + (height - (bottom - top)) / 2.0 - top - baseline,+ text,+ color,+ width,+ )+ }++ fn import_heading_height(&self, width: f32, title: &str, description: &str) -> f32 {+ let title_height = RenderMetrics::with_font_metrics(&self.import_title_font.metrics())+ .cell_size+ .height as f32;+ let title_lines = self+ .wrap_settings_text(&self.import_title_font, title, width)+ .len();+ let body_lines: usize = description+ .split('\n')+ .map(|line| {+ self.wrap_settings_text(&self.import_body_font, line, width)+ .len()+ })+ .sum();+ title_height * title_lines as f32+ + self.ui_px(4.0)+ + self.import_line_step() * body_lines as f32+ }++ fn paint_import_heading(+ &self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ title: &str,+ description: &str,+ ) -> anyhow::Result<f32> {+ let font = Rc::clone(&self.import_title_font);+ let step = RenderMetrics::with_font_metrics(&font.metrics())+ .cell_size+ .height as f32;+ let mut top = y;+ for line in self.wrap_settings_text(&font, title, width) {+ self.draw_text(+ layers,+ &font,+ x + ((width - self.measure_text_width(&font, &line)) / 2.0).max(0.0),+ top,+ &line,+ self.palette().title,+ width,+ )?;+ top += step;+ }+ self.paint_import_centered_copy(layers, x, top + self.ui_px(4.0), width, description)+ }++ pub(super) fn paint_import_centered_copy(+ &self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ text: &str,+ ) -> anyhow::Result<f32> {+ let font = Rc::clone(&self.import_body_font);+ let mut top = y;+ for paragraph in text.split('\n') {+ for line in self.wrap_settings_text(&font, paragraph, width) {+ self.draw_text(+ layers,+ &font,+ x + ((width - self.measure_text_width(&font, &line)) / 2.0).max(0.0),+ top,+ &line,+ self.palette().secondary_text,+ width,+ )?;+ top += self.import_line_step();+ }+ }+ Ok(top)+ }++ pub(super) fn paint_import_source_heading(+ &self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ title: &str,+ description: &str,+ ) -> anyhow::Result<f32> {+ let mark = self.ui_px(88.0).min(width * 0.2);+ let gap = self.ui_px(24.0);+ let left = x + mark + gap;+ let inner = (width - mark - gap).max(1.0);+ let title_font = Rc::clone(&self.title_font);+ let body_font = Rc::clone(&self.import_body_font);+ let title_lines = self.wrap_settings_text(&title_font, title, inner);+ let body_lines = self.wrap_settings_text(&body_font, description, inner);+ let line_height = |font, lines: &[String], minimum| {+ lines+ .iter()+ .filter_map(|line| self.import_ink_bounds(font, line))+ .map(|(_, top, _, bottom)| bottom - top)+ .fold(self.ui_px(minimum), f32::max)+ + self.ui_px(8.0)+ };+ let title_height = line_height(&title_font, &title_lines, 32.0);+ let body_height = line_height(&body_font, &body_lines, 24.0);+ let text_height = title_height * title_lines.len() as f32+ + self.ui_px(4.0)+ + body_height * body_lines.len() as f32;+ let height = mark.max(text_height);+ if let Some(icon) = self.ui.import_source.icon() {+ self.draw_brand_icon(layers, icon, x, y + (height - mark) / 2.0, mark)?;+ } else {+ self.draw_svg_icon(+ layers,+ SvgIcon::Terminal,+ x,+ y + (height - mark) / 2.0,+ mark,+ self.palette().text,+ )?;+ }+ let mut top = y + (height - text_height) / 2.0;+ for line in title_lines {+ self.draw_import_line(+ layers,+ &title_font,+ left,+ top,+ inner,+ title_height,+ &line,+ self.palette().title,+ )?;+ top += title_height;+ }+ top += self.ui_px(4.0);+ for line in body_lines {+ self.draw_import_line(+ layers,+ &body_font,+ left,+ top,+ inner,+ body_height,+ &line,+ self.palette().secondary_text,+ )?;+ top += body_height;+ }+ Ok(y + height)+ }++ pub(super) fn paint_import_result(+ &self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ message: &str,+ ) -> anyhow::Result<f32> {+ let side = self.ui_px(88.0);+ self.draw_svg_icon(+ layers,+ SvgIcon::CircleCheck,+ x + (width - side) / 2.0,+ y,+ side,+ TileColor::Green.linear(),+ )?;+ self.paint_import_heading(+ layers,+ x,+ y + side + self.ui_px(32.0),+ width,+ &crate::i18n::tr("session-import-status-done"),+ message,+ )+ }++ pub(super) fn paint_import_footer(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ body_bottom: f32,+ width: f32,+ back: Option<SettingsAction>,+ buttons: &[ImportButton],+ ) -> anyhow::Result<f32> {+ let top = body_bottom+ .max(self.content_bottom() - self.ui.content_scroll.offset - self.ui_px(132.0));+ self.draw_rect(+ layers,+ 0,+ x,+ top,+ width,+ self.ui_px(1.0),+ self.palette().separator.mul_alpha(0.7),+ )?;+ let button_y = top + self.ui_px(24.0);+ let mut action_x = x;+ let mut action_y = button_y;+ let mut action_width = width;+ if let Some(action) = back {+ let label = crate::i18n::tr(if action == SettingsAction::ImportStartOver {+ "settings-import-again"+ } else {+ "session-import-back"+ });+ let button_width = self.button_width_for_label(&label, 0.0).min(width);+ let right_width: f32 = buttons+ .iter()+ .map(|button| self.import_button_width(button))+ .sum::<f32>()+ + self.ui_px(12.0) * buttons.len().saturating_sub(1) as f32;+ self.paint_import_actions(+ layers,+ x,+ button_y,+ button_width,+ &[ImportButton {+ label,+ action,+ primary: false,+ enabled: !self.import_busy(),+ }],+ )?;+ if right_width + button_width + self.ui_px(24.0) <= width {+ action_x += button_width + self.ui_px(24.0);+ action_width -= button_width + self.ui_px(24.0);+ } else {+ action_y += self.ui_px(CONTROL_HEIGHT + 12.0);+ }+ }+ Ok(+ self.paint_import_actions(layers, action_x, action_y, action_width, buttons)?+ + self.ui_px(48.0),+ )+ }++ fn import_source_layout(&self, width: f32) -> ImportSourceLayout {+ let sources = ImportSource::all();+ let columns = if width >= self.ui_px(600.0) {+ sources.len().min(3)+ } else {+ 1+ };+ let gap = self.ui_px(28.0);+ let card_width =+ ((width - gap * (columns - 1) as f32) / columns as f32).min(self.ui_px(360.0));+ let pad = self.ui_px(36.0);+ let descriptions: Vec<_> = sources+ .iter()+ .map(|source| {+ self.wrap_settings_text(+ &self.import_body_font,+ &source.description(),+ (card_width - pad * 2.0).max(1.0),+ )+ })+ .collect();+ let card_height = pad * 2.0+ + self.ui_px(144.0 + 24.0 + 8.0)+ + self.metrics.cell_size.height as f32+ + self.import_line_step() * descriptions.iter().map(Vec::len).max().unwrap_or(1) as f32;+ let rows = sources.len().div_ceil(columns);+ ImportSourceLayout {+ columns,+ card_width,+ card_height,+ total_height: card_height * rows as f32 + gap * (rows - 1) as f32,+ descriptions,+ }+ }++ fn paint_import_sources(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ layout: &ImportSourceLayout,+ ) -> anyhow::Result<f32> {+ let sources = ImportSource::all();+ let palette = self.palette();+ let heading = Rc::clone(&self.ui_font);+ let body = Rc::clone(&self.import_body_font);+ let cell = self.metrics.cell_size.height as f32;+ let step = self.import_line_step();+ let pad = self.ui_px(36.0);+ let gap = self.ui_px(28.0);+ let icon = self.ui_px(144.0);+ let columns = layout.columns;+ let card_width = layout.card_width;+ let height = layout.card_height;+ let descriptions = &layout.descriptions;+ let text_width = (card_width - pad * 2.0).max(1.0);+ let start = x + (width - card_width * columns as f32 - gap * (columns - 1) as f32) / 2.0;+ for (index, source) in sources.iter().enumerate() {+ let left = start + (index % columns) as f32 * (card_width + gap);+ let top = y + (index / columns) as f32 * (height + gap);+ let action = SettingsAction::SelectImportSource(*source);+ let selected = *source == self.ui.import_source;+ let ground = if self.ui.interaction.pressed == Some(action) {+ palette.control_pressed_bg+ } else if self.ui.interaction.hovered == Some(action) {+ palette.control_hover_bg+ } else if selected {+ palette.card_bg+ } else {+ palette.window_bg+ };+ self.ui_context.push(+ rect(left, top, card_width, height),+ WidgetKind::Button,+ action,+ );+ self.draw_rounded_frame(+ layers,+ 0,+ left,+ top,+ card_width,+ height,+ ground,+ if selected {+ self.chrome_palette.accent+ } else {+ palette.separator+ },+ self.ui_px(32.0),+ )?;+ if let Some(brand) = source.icon() {+ self.draw_brand_icon(+ layers,+ brand,+ left + (card_width - icon) / 2.0,+ top + pad,+ icon,+ )?;+ } else {+ self.draw_svg_icon(+ layers,+ SvgIcon::Terminal,+ left + (card_width - icon) / 2.0,+ top + pad,+ icon,+ palette.muted_text,+ )?;+ }+ let title_y = top + pad + icon + self.ui_px(24.0);+ self.draw_text(+ layers,+ &heading,+ left + ((card_width - self.measure_text_width(&heading, source.label())) / 2.0)+ .max(pad),+ title_y,+ source.label(),+ palette.title,+ text_width,+ )?;+ for (row, line) in descriptions[index].iter().enumerate() {+ self.draw_text(+ layers,+ &body,+ left + ((card_width - self.measure_text_width(&body, line)) / 2.0).max(pad),+ title_y + cell + self.ui_px(8.0) + step * row as f32,+ line,+ palette.secondary_text,+ text_width,+ )?;+ }+ if selected {+ let side = self.ui_px(28.0);+ let mark_x = left + card_width - side - self.ui_px(20.0);+ let mark_y = top + self.ui_px(20.0);+ self.draw_rounded_rect(+ layers,+ 1,+ mark_x,+ mark_y,+ side,+ side,+ self.chrome_palette.accent,+ side / 2.0,+ )?;+ self.draw_svg_icon(+ layers,+ SvgIcon::Check,+ mark_x + self.ui_px(6.0),+ mark_y + self.ui_px(6.0),+ side - self.ui_px(12.0),+ palette.on_accent,+ )?;+ }+ }+ Ok(y + layout.total_height)+ }++ fn paint_wezterm_import(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ ) -> anyhow::Result<f32> {+ let palette = self.palette();+ let source = self.selected_wezterm_source_path();+ let destination = Self::thinkterm_compatible_config_path();+ let fields = self.compatibility_import.fields.clone();+ let selected_count = fields+ .iter()+ .filter(|field| field.lua_value.is_some() && self.import_field_selected(field.id))+ .count();+ let error = self.compatibility_import.error.clone();+ let left = x;+ let inner = width;+ let top = y;+ let font = Rc::clone(&self.ui_font);+ let cell = self.metrics.cell_size.height as f32;+ let mut bottom = self.paint_import_source_heading(+ layers,+ left,+ top,+ inner,+ &crate::i18n::tr("settings-import-wezterm-title"),+ &crate::i18n::tr("settings-compatibility-description"),+ )?;+ bottom += self.ui_px(28.0);+ let columns = if inner >= self.ui_px(840.0) { 2 } else { 1 };+ let gap = self.ui_px(56.0);+ let column_width = (inner - gap * (columns - 1) as f32) / columns as f32;+ let source_path = source+ .as_ref()+ .map(|path| home_relative(path))+ .unwrap_or_else(|| crate::i18n::tr("settings-wezterm-source-missing"));+ let paths = [+ (+ "WezTerm",+ source_path,+ crate::i18n::tr(if source.is_some() {+ "common-found"+ } else {+ "common-missing"+ }),+ SettingsAction::OpenWezTermConfigFile,+ source.is_some(),+ ),+ (+ "ThinkTerm",+ home_relative(&destination),+ crate::i18n::tr(if destination.exists() {+ "settings-import-config-ready"+ } else {+ "settings-import-config-will-create"+ }),+ SettingsAction::OpenThinkTermConfigFile,+ true,+ ),+ ];+ let path_lines = paths+ .iter()+ .map(|(_, path, ..)| {+ self.wrap_settings_text(&self.import_body_font, path, column_width)+ .len()+ })+ .max()+ .unwrap_or(1);+ let mut row_bottom = bottom;+ for (index, (name, path, status, action, enabled)) in paths.iter().enumerate() {+ let column_x = left + (index % columns) as f32 * (column_width + gap);+ let column_y = if columns == 1 && index > 0 {+ row_bottom + self.ui_px(24.0)+ } else {+ bottom+ };+ self.draw_text(+ layers,+ &font,+ column_x,+ column_y,+ name,+ palette.text,+ column_width,+ )?;+ let mut path_bottom = self.paint_import_copy(+ layers,+ column_x,+ column_y + cell + self.ui_px(8.0),+ column_width,+ path,+ palette.secondary_text,+ )?;+ if columns == 2 {+ path_bottom = path_bottom.max(+ column_y + cell + self.ui_px(8.0) + path_lines as f32 * self.import_line_step(),+ );+ }+ let block_bottom = self.paint_import_link(+ layers,+ column_x,+ path_bottom + self.ui_px(12.0),+ column_width,+ status,+ *action,+ *enabled,+ )?;+ row_bottom = row_bottom.max(block_bottom);+ }+ if columns == 2 {+ let side = self.ui_px(28.0);+ self.draw_svg_icon(+ layers,+ SvgIcon::ArrowRight,+ left + column_width + (gap - side) / 2.0,+ (bottom + row_bottom - side) / 2.0,+ side,+ palette.muted_text,+ )?;+ }+ bottom = row_bottom + self.ui_px(24.0);+ if let Some(error) = &error {+ bottom = self.paint_import_notice(layers, left, bottom, inner, error, true)?+ + self.ui_px(24.0);+ }+ if !fields.is_empty() {+ self.paint_separator(layers, left, bottom, inner)?;+ bottom += self.ui_px(24.0);+ let mut args = FluentArgs::new();+ args.set("selected", selected_count);+ args.set("total", fields.len());+ bottom = self.paint_import_copy(+ layers,+ left,+ bottom,+ inner,+ &crate::i18n::tr_args("settings-fields-selected", &args),+ palette.secondary_text,+ )?;+ let buttons = [+ ImportButton {+ label: crate::i18n::tr("common-select-all"),+ action: SettingsAction::SelectAllImportFields,+ enabled: true,+ primary: false,+ },+ ImportButton {+ label: crate::i18n::tr("common-clear"),+ action: SettingsAction::ClearImportFields,+ enabled: true,+ primary: false,+ },+ ];+ bottom = self.paint_import_actions(+ layers,+ left,+ bottom + self.ui_px(12.0),+ inner,+ &buttons,+ )?;+ let mut rows = RowCursor::new(bottom + self.ui_px(36.0), self);+ let mut category = None;+ for (index, field) in fields.iter().enumerate() {+ let group_start = category != Some(field.category.as_str());+ if group_start {+ if index > 0 {+ rows.y += self.ui_px(16.0);+ }+ self.draw_text(+ layers,+ &Rc::clone(&self.import_body_font),+ left,+ rows.y,+ &field.category,+ palette.secondary_text,+ inner,+ )?;+ rows.y += self.import_line_step() + self.ui_px(24.0);+ category = Some(field.category.as_str());+ }+ self.paint_import_field_row(layers, left, rows.y, inner, field, !group_start)?;+ rows.add(0.0);+ }+ bottom = rows.bottom + self.ui_px(24.0);+ }+ let mut buttons = vec![ImportButton {+ label: crate::i18n::tr("settings-import-reload"),+ action: SettingsAction::LoadWezTermSource,+ enabled: source.is_some(),+ primary: fields.is_empty(),+ }];+ if !fields.is_empty() {+ buttons.push(ImportButton {+ label: crate::i18n::tr("settings-import-selected"),+ action: SettingsAction::ImportSelectedFields,+ enabled: source.is_some() && selected_count > 0,+ primary: true,+ });+ }+ self.paint_import_footer(+ layers,+ left,+ bottom + self.ui_px(32.0),+ inner,+ Some(SettingsAction::ImportBack),+ &buttons,+ )+ }++ fn paint_import_link(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ status: &str,+ action: SettingsAction,+ enabled: bool,+ ) -> anyhow::Result<f32> {+ let palette = self.palette();+ let font = Rc::clone(&self.import_body_font);+ let cell = self.metrics.cell_size.height as f32;+ let label = crate::i18n::tr("settings-import-open");+ let icon = self.ui_px(18.0);+ let gap = self.ui_px(8.0);+ let link_width = self.measure_text_width(&font, &label) + gap + icon;+ let left = x + width - link_width;+ self.draw_text(+ layers,+ &font,+ x,+ y,+ status,+ palette.muted_text,+ (width - link_width - gap).max(1.0),+ )?;+ if enabled {+ self.ui_context.push(+ rect(+ left - gap,+ y - gap,+ link_width + gap * 2.0,+ cell + gap * 2.0,+ ),+ WidgetKind::Button,+ action,+ );+ if self.ui.interaction.hovered == Some(action) {+ self.draw_rect(+ layers,+ 0,+ left,+ y + cell,+ link_width,+ self.ui_px(1.0),+ self.chrome_palette.accent,+ )?;+ }+ }+ let color = if enabled {+ self.chrome_palette.accent+ } else {+ palette.muted_text+ };+ self.draw_text(+ layers,+ &font,+ left,+ y,+ &label,+ color,+ link_width - icon - gap,+ )?;+ self.draw_svg_icon(+ layers,+ SvgIcon::ExternalLink,+ x + width - icon,+ y + (cell - icon) / 2.0,+ icon,+ color,+ )?;+ Ok(y + cell)+ }++ pub(super) fn import_line_step(&self) -> f32 {+ RenderMetrics::with_font_metrics(&self.import_body_font.metrics())+ .cell_size+ .height as f32+ + self.ui_px(5.0)+ }++ pub(super) fn paint_import_copy(+ &self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ text: &str,+ color: LinearRgba,+ ) -> anyhow::Result<f32> {+ let font = Rc::clone(&self.import_body_font);+ let step = self.import_line_step();+ let mut top = y;+ for paragraph in text.split('\n') {+ for line in self.wrap_settings_text(&font, paragraph, width.max(1.0)) {+ self.draw_text(layers, &font, x, top, &line, color, width.max(1.0))?;+ top += step;+ }+ if paragraph.is_empty() {+ top += self.ui_px(8.0);+ }+ }+ Ok(top)+ }++ pub(super) fn paint_import_notice(+ &self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ text: &str,+ warning: bool,+ ) -> anyhow::Result<f32> {+ let palette = self.palette();+ let mut buffer = HeapQuadAllocator::default();+ let pad = self.ui_px(24.0);+ let icon = self.ui_px(20.0);+ let inset = pad * 2.0 + icon;+ let bottom = self.paint_import_copy(+ &mut TripleLayerQuadAllocator::Heap(&mut buffer),+ x + inset,+ y + pad,+ width - inset - pad,+ text,+ palette.secondary_text,+ )? + pad;+ self.draw_rounded_rect(+ layers,+ 0,+ x,+ y,+ width,+ bottom - y,+ if warning {+ TileColor::Orange.linear().mul_alpha(0.10)+ } else {+ palette.control_bg+ },+ self.ui_px(24.0),+ )?;+ self.draw_svg_icon(+ layers,+ if warning {+ SvgIcon::CircleAlert+ } else {+ SvgIcon::Info+ },+ x + pad,+ y + pad,+ icon,+ if warning {+ TileColor::Orange.linear()+ } else {+ palette.muted_text+ },+ )?;+ buffer.apply_to(layers)?;+ Ok(bottom)+ }++ pub(super) fn paint_import_actions(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ buttons: &[ImportButton],+ ) -> anyhow::Result<f32> {+ let palette = self.palette();+ let gap = self.ui_px(12.0);+ let height = self.ui_px(CONTROL_HEIGHT);+ let widths: Vec<_> = buttons+ .iter()+ .map(|button| self.import_button_width(button).min(width))+ .collect();+ let (places, rows) = flow_right(&widths, width, gap);+ for ((button, button_width), (offset, row)) in buttons.iter().zip(widths).zip(places) {+ let left = x + offset;+ let top = y + row as f32 * (height + gap);+ let ImportButton {+ label,+ action,+ primary,+ enabled,+ } = button;+ let state = if !enabled {+ ControlState::Disabled+ } else if self.ui.interaction.pressed == Some(*action) {+ ControlState::Pressed+ } else if self.ui.interaction.hovered == Some(*action) {+ ControlState::Hovered+ } else {+ ControlState::Normal+ };+ let (mut ground, mut border) = state.colors(self.chrome_palette);+ if *primary && *enabled {+ ground = match state {+ ControlState::Pressed => self.chrome_palette.accent.mul_alpha(0.70),+ ControlState::Hovered => self.chrome_palette.accent.mul_alpha(0.85),+ _ => self.chrome_palette.accent,+ };+ border = ground;+ }+ if *enabled {+ self.ui_context.push(+ rect(left, top, button_width, height),+ WidgetKind::Button,+ *action,+ );+ }+ self.draw_rounded_frame(+ layers,+ 0,+ left,+ top,+ button_width,+ height,+ ground,+ border,+ height / 2.0,+ )?;+ let font = Rc::clone(&self.ui_font);+ let icon = *action == SettingsAction::ImportContinue;+ let extra = if icon { self.ui_px(32.0) } else { 0.0 };+ let label_width = self.measure_text_width(&font, label);+ let text_x = left + ((button_width - label_width - extra) / 2.0).max(self.ui_px(12.0));+ let text_color = if !enabled {+ palette.muted_text+ } else if *primary {+ palette.on_accent+ } else {+ palette.text+ };+ self.draw_import_line(+ layers,+ &font,+ text_x,+ top,+ (left + button_width - self.ui_px(12.0) - text_x - extra).max(1.0),+ height,+ label,+ text_color,+ )?;+ if icon {+ let side = self.ui_px(20.0);+ self.draw_svg_icon(+ layers,+ SvgIcon::ArrowRight,+ (text_x + label_width + self.ui_px(12.0))+ .min(left + button_width - side - self.ui_px(12.0)),+ top + (height - side) / 2.0,+ side,+ text_color,+ )?;+ }+ }+ Ok(y + rows as f32 * height + rows.saturating_sub(1) as f32 * gap)+ }++ fn import_button_width(&self, button: &ImportButton) -> f32 {+ self.button_width_for_label(&button.label, 0.0)+ + if button.action == SettingsAction::ImportContinue {+ self.ui_px(32.0)+ } else {+ 0.0+ }+ }+}diff --git a/wezterm-gui/src/settings_window/session_import.rs b/wezterm-gui/src/settings_window/session_import.rsnew file mode 100644index 00000000..26ad0a59--- /dev/null+++ b/wezterm-gui/src/settings_window/session_import.rs@@ -0,0 +1,1275 @@+use super::*;+use mux::domain::{Domain, DomainId, DomainState};+use std::sync::Arc;+use thinkterm_import::{ImportMode, Preview, Session};+use wezterm_mux_server_impl::session_import;++#[derive(Debug, Clone)]+pub(super) struct ImportUi {+ sessions: Vec<Session>,+ target: Option<ImportTarget>,+ origin_window: Option<MuxWindowId>,+ notes: Vec<String>,+ preview: Option<Preview>,+ result: Option<codec::ImportSessionResponse>,+ pending: Option<codec::ImportSessionRequest>,+ busy: bool,+ failed: bool,+ message: String,+}++thread_local! {+ // Keep the request while Settings is closed, until its outcome is known.+ static UNRESOLVED: RefCell<Option<ImportUi>> = const { RefCell::new(None) };+}++pub(super) fn remembered_source() -> Option<ImportSource> {+ UNRESOLVED.with(|slot| {+ let state = slot.borrow();+ let id = &state.as_ref()?.pending.as_ref()?.request.source;+ thinkterm_import::sources()+ .into_iter()+ .find(|s| s.id == id)+ .map(|s| ImportSource::Session(s.id))+ })+}++impl Default for ImportUi {+ fn default() -> Self {+ UNRESOLVED+ .with(|slot| slot.borrow().clone())+ .map(|mut state| {+ state.busy = false;+ state+ })+ .unwrap_or_else(|| Self {+ sessions: Vec::new(),+ target: None,+ origin_window: None,+ notes: Vec::new(),+ preview: None,+ result: None,+ pending: None,+ busy: false,+ failed: false,+ message: String::new(),+ })+ }+}++impl ImportUi {+ pub(super) fn busy(&self) -> bool {+ self.busy || self.pending.is_some()+ }++ pub(super) fn has_preview(&self) -> bool {+ self.preview.is_some()+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+enum ImportTarget {+ Local,+ Remote { name: String, domain_id: DomainId },+}++impl ImportTarget {+ fn current() -> anyhow::Result<Self> {+ let space_id = OPENED_FROM_SPACE.with(|slot| slot.borrow().clone());+ let Some(space_id) = space_id else {+ return Ok(Self::Local);+ };+ let store = crate::workspace_threads::workspace_thread_store_snapshot();+ let Some(name) = origin_domain(&store, &space_id)? else {+ return Ok(Self::Local);+ };+ let domain = mux::Mux::get()+ .get_domain_by_name(&name)+ .context("The import connection is no longer available")?;+ anyhow::ensure!(+ domain+ .downcast_ref::<wezterm_client::domain::ClientDomain>()+ .is_some(),+ "Session import requires a ThinkTerm connection"+ );+ Ok(Self::Remote {+ name: name.clone(),+ domain_id: domain.domain_id(),+ })+ }++ fn location(&self, source: ImportSource) -> String {+ match self {+ Self::Local => source.text("session-import-location-local"),+ Self::Remote { name, .. } => {+ source.text_args("session-import-location-remote", &[("host", name.clone())])+ }+ }+ }++ async fn owner(&self) -> anyhow::Result<Option<Arc<dyn Domain>>> {+ let name = match self {+ Self::Local => crate::local_sessions::host_domain_name(),+ Self::Remote { name, .. } => Some(name.clone()),+ };+ let Some(name) = name else {+ return Ok(None);+ };+ let domain = mux::Mux::get()+ .get_domain_by_name(&name)+ .context("The import connection is no longer available")?;+ if let Self::Remote { domain_id, .. } = self {+ anyhow::ensure!(+ *domain_id == domain.domain_id(),+ "The import connection changed; inspect the session again"+ );+ }+ let client = domain+ .downcast_ref::<wezterm_client::domain::ClientDomain>()+ .context("Session import requires a ThinkTerm connection")?;+ if client.state() != DomainState::Attached {+ client+ .attach_with_ui(+ None,+ mux::connui::ConnectionUI::new_lazy(Default::default()),+ )+ .await?;+ }+ Ok(Some(domain))+ }++ async fn discover(&self, source: String) -> anyhow::Result<codec::ListImportSessionsResponse> {+ if let Some(domain) = self.owner().await? {+ domain+ .downcast_ref::<wezterm_client::domain::ClientDomain>()+ .unwrap()+ .list_import_sessions(source)+ .await+ } else {+ promise::spawn::spawn_into_new_thread(move || {+ session_import::discover(codec::ListImportSessions { source })+ })+ .await+ }+ }++ async fn preview(+ &self,+ source: String,+ session: String,+ ) -> anyhow::Result<codec::PreviewImportSessionResponse> {+ if let Some(domain) = self.owner().await? {+ domain+ .downcast_ref::<wezterm_client::domain::ClientDomain>()+ .unwrap()+ .preview_import_session(source, session)+ .await+ } else {+ promise::spawn::spawn_into_new_thread(move || {+ session_import::preview(codec::PreviewImportSession { source, session })+ })+ .await+ }+ }++ async fn recover(+ &self,+ request: codec::ImportSessionRequest,+ ) -> anyhow::Result<codec::ImportSessionStatus> {+ let status = if let Some(domain) = self.owner().await? {+ domain+ .downcast_ref::<wezterm_client::domain::ClientDomain>()+ .unwrap()+ .get_import_session_status(request.request_id.clone())+ .await?+ } else {+ session_import::status(&request.request_id)?+ };+ match status {+ codec::ImportSessionStatus::NotFound => self+ .import(request)+ .await+ .map(codec::ImportSessionStatus::Completed),+ status => Ok(status),+ }+ }++ async fn import(+ &self,+ request: codec::ImportSessionRequest,+ ) -> anyhow::Result<codec::ImportSessionResponse> {+ if let Some(domain) = self.owner().await? {+ domain+ .downcast_ref::<wezterm_client::domain::ClientDomain>()+ .unwrap()+ .import_session(request)+ .await+ } else {+ session_import::execute(request, crate::workspace_threads::persist_session_import).await+ }+ }+}++fn origin_domain(+ store: &crate::workspace_threads::WorkspaceThreadStore,+ space_id: &str,+) -> anyhow::Result<Option<String>> {+ let space = store+ .spaces+ .iter()+ .find(|space| space.id == space_id)+ .context("The import origin Space is no longer available")?;+ Ok(space.client_domain.clone())+}++fn localized_error(source: ImportSource, message: &str, fallback: &'static str) -> String {+ let generic = [+ (+ "An imported working directory is unavailable",+ "session-import-error-directory-missing",+ ),+ (+ "Import mode changed after preview",+ "session-import-error-changed",+ ),+ (+ "Session import requires an authenticated desktop connection",+ "session-import-error-local-user",+ ),+ (+ "Session import requires a local terminal owner",+ "session-import-error-local-user",+ ),+ (+ "Some imported panes have no live terminal",+ "session-import-error-terminal-missing",+ ),+ ]+ .iter()+ .find_map(|(reason, key)| message.ends_with(reason).then_some(*key));+ let known = generic.or_else(|| source.provider().ok()?.error_key(message));+ if let Some(key) = known.filter(|key| *key != "session-import-error-receiver") {+ return source.text(key);+ }+ format!(+ "{}\n\n{}",+ source.text(known.unwrap_or(fallback)),+ source.text_args(+ "session-import-error-details",+ &[("error", message.to_string())]+ )+ )+}++async fn open_import(+ target: ImportTarget,+ result: codec::ImportSessionResponse,+ origin_window: Option<MuxWindowId>,+) -> anyhow::Result<()> {+ if let Some(domain) = target.owner().await? {+ let client = domain+ .downcast_ref::<wezterm_client::domain::ClientDomain>()+ .unwrap();+ client.fetch_thinkterm_tree().await?;+ client.resync().await?;+ }+ let expected_domain = match &target {+ ImportTarget::Local => None,+ ImportTarget::Remote { name, .. } => Some(name.as_str()),+ };+ let store = crate::workspace_threads::workspace_thread_store_snapshot();+ anyhow::ensure!(+ store.spaces.iter().any(|space| space.id == result.space_id+ && space.client_domain.as_deref() == expected_domain),+ "The imported Space is not available on its original connection"+ );+ let frontend = crate::frontend::try_front_end().context("ThinkTerm frontend is unavailable")?;+ let windows = frontend.gui_windows();+ let mux = mux::Mux::get();+ let already_open = windows.iter().find(|gui| {+ mux.get_window(gui.mux_window_id).is_some_and(|window| {+ crate::workspace_threads::space_id_for_workspace(window.get_workspace()).as_deref()+ == Some(result.space_id.as_str())+ })+ });+ if let Some(gui) = already_open+ .or_else(|| {+ windows+ .iter()+ .find(|gui| Some(gui.mux_window_id) == origin_window)+ })+ .or_else(|| windows.first())+ {+ let window = gui.window.clone();+ gui.window+ .notify(crate::termwindow::TermWindowNotif::Apply(Box::new(+ move |tw| {+ let thread = result+ .tree+ .projects+ .iter()+ .flat_map(|p| &p.threads)+ .find(|t| {+ t.materialized_workspace_name.as_deref()+ == Some(result.workspace.as_str())+ })+ .map(|t| t.id.clone());+ tw.switch_space_to_thread(result.space_id, thread, &window);+ window.focus();+ },+ )));+ return Ok(());+ }+ let window_id = crate::workspace_threads::window_to_show_in_workspace(&result.workspace)+ .context("The imported session is not connected; reopen its Space after connecting to its session server")?;+ let owner = crate::workspace_threads::next_space_owner_id();+ anyhow::ensure!(+ crate::workspace_threads::switch_window_space(owner, &result.space_id),+ "The imported Space is already open"+ );+ frontend.claim_spawned_mux_window(window_id);+ frontend.set_switching_workspaces(true);+ let opened = crate::termwindow::TermWindow::new_window_with_claimed_space(+ window_id,+ owner,+ result.space_id,+ None,+ )+ .await;+ frontend.set_switching_workspaces(false);+ if opened.is_err() {+ crate::workspace_threads::release_window_space(owner);+ }+ opened+}++impl SettingsWindow {+ fn apply_import_status(+ &mut self,+ source: ImportSource,+ status: anyhow::Result<codec::ImportSessionStatus>,+ ) {+ use codec::ImportSessionStatus;+ let state = &mut self.ui.session_import;+ state.busy = false;+ match status {+ Ok(ImportSessionStatus::Completed(result)) => {+ state.pending = None;+ state.preview = None;+ state.sessions.clear();+ state.result = Some(result);+ state.failed = false;+ state.message.clear();+ self.ui.import_step = ImportStep::Result;+ self.ui.content_scroll.reset();+ }+ Ok(ImportSessionStatus::Running) => {+ state.failed = false;+ state.message = source.text("session-import-still-running");+ }+ Ok(ImportSessionStatus::Failed(error)) => {+ state.pending = None;+ state.failed = true;+ state.message = localized_error(source, &error, "session-import-error-import");+ }+ Ok(ImportSessionStatus::Interrupted { .. } | ImportSessionStatus::Expired) => {+ state.pending = None;+ state.failed = true;+ state.message = source.text("session-import-result-interrupted");+ }+ Ok(ImportSessionStatus::NotFound) => unreachable!("recovery resends the same request"),+ Err(err) => {+ state.failed = true;+ state.message = localized_error(+ source,+ &format!("{err:#}"),+ "session-import-result-unavailable",+ );+ }+ }+ UNRESOLVED.with(|slot| {+ *slot.borrow_mut() = state.pending.as_ref().map(|_| state.clone());+ });+ }++ pub(super) fn perform_session_import_action(&mut self, action: SettingsAction) {+ if self.ui.session_import.busy {+ return;+ }+ if self.ui.session_import.pending.is_some()+ && !matches!(action, SettingsAction::SessionImportRecover)+ {+ return;+ }+ let selected_source = self.ui.import_source;+ let Ok(provider) = selected_source.provider() else {+ return;+ };+ let instance_id = self.instance_id;+ match action {+ SettingsAction::SessionImportDetect => {+ let target = match self+ .ui+ .session_import+ .target+ .clone()+ .map(Ok)+ .unwrap_or_else(ImportTarget::current)+ {+ Ok(target) => target,+ Err(err) => {+ self.ui.session_import.failed = true;+ self.ui.session_import.message = localized_error(+ selected_source,+ &format!("{err:#}"),+ "session-import-error-inspect",+ );+ return;+ }+ };+ self.ui.session_import = ImportUi {+ target: Some(target.clone()),+ origin_window: OPENED_FROM.with(|slot| slot.get()),+ busy: true,+ message: selected_source.text("session-import-detecting"),+ ..ImportUi::default()+ };+ promise::spawn::spawn(async move {+ let found = target.discover(provider.info().id.into()).await;+ if let Some(settings) = settings_window_for_instance(instance_id) {+ let mut settings = settings.borrow_mut();+ if settings.ui.import_source != selected_source {+ return;+ }+ settings.ui.session_import.busy = false;+ match found {+ Ok(found) => {+ let sessions = found.sessions;+ settings.ui.session_import.notes = found.notes;+ settings.ui.session_import.message = if sessions.is_empty() {+ selected_source.text("session-import-none")+ } else {+ String::new()+ };+ settings.ui.session_import.sessions = sessions;+ if settings.ui.session_import.sessions.len() == 1 {+ let key =+ web_token_key(&settings.ui.session_import.sessions[0].name);+ settings.perform_session_import_action(+ SettingsAction::SessionImportPreview(key),+ );+ }+ }+ Err(err) => {+ settings.ui.session_import.failed = true;+ settings.ui.session_import.message = localized_error(+ selected_source,+ &format!("{err:#}"),+ "session-import-error-inspect",+ );+ }+ }+ if let Some(window) = &settings.window {+ window.invalidate();+ }+ }+ })+ .detach();+ }+ SettingsAction::SessionImportPreview(key) => {+ let Some(target) = self.ui.session_import.target.clone() else {+ return;+ };+ let Some(session) = self+ .ui+ .session_import+ .sessions+ .iter()+ .find(|session| web_token_key(&session.name) == key)+ .cloned()+ else {+ return;+ };+ self.ui.session_import.preview = None;+ self.ui.session_import.busy = true;+ self.ui.session_import.failed = false;+ self.ui.session_import.message = selected_source.text("session-import-detecting");+ promise::spawn::spawn(async move {+ let preview = target+ .preview(provider.info().id.into(), session.name)+ .await;+ if let Some(settings) = settings_window_for_instance(instance_id) {+ let mut settings = settings.borrow_mut();+ if settings.ui.import_source != selected_source {+ return;+ }+ settings.ui.session_import.busy = false;+ match preview {+ Ok(response) => {+ settings.ui.session_import.notes = response.notes;+ settings.ui.session_import.preview = Some(response.preview);+ settings.ui.session_import.message.clear();+ settings.ui.content_scroll.reset();+ #[cfg(debug_assertions)]+ if std::env::var("THINKTERM_SETTINGS_EXPAND")+ .is_ok_and(|value| value == "import-preview")+ {+ if let Some(offset) = initial_scroll() {+ settings.ui.content_scroll.offset = offset;+ settings.ui.content_scroll.target_offset = offset;+ }+ }+ }+ Err(err) => {+ settings.ui.session_import.failed = true;+ settings.ui.session_import.message = localized_error(+ selected_source,+ &format!("{err:#}"),+ "session-import-error-inspect",+ );+ }+ }+ if let Some(window) = &settings.window {+ window.invalidate();+ }+ }+ })+ .detach();+ }+ SettingsAction::SessionImportBack => {+ self.ui.session_import.preview = None;+ self.ui.session_import.failed = false;+ self.ui.session_import.message.clear();+ }+ SettingsAction::SessionImportConfirm => {+ let Some(target) = self.ui.session_import.target.clone() else {+ return;+ };+ let Some(preview) = &self.ui.session_import.preview else {+ return;+ };+ if preview.unavailable.is_some() || self.ui.session_import.failed {+ return;+ }+ let request = codec::ImportSessionRequest {+ request_id: format!(+ "{}-{}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs(),+ uuid::Uuid::new_v4()+ ),+ request: thinkterm_import::ImportRequest {+ source: provider.info().id.into(),+ session: preview.session.clone(),+ mode: if preview.live {+ ImportMode::Live+ } else {+ ImportMode::Layout+ },+ fingerprint: preview.fingerprint.clone(),+ space_name: format!("{} — {}", selected_source.label(), preview.session),+ },+ };+ self.ui.session_import.busy = true;+ self.ui.session_import.failed = false;+ self.ui.session_import.pending = Some(request.clone());+ self.ui.session_import.message = selected_source.text("session-import-importing");+ UNRESOLVED.with(|slot| *slot.borrow_mut() = Some(self.ui.session_import.clone()));+ promise::spawn::spawn(async move {+ let imported = match target.import(request.clone()).await {+ Ok(result) => Ok(codec::ImportSessionStatus::Completed(result)),+ Err(_) => target.recover(request).await,+ };+ if let Some(settings) = settings_window_for_instance(instance_id) {+ let mut settings = settings.borrow_mut();+ if settings.ui.import_source != selected_source {+ return;+ }+ settings.apply_import_status(selected_source, imported);+ if let Some(window) = &settings.window {+ window.invalidate();+ }+ }+ })+ .detach();+ }+ SettingsAction::SessionImportRecover => {+ let (Some(target), Some(request)) = (+ self.ui.session_import.target.clone(),+ self.ui.session_import.pending.clone(),+ ) else {+ return;+ };+ self.ui.session_import.busy = true;+ promise::spawn::spawn(async move {+ let status = target.recover(request).await;+ if let Some(settings) = settings_window_for_instance(instance_id) {+ let mut settings = settings.borrow_mut();+ settings.apply_import_status(selected_source, status);+ if let Some(window) = &settings.window {+ window.invalidate();+ }+ }+ })+ .detach();+ }+ SettingsAction::SessionImportOpen => {+ let Some(target) = self.ui.session_import.target.clone() else {+ return;+ };+ let origin_window = self.ui.session_import.origin_window;+ let Some(result) = self.ui.session_import.result.clone() else {+ return;+ };+ self.ui.session_import.busy = true;+ self.ui.session_import.failed = false;+ self.ui.session_import.message.clear();+ promise::spawn::spawn(async move {+ let opened = open_import(target, result, origin_window).await;+ if let Some(settings) = settings_window_for_instance(instance_id) {+ let mut settings = settings.borrow_mut();+ if settings.ui.import_source != selected_source {+ return;+ }+ settings.ui.session_import.busy = false;+ if let Err(err) = opened {+ settings.ui.session_import.failed = true;+ settings.ui.session_import.message = localized_error(+ selected_source,+ &format!("{err:#}"),+ "session-import-error-open",+ );+ }+ if let Some(window) = &settings.window {+ window.invalidate();+ }+ }+ })+ .detach();+ }+ _ => {}+ }+ }++ pub(super) fn paint_session_import(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ ) -> anyhow::Result<f32> {+ let selected_source = self.ui.import_source;+ let state = self.ui.session_import.clone();+ let palette = self.palette();+ let title = Rc::clone(&self.ui_font);+ let left = x;+ let inner = width;+ let gap = self.ui_px(20.0);+ let cell = self.metrics.cell_size.height as f32;+ let mut top = y;+ top = self.paint_import_source_heading(+ layers,+ left,+ top,+ inner,+ &selected_source.text("session-import-title"),+ &selected_source.text(if state.preview.is_some() {+ "session-import-preview-title"+ } else {+ "session-import-select-session"+ }),+ )? + self.ui_px(24.0);+ if let Some(target) = &state.target {+ top = self.paint_import_copy(+ layers,+ left,+ top,+ inner,+ &target.location(selected_source),+ palette.secondary_text,+ )? + gap;+ }+ if let Some(preview) = &state.preview {+ let status = selected_source.text(if preview.live {+ "session-import-status-live"+ } else {+ "session-import-status-layout"+ });+ let status = match &preview.version {+ Some(version) => format!("{status} · {} {version}", selected_source.label()),+ None => status,+ };+ top = self.paint_import_copy(+ layers,+ left,+ top,+ inner,+ &status,+ TileColor::Teal.linear(),+ )? + gap;+ } else if state.result.is_none() {+ top = self.paint_import_copy(+ layers,+ left,+ top,+ inner,+ &selected_source.text("session-import-description"),+ palette.secondary_text,+ )? + gap;+ } else {+ top += gap;+ }++ let live = state.preview.as_ref().map(|preview| preview.live);+ let mut requirements = vec![selected_source.text(+ if matches!(state.target, Some(ImportTarget::Remote { .. })) {+ "session-import-requirements-remote"+ } else {+ "session-import-requirements-local"+ },+ )];+ if live != Some(true) {+ requirements.push(selected_source.text("session-import-requirements-layout"));+ }+ requirements.push(selected_source.text("session-import-requirements-refresh"));+ requirements.extend(state.notes.iter().map(|key| selected_source.text(key)));+ if let Some(reason) = state+ .preview+ .as_ref()+ .and_then(|preview| preview.unavailable.as_ref())+ {+ top = self.paint_import_notice(+ layers,+ left,+ top,+ inner,+ &localized_error(selected_source, reason, "session-import-error-inspect"),+ true,+ )? + gap;+ }++ if let Some(preview) = &state.preview {+ let destination = selected_source.text_args(+ "session-import-destination",+ &[(+ "name",+ format!("{} — {}", selected_source.label(), preview.session),+ )],+ );+ self.draw_svg_icon(layers, SvgIcon::Layers, left, top, cell, palette.muted_text)?;+ top = self.paint_import_copy(+ layers,+ left + cell + self.ui_px(10.0),+ top,+ inner - cell - self.ui_px(10.0),+ &destination,+ palette.text,+ )? + gap;+ let tabs = preview.projects.iter().map(|p| p.tabs).sum::<usize>();+ top = self.paint_session_counts(+ layers,+ left,+ top,+ inner,+ [preview.projects.len(), tabs, preview.pane_count()],+ )? + gap;+ top = self.paint_import_copy(+ layers,+ left,+ top,+ inner,+ &selected_source.text(if preview.live {+ "session-import-live"+ } else {+ "session-import-offline"+ }),+ palette.secondary_text,+ )? + gap;+ for project in &preview.projects {+ self.draw_rect(+ layers,+ 0,+ left,+ top,+ inner,+ self.ui_px(1.0),+ palette.separator,+ )?;+ top += self.ui_px(16.0);+ let icon = self.ui_px(24.0);+ self.draw_svg_icon(+ layers,+ SvgIcon::FolderOpen,+ left,+ top + (self.description_line_step() - icon) / 2.0,+ icon,+ palette.muted_text,+ )?;+ let text_x = left + icon + self.ui_px(14.0);+ let text_width = inner - icon - self.ui_px(14.0);+ let lines = self.wrap_settings_text(&title, &project.name, text_width);+ for line in lines {+ self.draw_import_line(+ layers,+ &title,+ text_x,+ top,+ text_width,+ self.description_line_step(),+ &line,+ palette.text,+ )?;+ top += self.description_line_step();+ }+ let detail = selected_source.text_args(+ "session-import-project-meta",+ &[+ ("threads", project.threads.to_string()),+ ("tabs", project.tabs.to_string()),+ ("panes", project.panes.to_string()),+ ],+ );+ top = self.paint_import_copy(+ layers,+ text_x,+ top + self.ui_px(4.0),+ text_width,+ &detail,+ palette.secondary_text,+ )? + self.ui_px(12.0);+ let terminal_icon = self.ui_px(20.0);+ let terminal_x = text_x + terminal_icon + self.ui_px(10.0);+ let terminal_width = (left + inner - terminal_x).max(1.0);+ let line_height = self.description_line_step();+ for (index, terminal) in project.terminals.iter().enumerate() {+ let label = terminal+ .title+ .as_deref()+ .or(terminal.tab_name.as_deref())+ .or_else(|| {+ terminal.cwd.as_deref().and_then(|cwd| {+ Path::new(cwd).file_name().and_then(|name| name.to_str())+ })+ })+ .map(str::to_owned)+ .unwrap_or_else(|| {+ selected_source.text_args(+ "session-import-terminal-untitled",+ &[("number", (index + 1).to_string())],+ )+ });+ self.draw_svg_icon(+ layers,+ SvgIcon::Terminal,+ text_x,+ top + (line_height - terminal_icon) / 2.0,+ terminal_icon,+ palette.muted_text,+ )?;+ self.draw_import_line(+ layers,+ &self.import_body_font,+ terminal_x,+ top,+ terminal_width,+ line_height,+ &self.text_with_ellipsis(&self.import_body_font, &label, terminal_width),+ palette.text,+ )?;+ top += line_height;+ let mut details = Vec::new();+ if let Some(tab) = &terminal.tab_name {+ if tab != &label {+ details.push(tab.clone());+ }+ }+ if let Some(cwd) = &terminal.cwd {+ details.push(home_relative(Path::new(cwd)));+ }+ if !details.is_empty() {+ self.draw_import_line(+ layers,+ &self.import_body_font,+ terminal_x,+ top,+ terminal_width,+ line_height,+ &self.text_with_ellipsis(+ &self.import_body_font,+ &details.join(" · "),+ terminal_width,+ ),+ palette.secondary_text,+ )?;+ top += line_height;+ }+ top += self.ui_px(8.0);+ }+ top += self.ui_px(8.0);+ }+ } else {+ for session in &state.sessions {+ self.draw_rect(+ layers,+ 0,+ left,+ top,+ inner,+ self.ui_px(1.0),+ palette.separator,+ )?;+ top += self.ui_px(16.0);+ let label = selected_source.text("session-import-preview");+ let button_width = self.button_width_for_label(&label, 0.0).min(inner * 0.45);+ let height = self.ui_px(CONTROL_HEIGHT);+ self.draw_svg_icon(+ layers,+ SvgIcon::Terminal,+ left,+ top + (height - cell) / 2.0,+ cell,+ palette.muted_text,+ )?;+ let name_x = left + cell + self.ui_px(12.0);+ self.draw_text(+ layers,+ &title,+ name_x,+ self.control_text_y(top, height),+ &session.name,+ palette.text,+ (inner - (name_x - left) - button_width - self.ui_px(16.0)).max(1.0),+ )?;+ self.paint_import_actions(+ layers,+ left + inner - button_width,+ top,+ button_width,+ &[ImportButton {+ label,+ action: SettingsAction::SessionImportPreview(web_token_key(&session.name)),+ primary: false,+ enabled: !state.busy,+ }],+ )?;+ top += height + self.ui_px(16.0);+ }+ }+ if !state.message.is_empty() {+ top = if state.failed {+ self.paint_import_notice(layers, left, top, inner, &state.message, true)?+ } else {+ self.paint_import_copy(+ layers,+ left,+ top,+ inner,+ &state.message,+ palette.secondary_text,+ )?+ } + gap;+ }+ top = self.paint_session_notes(layers, left, top + gap, inner, &requirements)?;+ let buttons = if state.pending.is_some() {+ vec![ImportButton {+ label: selected_source.text("session-import-check-result"),+ action: SettingsAction::SessionImportRecover,+ primary: true,+ enabled: !state.busy,+ }]+ } else if let Some(preview) = &state.preview {+ vec![+ ImportButton {+ label: selected_source.text("session-import-refresh-preview"),+ action: SettingsAction::SessionImportPreview(web_token_key(&preview.session)),+ primary: false,+ enabled: !state.busy,+ },+ ImportButton {+ label: selected_source.text(if preview.live {+ "session-import-confirm-live"+ } else {+ "session-import-confirm-offline"+ }),+ action: SettingsAction::SessionImportConfirm,+ primary: true,+ enabled: !state.busy && !state.failed && preview.unavailable.is_none(),+ },+ ]+ } else {+ vec![ImportButton {+ label: selected_source.text("session-import-detect"),+ action: SettingsAction::SessionImportDetect,+ primary: true,+ enabled: !state.busy,+ }]+ };+ self.paint_import_footer(+ layers,+ left,+ top + gap,+ inner,+ Some(SettingsAction::ImportBack),+ &buttons,+ )+ }++ pub(super) fn paint_session_result(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ ) -> anyhow::Result<f32> {+ let selected_source = self.ui.import_source;+ let provider = selected_source.provider()?;+ let state = self.ui.session_import.clone();+ let Some(result) = &state.result else {+ return Ok(y);+ };+ let message = selected_source.text_args(+ if result.live {+ "session-import-done-live"+ } else {+ "session-import-done-offline"+ },+ &[("count", result.pane_count.to_string())],+ );+ let mut bottom =+ self.paint_import_result(layers, x, y + self.ui_px(64.0), width, &message)?;+ if let Some(target) = &state.target {+ bottom = self.paint_import_centered_copy(+ layers,+ x,+ bottom + self.ui_px(16.0),+ width,+ &target.location(selected_source),+ )?;+ }+ if let Some(space) = result.tree.spaces.first() {+ bottom = self.paint_import_centered_copy(+ layers,+ x,+ bottom + self.ui_px(24.0),+ width,+ &selected_source.text_args(+ "session-import-destination",+ &[("name", space.name.clone())],+ ),+ )?;+ }+ bottom = self.paint_session_notes(+ layers,+ x,+ bottom + self.ui_px(40.0),+ width,+ &provider+ .result_notes()+ .iter()+ .map(|key| selected_source.text(key))+ .collect::<Vec<_>>(),+ )?;+ if !state.message.is_empty() {+ bottom = self.paint_import_notice(+ layers,+ x,+ bottom + self.ui_px(20.0),+ width,+ &state.message,+ state.failed,+ )?;+ }+ self.paint_import_footer(+ layers,+ x,+ bottom + self.ui_px(32.0),+ width,+ Some(SettingsAction::ImportStartOver),+ &[ImportButton {+ label: selected_source.text("session-import-open"),+ action: SettingsAction::SessionImportOpen,+ primary: true,+ enabled: !state.busy,+ }],+ )+ }++ fn paint_session_notes(+ &self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ notes: &[String],+ ) -> anyhow::Result<f32> {+ let selected_source = self.ui.import_source;+ let palette = self.palette();+ self.draw_rect(+ layers,+ 0,+ x,+ y,+ width,+ self.ui_px(1.0),+ palette.separator.mul_alpha(0.7),+ )?;+ let mut top = y + self.ui_px(24.0);+ let icon = self.ui_px(20.0);+ let inset = self.ui_px(32.0);+ self.draw_svg_icon(+ layers,+ SvgIcon::Info,+ x,+ top + (self.import_line_step() - icon) / 2.0,+ icon,+ palette.muted_text,+ )?;+ let font = Rc::clone(&self.import_body_font);+ for line in self.wrap_settings_text(+ &font,+ &selected_source.text("session-import-notes-title"),+ width - inset,+ ) {+ self.draw_import_line(+ layers,+ &font,+ x + inset,+ top,+ width - inset,+ self.import_line_step(),+ &line,+ palette.text,+ )?;+ top += self.import_line_step();+ }+ top += self.ui_px(12.0);+ for note in notes {+ self.draw_rounded_rect(+ layers,+ 0,+ x + self.ui_px(8.0),+ top + self.import_line_step() / 2.0,+ self.ui_px(4.0),+ self.ui_px(4.0),+ palette.muted_text,+ self.ui_px(2.0),+ )?;+ top = self.paint_import_copy(+ layers,+ x + inset,+ top,+ width - inset,+ note,+ palette.secondary_text,+ )? + self.ui_px(8.0);+ }+ Ok(top)+ }++ fn paint_session_counts(+ &self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ counts: [usize; 3],+ ) -> anyhow::Result<f32> {+ let palette = self.palette();+ let gap = self.ui_px(12.0);+ let columns = if width >= self.ui_px(480.0) { 3 } else { 1 };+ let tile_width = (width - gap * (columns - 1) as f32) / columns as f32;+ let pad = self.ui_px(12.0);+ let labels = [+ "session-import-projects",+ "session-import-tabs",+ "session-import-terminals",+ ]+ .map(crate::i18n::tr);+ let font = Rc::clone(&self.ui_font);+ let lines: Vec<_> = counts+ .iter()+ .zip(labels.iter())+ .map(|(count, label)| {+ self.wrap_settings_text(&font, &format!("{count} {label}"), tile_width - pad * 2.0)+ })+ .collect();+ let height = pad * 2.0+ + self.import_line_step() * lines.iter().map(Vec::len).max().unwrap_or(1) as f32;+ for (index, lines) in lines.iter().enumerate() {+ let left = x + (index % columns) as f32 * (tile_width + gap);+ let top = y + (index / columns) as f32 * (height + gap);+ if columns > 1 && index > 0 {+ self.draw_rect(+ layers,+ 0,+ left - gap / 2.0,+ top + pad,+ self.ui_px(1.0),+ height - pad * 2.0,+ palette.separator,+ )?;+ }+ for (row, line) in lines.iter().enumerate() {+ self.draw_text(+ layers,+ &font,+ left + pad,+ top + pad + row as f32 * self.import_line_step(),+ line,+ palette.text,+ tile_width - pad * 2.0,+ )?;+ }+ }+ let rows = 3 / columns;+ Ok(y + height * rows as f32 + gap * (rows - 1) as f32)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn import_follows_the_space_owner_and_never_falls_back_for_a_missing_space() {+ let store: crate::workspace_threads::WorkspaceThreadStore = serde_json::from_value(serde_json::json!({+ "spaces": [+ {"id": "local", "name": "Local", "active_project_id": null, "thread_refs": ["remote-thread"]},+ {"id": "remote", "name": "Remote", "active_project_id": null, "client_domain": "server-a"},+ {"id": "named-local", "name": "Remote", "active_project_id": null, "client_domain": "Local"}+ ], "projects": []+ })).unwrap();+ assert_eq!(origin_domain(&store, "local").unwrap(), None);+ assert_eq!(+ origin_domain(&store, "remote").unwrap().as_deref(),+ Some("server-a")+ );+ assert_eq!(+ origin_domain(&store, "named-local").unwrap().as_deref(),+ Some("Local")+ );+ assert!(origin_domain(&store, "missing").is_err());+ }++ #[test]+ fn generic_errors_are_localized_and_unknown_errors_keep_details() {+ let source = ImportSource::Session("example");+ assert_eq!(+ localized_error(+ source,+ "Prepare import: An imported working directory is unavailable",+ "session-import-error-import"+ ),+ source.text("session-import-error-directory-missing")+ );+ let message = localized_error(+ source,+ "An unexpected import failure",+ "session-import-error-import",+ );+ assert!(message.contains("An unexpected import failure"));+ assert!(message.starts_with(&source.text("session-import-error-import")));+ }+}diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 14c33d57..f4b7e61d 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -10944,7 +10944,7 @@ impl TermWindow {wezterm_open_url::open_url(link);}OpenSettings => {- crate::settings_window::show_from(self.mux_window_id);+ crate::settings_window::show_from(self.mux_window_id, &self.active_space_id);}FocusPluginPanel(plugin) => self.focus_plugin_panel(plugin),QuitAndStopSessionServer => {diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 552da6b5..17481ae0 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -5376,7 +5376,7 @@ impl super::TermWindow {) {context.set_cursor(Some(MouseCursor::Hand));if event.kind == WMEK::Press(MousePress::Left) {- crate::settings_window::show();+ crate::settings_window::show_from(self.mux_window_id, &self.active_space_id);}}diff --git a/wezterm-gui/src/termwindow/ui/agent_panel.rs b/wezterm-gui/src/termwindow/ui/agent_panel.rsindex fe4cb1b6..b64089df 100644--- a/wezterm-gui/src/termwindow/ui/agent_panel.rs+++ b/wezterm-gui/src/termwindow/ui/agent_panel.rs@@ -525,7 +525,7 @@ impl TermWindow {});}AgentPanelAction::OpenSettings => {- crate::settings_window::show();+ crate::settings_window::show_from(self.mux_window_id, &self.active_space_id);}AgentPanelAction::Reveal(pane_id) => {self.reveal_agent_pane(pane_id);diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rsindex ee53340b..b7d3a127 100644--- a/wezterm-gui/src/termwindow/ui/icons.rs+++ b/wezterm-gui/src/termwindow/ui/icons.rs@@ -541,12 +541,14 @@ pub enum BrandIcon {Fedora,Git,GitHub,+ Herdr,Linux,NixOS,Proxmox,RaspberryPi,RedHat,Ubuntu,+ WezTerm,}/// Brand colors darker than this perceived luminance (0..=255) are rendered@@ -582,6 +584,7 @@ impl BrandIcon {Self::Fedora => include_bytes!("../../../../third_party/simple-icons/icons/fedora.svg"),Self::Git => include_bytes!("../../../../third_party/simple-icons/icons/git.svg"),Self::GitHub => include_bytes!("../../../../third_party/simple-icons/icons/github.svg"),+ Self::Herdr => include_bytes!("../../../../third_party/herdr/logo.svg"),Self::Linux => include_bytes!("../../../../third_party/simple-icons/icons/linux.svg"),Self::NixOS => include_bytes!("../../../../third_party/simple-icons/icons/nixos.svg"),Self::Proxmox => {@@ -592,6 +595,7 @@ impl BrandIcon {}Self::RedHat => include_bytes!("../../../../third_party/simple-icons/icons/redhat.svg"),Self::Ubuntu => include_bytes!("../../../../third_party/simple-icons/icons/ubuntu.svg"),+ Self::WezTerm => include_bytes!("../../../../assets/icon/wezterm-icon.svg"),}}@@ -603,7 +607,7 @@ impl BrandIcon {fn has_embedded_color(self) -> bool {matches!(self,- Self::AgentClaude | Self::AgentCopilot | Self::AgentKimi+ Self::AgentClaude | Self::AgentCopilot | Self::AgentKimi | Self::Herdr | Self::WezTerm)}@@ -626,12 +630,14 @@ impl BrandIcon {Self::Fedora => (0x51, 0xA2, 0xDA),Self::Git => (0xF0, 0x3C, 0x2E),Self::GitHub => (0x18, 0x17, 0x17),+ Self::Herdr => (0x30, 0x34, 0x38),Self::Linux => (0xFC, 0xC6, 0x24),Self::NixOS => (0x52, 0x77, 0xC3),Self::Proxmox => (0xE5, 0x70, 0x00),Self::RaspberryPi => (0xA2, 0x28, 0x46),Self::RedHat => (0xEE, 0x00, 0x00),Self::Ubuntu => (0xE9, 0x54, 0x20),+ Self::WezTerm => (0x4E, 0x49, 0xEE),}}@@ -648,6 +654,21 @@ impl BrandIcon {pub fn rasterize(self, size: usize) -> Result<Image> {let svg = std::str::from_utf8(self.bytes()).context("brand SVG asset is not UTF-8")?;+ if matches!(self, Self::Herdr | Self::WezTerm) {+ let root = svg.find("<svg").context("brand SVG root is missing")?;+ let start = root+ + svg[root..]+ .find('>')+ .context("brand SVG root is incomplete")?+ + 1;+ let end = svg.rfind("</svg>").context("brand SVG end is missing")?;+ let clipped = format!(+ r#"{}<defs><clipPath id="app-icon" clipPathUnits="objectBoundingBox"><rect width="1" height="1" rx="0.27"/></clipPath></defs><g clip-path="url(#app-icon)">{}</g></svg>"#,+ &svg[..start],+ &svg[start..end],+ );+ return rasterize_svg_str(&clipped, size, 0.0);+ }if self.has_embedded_color() {return rasterize_svg_str(svg, size, 0.0);}@@ -871,12 +892,14 @@ mod tests {BrandIcon::Fedora,BrandIcon::Git,BrandIcon::GitHub,+ BrandIcon::Herdr,BrandIcon::Linux,BrandIcon::NixOS,BrandIcon::Proxmox,BrandIcon::RaspberryPi,BrandIcon::RedHat,BrandIcon::Ubuntu,+ BrandIcon::WezTerm,] {let data: Vec<u8> = icon.rasterize(24).unwrap().into();assert_eq!(data.len(), 24 * 24 * 4);diff --git a/wezterm-gui/src/ui/icons.rs b/wezterm-gui/src/ui/icons.rsindex 490cada5..07022883 100644--- a/wezterm-gui/src/ui/icons.rs+++ b/wezterm-gui/src/ui/icons.rs@@ -10,7 +10,7 @@ pub(crate) enum SettingsIcon {Workspaces,Agents,Keymap,- Sync,+ Import,Developer,UiKit,Memory,@@ -36,7 +36,7 @@ impl SettingsIcon {Self::Workspaces => SvgIcon::FolderOpen,Self::Agents => SvgIcon::Bot,Self::Keymap => SvgIcon::Keyboard,- Self::Sync => SvgIcon::Cloud,+ Self::Import => SvgIcon::Download,Self::Developer => SvgIcon::Settings,Self::UiKit => SvgIcon::SlidersVertical,Self::Memory => SvgIcon::MemoryStick,diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex 95ff97be..5ba5f6a4 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -1342,6 +1342,98 @@ pub fn create_space(name: Option<String>) -> SpaceId {id}+#[cfg(unix)]+pub(crate) fn persist_session_import(+ tree: &codec::ThinkTermTree,+ add: bool,+ layouts: &[wezterm_mux_server_impl::session_import::ImportedThreadLayout],+) -> Result<()> {+ anyhow::ensure!(+ !STORE_IS_UNREADABLE.load(Ordering::Acquire),+ "The ThinkTerm workspace store could not be read"+ );+ let mut store = THREAD_STORE.lock();+ let candidate = store_with_session_import(&store, tree, add, layouts)?;+ let mut saved = Ok(());+ THREAD_STORE_WRITES.write_if_newest(THREAD_STORE_WRITES.claim(), || {+ saved = save_workspace_thread_store(&candidate);+ saved.is_ok()+ });+ saved?;+ *store = candidate;+ drop(store);+ publish_thinkterm_session_changed();+ Ok(())+}++#[cfg(unix)]+fn store_with_session_import(+ store: &WorkspaceThreadStore,+ tree: &codec::ThinkTermTree,+ add: bool,+ layouts: &[wezterm_mux_server_impl::session_import::ImportedThreadLayout],+) -> Result<WorkspaceThreadStore> {+ let mut candidate = store.clone();+ if add {+ anyhow::ensure!(+ tree.spaces+ .iter()+ .all(|space| !candidate.has_space(&space.id)),+ "Imported Space already exists"+ );+ candidate.ingest_host_tree(tree, None);+ for project in &tree.projects {+ for imported in &project.threads {+ let layout = layouts+ .iter()+ .find(|layout| layout.thread_id == imported.id)+ .context("Imported thread layout is missing")?;+ anyhow::ensure!(+ !layout.tabs.is_empty() && layout.active_tab < layout.tabs.len(),+ "Imported thread layout is invalid"+ );+ let snapshot = WorkspaceThreadLayoutSnapshot {+ active_tab: layout.active_tab,+ tabs: layout+ .tabs+ .iter()+ .map(serde_json::to_value)+ .collect::<Result<_, _>>()?,+ terminal_specs: layout+ .tabs+ .iter()+ .flat_map(|tab| tab.entries())+ .map(|entry| TerminalSpecEntry {+ pane_id: entry.pane_id,+ spec: TerminalSpawnSpec {+ cwd: working_dir_from_entry(entry),+ domain: Some("local".into()),+ title: entry.title.clone(),+ },+ font_scale: None,+ })+ .collect(),+ strict_cwd_spawns: true,+ };+ let thread = candidate+ .projects+ .iter_mut()+ .flat_map(|project| &mut project.threads)+ .find(|thread| thread.id == imported.id)+ .context("Imported thread is missing")?;+ thread.layout = Some(snapshot);+ }+ }+ } else {+ let imported = |id: &str| tree.spaces.iter().any(|space| space.id == id);+ candidate.spaces.retain(|space| !imported(&space.id));+ candidate+ .projects+ .retain(|project| !imported(&project.space_id));+ }+ Ok(candidate)+}+pub fn add_thread_ref(collection_space_id: &str, thread_id: &str) -> bool {let mut store = THREAD_STORE.lock();store.normalize_after_load();@@ -3009,6 +3101,8 @@ pub(crate) async fn materialize_thread(// *from* this materialization, and no window is worse than the wrong cwd.strict_project_cwd: bool,) -> Result<ThreadMaterializationOutcome> {+ #[cfg(unix)]+ wezterm_mux_server_impl::session_import::wait_for_workspace(&workspace_name).await?;let mux = Mux::get();if !mux.iter_windows_in_workspace(&workspace_name).is_empty() {return Ok(ThreadMaterializationOutcome::AlreadyLive);@@ -3221,6 +3315,8 @@ pub async fn materialize_thread_spawn(size: TerminalSize,term_config: Arc<dyn TerminalConfiguration>,) -> Result<()> {+ #[cfg(unix)]+ wezterm_mux_server_impl::session_import::wait_for_workspace(&workspace_name).await?;let mux = Mux::get();if !mux.iter_windows_in_workspace(&workspace_name).is_empty() {return Ok(());@@ -13191,6 +13287,156 @@ mod tests {tree}+ #[cfg(unix)]+ fn import_layout_fixture() -> (+ codec::ThinkTermTree,+ Vec<wezterm_mux_server_impl::session_import::ImportedThreadLayout>,+ ) {+ let mut tree = codec::ThinkTermTree::default();+ codec::apply_op(+ &mut tree,+ &codec::TreeOp::CreateSpace {+ space_id: "imported-space".into(),+ name: "Example".into(),+ },+ );+ let mut layouts = Vec::new();+ for project_index in 0..2 {+ let project_id = format!("imported-project-{project_index}");+ codec::apply_op(+ &mut tree,+ &codec::TreeOp::CreateProject {+ project_id: project_id.clone(),+ space_id: "imported-space".into(),+ name: "example".into(),+ path: "/home/user/example".into(),+ },+ );+ for thread_index in 0..2 {+ let thread_id = format!("imported-thread-{project_index}-{thread_index}");+ let workspace = format!("thinkterm:{project_id}:{thread_id}");+ codec::apply_op(+ &mut tree,+ &codec::TreeOp::CreateThread {+ thread_id: thread_id.clone(),+ project_id: project_id.clone(),+ name: "example".into(),+ workspace: Some(workspace.clone()),+ created_at: 1,+ },+ );+ let entry = |index: usize| PaneEntry {+ window_id: project_index * 2 + thread_index,+ tab_id: index / 2,+ pane_id: (project_index * 2 + thread_index) * 4 + index,+ title: format!("shell-{index}"),+ size: TerminalSize::default(),+ working_dir: Some(+ url::Url::parse(&format!("file:///home/user/example/pane-{index}"))+ .unwrap()+ .into(),+ ),+ is_active_pane: index == 3,+ is_zoomed_pane: index == 3,+ alt_screen: false,+ workspace: workspace.clone(),+ cursor_pos: Default::default(),+ physical_top: 0,+ top_row: 0,+ left_col: 0,+ tty_name: None,+ };+ layouts.push(+ wezterm_mux_server_impl::session_import::ImportedThreadLayout {+ thread_id,+ active_tab: 1,+ tabs: vec![+ PaneNode::Split {+ left: Box::new(PaneNode::Leaf(entry(0))),+ right: Box::new(PaneNode::Leaf(entry(1))),+ node: mux::tab::SplitDirectionAndSize {+ direction: SplitDirection::Horizontal,+ first: TerminalSize {+ cols: 30,+ ..TerminalSize::default()+ },+ second: TerminalSize {+ cols: 89,+ ..TerminalSize::default()+ },+ },+ },+ PaneNode::Stack(PaneStackEntry {+ panes: vec![entry(2), entry(3)],+ active: 1,+ pane_stack_id: None,+ }),+ ],+ },+ );+ }+ }+ (tree, layouts)+ }++ #[cfg(unix)]+ #[test]+ fn imported_import_appends_and_rolls_back_only_its_own_rows() {+ let store = host_test_store();+ let (tree, layouts) = import_layout_fixture();+ let imported = store_with_session_import(&store, &tree, true, &layouts).unwrap();+ assert_eq!(imported.spaces.len(), store.spaces.len() + 1);+ assert_eq!(imported.projects.len(), store.projects.len() + 2);+ assert!(store_with_session_import(&imported, &tree, true, &layouts).is_err());+ assert!(store_with_session_import(&store, &tree, true, &layouts[..3]).is_err());+ let rolled_back = store_with_session_import(&imported, &tree, false, &[]).unwrap();+ assert_eq!(rolled_back, store);+ }++ #[cfg(unix)]+ #[test]+ fn unopened_imported_threads_keep_every_layout_after_reload() {+ let (tree, layouts) = import_layout_fixture();+ // No mux windows or GUI snapshots: quit immediately after import.+ let imported =+ store_with_session_import(&host_test_store(), &tree, true, &layouts).unwrap();+ let dir = tempdir().unwrap();+ let path = dir.path().join("workspace_threads.json");+ save_workspace_thread_store_to_path(&path, &imported).unwrap();+ let loaded = load_workspace_thread_store_from_path(&path).unwrap();+ for expected in &layouts {+ let thread = loaded+ .projects+ .iter()+ .flat_map(|project| &project.threads)+ .find(|thread| thread.id == expected.thread_id)+ .unwrap();+ let snapshot = thread+ .layout+ .as_ref()+ .expect("unopened thread has a saved layout");+ assert_eq!(snapshot.active_tab, 1);+ assert!(snapshot.strict_cwd_spawns);+ let tabs = decode_layout_tabs(+ thread.materialized_workspace_name.as_deref().unwrap(),+ snapshot,+ )+ .expect("restart can decode the saved tabs");+ assert_eq!(+ serde_json::to_value(&tabs).unwrap(),+ serde_json::to_value(&expected.tabs).unwrap()+ );+ let entries: Vec<_> = expected.tabs.iter().flat_map(|tab| tab.entries()).collect();+ assert_eq!(snapshot.terminal_specs.len(), 4);+ for (spec, entry) in snapshot.terminal_specs.iter().zip(entries) {+ assert_eq!(spec.pane_id, entry.pane_id);+ assert_eq!(spec.spec.cwd, working_dir_from_entry(entry));+ assert_eq!(spec.spec.domain.as_deref(), Some("local"));+ assert_eq!(spec.spec.title, entry.title);+ }+ }+ }+#[test]fn ingesting_the_hosts_tree_keeps_local_state_and_ssh_projects() {let mut store = host_test_store();