Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qcocoamessagedialog.mm
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6
7#include "qcocoawindow.h"
10
11#include <QtCore/qmetaobject.h>
12#include <QtCore/qpointer.h>
13#include <QtCore/qscopedvaluerollback.h>
14#include <QtCore/qtimer.h>
15
16#include <QtGui/qtextdocument.h>
17#include <QtGui/private/qguiapplication_p.h>
18#include <QtGui/private/qcoregraphics_p.h>
19#include <QtGui/qpa/qplatformtheme.h>
20
21#include <AppKit/NSAlert.h>
22#include <AppKit/NSButton.h>
23
24QT_USE_NAMESPACE
25
26using namespace Qt::StringLiterals;
27
29
31{
32 hide();
33 [m_alert release];
34}
35
36static QString toPlainText(const QString &text)
37{
38 // FIXME: QMessageDialog supports Qt::TextFormat, which
39 // nowadays includes Qt::MarkdownText, but we don't have
40 // the machinery to deal with that yet. We should as a
41 // start plumb the dialog's text format to the platform
42 // via the dialog options.
43
44 if (!Qt::mightBeRichText(text))
45 return text;
46
47 QTextDocument textDocument;
48 textDocument.setHtml(text);
49 return textDocument.toPlainText();
50}
51
52static NSControlStateValue controlStateFor(Qt::CheckState state)
53{
54 switch (state) {
55 case Qt::Checked: return NSControlStateValueOn;
56 case Qt::Unchecked: return NSControlStateValueOff;
57 case Qt::PartiallyChecked: return NSControlStateValueMixed;
58 }
59 Q_UNREACHABLE();
60}
61
62/*
63 Called from QDialogPrivate::setNativeDialogVisible() when the message box
64 is ready to be shown.
65
66 At this point the options() will reflect the specific dialog shown.
67
68 Returns true if the helper could successfully show the dialog, or
69 false if the cross platform fallback dialog should be used instead.
70*/
71bool QCocoaMessageDialog::show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow *parent)
72{
73 Q_UNUSED(windowFlags);
74
75 qCDebug(lcQpaDialogs) << "Asked to show" << windowModality << "dialog with parent" << parent;
76
77 if (m_alert.window.visible) {
78 qCDebug(lcQpaDialogs) << "Dialog already visible, ignoring request to show";
79 return true; // But we don't want to show the fallback dialog instead
80 }
81
82 // We can only do application and window modal dialogs
83 if (windowModality == Qt::NonModal)
84 return false;
85
86 // And only window modal if we have a parent
87 if (windowModality == Qt::WindowModal && (!parent || !parent->handle())) {
88 qCWarning(lcQpaDialogs, "Cannot run window modal dialog without parent window");
89 return false;
90 }
91
92 // Tahoe has issues with window-modal alert buttons not responding to mouse
93 if (windowModality == Qt::WindowModal
94 && QOperatingSystemVersion::current() >= QOperatingSystemVersion::MacOSTahoe)
95 return false;
96
97 // And without options we don't know what to show
98 if (!options())
99 return false;
100
101 // NSAlert doesn't have a section for detailed text
102 if (!options()->detailedText().isEmpty()) {
103 qCWarning(lcQpaDialogs, "Message box contains detailed text");
104 return false;
105 }
106
107 if (Qt::mightBeRichText(options()->text()) ||
108 Qt::mightBeRichText(options()->informativeText())) {
109 // Let's fallback to non-native message box,
110 // we only have plain NSString/text in NSAlert.
111 qCDebug(lcQpaDialogs, "Message box contains text in rich text format");
112 return false;
113 }
114
115 Q_ASSERT(!m_alert);
116 m_alert = [NSAlert new];
117 m_alert.window.title = options()->windowTitle().toNSString();
118
119 const QString text = toPlainText(options()->text());
120 m_alert.messageText = text.toNSString();
121 m_alert.informativeText = toPlainText(options()->informativeText()).toNSString();
122
123 switch (options()->standardIcon()) {
124 case QMessageDialogOptions::NoIcon: {
125 // We only reflect the pixmap icon if the standard icon is unset,
126 // as setting a standard icon will also set a corresponding pixmap
127 // icon, which we don't want since it conflicts with the platform.
128 // If the user has set an explicit pixmap icon however, the standard
129 // icon will be NoIcon, so we're good.
130 QPixmap iconPixmap = options()->iconPixmap();
131 if (!iconPixmap.isNull())
132 m_alert.icon = [NSImage imageFromQImage:iconPixmap.toImage()];
133 break;
134 }
135 case QMessageDialogOptions::Information:
136 case QMessageDialogOptions::Question:
137 [m_alert setAlertStyle:NSAlertStyleInformational];
138 break;
139 case QMessageDialogOptions::Warning:
140 [m_alert setAlertStyle:NSAlertStyleWarning];
141 break;
142 case QMessageDialogOptions::Critical:
143 [m_alert setAlertStyle:NSAlertStyleCritical];
144 break;
145 }
146
147 auto defaultButton = options()->defaultButton();
148 auto escapeButton = options()->escapeButton();
149
150 const auto addButton = [&](auto title, auto tag, auto role) {
151 title = QPlatformTheme::removeMnemonics(title);
152 NSButton *button = [m_alert addButtonWithTitle:title.toNSString()];
153
154 // Calling addButtonWithTitle places buttons starting at the right side/top of the alert
155 // and going toward the left/bottom. By default, the first button has a key equivalent of
156 // Return, any button with a title of "Cancel" has a key equivalent of Escape, and any button
157 // with the title "Don't Save" has a key equivalent of Command-D (but only if it's not the first
158 // button). If an explicit default or escape button has been set, we respect these,
159 // and otherwise we fall back to role-based default and escape buttons.
160
161 qCDebug(lcQpaDialogs).verbosity(0) << "Adding button" << title << "with" << role;
162
163 if (!defaultButton && role == AcceptRole)
164 defaultButton = tag;
165
166 if (tag == defaultButton)
167 button.keyEquivalent = @"\r";
168 else if ([button.keyEquivalent isEqualToString:@"\r"])
169 button.keyEquivalent = @"";
170
171 if (!escapeButton && role == RejectRole)
172 escapeButton = tag;
173
174 // Don't override default button with escape button, to match AppKit default
175 if (tag == escapeButton && ![button.keyEquivalent isEqualToString:@"\r"])
176 button.keyEquivalent = @"\e";
177 else if ([button.keyEquivalent isEqualToString:@"\e"])
178 button.keyEquivalent = @"";
179
180 button.hasDestructiveAction = role == DestructiveRole;
181
182 // The NSModalResponse of showing an NSAlert normally depends on the order of the
183 // button that was clicked, starting from the right with NSAlertFirstButtonReturn (1000),
184 // NSAlertSecondButtonReturn (1001), NSAlertThirdButtonReturn (1002), and after that
185 // NSAlertThirdButtonReturn + n. The response can also be customized per button via its
186 // tag, which, following the above logic, can include any positive value from 1000 and up.
187 // In addition the system reserves the values from -1000 and down for its own modal responses,
188 // such as NSModalResponseStop, NSModalResponseAbort, and NSModalResponseContinue.
189 // Luckily for us, the QPlatformDialogHelper::StandardButton enum values all fall within
190 // the positive range, so we can use the standard button value as the tag directly.
191 // The same applies to the custom button IDs, as these are generated in sequence after
192 // the QPlatformDialogHelper::LastButton.
193 Q_ASSERT(tag >= NSAlertFirstButtonReturn);
194 button.tag = tag;
195 };
196
197 // Resolve all dialog buttons from the options, both standard and custom
198
199 struct Button { QString title; int identifier; ButtonRole role; };
200 std::vector<Button> buttons;
201
202 const auto *platformTheme = QGuiApplicationPrivate::platformTheme();
203 if (auto standardButtons = options()->standardButtons()) {
204 for (int standardButton = FirstButton; standardButton <= LastButton; standardButton <<= 1) {
205 if (standardButtons & standardButton) {
206 auto title = platformTheme->standardButtonText(standardButton);
207 buttons.push_back({
208 title, standardButton, buttonRole(StandardButton(standardButton))
209 });
210 }
211 }
212 }
213 const auto customButtons = options()->customButtons();
214 for (auto customButton : customButtons)
215 buttons.push_back({customButton.label, customButton.id, customButton.role});
216
217 // Sort them according to the QPlatformDialogHelper::ButtonLayout for macOS
218
219 // The ButtonLayout adds one additional role, AlternateRole, which is used
220 // for any AcceptRole beyond the first one, and should be ordered before the
221 // AcceptRole. Set this up by fixing the roles up front.
222 bool seenAccept = false;
223 for (auto &button : buttons) {
224 if (button.role == AcceptRole) {
225 if (!seenAccept)
226 seenAccept = true;
227 else
228 button.role = AlternateRole;
229 }
230 }
231
232 std::vector<Button> orderedButtons;
233 const int *layoutEntry = buttonLayout(Qt::Horizontal, ButtonLayout::MacLayout);
234 while (*layoutEntry != QPlatformDialogHelper::EOL) {
235 const auto role = ButtonRole(*layoutEntry & ~ButtonRole::Reverse);
236 const bool reverse = *layoutEntry & ButtonRole::Reverse;
237
238 auto addButton = [&](const Button &button) {
239 if (button.role == role)
240 orderedButtons.push_back(button);
241 };
242
243 if (reverse)
244 std::for_each(std::crbegin(buttons), std::crend(buttons), addButton);
245 else
246 std::for_each(std::cbegin(buttons), std::cend(buttons), addButton);
247
248 ++layoutEntry;
249 }
250
251 // Add them to the alert in reverse order, since buttons are added right to left
252 for (auto button = orderedButtons.crbegin(); button != orderedButtons.crend(); ++button)
253 addButton(button->title, button->identifier, button->role);
254
255 // If we didn't find a an explicit or implicit default button above
256 // we restore the AppKit behavior of making the first button default.
257 if (!defaultButton)
258 m_alert.buttons.firstObject.keyEquivalent = @"\r";
259
260 if (auto checkBoxLabel = options()->checkBoxLabel(); !checkBoxLabel.isNull()) {
261 checkBoxLabel = QPlatformTheme::removeMnemonics(checkBoxLabel);
262 m_alert.suppressionButton.title = checkBoxLabel.toNSString();
263 auto state = options()->checkBoxState();
264 m_alert.suppressionButton.allowsMixedState = state == Qt::PartiallyChecked;
265 m_alert.suppressionButton.state = controlStateFor(state);
266 m_alert.showsSuppressionButton = YES;
267 }
268
269 qCDebug(lcQpaDialogs) << "Showing" << m_alert;
270
271 if (windowModality == Qt::WindowModal) {
272 auto *cocoaWindow = static_cast<QCocoaWindow*>(parent->handle());
273 [m_alert beginSheetModalForWindow:cocoaWindow->nativeWindow()
274 completionHandler:^(NSModalResponse response) {
275 processResponse(response);
276 }
277 ];
278 } else {
279 // The dialog is application modal, so we need to call runModal,
280 // but we can't call it here as the nativeDialogInUse state of QDialog
281 // depends on the result of show(), and we can't rely on doing it
282 // in exec(), as we can't guarantee that the user will call exec()
283 // after showing the dialog. As a workaround, we call it from exec(),
284 // but also make sure that if the user returns to the main runloop
285 // we'll run the modal dialog from there.
286 QTimer::singleShot(0, this, [this]{
287 if (m_alert && !m_alert.window.visible) {
288 qCDebug(lcQpaDialogs) << "Running deferred modal" << m_alert;
289 runModalAndProcessResponse();
290 }
291 });
292 }
293
294 return true;
295}
296
297// We shouldn't get NSModalResponseContinue as a response from NSAlert::runModal,
298// and processResponse must not be called with that value (if we are there, it's
299// too late to do anything about it.
300// However, as QTBUG-114546 shows, there are scenarios where we might get that
301// response anyway. We interpret it to keep the modal loop running, and we only
302// return if we got something else and passed it to processResponse.
303void QCocoaMessageDialog::runModalAndProcessResponse()
304{
306 QPointer that(this);
307 NSAlert *alert = [[m_alert retain] autorelease]; // keeps it alive even if *this is deleted
308 NSModalResponse response;
309 do {
310 response = [alert runModal];
311 if (!that) // deleted while the modal loop was running
312 return;
313 } while (response == NSModalResponseContinue);
314 processResponse(response);
315}
316
318{
319 Q_ASSERT(m_alert);
320
321 if (modality() == Qt::WindowModal) {
322 qCDebug(lcQpaDialogs) << "Running local event loop for window modal" << m_alert;
323 QEventLoop eventLoop;
324 QScopedValueRollback updateGuard(m_eventLoop, &eventLoop);
325 m_eventLoop->exec(QEventLoop::DialogExec);
326 } else {
327 qCDebug(lcQpaDialogs) << "Running modal" << m_alert;
328 runModalAndProcessResponse();
329 }
330}
331
332// Custom modal response code to record that the dialog was hidden by us
333static const NSInteger kModalResponseDialogHidden = NSAlertThirdButtonReturn + 1;
334
335static Qt::CheckState checkStateFor(NSControlStateValue state)
336{
337 switch (state) {
338 case NSControlStateValueOn: return Qt::Checked;
339 case NSControlStateValueOff: return Qt::Unchecked;
340 case NSControlStateValueMixed: return Qt::PartiallyChecked;
341 }
342 Q_UNREACHABLE();
343}
344
345void QCocoaMessageDialog::processResponse(NSModalResponse response)
346{
347 qCDebug(lcQpaDialogs) << "Processing response" << response << "for" << m_alert;
348
349 // We can't re-use the same dialog for the next show() anyways,
350 // since the options may have changed, so get rid of it now,
351 // before we emit anything that might recurse back to hide/show/etc.
352 auto alert = std::exchange(m_alert, nil);
353 [alert autorelease];
354
355 if (alert.showsSuppressionButton)
356 emit checkBoxStateChanged(checkStateFor(alert.suppressionButton.state));
357
358 if (response >= NSAlertFirstButtonReturn) {
359 // Safe range for user-defined modal responses
360 if (response == kModalResponseDialogHidden) {
361 // Dialog was explicitly hidden by us, so nothing to report
362 qCDebug(lcQpaDialogs) << "Dialog was hidden; ignoring response";
363 } else {
364 // Dialog buttons
365 if (response <= StandardButton::LastButton) {
366 Q_ASSERT(response >= StandardButton::FirstButton);
367 auto standardButton = StandardButton(response);
368 emit clicked(standardButton, buttonRole(standardButton));
369 } else {
370 auto *customButton = options()->customButton(response);
371 Q_ASSERT(customButton);
372 emit clicked(StandardButton(customButton->id), customButton->role);
373 }
374 }
375 } else {
376 // We have to consider NSModalResponses beyond the ones specific to
377 // the alert buttons as the alert may be canceled programmatically.
378
379 switch (response) {
380 case NSModalResponseContinue:
381 // Modal session is continuing (returned by runModalSession: only)
382 Q_UNREACHABLE();
383 case NSModalResponseOK:
384 emit accept();
385 break;
386 case NSModalResponseCancel:
387 case NSModalResponseStop: // Modal session was broken with stopModal
388 case NSModalResponseAbort: // Modal session was broken with abortModal
389 emit reject();
390 break;
391 default:
392 qCWarning(lcQpaDialogs) << "Unrecognized modal response" << response;
393 }
394 }
395
396 if (m_eventLoop)
397 m_eventLoop->exit(response);
398}
399
401{
402 if (!m_alert)
403 return;
404
405 if (m_alert.window.visible) {
406 qCDebug(lcQpaDialogs) << "Hiding" << modality() << m_alert;
407
408 // Note: Just hiding or closing the NSAlert's NWindow here is not sufficient,
409 // as the dialog is running a modal event loop as well, which we need to end.
410
411 if (modality() == Qt::WindowModal) {
412 // Will call processResponse() synchronously
413 [m_alert.window.sheetParent endSheet:m_alert.window returnCode:kModalResponseDialogHidden];
414 } else {
415 if (NSApp.modalWindow == m_alert.window) {
416 // Will call processResponse() asynchronously
417 [NSApp stopModalWithCode:kModalResponseDialogHidden];
418 } else {
419 qCWarning(lcQpaDialogs, "Dialog is not top level modal window. Cannot hide.");
420 }
421 }
422 } else {
423 qCDebug(lcQpaDialogs) << "No need to hide already hidden" << m_alert;
424 auto alert = std::exchange(m_alert, nil);
425 [alert autorelease];
426 }
427}
428
429Qt::WindowModality QCocoaMessageDialog::modality() const
430{
431 Q_ASSERT(m_alert && m_alert.window);
432 return m_alert.window.sheetParent ? Qt::WindowModal : Qt::ApplicationModal;
433}
434
435QT_END_NAMESPACE
static void clearCurrentThreadCocoaEventDispatcherInterruptFlag()
bool show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow *parent) override
NSInteger NSModalResponse
static const NSInteger kModalResponseDialogHidden
static NSControlStateValue controlStateFor(Qt::CheckState state)
static QString toPlainText(const QString &text)
static Qt::CheckState checkStateFor(NSControlStateValue state)
long NSInteger