From 6a4a289c3e51ced799f61ed376aa1d8dc4a66ac9 Mon Sep 17 00:00:00 2001 From: Yuval Tassa Date: Wed, 29 Jul 2026 07:24:22 -0700 Subject: [PATCH] Open macOS file dialogs in the directory of the seeded path. OpenFileDialog and SaveFileDialog hardcoded the user's Documents directory and placed the full seed path in the name field. Studio seeds dialogs with the current model's path, so File > Open now starts in the model's directory with the filename pre-filled, falling back to Documents when no path is available. Also avoids passing a potentially non-NUL-terminated string_view to stringWithUTF8String. PiperOrigin-RevId: 955869713 Change-Id: I7563f2cb2e39089883d5e37a3d259055c26e146c --- .../platform/ux/file_dialog_cocoa.mm | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/experimental/platform/ux/file_dialog_cocoa.mm b/src/experimental/platform/ux/file_dialog_cocoa.mm index a17e20ce..54992b17 100644 --- a/src/experimental/platform/ux/file_dialog_cocoa.mm +++ b/src/experimental/platform/ux/file_dialog_cocoa.mm @@ -20,13 +20,30 @@ namespace mujoco::platform { +// Points the panel at the directory of `path` with its filename pre-filled, +// falling back to the user's Documents directory when no path is given. +// NSOpenPanel inherits from NSSavePanel. +static void SetInitialPath(NSSavePanel* panel, std::string_view path) { + NSString* str = [[NSString alloc] initWithBytes:path.data() + length:path.size() + encoding:NSUTF8StringEncoding]; + if (str.length > 0) { + [panel setDirectoryURL: + [NSURL fileURLWithPath:[str stringByDeletingLastPathComponent] + isDirectory:YES]]; + [panel setNameFieldStringValue:[str lastPathComponent]]; + } else { + NSURL* userDocumentsDir = + [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory + inDomains:NSUserDomainMask].firstObject; + [panel setDirectoryURL:userDocumentsDir]; + } +} + DialogResult OpenFileDialog(std::string_view path, std::span filters) { NSOpenPanel* panel = [NSOpenPanel openPanel]; - NSURL* userDocumentsDir = [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory - inDomains:NSUserDomainMask].firstObject; - [panel setDirectoryURL:userDocumentsDir]; - [panel setNameFieldStringValue:[NSString stringWithUTF8String:path.data()]]; + SetInitialPath(panel, path); DialogResult result; if ([panel runModal] == NSModalResponseOK) { @@ -43,10 +60,7 @@ DialogResult OpenFileDialog(std::string_view path, DialogResult SaveFileDialog(std::string_view path, std::span filters) { NSSavePanel* panel = [NSSavePanel savePanel]; - NSURL* userDocumentsDir = [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory - inDomains:NSUserDomainMask].firstObject; - [panel setDirectoryURL:userDocumentsDir]; - [panel setNameFieldStringValue:[NSString stringWithUTF8String:path.data()]]; + SetInitialPath(panel, path); DialogResult result; if ([panel runModal] == NSModalResponseOK) {