diff --git a/src/message_dialog.h b/src/message_dialog.h index 33e6403..d605397 100644 --- a/src/message_dialog.h +++ b/src/message_dialog.h @@ -61,9 +61,9 @@ class MessageDialog : public Dialog { /** * @brief Whether the native backend supports the extended dialog controls. * @note Platform availability: - * - macOS: ❌ Not supported. - * - Windows: ✅ WinUI3 backend. - * - Linux: ❌ Not supported. + * - macOS: ✅ Supported (NSAlert; non-blocking sheet when parent window is set). + * - Windows: ✅ Supported (Win32 TaskDialogIndirect and WinUI3 backends). + * - Linux: ✅ Supported (GTK 3 GtkMessageDialog and GTK 4 GtkAlertDialog). * - Android: ❌ Not supported. * - iOS: ❌ Not supported. * - OpenHarmony: ✅ Native ArkUI controls after UI host initialization; API 23+. diff --git a/src/platform/linux/message_dialog_linux.cpp b/src/platform/linux/message_dialog_linux.cpp index 9e5d08f..5275b60 100644 --- a/src/platform/linux/message_dialog_linux.cpp +++ b/src/platform/linux/message_dialog_linux.cpp @@ -1,4 +1,6 @@ #include "../message_dialog_state.h" +#include +#include #include "../../dialog.h" #include "../../message_dialog.h" @@ -6,13 +8,35 @@ namespace nativeapi { -// Private implementation class for MessageDialog +namespace { + +GtkWindow* ResolveParentWindow(const std::shared_ptr& parent, bool* valid) { + *valid = true; + if (!parent) { + return nullptr; + } + GtkWidget* widget = static_cast(parent->GetNativeObject()); + if (!widget || !GTK_IS_WINDOW(widget)) { + *valid = false; + return nullptr; + } + return GTK_WINDOW(widget); +} + +} // namespace + +// Private implementation class for MessageDialog (GTK 3) class MessageDialog::Impl { public: MessageDialogState state_; - void RefreshExtended() {} + Impl(const std::string& title, const std::string& message) - : title_(title), message_(message), dialog_(nullptr), is_open_(false) { + : title_(title), + message_(message), + dialog_(nullptr), + input_entry_(nullptr), + checkbox_(nullptr), + progress_bar_(nullptr) { // Ensure GTK is initialized if (!gdk_display_get_default()) { gtk_init_check(nullptr, nullptr); @@ -28,19 +52,47 @@ class MessageDialog::Impl { void SetTitle(const std::string& title) { title_ = title; - // Title will be applied when dialog is opened + if (dialog_ && GTK_IS_WINDOW(dialog_)) { + gtk_window_set_title(GTK_WINDOW(dialog_), title_.c_str()); + } } std::string GetTitle() const { return title_; } void SetMessage(const std::string& message) { message_ = message; - // Message will be applied when dialog is opened + if (dialog_ && GTK_IS_MESSAGE_DIALOG(dialog_)) { + gtk_message_dialog_set_markup(GTK_MESSAGE_DIALOG(dialog_), message_.c_str()); + } } std::string GetMessage() const { return message_; } + void RefreshExtended() { + if (!dialog_) { + return; + } + if (input_entry_) { + const char* current = gtk_entry_get_text(GTK_ENTRY(input_entry_)); + if (!current || state_.input != current) { + gtk_entry_set_text(GTK_ENTRY(input_entry_), state_.input.c_str()); + } + gtk_widget_set_visible(input_entry_, state_.input_enabled ? TRUE : FALSE); + } + if (checkbox_) { + gtk_button_set_label(GTK_BUTTON(checkbox_), state_.checkbox.c_str()); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbox_), state_.checked ? TRUE : FALSE); + gtk_widget_set_visible(checkbox_, !state_.checkbox.empty() ? TRUE : FALSE); + } + if (progress_bar_) { + ApplyProgress(progress_bar_, state_.progress); + } + } + bool Open(DialogModality modality) { + if (state_.open) { + return false; + } // Ensure GTK is initialized if (!gdk_display_get_default()) { if (!gtk_init_check(nullptr, nullptr)) { @@ -48,58 +100,106 @@ class MessageDialog::Impl { } } - // For modal dialogs, always create a new dialog since gtk_dialog_run destroys it - // For non-modal dialogs, close existing dialog if open before creating new one - // This ensures title and message are always up to date + bool parent_valid = true; + GtkWindow* parent = ResolveParentWindow(state_.parent, &parent_valid); + if (!parent_valid) { + return false; + } + if (dialog_ && GTK_IS_WIDGET(dialog_)) { - // Destroy old dialog if exists gtk_widget_destroy(dialog_); dialog_ = nullptr; - is_open_ = false; } - // Create a new message dialog + GtkDialogFlags flags = + (modality != DialogModality::None) ? GTK_DIALOG_MODAL : GTK_DIALOG_DESTROY_WITH_PARENT; dialog_ = gtk_message_dialog_new( - nullptr, // No parent window - GTK_DIALOG_MODAL, // Default to modal (will be overridden for non-modal) - GTK_MESSAGE_INFO, // Message type - GTK_BUTTONS_OK, // Buttons - "%s", // Format string - message_.c_str()); - + parent, flags, GTK_MESSAGE_INFO, GTK_BUTTONS_NONE, "%s", message_.c_str()); if (!dialog_) { return false; } - // Set title gtk_window_set_title(GTK_WINDOW(dialog_), title_.c_str()); - // Connect destroy signal to track when dialog is closed by user + // Add configured buttons (close, secondary, primary -> primary on the right). + bool added_any = false; + gint default_response = GTK_RESPONSE_NONE; + auto add_button = [&](const std::string& label, gint response_id, MessageDialogResult res) { + if (label.empty()) { + return; + } + gtk_dialog_add_button(GTK_DIALOG(dialog_), label.c_str(), response_id); + added_any = true; + if (res == state_.default_button) { + default_response = response_id; + } + }; + add_button(state_.close, kResponseClose, MessageDialogResult::Close); + add_button(state_.secondary, kResponseSecondary, MessageDialogResult::Secondary); + add_button(state_.primary, kResponsePrimary, MessageDialogResult::Primary); + if (!added_any) { + gtk_dialog_add_button(GTK_DIALOG(dialog_), "OK", kResponseClose); + default_response = kResponseClose; + } + if (default_response != GTK_RESPONSE_NONE) { + gtk_dialog_set_default_response(GTK_DIALOG(dialog_), default_response); + } + + // Add optional extended controls to the message area. + input_entry_ = nullptr; + checkbox_ = nullptr; + progress_bar_ = nullptr; + GtkWidget* area = gtk_message_dialog_get_message_area(GTK_MESSAGE_DIALOG(dialog_)); + if (area) { + if (state_.input_enabled) { + input_entry_ = gtk_entry_new(); + gtk_entry_set_text(GTK_ENTRY(input_entry_), state_.input.c_str()); + gtk_entry_set_activates_default(GTK_ENTRY(input_entry_), TRUE); + g_signal_connect(input_entry_, "changed", G_CALLBACK(OnInputChanged), this); + gtk_box_pack_start(GTK_BOX(area), input_entry_, FALSE, FALSE, 4); + gtk_widget_show(input_entry_); + } + if (!state_.checkbox.empty()) { + checkbox_ = gtk_check_button_new_with_label(state_.checkbox.c_str()); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbox_), state_.checked ? TRUE : FALSE); + g_signal_connect(checkbox_, "toggled", G_CALLBACK(OnCheckboxToggled), this); + gtk_box_pack_start(GTK_BOX(area), checkbox_, FALSE, FALSE, 4); + gtk_widget_show(checkbox_); + } + if (state_.progress != -2) { + progress_bar_ = gtk_progress_bar_new(); + ApplyProgress(progress_bar_, state_.progress); + gtk_box_pack_start(GTK_BOX(area), progress_bar_, FALSE, FALSE, 4); + gtk_widget_show(progress_bar_); + } + } + + state_.result = MessageDialogResult::None; g_signal_connect(dialog_, "response", G_CALLBACK(OnResponse), this); g_signal_connect(dialog_, "destroy", G_CALLBACK(OnDestroy), this); - // Handle modality switch (modality) { case DialogModality::None: - // Non-modal: show the dialog without blocking gtk_window_set_modal(GTK_WINDOW(dialog_), FALSE); + state_.open = true; gtk_widget_show(dialog_); - is_open_ = true; break; case DialogModality::Application: case DialogModality::Window: - // Modal: block until user responds gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE); - is_open_ = true; - - // Run the dialog modally - this blocks until user responds - // Note: gtk_dialog_run automatically destroys the dialog when done - gtk_dialog_run(GTK_DIALOG(dialog_)); - - // After gtk_dialog_run returns, the dialog has been dismissed and destroyed - // The OnDestroy callback will set dialog_ to nullptr - is_open_ = false; + state_.open = true; + { + const gint response_id = gtk_dialog_run(GTK_DIALOG(dialog_)); + if (state_.result == MessageDialogResult::None) { + state_.result = MapResponse(response_id); + } + } + if (dialog_ && GTK_IS_WIDGET(dialog_)) { + gtk_widget_destroy(dialog_); + dialog_ = nullptr; + } + state_.open = false; break; } @@ -107,37 +207,66 @@ class MessageDialog::Impl { } bool Close() { - if (!dialog_ || !is_open_) { + if (!dialog_ || !state_.open) { return false; } - // Close the dialog programmatically gtk_dialog_response(GTK_DIALOG(dialog_), GTK_RESPONSE_CLOSE); - // If it's a modal dialog, we need to destroy it manually - // (gtk_dialog_run already destroyed it) - if (dialog_) { + if (dialog_ && GTK_IS_WIDGET(dialog_)) { gtk_widget_destroy(dialog_); dialog_ = nullptr; } - is_open_ = false; + state_.open = false; return true; } private: - std::string title_; - std::string message_; - GtkWidget* dialog_; - bool is_open_; + static constexpr gint kResponsePrimary = 1; + static constexpr gint kResponseSecondary = 2; + static constexpr gint kResponseClose = 3; + + static MessageDialogResult MapResponse(gint response_id) { + switch (response_id) { + case kResponsePrimary: + return MessageDialogResult::Primary; + case kResponseSecondary: + return MessageDialogResult::Secondary; + default: + return MessageDialogResult::Close; + } + } + + static void ApplyProgress(GtkWidget* bar, double value) { + if (value == -2) { + gtk_widget_hide(bar); + return; + } + gtk_widget_show(bar); + if (value == -1) { + gtk_progress_bar_pulse(GTK_PROGRESS_BAR(bar)); + } else { + gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(bar), std::clamp(value, 0.0, 1.0)); + } + } + + static void OnInputChanged(GtkEditable* editable, gpointer user_data) { + auto* impl = static_cast(user_data); + const char* text = gtk_entry_get_text(GTK_ENTRY(editable)); + impl->state_.input = text ? text : ""; + } + + static void OnCheckboxToggled(GtkToggleButton* button, gpointer user_data) { + auto* impl = static_cast(user_data); + impl->state_.checked = gtk_toggle_button_get_active(button) != FALSE; + } static void OnResponse(GtkDialog* dialog, gint response_id, gpointer user_data) { Impl* impl = static_cast(user_data); + impl->state_.result = MapResponse(response_id); + impl->state_.open = false; - // Mark as closed - impl->is_open_ = false; - - // For non-modal dialogs, destroy the dialog when user responds if (!gtk_window_get_modal(GTK_WINDOW(dialog))) { gtk_widget_destroy(GTK_WIDGET(dialog)); impl->dialog_ = nullptr; @@ -146,13 +275,21 @@ class MessageDialog::Impl { static void OnDestroy(GtkWidget* widget, gpointer user_data) { Impl* impl = static_cast(user_data); - - // Clear the dialog pointer when it's destroyed if (impl->dialog_ == widget) { impl->dialog_ = nullptr; - impl->is_open_ = false; + impl->input_entry_ = nullptr; + impl->checkbox_ = nullptr; + impl->progress_bar_ = nullptr; + impl->state_.open = false; } } + + std::string title_; + std::string message_; + GtkWidget* dialog_; + GtkWidget* input_entry_; + GtkWidget* checkbox_; + GtkWidget* progress_bar_; }; // MessageDialog implementation @@ -197,7 +334,7 @@ bool MessageDialog::Close() { return pimpl_->Close(); } -bool MessageDialog::IsExtendedSupported() { return false; } +bool MessageDialog::IsExtendedSupported() { return true; } #include "../message_dialog_extensions.inc" } // namespace nativeapi diff --git a/src/platform/macos/message_dialog_macos.mm b/src/platform/macos/message_dialog_macos.mm index 6a67009..27b1008 100644 --- a/src/platform/macos/message_dialog_macos.mm +++ b/src/platform/macos/message_dialog_macos.mm @@ -1,5 +1,8 @@ #include "../message_dialog_state.h" #import +#include +#include +#include #include "../../dialog.h" #include "../../message_dialog.h" @@ -9,50 +12,77 @@ class MessageDialog::Impl { public: MessageDialogState state_; - void RefreshExtended() {} - Impl(const std::string& title, const std::string& message) - : title_(title), message_(message), ns_alert_(nil), is_open_(false) { - // Create NSAlert instance - ns_alert_ = [[NSAlert alloc] init]; - - // Set default values - [ns_alert_ setMessageText:[NSString stringWithUTF8String:title.c_str()]]; - [ns_alert_ setInformativeText:[NSString stringWithUTF8String:message.c_str()]]; - // Set default alert style to informational - [ns_alert_ setAlertStyle:NSAlertStyleInformational]; - } + Impl(const std::string& title, const std::string& message) + : title_(title), + message_(message), + active_alert_(nil), + sheet_parent_(nil), + input_field_(nil), + progress_bar_(nil), + alive_(std::make_shared(true)) {} ~Impl() { - if (ns_alert_) { - ns_alert_ = nil; + *alive_ = false; + if (state_.open) { + Close(); } +#if !__has_feature(objc_arc) + if (active_alert_) { + [active_alert_ release]; + active_alert_ = nil; + } +#endif } void SetTitle(const std::string& title) { title_ = title; - if (ns_alert_) { - [ns_alert_ setMessageText:[NSString stringWithUTF8String:title.c_str()]]; - } + RunOnMainThread(^{ + if (active_alert_) { + [active_alert_ setMessageText:[NSString stringWithUTF8String:title_.c_str()]]; + } + }); } std::string GetTitle() const { return title_; } void SetMessage(const std::string& message) { message_ = message; - if (ns_alert_) { - [ns_alert_ setInformativeText:[NSString stringWithUTF8String:message.c_str()]]; - } + RunOnMainThread(^{ + if (active_alert_) { + [active_alert_ setInformativeText:[NSString stringWithUTF8String:message_.c_str()]]; + } + }); } std::string GetMessage() const { return message_; } - bool Open(DialogModality modality) { - if (!ns_alert_) { - return false; - } + void RefreshExtended() { + RunOnMainThread(^{ + if (!active_alert_) { + return; + } + if (input_field_) { + NSString* current = [input_field_ stringValue]; + NSString* desired = [NSString stringWithUTF8String:state_.input.c_str()]; + if (![current isEqualToString:desired]) { + [input_field_ setStringValue:desired]; + } + [input_field_ setHidden:!state_.input_enabled]; + } + if ([active_alert_ showsSuppressionButton] && [active_alert_ suppressionButton]) { + [[active_alert_ suppressionButton] + setTitle:[NSString stringWithUTF8String:state_.checkbox.c_str()]]; + [[active_alert_ suppressionButton] + setState:(state_.checked ? NSControlStateValueOn : NSControlStateValueOff)]; + } + if (progress_bar_) { + ApplyProgressToBar(progress_bar_, state_.progress); + } + }); + } - // Ensure we're on the main thread for UI operations + bool Open(DialogModality modality) { if (![NSThread isMainThread]) { __block bool result = false; dispatch_sync(dispatch_get_main_queue(), ^{ @@ -60,73 +90,235 @@ bool Open(DialogModality modality) { }); return result; } - return OpenOnMainThread(modality); } - bool OpenOnMainThread(DialogModality modality) { - if (!ns_alert_) { + bool OpenOnMainThread(DialogModality /*modality*/) { + if (state_.open) { return false; } - // Configure alert style based on modality - // Note: macOS doesn't have true system modal dialogs in modern versions - // Application is the standard modal behavior - // Window behaves as Application on macOS - switch (modality) { - case DialogModality::None: - // Non-modal: show as sheet or window that doesn't block - // For NSAlert, we can use beginSheetModalForWindow:completionHandler: - // However, NSAlert doesn't have a direct non-modal display method - // We'll use runModal with a workaround, or implement as sheet - // For now, treat None as non-blocking modal (temporary solution) - is_open_ = true; - @autoreleasepool { - // Note: NSAlert doesn't have a true non-modal mode - // This is a limitation of NSAlert API - // Consider using NSPanel or custom window for true non-modal dialogs - [ns_alert_ runModal]; - } - is_open_ = false; - break; - case DialogModality::Application: - case DialogModality::Window: - // Both use application modal behavior on macOS - // Run the alert modally - this blocks until the user dismisses the dialog - is_open_ = true; - @autoreleasepool { - [ns_alert_ runModal]; + NSWindow* parent_window = nil; + if (state_.parent) { + parent_window = (__bridge NSWindow*)state_.parent->GetNativeObject(); + if (!parent_window) { + return false; + } + } + + state_.result = MessageDialogResult::None; + button_results_.clear(); + + NSAlert* alert = [[NSAlert alloc] init]; + [alert setMessageText:[NSString stringWithUTF8String:title_.c_str()]]; + [alert setInformativeText:[NSString stringWithUTF8String:message_.c_str()]]; + [alert setAlertStyle:NSAlertStyleInformational]; + + // Add configured buttons in AppKit order (first added is rightmost / primary). + auto add_button = [&](const std::string& label, MessageDialogResult res) { + if (label.empty()) { + return; + } + [alert addButtonWithTitle:[NSString stringWithUTF8String:label.c_str()]]; + button_results_.push_back(res); + }; + add_button(state_.primary, MessageDialogResult::Primary); + add_button(state_.secondary, MessageDialogResult::Secondary); + add_button(state_.close, MessageDialogResult::Close); + if (button_results_.empty()) { + add_button("OK", MessageDialogResult::Close); + } + + // Checkbox via NSAlert's native suppression button. + if (!state_.checkbox.empty()) { + [alert setShowsSuppressionButton:YES]; + [[alert suppressionButton] + setTitle:[NSString stringWithUTF8String:state_.checkbox.c_str()]]; + [[alert suppressionButton] + setState:(state_.checked ? NSControlStateValueOn : NSControlStateValueOff)]; + } + + // Optional text input and/or progress bar via accessoryView. + input_field_ = nil; + progress_bar_ = nil; + if (state_.input_enabled || state_.progress != -2) { + constexpr CGFloat kAccessoryWidth = 280.0; + NSStackView* stack = [[NSStackView alloc] initWithFrame:NSMakeRect(0, 0, kAccessoryWidth, 0)]; + [stack setOrientation:NSUserInterfaceLayoutOrientationVertical]; + [stack setAlignment:NSLayoutAttributeLeading]; + [stack setSpacing:8.0]; + [stack setTranslatesAutoresizingMaskIntoConstraints:NO]; + + CGFloat total_height = 0.0; + if (state_.input_enabled) { + NSTextField* field = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, kAccessoryWidth, 24)]; + [field setStringValue:[NSString stringWithUTF8String:state_.input.c_str()]]; + [field setEditable:YES]; + [field setBezeled:YES]; + [field setTranslatesAutoresizingMaskIntoConstraints:NO]; + [[field.widthAnchor constraintEqualToConstant:kAccessoryWidth] setActive:YES]; + [stack addArrangedSubview:field]; +#if !__has_feature(objc_arc) + [field release]; +#endif + input_field_ = field; + total_height += 24.0; + } + if (state_.progress != -2) { + NSProgressIndicator* bar = + [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, kAccessoryWidth, 16)]; + [bar setStyle:NSProgressIndicatorStyleBar]; + [bar setMinValue:0.0]; + [bar setMaxValue:1.0]; + [bar setTranslatesAutoresizingMaskIntoConstraints:NO]; + [[bar.widthAnchor constraintEqualToConstant:kAccessoryWidth] setActive:YES]; + ApplyProgressToBar(bar, state_.progress); + [stack addArrangedSubview:bar]; +#if !__has_feature(objc_arc) + [bar release]; +#endif + progress_bar_ = bar; + if (total_height > 0.0) { + total_height += 8.0; } - // After runModal returns, the dialog has been dismissed - is_open_ = false; - break; + total_height += 16.0; + } + [stack setFrame:NSMakeRect(0, 0, kAccessoryWidth, total_height)]; + [alert setAccessoryView:stack]; +#if !__has_feature(objc_arc) + [stack release]; +#endif + } + + [alert layout]; + + // Configure Return (default) and Escape (close) key equivalents after layout + // so NSAlert does not reset them during initial layout. + NSArray* buttons = [alert buttons]; + for (NSUInteger i = 0; i < [buttons count]; ++i) { + [[buttons objectAtIndex:i] setKeyEquivalent:@""]; + } + for (size_t i = 0; i < button_results_.size() && i < [buttons count]; ++i) { + NSButton* button = [buttons objectAtIndex:i]; + if (button_results_[i] == state_.default_button) { + [button setKeyEquivalent:@"\r"]; + } else if (button_results_[i] == MessageDialogResult::Close) { + [button setKeyEquivalent:@"\x1b"]; + } + } + + active_alert_ = alert; + state_.open = true; + + if (parent_window) { + // Non-blocking sheet attached to the parent window. + sheet_parent_ = parent_window; + std::shared_ptr alive = alive_; + [alert beginSheetModalForWindow:parent_window + completionHandler:^(NSModalResponse returnCode) { + if (!*alive) { + return; + } + FinishDismissal(returnCode); + }]; + return true; } + // No parent window: run application-modal. + NSModalResponse response = NSModalResponseCancel; + @autoreleasepool { + response = [alert runModal]; + } + if (*alive_) { + FinishDismissal(response); + } return true; } bool Close() { - if (!ns_alert_ || !is_open_) { + if (![NSThread isMainThread]) { + __block bool result = false; + dispatch_sync(dispatch_get_main_queue(), ^{ + result = CloseOnMainThread(); + }); + return result; + } + return CloseOnMainThread(); + } + + bool CloseOnMainThread() { + if (!state_.open || !active_alert_) { return false; } + if (sheet_parent_) { + [sheet_parent_ endSheet:[active_alert_ window] returnCode:NSModalResponseCancel]; + return true; + } + [NSApp abortModal]; + return true; + } - // NSAlert doesn't have a direct close method - // We need to stop the modal session if it's running - // For sheet-based dialogs, we can dismiss the sheet - // Note: This is a limitation of NSAlert API - // In practice, the user must dismiss the dialog manually + private: + static void RunOnMainThread(dispatch_block_t block) { + if ([NSThread isMainThread]) { + block(); + } else { + dispatch_sync(dispatch_get_main_queue(), block); + } + } - is_open_ = false; - return true; + static void ApplyProgressToBar(NSProgressIndicator* bar, double value) { + if (value == -2) { + [bar stopAnimation:nil]; + [bar setHidden:YES]; + return; + } + [bar setHidden:NO]; + if (value == -1) { + [bar setIndeterminate:YES]; + [bar startAnimation:nil]; + } else { + [bar stopAnimation:nil]; + [bar setIndeterminate:NO]; + [bar setDoubleValue:std::clamp(value, 0.0, 1.0)]; + } } - bool IsOpen() const { return is_open_; } + void FinishDismissal(NSModalResponse response) { + if (input_field_) { + NSString* text = [input_field_ stringValue]; + state_.input = text ? std::string([text UTF8String]) : std::string(); + } + if (active_alert_ && [active_alert_ showsSuppressionButton] && + [active_alert_ suppressionButton]) { + state_.checked = ([[active_alert_ suppressionButton] state] == NSControlStateValueOn); + } + + const NSInteger index = response - NSAlertFirstButtonReturn; + if (index >= 0 && static_cast(index) < button_results_.size()) { + state_.result = button_results_[static_cast(index)]; + } else { + state_.result = MessageDialogResult::Close; + } + +#if !__has_feature(objc_arc) + [active_alert_ release]; +#endif + active_alert_ = nil; + sheet_parent_ = nil; + input_field_ = nil; + progress_bar_ = nil; + state_.open = false; + } - private: std::string title_; std::string message_; - NSAlert* ns_alert_; - bool is_open_; + NSAlert* active_alert_; + NSWindow* sheet_parent_; + NSTextField* input_field_; + NSProgressIndicator* progress_bar_; + std::vector button_results_; + std::shared_ptr alive_; }; // MessageDialog implementation @@ -171,7 +363,7 @@ bool Close() { return pimpl_->Close(); } -bool MessageDialog::IsExtendedSupported() { return false; } +bool MessageDialog::IsExtendedSupported() { return true; } #include "../message_dialog_extensions.inc" } // namespace nativeapi diff --git a/src/platform/windows/message_dialog_windows.cpp b/src/platform/windows/message_dialog_windows.cpp index a78578d..8747bca 100644 --- a/src/platform/windows/message_dialog_windows.cpp +++ b/src/platform/windows/message_dialog_windows.cpp @@ -2,6 +2,7 @@ // clang-format off #include #include +#include // clang-format on // Undefine Windows API macros that conflict with our method names @@ -9,8 +10,11 @@ #undef GetMessage #endif +#include +#include #include #include +#include #include "../../dialog.h" #include "../../message_dialog.h" @@ -18,14 +22,70 @@ namespace nativeapi { -// Private implementation class for MessageDialog using Win32 MessageBox +namespace { + +constexpr int kButtonPrimary = 1001; +constexpr int kButtonSecondary = 1002; +constexpr int kButtonClose = 1003; + +using TaskDialogIndirectFn = + HRESULT(WINAPI*)(const TASKDIALOGCONFIG*, int*, int*, BOOL*); + +// Activates a ComCtl32 v6 context via shell32's built-in manifest (resource 124) +// so TaskDialogIndirect works even in manifest-less host executables. +class ComCtlV6Scope { + public: + ComCtlV6Scope() { + HMODULE shell32 = LoadLibraryW(L"shell32.dll"); + if (!shell32) { + return; + } + ACTCTXW actctx = {}; + actctx.cbSize = sizeof(actctx); + actctx.dwFlags = ACTCTX_FLAG_HMODULE_VALID | ACTCTX_FLAG_RESOURCE_NAME_VALID; + actctx.hModule = shell32; + actctx.lpResourceName = MAKEINTRESOURCEW(124); + ctx_ = CreateActCtxW(&actctx); + FreeLibrary(shell32); + if (ctx_ != INVALID_HANDLE_VALUE) { + active_ = ActivateActCtx(ctx_, &cookie_) != FALSE; + } + } + + ~ComCtlV6Scope() { + if (active_) { + DeactivateActCtx(0, cookie_); + } + if (ctx_ != INVALID_HANDLE_VALUE) { + ReleaseActCtx(ctx_); + } + } + + ComCtlV6Scope(const ComCtlV6Scope&) = delete; + ComCtlV6Scope& operator=(const ComCtlV6Scope&) = delete; + + private: + HANDLE ctx_ = INVALID_HANDLE_VALUE; + ULONG_PTR cookie_ = 0; + bool active_ = false; +}; + +} // namespace + +// Private implementation class for MessageDialog using Win32 TaskDialogIndirect +// (with MessageBoxW fallback if ComCtl32 v6 cannot be loaded). class MessageDialog::Impl { public: MessageDialogState state_; - void RefreshExtended() {} - Impl(const std::string& title, const std::string& message) : title_(title), message_(message) {} - ~Impl() = default; + Impl(const std::string& title, const std::string& message) + : title_(title), message_(message) {} + + ~Impl() { + if (state_.open) { + Close(); + } + } void SetTitle(const std::string& title) { title_ = title; } @@ -35,31 +95,226 @@ class MessageDialog::Impl { std::string GetMessage() const { return message_; } + void RefreshExtended() { + HWND hwnd = dialog_hwnd_.load(); + if (!hwnd) { + return; + } + if (state_.progress == -1) { + PostMessageW(hwnd, TDM_SET_MARQUEE_PROGRESS_BAR, TRUE, 0); + PostMessageW(hwnd, TDM_SET_PROGRESS_BAR_MARQUEE, TRUE, 0); + } else if (state_.progress >= 0) { + PostMessageW(hwnd, TDM_SET_MARQUEE_PROGRESS_BAR, FALSE, 0); + PostMessageW(hwnd, TDM_SET_PROGRESS_BAR_RANGE, 0, MAKELPARAM(0, 1000)); + PostMessageW( + hwnd, TDM_SET_PROGRESS_BAR_POS, + static_cast(std::clamp(state_.progress, 0.0, 1.0) * 1000.0), 0); + } + } + bool Open(DialogModality modality) { - std::wstring wtitle = StringToWString(title_); - std::wstring wmessage = StringToWString(message_); + if (state_.open) { + return false; + } - UINT uType = MB_OK | MB_ICONINFORMATION; + HWND parent = nullptr; + if (state_.parent) { + parent = static_cast(state_.parent->GetNativeObject()); + if (!parent || !IsWindow(parent)) { + return false; + } + } - // Set modality - if (modality == DialogModality::Application) { - uType |= MB_APPLMODAL; - } else if (modality == DialogModality::Window) { - uType |= MB_SYSTEMMODAL; // Use system modal as approximation + state_.result = MessageDialogResult::None; + state_.open = true; + + const std::wstring wtitle = StringToWString(title_); + const std::wstring wmessage = StringToWString(message_); + + // Try already-loaded comctl32 first; if v5 is loaded, activate v6 context. + HMODULE comctl = GetModuleHandleW(L"comctl32.dll"); + TaskDialogIndirectFn task_dialog_indirect = + comctl ? reinterpret_cast( + GetProcAddress(comctl, "TaskDialogIndirect")) + : nullptr; + + std::unique_ptr v6_scope; + HMODULE loaded_comctl = nullptr; + if (!task_dialog_indirect) { + v6_scope = std::make_unique(); + loaded_comctl = LoadLibraryW(L"comctl32.dll"); + if (loaded_comctl) { + task_dialog_indirect = reinterpret_cast( + GetProcAddress(loaded_comctl, "TaskDialogIndirect")); + } + } + + bool opened = false; + if (task_dialog_indirect) { + opened = OpenWithTaskDialog(task_dialog_indirect, parent, wtitle, wmessage); + } else { + opened = OpenWithMessageBox(parent, modality, wtitle, wmessage); } - int result = MessageBoxW(nullptr, wmessage.c_str(), wtitle.c_str(), uType); - return result != 0; + if (loaded_comctl) { + FreeLibrary(loaded_comctl); + } + dialog_hwnd_.store(nullptr); + state_.open = false; + return opened; } bool Close() { - // MessageBox doesn't support programmatic closing - return false; + HWND hwnd = dialog_hwnd_.load(); + if (!state_.open || !hwnd) { + return false; + } + return PostMessageW(hwnd, TDM_CLICK_BUTTON, IDCANCEL, 0) != FALSE; } private: + static HRESULT CALLBACK TaskDialogCallback(HWND hwnd, UINT msg, WPARAM /*wp*/, + LPARAM /*lp*/, LONG_PTR ref_data) { + auto* self = reinterpret_cast(ref_data); + if (!self) { + return S_OK; + } + if (msg == TDN_CREATED) { + self->dialog_hwnd_.store(hwnd); + if (self->state_.progress == -1) { + SendMessageW(hwnd, TDM_SET_MARQUEE_PROGRESS_BAR, TRUE, 0); + SendMessageW(hwnd, TDM_SET_PROGRESS_BAR_MARQUEE, TRUE, 0); + } else if (self->state_.progress >= 0) { + SendMessageW(hwnd, TDM_SET_PROGRESS_BAR_RANGE, 0, MAKELPARAM(0, 1000)); + SendMessageW( + hwnd, TDM_SET_PROGRESS_BAR_POS, + static_cast(std::clamp(self->state_.progress, 0.0, 1.0) * 1000.0), 0); + } + } else if (msg == TDN_DESTROYED) { + self->dialog_hwnd_.store(nullptr); + } + return S_OK; + } + + bool OpenWithTaskDialog(TaskDialogIndirectFn fn, HWND parent, + const std::wstring& wtitle, + const std::wstring& wmessage) { + std::vector labels; + labels.reserve(3); + std::vector ids; + ids.reserve(3); + + auto add_button = [&](const std::string& text, int id) { + if (text.empty()) { + return; + } + labels.push_back(StringToWString(text)); + ids.push_back(id); + }; + add_button(state_.primary, kButtonPrimary); + add_button(state_.secondary, kButtonSecondary); + add_button(state_.close, kButtonClose); + if (labels.empty()) { + labels.push_back(L"OK"); + ids.push_back(kButtonClose); + } + + std::vector buttons; + buttons.reserve(labels.size()); + for (size_t i = 0; i < labels.size(); ++i) { + TASKDIALOG_BUTTON btn = {}; + btn.nButtonID = ids[i]; + btn.pszButtonText = labels[i].c_str(); + buttons.push_back(btn); + } + + TASKDIALOGCONFIG config = {}; + config.cbSize = sizeof(config); + config.hwndParent = parent; + config.dwFlags = TDF_ALLOW_DIALOG_CANCELLATION; + if (parent) { + config.dwFlags |= TDF_POSITION_RELATIVE_TO_WINDOW; + } + config.pszWindowTitle = wtitle.c_str(); + config.pszContent = wmessage.c_str(); + config.pszMainIcon = TD_INFORMATION_ICON; + config.pButtons = buttons.data(); + config.cButtons = static_cast(buttons.size()); + + int default_id = 0; + if (state_.default_button == MessageDialogResult::Primary && !state_.primary.empty()) { + default_id = kButtonPrimary; + } else if (state_.default_button == MessageDialogResult::Secondary && + !state_.secondary.empty()) { + default_id = kButtonSecondary; + } else if (state_.default_button == MessageDialogResult::Close && !state_.close.empty()) { + default_id = kButtonClose; + } + config.nDefaultButton = default_id; + + std::wstring wcheckbox; + if (!state_.checkbox.empty()) { + wcheckbox = StringToWString(state_.checkbox); + config.pszVerificationText = wcheckbox.c_str(); + if (state_.checked) { + config.dwFlags |= TDF_VERIFICATION_FLAG_CHECKED; + } + } + + if (state_.progress == -1) { + config.dwFlags |= TDF_SHOW_MARQUEE_PROGRESS_BAR; + } else if (state_.progress >= 0) { + config.dwFlags |= TDF_SHOW_PROGRESS_BAR; + } + + config.pfCallback = TaskDialogCallback; + config.lpCallbackData = reinterpret_cast(this); + + int pressed_button = 0; + BOOL verification_checked = FALSE; + HRESULT hr = fn(&config, &pressed_button, nullptr, + state_.checkbox.empty() ? nullptr : &verification_checked); + if (FAILED(hr)) { + return false; + } + + if (!state_.checkbox.empty()) { + state_.checked = (verification_checked != FALSE); + } + switch (pressed_button) { + case kButtonPrimary: + state_.result = MessageDialogResult::Primary; + break; + case kButtonSecondary: + state_.result = MessageDialogResult::Secondary; + break; + default: + state_.result = MessageDialogResult::Close; + break; + } + return true; + } + + bool OpenWithMessageBox(HWND parent, DialogModality modality, + const std::wstring& wtitle, + const std::wstring& wmessage) { + UINT uType = MB_OK | MB_ICONINFORMATION; + if (modality == DialogModality::Application) { + uType |= MB_APPLMODAL; + } else if (modality == DialogModality::Window) { + uType |= MB_SYSTEMMODAL; + } + int result = MessageBoxW(parent, wmessage.c_str(), wtitle.c_str(), uType); + if (result != 0) { + state_.result = MessageDialogResult::Close; + return true; + } + return false; + } + std::string title_; std::string message_; + std::atomic dialog_hwnd_{nullptr}; }; // MessageDialog implementation @@ -104,7 +359,7 @@ bool MessageDialog::Close() { return pimpl_->Close(); } -bool MessageDialog::IsExtendedSupported() { return false; } +bool MessageDialog::IsExtendedSupported() { return true; } #include "../message_dialog_extensions.inc" } // namespace nativeapi diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4e84d70..514e20f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -672,3 +672,16 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux") add_test(NAME tray_context_menu_linux_test COMMAND tray_context_menu_linux_test) set_tests_properties(tray_context_menu_linux_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 20) endif() + +add_executable(message_dialog_extended_test message_dialog_extended_test.cpp) +target_link_libraries(message_dialog_extended_test PRIVATE nativeapi) +add_test(NAME message_dialog_extended_test COMMAND message_dialog_extended_test) +set_tests_properties(message_dialog_extended_test PROPERTIES TIMEOUT 10) + +if(APPLE AND NOT CMAKE_SYSTEM_NAME STREQUAL "iOS") + add_executable(message_dialog_macos_sheet_test message_dialog_macos_sheet_test.mm) + target_compile_options(message_dialog_macos_sheet_test PRIVATE -fobjc-arc) + target_link_libraries(message_dialog_macos_sheet_test PRIVATE nativeapi "-framework Cocoa") + add_test(NAME message_dialog_macos_sheet_test COMMAND message_dialog_macos_sheet_test) + set_tests_properties(message_dialog_macos_sheet_test PROPERTIES TIMEOUT 15) +endif() diff --git a/tests/message_dialog_extended_test.cpp b/tests/message_dialog_extended_test.cpp new file mode 100644 index 0000000..b991311 --- /dev/null +++ b/tests/message_dialog_extended_test.cpp @@ -0,0 +1,70 @@ +#ifdef __APPLE__ +#include +#endif +#include +#include +#include "../src/message_dialog.h" + +using nativeapi::MessageDialog; +using nativeapi::MessageDialogResult; + +int main() { + int failures = 0; + auto check = [&](bool ok, const char* what) { + if (!ok) { + std::cerr << "FAIL: " << what << std::endl; + ++failures; + } + }; + +#if (defined(__APPLE__) && !defined(TARGET_OS_IPHONE)) || defined(_WIN32) || \ + (defined(__linux__) && !defined(__ANDROID__)) + check(MessageDialog::IsExtendedSupported(), + "MessageDialog::IsExtendedSupported() is true on desktop"); +#endif + + if (!MessageDialog::IsExtendedSupported()) { + std::cout << "message_dialog_extended_test: extended unsupported on this platform" + << std::endl; + return failures == 0 ? 0 : 1; + } + + auto dialog = std::make_shared("Unsaved Changes", "Save before closing?"); + check(!dialog->IsOpen(), "initially not open"); + check(dialog->GetResult() == MessageDialogResult::None, "initial result is None"); + check(!dialog->Close(), "Close() returns false when not open"); + + check(!dialog->SetButtons("", "", ""), "SetButtons rejects all-empty labels"); + check(dialog->SetButtons("Save", "Don't Save", "Cancel"), + "SetButtons accepts three custom labels"); + check(dialog->SetDefaultButton(MessageDialogResult::Primary), + "SetDefaultButton accepts Primary"); + check(dialog->SetDefaultButton(MessageDialogResult::Secondary), + "SetDefaultButton accepts Secondary"); + check(dialog->SetDefaultButton(MessageDialogResult::Close), + "SetDefaultButton accepts Close"); + check(dialog->SetDefaultButton(MessageDialogResult::None), + "SetDefaultButton accepts None"); + + check(dialog->SetInputEnabled(true), "SetInputEnabled(true)"); + check(dialog->SetInputText("draft.txt"), "SetInputText"); + check(dialog->GetInputText() == "draft.txt", "GetInputText roundtrip"); + + check(dialog->SetCheckbox("Remember my choice", true), "SetCheckbox"); + check(dialog->IsCheckboxChecked(), "IsCheckboxChecked returns true"); + check(dialog->SetCheckbox("Remember my choice", false), "SetCheckbox unchecked"); + check(!dialog->IsCheckboxChecked(), "IsCheckboxChecked returns false"); + + check(dialog->SetProgress(-2), "SetProgress(-2) hides progress"); + check(dialog->SetProgress(-1), "SetProgress(-1) indeterminate"); + check(dialog->SetProgress(0.0), "SetProgress(0.0)"); + check(dialog->SetProgress(0.5), "SetProgress(0.5)"); + check(dialog->SetProgress(1.0), "SetProgress(1.0)"); + check(!dialog->SetProgress(-3), "SetProgress rejects -3"); + check(!dialog->SetProgress(1.5), "SetProgress rejects 1.5"); + + if (failures == 0) { + std::cout << "message_dialog_extended_test: all passed" << std::endl; + } + return failures == 0 ? 0 : 1; +} diff --git a/tests/message_dialog_macos_sheet_test.mm b/tests/message_dialog_macos_sheet_test.mm new file mode 100644 index 0000000..67da957 --- /dev/null +++ b/tests/message_dialog_macos_sheet_test.mm @@ -0,0 +1,132 @@ +#import +#include +#include +#include +#include "../src/application.h" +#include "../src/message_dialog.h" +#include "../src/window.h" + +using nativeapi::Application; +using nativeapi::MessageDialog; +using nativeapi::MessageDialogResult; +using nativeapi::Window; + +static void PumpRunLoop(double seconds) { + NSDate* until = [NSDate dateWithTimeIntervalSinceNow:seconds]; + while ([until timeIntervalSinceNow] > 0) { + NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny + untilDate:[NSDate dateWithTimeIntervalSinceNow:0.01] + inMode:NSDefaultRunLoopMode + dequeue:YES]; + if (event) { + [NSApp sendEvent:event]; + } + } +} + +static NSButton* FindButtonWithTitle(NSView* root, NSString* title) { + if ([root isKindOfClass:[NSButton class]]) { + NSButton* btn = (NSButton*)root; + if ([[btn title] isEqualToString:title]) { + return btn; + } + } + for (NSView* sub in [root subviews]) { + if (NSButton* found = FindButtonWithTitle(sub, title)) { + return found; + } + } + return nil; +} + +int main() { + int failures = 0; + auto check = [&](bool ok, const char* what) { + if (!ok) { + std::cerr << "FAIL: " << what << std::endl; + ++failures; + } + }; + + @autoreleasepool { + Application::GetInstance(); + [NSApplication sharedApplication]; + + NSWindow* ns_window = + [[NSWindow alloc] initWithContentRect:NSMakeRect(100, 100, 320, 200) + styleMask:(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable) + backing:NSBackingStoreBuffered + defer:NO]; + [ns_window setReleasedWhenClosed:NO]; + [ns_window orderBack:nil]; + auto parent = std::make_shared((__bridge void*)ns_window); + + // 1. Non-blocking sheet with 3 custom buttons, default Return, Escape close, and Primary click. + auto dialog = std::make_shared("Unsaved Changes", "Save before closing?"); + check(dialog->SetParentWindow(parent), "SetParentWindow succeeds"); + check(dialog->SetButtons("Save", "Don't Save", "Cancel"), "SetButtons succeeds"); + check(dialog->SetDefaultButton(MessageDialogResult::Primary), "SetDefaultButton succeeds"); + check(dialog->SetCheckbox("Apply to all", true), "SetCheckbox succeeds"); + check(dialog->SetInputEnabled(true), "SetInputEnabled succeeds"); + check(dialog->SetInputText("report.md"), "SetInputText succeeds"); + check(dialog->SetProgress(0.4), "SetProgress succeeds"); + + check(dialog->Open(), "Open() returns true immediately for sheet"); + check(dialog->IsOpen(), "IsOpen() is true while sheet is open"); + check(dialog->GetResult() == MessageDialogResult::None, "GetResult() is None while open"); + + PumpRunLoop(0.1); + NSWindow* sheet = [ns_window attachedSheet]; + check(sheet != nil, "parent window has attachedSheet"); + if (sheet) { + NSButton* save_btn = FindButtonWithTitle([sheet contentView], @"Save"); + NSButton* dont_save_btn = FindButtonWithTitle([sheet contentView], @"Don't Save"); + NSButton* cancel_btn = FindButtonWithTitle([sheet contentView], @"Cancel"); + check(save_btn != nil, "Save button present in sheet"); + check(dont_save_btn != nil, "Don't Save button present in sheet"); + check(cancel_btn != nil, "Cancel button present in sheet"); + if (save_btn) { + check([[save_btn keyEquivalent] isEqualToString:@"\r"], + "Primary button has Return keyEquivalent"); + } + if (cancel_btn) { + check([[cancel_btn keyEquivalent] isEqualToString:@"\x1b"], + "Close button has Escape keyEquivalent"); + } + // Live progress update while open. + check(dialog->SetProgress(0.8), "live SetProgress(0.8) succeeds while open"); + if (save_btn) { + [save_btn performClick:nil]; + } + } + + for (int i = 0; i < 30 && dialog->IsOpen(); ++i) { + PumpRunLoop(0.05); + } + check(!dialog->IsOpen(), "IsOpen() becomes false after Primary click"); + check(dialog->GetResult() == MessageDialogResult::Primary, + "GetResult() is Primary after clicking Save"); + check(dialog->IsCheckboxChecked(), "checkbox state persisted after dismissal"); + check(dialog->GetInputText() == "report.md", "input text persisted after dismissal"); + + // 2. Programmatic Close() dismisses an open sheet. + check(dialog->SetButtons("OK", "", "Cancel"), "SetButtons for second sheet"); + check(dialog->Open(), "second Open() returns true"); + check(dialog->IsOpen(), "second sheet is open"); + PumpRunLoop(0.1); + check(dialog->Close(), "Close() returns true on open sheet"); + for (int i = 0; i < 30 && dialog->IsOpen(); ++i) { + PumpRunLoop(0.05); + } + check(!dialog->IsOpen(), "IsOpen() becomes false after Close()"); + check(dialog->GetResult() == MessageDialogResult::Close, + "GetResult() is Close after programmatic Close()"); + + [ns_window close]; + } + + if (failures == 0) { + std::cout << "message_dialog_macos_sheet_test: all passed" << std::endl; + } + return failures == 0 ? 0 : 1; +}