Add function to safely access the shared application on Apple platforms

Change-Id: I52910309ba94d84d69f049b5c1990f1f866e1698
Reviewed-by: Richard Moe Gustavsen <richard.gustavsen@qt.io>
This commit is contained in:
Tor Arne Vestbø 2018-05-07 15:10:01 +02:00
parent 6ada504475
commit 0587941f6e
3 changed files with 41 additions and 11 deletions

View File

@ -167,6 +167,28 @@ bool qt_apple_isApplicationExtension()
return isExtension;
}
#if !defined(QT_BOOTSTRAPPED) && !defined(Q_OS_WATCHOS)
AppleApplication *qt_apple_sharedApplication()
{
// Application extensions are not allowed to access the shared application
if (qt_apple_isApplicationExtension()) {
qWarning() << "accessing the shared" << [AppleApplication class]
<< "is not allowed in application extensions";
// In practice the application is actually available, but the the App
// review process will likely catch uses of it, so we return nil just
// in case, unless we don't care about being App Store compliant.
#if QT_CONFIG(appstore_compliant)
return nil;
#endif
}
// We use performSelector so that building with -fapplication-extension will
// not mistakenly think we're using the shared application in extensions.
return [[AppleApplication class] performSelector:@selector(sharedApplication)];
}
#endif
#ifdef Q_OS_MACOS
/*
Ensure that Objective-C objects auto-released in main(), directly or indirectly,

View File

@ -160,6 +160,19 @@ QDebug operator<<(QDebug debug, const QMacAutoReleasePool *pool);
Q_CORE_EXPORT void qt_apple_check_os_version();
Q_CORE_EXPORT bool qt_apple_isApplicationExtension();
#if !defined(QT_BOOTSTRAPPED) && !defined(Q_OS_WATCHOS)
QT_END_NAMESPACE
# if defined(Q_OS_MACOS)
Q_FORWARD_DECLARE_OBJC_CLASS(NSApplication);
using AppleApplication = NSApplication;
# else
Q_FORWARD_DECLARE_OBJC_CLASS(UIApplication);
using AppleApplication = UIApplication;
# endif
QT_BEGIN_NAMESPACE
Q_CORE_EXPORT AppleApplication *qt_apple_sharedApplication();
#endif
// --------------------------------------------------------------------------
#if !defined(QT_BOOTSTRAPPED) && (QT_MACOS_PLATFORM_SDK_EQUAL_OR_ABOVE(__MAC_10_12) || !defined(Q_OS_MACOS))

View File

@ -72,17 +72,12 @@ QT_NAMESPACE_ALIAS_OBJC_CLASS(RunLoopModeTracker);
if (self = [super init]) {
m_runLoopModes.push(kCFRunLoopDefaultMode);
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(receivedNotification:)
name:nil
#ifdef Q_OS_OSX
object:[NSApplication sharedApplication]];
#elif defined(Q_OS_WATCHOS)
object:[WKExtension sharedExtension]];
#else
// Use performSelector so this can work in an App Extension
object:[[UIApplication class] performSelector:@selector(sharedApplication)]];
#if !defined(Q_OS_WATCHOS)
if (!qt_apple_isApplicationExtension()) {
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(receivedNotification:)
name:nil object:qt_apple_sharedApplication()];
}
#endif
}